/*
Documentation according http://www.aeneas-software.nl/JSdocGenerator/

<documentation about="ABOUT library.js" type="GENERAL">
	<summary>This file is a library: it contains general functions used for the entire application.
		No page initialisation calls are made in this file; there is one exception: Lib.addEvent(window, "unload", Lib.eventCache.flush): This removes all attached events.
		Make your function calls in the specific javascript files, in the [namespace].init()
	</summary>
	<namespace>Lib</namespace>
</documentation> */
var Lib = {};

/* <documentation about="Lib.debug/Lib.allowAlert" type="global variables">
	<summary>These variables are used for debugging - do not change</summary>
	<namespace>Lib</namespace>
</documentation> */
Lib.debug = false;
Lib.allowAlert = true;

/* <documentation about="Lib.safari/Lib.opera/Lib.ie/Lib.ie6" type="global variables">
	<summary>Browser checks</summary>
	<namespace>Lib</namespace>
</documentation> */
Lib.safari = (navigator.userAgent.toLowerCase().indexOf("safari") != - 1);
Lib.opera = window.opera ? true : false;
Lib.ie = (document.all && document.getElementById) ? true:false;
Lib.ie6 = navigator.appVersion.indexOf("MSIE 6")!=-1 ? true:false;

/*<documentation about="Global variables" type="Global variables">
	<summary>
		Content.setTimeOut -> Used for delay in folding back of main navigation
		Content.iframe -> Iframe used for main navaigation
		Content.mainTopPadding=0 -> Top margin of "main" used for folding out main navigation
	</summary>
	<namespace>Content</namespace>
</documentation> */
Lib.setTimeOut;
Lib.iframe;
Lib.mainTopPadding=0;

/* <documentation about="Lib.pageIsStyled" type="global variables">
	<summary>Used to keep status if page is styled</summary>
	<namespace>Lib</namespace>
</documentation> */
Lib.pageIsStyled = false;

/* ========== CORE ============================================================================ */
/* <documentation about="Lib.addEvent" type="CORE FUNCTION">
	<summary>Adds events to elements of the DOM</summary>
	<namespace>Lib</namespace>
	<param type="object" descr="A reference to the node on which the event has been set (HTML element).">obj</param>
	<param type="string" descr="The name of the event ">evt</param>
	<param type="object" descr="A reference to the function which handles the event.">fn</param>
</documentation> */
Lib.addEvent = function (obj,evt,fn) {
	if (obj.addEventListener)
		obj.addEventListener(evt,fn,false);
	else if (obj.attachEvent)
		obj.attachEvent("on"+evt,fn);
}

/* <documentation about="Lib.removeEvent" type="CORE FUNCTION">
	<summary>Removes events to elements of the DOM</summary>
	<namespace>Lib</namespace>
	<param type="object" descr="A reference to the node on which the event has been set (HTML element).">obj</param>
	<param type="string" descr="The name of the event ">evt</param>
	<param type="object" descr="A reference to the function which handles the event.">fn</param>
</documentation> */
Lib.removeEvent = function (obj,evt,fn) {
	if (obj.removeEventListener)
		obj.removeEventListener(evt,fn,false);
	else if (obj.detachEvent)
		obj.detachEvent('on'+evt,fn);
}

Lib.eventCache = function(){
	try {
		var listEvents = [];

		/*  Implement array.push for browsers which don't support it natively. (used in EventCache)
		Please remove this if it's already in other code */
		if(Array.prototype.push == null){
			Array.prototype.push = function(){
				for(var i = 0; i < arguments.length; i++){
					this[this.length] = arguments[i];
		       	};
		        return this.length;
			};
		};

	    return {
			listEvents : listEvents,

			/* <documentation about="Lib.eventCache.add" type="CORE FUNCTION">
				<summary>Keeping track of all the attached events</summary>
				<namespace>Lib</namespace>
				<param type="object" descr="A reference to the node on which the event has been set (HTML element).">node</param>
				<param type="string" descr="The name of the event">sEventName</param>
				<param type="object" descr="A reference to the function which handles the event. ">fHandler</param>
				<param type="bool" descr="A boolean which determines whether the event is triggered in capture mode or not. Does not apply to Internet Explorer.">bCapture</param>
			</documentation> */
			add : 	function(node, sEventName, fHandler, bCapture){
						listEvents.push(arguments);
					},

		 	/* <documentation about="Lib.eventCache.flush" type="CORE FUNCTION">
				<summary>Used to remove (detach) all cached events.</summary>
			</documentation> */
			flush : 	function(){
					var i, item;
					for(i = listEvents.length - 1; i >= 0; i = i - 1){
						item = listEvents[i];
	                 	Lib.removeEvent(item[0], item[1], item[2])

						item[0][item[1]] = null;
					};
			}
	      };
	} catch (ex){ Lib.errHandler(ex); }
}();

