/**
 * Een methode aan een onload event hangen.
 * vb: addEvent(window, 'load', startOnLoadFunction);
 *
 * @param el  Het element
 * @param ev  Naam van event (load, resize, enz...)
 * @param fn  Referentie naar aan te roepen functie.
 */
function addEvent(el, ev, fn) {

	if (!el) {
		return;
	}
	// IE
	if (window.attachEvent) {
		el.attachEvent('on' + ev, fn);
	}
	else if (el.addEventListener) {
		el.addEventListener(ev, fn, false);
	}
}


/**
 * Preload gegeven afbeelding.
 *
 * @param pImgObj  Image Object
 * @param pImgSrc  Locatie van de afbeelding
 */
function preloadImage(pImgObj, pImgSrc) {
	if (document.images) {
		eval(pImgObj + ' = new Image()');
		eval(pImgObj + ".src = '" + pImgSrc + "'");
	}
}


/**
 * Een array van foto's inladen in de cache
 *
 * vars,  De image namen
 */
function preloadImages() {

	var lArguments;
	if (document.images) {
		if (!document.imageArray) {
			document.imageArray = new Array();
		}
		var j = document.imageArray.length;
		lArguments = preloadImages.arguments;
		for (var i = 0; i < lArguments.length; i++) {
			if (lArguments[i].indexOf("#") != 0) {
				document.imageArray[j] = new Image;
				document.imageArray[j].src = lArguments[i];
				j++;
			}
		}
	}
}


/**
 * Print emailadres mbv JavaScript zodat deze verborgen blijft

 * voor email spiders. (tbv SPAM)
 * @param pUser	  De naam van de gebruiker (het eerste deel voor de @)
 * @param pDomain	De domainnaam
 * @param pTopDomain Het laatste deel van de domeinnaam
 */
function printEmail(pUser, pDomain, pTopDomain) {
	var lAt = "@";
	var lDot = ".";
	document.write('<a href="mailto:' + pUser + lAt + pDomain + lDot + pTopDomain + '">');
	document.write(pUser + lAt + pDomain + lDot + pTopDomain);
	document.write('</a>');
}


/**
 * Een terug verwijzing afbeelden, alleen als er ook terug gebladerd kan worden.
 *
 * @param pDescription  Zichtbare titel van de link
 */
function displayGoBack(pDescription) {
	if (window.history) {
		if (window.history.length > 1) {
			document.write('<p style="margin-top:1.5em" class="backlink"><a href="Javascript:goBack()">' + pDescription + '</a></p>');
		}
	}
}


/**
 * Een terug verwijzing afbeelden, alleen als er ook terug gebladerd kan worden.
 *
 * @param pOffset	   Het aantal pagina's dat teruggesprongen moet worden in de history of het form-field.
 * @param pDescription  Zichtbare titel van de link.
 */
function displayGoBackN(pOffset, pDescription) {
	if (window.history && pOffset != null && pOffset != '') {
		var lOffset = 0;
		if (pOffset.value) {
			lOffset = parseInt(pOffset.value) + 1;
		} else {
			lOffset = parseInt(pOffset) + 1;
		}
		if (window.history.length > lOffset) {
			document.write('<p style="margin-top:1.5em" class="backlink"><a href="Javascript:goBackN(' + lOffset + ')">' + pDescription + '</a></p>');
		}
	}
}


/**
 * Ga direct een stap terug. In Mozilla is de history niet leesbaar (om veiligheidsredenen)
 */
function goBack() {
	if (window.history)
		window.history.go(-1);
	else
		window.back();
}

/**
 * Een of meerdere stappen terug in de geschiedenis.
 */
function goBackN(n) {
	if (window.history)
		window.history.go(n * -1);
	else
		history.go(n * -1);
}


function popup(url) {
	window.open(url, "_blank", "toolbar=no,location=no,menubar=no,scrollbars=yes,width=467,height=460,resizeable=yes,status=yes");
}

function pop(url, width, height) {
	window.open(url, "_blank", "toolbar=no,location=no,menubar=no,scrollbars=yes,width=" + width + ",height=" + height + ",resizeable=yes,status=yes");
}

function popPhoto(url) {
	var width = 886;
	var height = 690;
	window.open(url, "_blank", "toolbar=no,location=no,menubar=no,scrollbars=yes,width=" + width + ",height=" + height + ",resizeable=yes,status=yes");
}

function refresh() {
	parent.window.opener.location.reload();
}


/**
 * Threadsafe asynchronous XMLHTTPRequest code.
 * Source: http://www.xml.com/pub/a/2005/02/09/xml-http-request.html
 *
 * Voorkom syntax error in FireFox: http_request.overrideMimeType('text/html')
 *
 * @param pUrl	   Url to open
 * @param pCallback  Callback function
 * @param pPostData  Optioneel - Inhoud voor POST request, default wordt een GET request uitgevoerd
 */
