/// <reference path="http://ajax.microsoft.com/ajax/jQuery/jquery-1.5.2-vsdoc.js" /> 

// main navigation:
function initMainNav() {
	var innermainnav = $("ul#innermainnav");
	innermainnav.find(" > li").removeClass("open");
	innermainnav.find(" > .mainitem").hoverIntent({
		interval: 10,
		over: showSubnav,
		sensitivity: 4,
		timeout: 10,
		out: hideSubnav
	});
	addLastItem();
}

function showSubnav() {
	$(this).addClass("open posover");
}

function hideSubnav() {
	$(this).removeClass("open posover");
}

function addLastItem() {
	$(".innersubnav .subitem:last-child").addClass("lastitem");
}

// Handle PNG transparency for images in Win IE 5.5 & 6.
function initCorrectPNG() {
	var arVersion = navigator.appVersion.split("MSIE")
	var version = parseFloat(arVersion[1])
	if ((version <= 6.0) && (document.body.filters)) {
		for (var i = 0; i < document.images.length; i++) {
			var img = document.images[i]
			var imgName = img.src.toUpperCase()
			if (imgName.substring(imgName.length - 3, imgName.length) == "PNG") {
				var imgID = (img.id) ? "id='" + img.id + "' " : ""
				var imgClass = (img.className) ? "class='" + img.className + "' " : ""
				var imgTitle = (img.title) ? "title='" + img.title + "' " : "title='" + img.alt + "' "
				var imgStyle = "display:inline-block;" + img.style.cssText
				if (img.align == "left") imgStyle = "float:left;" + imgStyle
				if (img.align == "right") imgStyle = "float:right;" + imgStyle
				if (img.parentElement.href) imgStyle = "cursor:hand;" + imgStyle
				var strNewHTML = "<span " + imgID + imgClass + imgTitle
			+ " style=\"" + "width:" + img.width + "px; height:" + img.height + "px;" + imgStyle + ";"
			+ "filter:progid:DXImageTransform.Microsoft.AlphaImageLoader"
			+ "(src=\'" + img.src + "\', sizingMethod='scale');\"></span>"
				img.outerHTML = strNewHTML
				i = i - 1
			}
		}
	}
}

function initNewWindow() {
	$(".popup").popupWindow({ height: 500, width: 800, centerBrowser: 1 });
	$(".external").attr("target", "_blank");
	$(".extern").attr("target", "_blank");
	$(".pdf").attr("target", "_blank");
}

function setUploadImage() {
	var fileUpload = $("input[id$='FileUpload1']");
	var fileUploadDeleted = $("input[id$='FileUpload1_deleted']");

	if (fileUpload.length > 0 && fileUploadDeleted.length > 0) {

		var clientId = fileUpload.attr("id");
		var name = fileUpload.attr("text");

		if (name != '' && name != undefined && name != fileUploadDeleted.val()) {
			$('#' + clientId + '_wrap_list').html("<div class=\"MultiFile-label\"><span class=\"MultiFile-title\">" + name + "</span><a id=\"removeImage\" class=\"MultiFile-remove\" href=\"#" + clientId + "_wrap\">Verwijderen</a></div>");
			$('#' + clientId).attr('disabled', true);
			fileUploadDeleted.val('');
			$('#removeImage').click(function (event) {
				fileUpload.attr("text", '');
				$('#' + clientId).attr('disabled', false);
				$('#' + clientId + '_deleted').val(name);
				$(this).parent().remove();
				event.preventDefault();
			});
		}
	}
}