/* <documentation about="Lib.debugAlert" type="CORE FUNCTION">
	<summary>Displays alert with error message, if alert is allowed (not cancelled in confirm) and Lib.debug = true</summary>
	<namespace>Lib</namespace>
	<param type="string" descr="Message to display in alert">message</param>
</documentation> */
Lib.debugAlert = function (message) {
		if(Lib.allowAlert && Lib.debug) { Lib.allowAlert = confirm(message); }
	}


/* <documentation about="Lib.errHandler" type="CORE FUNCTION">
	<summary>Handles errors in javascript application</summary>
	<namespace>Lib</namespace>
	<param type="object" descr="Error object">err</param>
</documentation> */
Lib.errHandler = function (err) {
		var errorText = "";
		for (var i in err) { errorText += i + "=" + err[i] + "\n"; }
		Lib.debugAlert("An error has occured: \n\n" + errorText + "\nSee Firefox browser for correct linenumbers.");
		return true;
	}
/* ========== END CORE ====================================================================== */

/* ========== GENERAL FUNCTIONS ============================================================= */
/* <documentation about="Lib.elementsExists" type="general function">
	<summary>Checks if all the elements with the id specified in the arguments of this function exist; returns true if they do exist; false if one or more do not exist</summary>
	<namespace>Lib</namespace>
	<param type="array of strings" descr="Id's of HTML elements">[array]</param>
	<returns>boolean</returns>
</documentation> */
Lib.elementsExists = function () {
	var result = true;
	for(var i=0; i< arguments.length; i++) {
		if(!document.getElementById(arguments[i])) result=false;
	}
	return result;
}

/* <documentation about="Lib.addStyleSheet" type="general function">
	<summary>Adds stylesheet to the document</summary>
	<namespace>Lib</namespace>
	<param type="string" descr="Relative path to the stylesheet for example '../css/stylesheet.css'">relPath</param>
</documentation> */
Lib.addStyleSheet = function (relPath) {
	if(document.getElementsByTagName("head"))
	{
		var head = document.getElementsByTagName("head")[0];
		var newStyle = document.createElement("link");
   		newStyle.setAttribute("type", "text/css");
		newStyle.setAttribute("rel", "stylesheet");
		newStyle.setAttribute("href", relPath);
		head.appendChild(newStyle);
	}
}

/* <documentation about="Lib.removeStyleSheet" type="general function">
	<summary>Removes (or disables) stylesheet in document</summary>
	<namespace>Lib</namespace>
	<param type="string" descr="File name of stylesheet for example 'stylesheet.css'">stylesheetFileName</param>
</documentation> */
Lib.removeStyleSheet = function (stylesheetFileName) {
	if(document.getElementsByTagName("head"))
	{
		var head = document.getElementsByTagName("head")[0];
		var linkElements = head.getElementsByTagName("link");

		for(var i=0; i<linkElements.length; i++) {

			var href = linkElements[i].getAttribute("href");
			if( href.indexOf(stylesheetFileName) != -1) {
				linkElements[i].disabled=true;
				head.removeChild(linkElements[i]);
			}
		}
	}
}