function ajaxSend(pUrl, pCallback, pPostData) {

	// use a local variable to hold our request until the inner function is called...
	var ajaxRequest = null;

	function ajaxBindCallback() {
		if (ajaxRequest) {
			if (ajaxRequest.readyState == 4) {
				if (ajaxRequest.status == 200 || ajaxRequest.status == 304) {
					if (pCallback) {
						pCallback(ajaxRequest.responseText);
					} else {
						alert('no callback defined');
					}
				} else {
					alert("There was a problem retrieving the xml data:\n"
							+ ajaxRequest.status
							+ ":\t" + ajaxRequest.statusText
							+ "\n" + ajaxRequest.responseText);
				}
			}
		} else {
			// Er is een timeout opgetreden
			pCallback(false);
		}
	}

	// bind our callback then hit the server...
	if (window.XMLHttpRequest) {

		// ie7, moz et al
		ajaxRequest = new XMLHttpRequest();

		// Resultaat nooit parsen als XML
		if (ajaxRequest.overrideMimeType) {
			ajaxRequest.overrideMimeType('text/html;charset=UTF-8');
		}

		ajaxRequest.onreadystatechange = ajaxBindCallback;

		// Send the proper header information along with the request
		try {
			if (pPostData) {
				ajaxRequest.open("POST", pUrl, true);
				ajaxRequest.setRequestHeader("Content-type", "application/x-www-form-urlencoded");
				ajaxRequest.setRequestHeader("Content-length", pPostData.length);
				ajaxRequest.setRequestHeader("Connection", "close");
				ajaxRequest.send(pPostData);
			} else {
				ajaxRequest.open("GET", pUrl, true);
				ajaxRequest.send(null);
			}
		} catch(ex) {
			// Er is een onbekende error opgetreden (timeout?). De callback informeren
			ajaxRequest = false;
			ajaxBindCallback();
		}

	} else if (window.ActiveXObject) {

		// ie <= 6
		ajaxRequest = new ActiveXObject("Microsoft.XMLHTTP");
		if (ajaxRequest) {

			ajaxRequest.onreadystatechange = ajaxBindCallback;

			// Send the proper header information along with the request
			if (pPostData) {
				ajaxRequest.open("POST", pUrl, true);
				ajaxRequest.setRequestHeader("Content-type", "application/x-www-form-urlencoded");
				ajaxRequest.setRequestHeader("Content-length", pPostData.length);
				ajaxRequest.setRequestHeader("Connection", "close");
				ajaxRequest.send(pPostData);
			} else {
				ajaxRequest.open("GET", pUrl, true);
				ajaxRequest.send();
			}
		}
	}
}


function trim(str) {
	return str.replace(/^\s*|\s*$/g, "");
}


/**
 * Als op de huidige pagina een form aanwezig is, focus op het eerste veld zetten.
 */
function setFocusToFirstFormField() {

	if (document.getElementsByTagName) {
		var forms = document.getElementsByTagName("form");
		if (forms && forms.length > 0) {

			// Loop alle input/select fields van het formulier langs.
			var fields = forms[0];
			if (fields && fields.length > 0) {
				for (var i = 0; i < fields.length; i++) {

					if ((fields[i].type && fields[i].type != "hidden") &&
						!fields[i].disabled &&
						!fields[i].readOnly) {

						var lPos = findPos(fields[i]);
						if (lPos && lPos[1] < 500) {
							fields[i].focus();
						}
						break;
					}
				}
			}
		}
	}
}


/**
 * Bepaal positie van element in document
 * http://www.quirksmode.org/js/findpos.html
 */
function findPos(obj) {

	var curtop = 0;
	var curleft = 0;

	if (obj.offsetParent) {
		curleft = obj.offsetLeft;
		curtop = obj.offsetTop;
		while (obj = obj.offsetParent) {
			curleft += obj.offsetLeft;
			curtop += obj.offsetTop;
		}
	}
	return [curleft,curtop];
}


function flashErrorMessage() {
	$("#errorboxcontainer").css('visibility', 'visible');
	setTimeout('$("#errorboxcontainer").fadeOut(80).fadeIn(80).fadeOut(80).fadeIn(80).fadeOut(80).fadeIn(80);', 500);
}


/**
 * Functies overgenomen uit de tablesort javascript file,
 * functienamen niet wijzigen omdat tablesort deze naam verwacht.
 */
function setTableAlt() {
	$('table.alternate').each(function() {
		$('tr:visible:even', this).addClass('alt');
		$('tr:visible:odd', this).removeClass('alt');
	});
}

/**
 * Functies overgenomen uit de tablesort javascript file,
 * functienamen niet wijzigen omdat tablesort deze naam verwacht.
 */
function doEven(tr) {
	if (tr && tr.length > 0) {
		// Parent van de TR-elementen opzoeken en van daar uit strepen
		$('tr:visible:even', tr[0].parentNode).addClass('alt');
		$('tr:visible:odd', tr[0].parentNode).removeClass('alt');
	}
}