$(document).ready(function () {

	/*******
	** vp - initTabs - (c) - 0.0.1 **
	*******/
	if ($('.tabsnav').length > 0) {
		$('.tabsnav').each(function () {
			var root = $(this);
			root.find("a:not(.modify)").click(function (event) {
				var lastIndex = $(this).attr("href").lastIndexOf('=');
				var id = $(this).attr("href").substring(lastIndex + 1);
				root.find('li a').parent().removeClass('active');
				$(this).parent().addClass('active');
				root.parent().find('.tabscontent').removeClass('tabsselected').addClass("closed");
				$('#' + id).addClass('tabsselected').removeClass("closed");
				event.preventDefault();
				if ($('.myaccount').length > 0) {
					root.find('li a').parent().parent().parent().removeClass('active');
					$(this).parent().parent().parent().addClass('active');
				}
			});
		});
	}

	/*******
	** vp - multiFile upload - (c) - 0.0.1 **
	*******/
	$(".imageupload input").MultiFile({
		accept: "gif|jpg|png",
		max: 1,
		STRING: {
			remove: "Verwijderen",
			denied: "De afbeelding met type $ext is niet van het juiste type. Alleen .jpg, .png of .gif kan gebruikt worden.",
			duplicate: "Je hebt dit bestand al geselecteerd:\n$file"
		}
	});

	/****
	*  Bjorn L. Please note that I modified the plugin so it uses different html structure.
	****/
	$("#baseInput input[type=file]").MultiFile({
		accept: "doc|xls|pdf|ppt",
		list: "#uploadsList",
		customHtml: "true",
		namePattern: "uplDownload$i",
		STRING: {
			remove: "Verwijderen",
			denied: "De download met type $ext is niet van het juiste type. Alleen .pdf, .doc, .xls of .ppt kan gebruikt worden.",
			duplicate: "Je hebt dit bestand al geselecteerd:\n$file"
		},
		afterFileSelect: function (element, value, master_element) {
			$("input[name=txtDownload" + (master_element.slaves.length - 2) + "]").val($("#baseInput input[type=text]").val());
			$("#baseInput input[type=text]").val("");
		}
	});

	$(".removeDownload").click(function (event) {
		$(this).parent().parent().parent().remove();
		event.preventDefault();
	});


	/*******
	** vp - treeView - (c) - 0.0.3 **
	*******/
	if ($(".treeView").length > 0) {

		$(".treeView").each(function () {
			var root = $(this);
			var orgHeight = root.height();
			var is_msie = /msie 7/.test(navigator.userAgent.toLowerCase());

			root.find("a").click(function (event) {
				root.find("div.searchcontent").hide();

				if ($(this).parent().parent().parent().hasClass("treeView")) {
					root.find("a").removeClass("selected");
					root.find("ul").find("ul").not("ul.links").hide();
					root.find(".title h3:last-child").hide();
				}
				else {
					root.find("ul").find("ul").find("a").removeClass("selected");
				}

				// show next UL
				if ($(this).next("ul").length > 0) {
					root.find(".title h3:last-child").css("display", function () {
						return is_msie ? "inline" : "inline-block";
					});

					$(this).addClass("selected");
					$(this).next(0).show();

					setHeight(root, $(this).next(0), orgHeight, is_msie ? 17 : 22);
				}

				// show searchcontent
				if ($(this).siblings("div.searchcontent").length) {
					$(this).addClass("selected");
					$(this).siblings("div.searchcontent").first().show();

					setHeight(root, $(this).siblings("div.searchcontent").first(), orgHeight, 45);
				}

				if ($(this).attr("href") == "#") {
					event.preventDefault();
				}
			});
		});
	}

	var setHeight = function (setTo, setFrom, orgHeight, padding) {
		$(setTo).css("height", function () {
			var is_msie = /msie 7/.test(navigator.userAgent.toLowerCase());
			var elHeight = $(setFrom).height() + padding;
			var curHeight = $(setTo).height();

			if (curHeight > elHeight) {
				return curHeight;
			}
			else if ((elHeight > curHeight) || (elHeight > orgHeight)) {
				return elHeight;
			}
			else if ($(setFrom).get(0).tagName.toLowerCase() == "div") {
				if (elHeight < $(setFrom).parent().parent().height()) {
					return $(setFrom).parent().parent().height() + is_msie ? 17 : 22;
				}
			}
			else {
				return orgHeight;
			}
		});
	}

	/*******
	** fancybox **
	******
	$(".boxOverlay").fancybox({
	'centerOnScroll': 'true',
	'overlayOpacity': 0.8,
	'overlayColor': '#000',
	'titleShow': false,
	'transitionIn': 'none',
	'transitionOut': 'none'
	});*/

	/*******
	** position **
	*******/
	if ($(".inloglink").length > 0) {
		$(".relatedcontentForm").addClass("relatedcontentForm1");
	}
});