/* <documentation about="Lib.getElementsByClassName" type="general function">
	<summary>Used to find HTML elements with certain classname</summary>
	<namespace>Lib</namespace>
	<param type="string" descr="Classname you are looking for">searchClass</param>
	<param type="string" descr="An optional tag name to narrow the search to specific tags e.g. 'a' for links (optional, defaults to ‘*’).">tagName</param>
	<param type="string" descr="An optional object container to search inside. This narrows the scope of the search (optional, defaults to document).">elem</param>
	<returns>Array of HTML elements</returns>
</documentation> */
Lib.getElementsByClassName = function (searchClass, tagName, containerElement) {
	tagName = tagName || "*";
	containerElement = containerElement || document;

	var allElements = containerElement.getElementsByTagName(tagName);
	if (!allElements.length &&  tagName == "*" &&  containerElement.all) allElements = containerElement.all;

	var elementsFound = new Array();
	var delim = searchClass.indexOf("|") != -1  ? "|" : " ";

	var arrClass = searchClass.split(delim);
	for (var i = 0, j = allElements.length; i < j; i++) {
		var arrObjClass = allElements[i].className.split(" ");
		if (delim == " " && arrClass.length > arrObjClass.length) { continue; }
		var c = 0;
		comparisonLoop:
			for (var k = 0, l = arrObjClass.length; k < l; k++) {
				for (var m = 0, n = arrClass.length; m < n; m++) {
					if (arrClass[m] == arrObjClass[k]) c++;
					if (( delim == "|" && c == 1) || (delim == " " && c == arrClass.length)) {
						elementsFound.push(allElements[i]);
					break comparisonLoop;
				}
			}
		}
	}
	return elementsFound;
}

/* <documentation about="Lib.inputAutoClear" type="general function">
	<summary>Resets default value in text field when text field is left empty</summary>
	<namespace>Lib</namespace>
</documentation> */
Lib.inputAutoClear = function () {
	var inputFields = Lib.getElementsByClassName("text", "input");
	for (var i=0; i<inputFields.length; i++) {
		// Add a onfocus to every text input with class "text"
		// This will store the initial value for restoring it when the box stays empty when losing focus
		inputFields[i].onfocus = function() {  if (this.getAttribute("default") && this.getAttribute("default")== this.value) { this.value = "";  }};
		Lib.eventCache.add(inputFields[i], "onfocus", function() {  if (this.getAttribute("default") && this.getAttribute("default")== this.value) { this.value = "";  }}, false);

		// Add a onblur to every text input with class "text"
		// This will restore the initial value if no value is inserted
		inputFields[i].onblur = function() { if (this.value.length==0 && this.getAttribute("default")) { this.value = this.getAttribute("default")} };
		Lib.eventCache.add(inputFields[i], "onblur", function() { if (this.value.length==0 && this.getAttribute("default")) { this.value = this.getAttribute("default")} }, false);
	}
}

/* <documentation about="Lib.setCookie" type="general function">
	<summary>Sets cookie</summary>
	<namespace>Lib</namespace>
	<param type="string" descr="Name of cookie">name</param>&yuml;
	<param type="string" descr="Value of cookie">value</param>
</documentation> */
Lib.setCookie = function (name, value) {
	var argv = Lib.setCookie.arguments;
	var argc = Lib.setCookie.arguments.length;
	var expires = (argc > 2) ? argv[2] : null;
	var path = (argc > 3) ? argv[3] : null;
	var domain = (argc > 4) ? argv[4] : null;
	var secure = (argc > 5) ? argv[5] : false;
	document.cookie = name + "=" + escape (value) +
	((expires == null) ? "" : ("; expires=" + expires.toGMTString())) +
	((path == null) ? "" : ("; path=" + path)) +
	((domain == null) ? "" : ("; domain=" + domain)) +
	((secure == true) ? "; secure" : "");
}

/* <documentation about="Lib.getCookie" type="general function">
	<summary>Gets value of cookie</summary>
	<namespace>Lib</namespace>
	<param type="string" descr="Name of cookie">name</param>
	<returns>String with cookie value</returns>
</documentation> */
Lib.getCookie = function (name) {
	var start = document.cookie.indexOf(name+"=");
	var len = start+name.length+1;
	if ((!start) && (name != document.cookie.substring(0,name.length))) { return  null; }
	if (start == -1){ return null; }

	var end = document.cookie.indexOf(";",len);

	if (end == -1) { end = document.cookie.length; }
	return unescape(document.cookie.substring(len,end));
}

/* <documentation about="Lib.setPageIsStyled" type="general function">
	<summary>Sets variable Lib.pageIsStyled to true when HTML element 'utilities' is more than 100 px from the left. If the page is not styled, the stylesheet javascript.css is removed </summary>
	<namespace>Lib</namespace>
</documentation> */
Lib.setPageIsStyled = function () {
	if(Lib.elementsExists("utilities")) { if(parseInt(document.getElementById("utilities").offsetLeft) >100) { Lib.pageIsStyled = true; }	 }
	if(!Lib.pageIsStyled) { Lib.removeStyleSheet ("javascript.css"); }
}

/* <documentation about="Lib.getNextElement" type="general function">
	<summary>Gets next element in DOM tree; while ignoring text nodes</summary>
	<namespace>Lib</namespace>
	<param type="object" descr="HTML element">elem</param>
	<returns>HTML element</returns>
</documentation> */
Lib.getNextElement = function ( elem ) {
    do { elem = elem.nextSibling; }
	while ( elem && elem.nodeType != 1 );
    return elem;
}

/* <documentation about="Lib.getWindowWidth" type="general function">
	<summary>Gets innerwidth of browser window</summary>
	<namespace>Lib</namespace>
	<returns>Inner window width in pixels (integer)</returns>
</documentation> */
Lib.getWindowWidth = function () {
	var myWidth = 0;
	if( typeof( window.innerWidth ) == 'number' ) {
		//Non-IE
		myWidth = window.innerWidth;
	} else if( document.documentElement &&  document.documentElement.clientWidth  ) {
		//IE 6+ in 'standards compliant mode'
		myWidth = document.documentElement.clientWidth;
	} else if( document.body && document.body.clientWidth) {
		//IE 4 compatible
		myWidth = document.body.clientWidth;
	}
	return myWidth;
}

/* <documentation about="Lib.getWindowHeight" type="general function">
	<summary>Gets innerheight of browser window</summary>
	<namespace>Lib</namespace>
	<returns>Inner window height in pixels (integer)</returns>
</documentation> */
Lib.getWindowHeight = function () {
	var myHeight = 0;
	if( typeof( window.innerHeight ) == 'number' ) {
		//Non-IE
		myHeight = window.innerHeight;
	} else if( document.documentElement &&  document.documentElement.clientHeight  ) {
		//IE 6+ in 'standards compliant mode'
		myHeight = document.documentElement.clientHeight;
	} else if( document.body && document.body.clientHeight) {
		//IE 4 compatible
		myHeight = document.body.clientHeight;
	}
	return myHeight;
}

/* <documentation about="Lib.getScrollY" type="general function">
	<summary>Get scrolling distance from the top of the window in pixels</summary>
	<namespace>Lib</namespace>
	<returns>Scrolling distance in pixels (integer)</returns>
</documentation> */
Lib.getScrollY = function () {
  var scrOfY = 0;
  if( typeof( window.pageYOffset ) == 'number' ) {
    //Netscape compliant
    scrOfY = window.pageYOffset;
  } else if( document.body && ( document.body.scrollLeft || document.body.scrollTop ) ) {
    //DOM compliant
    scrOfY = document.body.scrollTop;
  } else if( document.documentElement && ( document.documentElement.scrollLeft || document.documentElement.scrollTop ) ) {
    //IE6 standards compliant mode
    scrOfY = document.documentElement.scrollTop;
  }
  return scrOfY;
}
/* ========== END GENERAL FUNCTIONS ========================================================= */

/* ========== START SPECIFIC FUNCTIONS ========================================================= */
/* <documentation about="Lib.addMainNavigationFoldOut" type="specific function">
	<summary>This function adds folding out of main navigation to the page; called on init</summary>
	<namespace>Lib</namespace>
</documentation> */
Lib.addMainNavigationFoldOut = function () {
	if(!Lib.pageIsStyled || !Lib.elementsExists("mainNavigation") ) {  return;  } //stop if page is not styled

	var mainNavigationDiv = document.getElementById("mainNavigation");
	var mainUL = mainNavigationDiv.getElementsByTagName("ul")[0];
	mainUL.className="closed"; //add style closed

	//add mouseover behaviour
	mainNavigationDiv.onmouseover = function() { clearTimeout(Lib.setTimeOut); Lib.toggleMainNavigation("open"); } ;
	Lib.eventCache.add(mainNavigationDiv, "onmouseover", function() { clearTimeout(Lib.setTimeOut);  Lib.toggleMainNavigation("open"); } );

	//add mouseout behaviour
	mainNavigationDiv.onmouseout = function() { Lib.setTimeOut = setTimeout('Lib.toggleMainNavigation("close");', 500);  } ;
	Lib.eventCache.add(mainNavigationDiv, "onmouseout", function() { Lib.setTimeOut = setTimeout('Lib.toggleMainNavigation("close");', 500); } );
}