function initTreeNav() {
	if (document.getElementById("treenav")) {
		var headings = $("#treenav").find(".plus,.min");
		var subitems = $("#treenav div");

		//Set default state
		$(subitems).addClass("closed");

		// Toggle heading-style and content on heading click
		$(headings).click(function (e) {
			var isOpen = $(this).is(".min");

			$(headings).removeClass("min").addClass("plus");
			$(subitems).addClass("closed").removeClass("open");
			$(this).addClass("min").removeClass("plus");
			$(this).find("+ div").removeClass("closed").addClass("open");

			if (isOpen) {
				$(this).removeClass("min").addClass("plus");
				$(this).find("+ div").addClass("closed").removeClass("open");
			}
			return false;
		});
	}
}

// AUTOLOAD CODE BLOCK (MAY BE CHANGED OR REMOVED)
if (!/android|iphone|ipod|series60|symbian|windows ce|blackberry/i.test(navigator.userAgent)) {
	jQuery(function ($) {
		$("a[rel^='lightbox']").slimbox({/* Put custom options here */
		},
			null,
			function (el) {
				return (this == el) || ((this.rel.length > 8) && (this.rel == el.rel));
			}
		);
	});
}

function initMaxLength() {
	$(".editorsform #intro").maxlength({ events: [], maxCharacters: 200 });
	$(".editorsform .text1").maxlength({ events: [], maxCharacters: 100 });
	$(".editorsform #links-intro").maxlength({ events: [], maxCharacters: 200 });
	$(".editorsform #download-intro").maxlength({ events: [], maxCharacters: 250 });
}

function initRemoveNewsAlert() {
	$("div.mynews a.remove").click(function () {
		return confirm("Weet je zeker dat dit bericht verwijderd mag worden?");
	});
}

function limitChars(textid, limit, infodiv) {
	var text = $("." + textid).val();
	var textlength = text.length;
	var infodiv = $("." + infodiv);
	if (textlength > limit) {
		infodiv.html("Geef uw commentaar in maximaal <span class='number'>" + limit + "</span> tekens");
		$("." + textid).val(text.substr(0, limit));
		return false;
	}
	else {
		infodiv.html("Nog " + (limit - textlength) + " tekens over");
		return true;
	}
}

function initLimitChars() {
	$('.reactionBox').keyup(function () {
		limitChars('reactionBox', 1500, 'signsleft');
	})
}

function initCloneLinkField() {
	$('.linkGroup:last-child input').live('blur.cloneLinkField', function (event) {
		if ($(this).val() != '') {
			var newCount = getIntAsString($('.linkGroup').length + 1);
			// clone the first link group and remove the labels and empty the input values.
			var linkGroup = $('.linkGroup:first').clone().find('label').remove().end().find('input').val('').each(function (index, element) {
				// we are always taking the first link group and therefore always replacing 01
				$(element).attr('name', element.name.replace('01', newCount));
				$(element).attr('id', element.id.replace('01', newCount));
			}).end();
			$('.linkGroup:last').after(linkGroup);
		}
	});
}

function getIntAsString(val) {
	if (val < 10) {
		return "0" + val;
	}
	else {
		return val;
	}
}

function initBrowserCheck() {

	jQuery.each(jQuery.browser, function (i) {
		if ($.browser.msie) {
			if (jQuery.browser.version.substr(0, 1) == "6") {
				if ($.cookie("ie6close") != "true") {
					$('#alertbar').css('display', 'block');

					$('#alertbar .close').click(function (e) {
						$('#alertbar').css("display", "none");
						$.cookie("ie6close", "true");
						return false;
					});
				}
			}
		}
	});
}