/* <documentation about="Lib.toggleMainNavigation" type="specific function">
	<summary>Shows or hides sub navigation in main naviagtion, depending on status - Used by Lib.addMainNavigationFoldOut</summary>
	<namespace>Lib</namespace>
	<param type="string" descr="'open' is show sub navigation, 'close' is hide navigation">status</param>
</documentation> */
Lib.toggleMainNavigation = function (status) {
	try {
		var main = document.getElementById("main");
		var mainNavigationDiv = document.getElementById("mainNavigation");
		var mainUL = mainNavigationDiv.getElementsByTagName("ul")[0];
		var subULs= mainUL.getElementsByTagName("ul");

		if(status=="open" && mainNavigationDiv.className != "absolute") {
			//because the main navigation position will be set to absolute, margin of "main" must be maintained
			Lib.mainTopPadding = mainNavigationDiv.offsetHeight;
			main.style.paddingTop = Lib.mainTopPadding + "px";

			mainNavigationDiv.className = "absolute";
			mainUL.className="";

			for(var i=0; i<subULs.length; i++) { subULs[i].className = "";}

			//if ie6, use iframe (avoids dropdown showing thogh navigation layer)
			if(Lib.ie6) { Lib.adjustIFrame(mainNavigationDiv, "on"); }
		}
		else if (status=="close") {
			mainNavigationDiv.className = "";
			main.style.paddingTop = "0px";
			mainUL.className="closed";

			for(var i=0; i<subULs.length; i++) { subULs[i].className = "hide";}

			//if ie6 hide iframe
			if(Lib.ie6) { Lib.adjustIFrame(mainNavigationDiv, "off"); }
		}
	}
	catch (ex){ Lib.errHandler(ex); }
}

/* <documentation about="Lib.adjustIFrame" type="specific function">
	<summary>Adds and adjust iframe for display behind main navigation - Used by Lib.toggleMainNavigation</summary>
	<namespace>Lib</namespace>
	<param type="HTML elemnt" descr="Main navigation layer">mainNavigationDiv</param>
	<param type="string" descr="If status = 'on' iframe is displayed, otherwise iframe is hidden">status</param>
</documentation> */
Lib.adjustIFrame = function (mainNavigationDiv, status) {
	if(status=="on") {
		if(!Lib.iframe) {
			Lib.iframe = document.createElement("iframe");
			Lib.iframe.id = "iFrameMainNav";
			mainNavigationDiv.parentNode.insertBefore(Lib.iframe, mainNavigationDiv);
		}
		Lib.iframe.style.height=mainNavigationDiv.offsetHeight;
		Lib.iframe.style.display="block";
	}
	else { document.getElementById("iFrameMainNav").style.display="none";  }
}

/* <documentation about="Lib.addResizingLinks" type="specific function">
	<summary>Adds increase/decrease font size links</summary>
	<namespace>Lib</namespace>
</documentation> */
Lib.addResizingLinks = function() {
	if(!Lib.pageIsStyled) {  return;  } //stop if page is not styled

	try {
		var h1 = document.getElementsByTagName("h1")[0];
		h1.className = "";

		//get first div for insert
		var firstDiv = Lib.getNextElement(h1); //div languages

		//make new div with id fontSize;
		var divFontSize = document.createElement("div");
		divFontSize.id = "fontSize";

		//add text
		var strong = document.createElement("strong");
		strong.innerHTML = "Tekstgrootte";
		divFontSize.appendChild(strong);

		var ul = document.createElement("ul");

		var firstLi = document.createElement("li");
		firstLi.id = "largerFont";
		var largerLink = document.createElement("a");
		largerLink.href="#";
		largerLink.id="largerLink";
		largerLink.innerHTML = "Groter";
		firstLi.appendChild(largerLink);
		ul.appendChild(firstLi);

		var secondeLi = document.createElement("li");
		secondeLi.id = "smallerFont";
		var smallerLink = document.createElement("a");
		smallerLink.href="#";
		smallerLink.id="smallerLink";
		smallerLink.innerHTML = "Kleiner";
		secondeLi.appendChild(smallerLink);
		ul.appendChild(secondeLi);

		largerLink.onclick = function() { changeFontSize("larger"); return false; };
		Lib.eventCache.add(largerLink, "onclick", function() { changeFontSize("larger"); return false; }, false );

		smallerLink.onclick = function() { changeFontSize("smaller"); return false; };
		Lib.eventCache.add(smallerLink, "onclick", function() { changeFontSize("smaller"); return false; }, false );

		if(Lib.getCookie("fontsize")) {
			if(Lib.getCookie("fontsize") == "scalingLargest") { largerLink.className = "disabled"; 	}
			if(Lib.getCookie("fontsize") == "scalingNormal") { smallerLink.className = "disabled"; 	}
		}
		else { smallerLink.className = "disabled"; }

		divFontSize.appendChild(ul);

		//add div id = fontSize
		h1.parentNode.insertBefore(divFontSize,  firstDiv);

		/* <documentation about="Lib.setFontSize" type="private function in Lib.addResizingLinks">
			<summary>Set font-size and updates font size links (enabled/disabled) according to status</summary>
			<namespace>Lib</namespace>
		</documentation> */
		var changeFontSize = function (status) {
			//get cookie value
			var cookieValue = "";
			if(Lib.getCookie("fontsize")) {
				cookieValue = Lib.getCookie("fontsize");
			}

			//reset links
			var largerLink = document.getElementById("largerLink")
			largerLink.className = "";

			var smallerLink = document.getElementById("smallerLink")
			smallerLink.className = "";

			if(status=="larger") {
				if(cookieValue.length == 0) { Lib.setFontSize("scalingLarge", true); }
				else if (cookieValue == "scalingNormal") { Lib.setFontSize("scalingLarge", true); }
				else if (cookieValue == "scalingLarge") {  largerLink.className = "disabled"; Lib.setFontSize("scalingLargest", true); }
				else if (cookieValue == "scalingLargest") { largerLink.className = "disabled"; }
			}
			else if(status=="smaller") {
				if (cookieValue == "scalingLargest") {  Lib.setFontSize("scalingLarge", true); }
				else if (cookieValue == "scalingLarge") {  smallerLink.className = "disabled"; Lib.setFontSize("scalingNormal", true); }
				else if (cookieValue == "scalingNormal") { smallerLink.className = "disabled"; }
			}
		};

	} catch (ex){ Lib.errHandler(ex); }
}

/* <documentation about="Lib.setFontSize" type="specific function">
	<summary>Sets font size by adding and removing stylesheets</summary>
	<namespace>Lib</namespace>
</documentation> */
Lib.setFontSize = function (status, removeStyleSheets) {
	if(removeStyleSheets) {
		//reset
		Lib.removeStyleSheet ("normal-font.css");
		Lib.removeStyleSheet ("large-font.css");
		Lib.removeStyleSheet ("largest-font.css");
	}

	if(status=="scalingNormal") { Lib.addStyleSheet("./styles/normal-font.css");  }
	else if(status=="scalingLarge") { Lib.addStyleSheet("./styles/large-font.css"); }
	else if(status=="scalingLargest") { Lib.addStyleSheet("./styles/largest-font.css"); }

	Lib.setCookie("fontsize", status)
}

/* <documentation about="Lib.addDefaultTextAttribute" type="specific function">
	<summary>Adds attribute "default" to text form elements</summary>
	<namespace>Lib</namespace>
	<param type="array of strings" descr="Id's of HTML elements">[array]</param>
</documentation> */
Lib.addDefaultTextAttribute = function () {
	for(var i=0; i< arguments.length; i++) {
		if(document.getElementById(arguments[i])) {
			var field = document.getElementById(arguments[i]);
			field.setAttribute("default", field.value);
		}
	}
}
/* ========== END SPECIFIC FUNCTIONS ========================================================= */

/* <documentation about="Add eventhandler Lib.eventCache.flush on window unload" type="FUNCTION CALL">
	<summary>Calling Lib.addEvent: Add Lib.eventCache.flush as eventhandler on window onunload: Detach all attached events (solves memory leak in ie)</summary>
</documentation> */
Lib.addEvent(window, "unload", Lib.eventCache.flush);