function initDetailsContent() {
	//table triggers
	$(".tableOverview a.showdetails").click(function () {
		$(this).closest('tr').next("tr.details").toggleClass("closed");
		return false;
	});

	$(".tableOverview a.hidedetails").click(function () {
		$(this).closest('tr.details').toggleClass("closed");
		return false;
	});

	//infoblock triggers
	$(".infoblock > .row a.showdetails").click(function () {
		$(this).closest('div.infoblock').find('div.infodetails').toggleClass("closed");
		return false;
	});

	$(".infoblock .infodetails a.hidedetails").click(function () {
		$(this).closest('div.infodetails').toggleClass("closed");
		return false;
	});
}

function initToolTip() {
	if ($(".tooltipwrapper").length) {

		// select all desired input fields and attach tooltips to them
		$(".tooltipwrapper a.infoTrigger").tooltip({
			position: 'bottom right',
			relative: 'true',
			offset: [3, -100]
		});
	}

	if ($(".tooltipwrapper2").length) {
		$(".tooltipwrapper2 .infoTrigger2").tooltip({
			position: "bottom left",
			relative: "true",
			offset: [3, -100]
		});

		$("div.reactbox > img.left").each(function () {

			var node = $(this).parent().find("div.tooltipwrapper2 > div.tooltip1");

			if (node.length == 0) {
				$(this).parent().find("span.infoTrigger2").removeClass("infoTrigger2");
			} else {
				$(this).addClass("infoTrigger2");

				$(this).mouseenter(function () {
					$(this).parent().find("span.infoTrigger2").mouseenter();
				});

				$(this).mouseleave(function () {
					$(this).parent().find("span.infoTrigger2").mouseleave();
				});
			}
		});
	}

	$(".infoTriggerClose").live("click", function () {
		$(this).next(".tooltipwrapper1").hide(0);
		$(this).removeClass("infoTriggerClose").addClass("infoTrigger1");
	});

	// remove existing title attribute from infotrigger.
	$("span.infoTrigger1[title!='']").live("mouseover", function () {
		$(this).attr("title", "");
	});

	$(".infoTrigger1").live("click", function (e) {
		$(this).addClass("infoTriggerClose").removeClass("infoTrigger1");

		$(".tooltipwrapper1").hide(0);

		$(this).next(".tooltipwrapper1").show(0);

		$(".tooltipwrapper1").find("a.tooltipclose1").click(function () {
			$(".tooltipwrapper1").hide(0);
		});

		$(".tooltipwrapper1").click(function (e) {
			e.stopPropagation(); //Stop click from bubbling to the body element				
		});

		$("body").click(function (e) {
			var targetLink = e.target.className;
			if (targetLink != "infoTriggerClose") {
				$(".tooltipwrapper1").hide(0);
				$(".infoTriggerClose").removeClass("infoTriggerClose").addClass("infoTrigger1");
			}
		});

		var parts = $(this).attr("id").split(".");
		if (parts.length == 2) {
			var cat = parts[0];
			var label = parts[1];
			_gaq.push(["_trackEvent", cat, "Tooltips", label]);
		}
	});
}

function initRadio() {
	var textID = $("input[name='member']:checked").val();
	$(".div" + textID).removeClass("closed");
	$(".divno").removeClass("closed");
	$(".divyes").addClass("closed");
	if ($("input[name='member']:checked").val() == 'yes') {
		$(".divyes").removeClass("closed");
		$(".divno").addClass("closed");
	}
	$("input[name='member']").change(function () {
		if ($("input[name='member']:checked").val() == 'yes') {
			$(".divyes").removeClass("closed");
			$(".divno").addClass("closed");
		}
		else if ($("input[name='member']:checked").val() == 'no') {
			$(".divno").removeClass("closed");
			$(".divyes").addClass("closed");
		}
	});
};


jQuery(function ($) {
	initMainNav();
	initCorrectPNG();
	initNewWindow();
	initTreeNav();
	initMaxLength();
	initRemoveNewsAlert();
	initLimitChars();
	initCloneLinkField();
	initBrowserCheck();
	initDetailsContent();
	initToolTip();
	initRadio();
	/* This is only an example of how to set an upload image when an article is edited */
	setUploadImage();
});
