/**
 * pantatype.js
 * Collection of commonly used functions
 * 
 * @author Alex van Niel - Pantamedia
 * @version 1.8.2 2008091501
 * @copyright ©2008 Pantamedia BV
 * @see prototype.js
 * 
 */

// If bind() is allready present (prototype library loaded)
// then don't create this function
if( typeof(Function.bind) == 'undefined' ){
/**
 * This function was inspired by Prototype.js
 * (c) 2005-2008 Sam Stephenson
 *
 * bind()
 * This function binds an object to a specific function
 * it however does not handle arguments passed to the function
 * the object is bound to. This on contrary to Prototype version
 * of bind() 
 * 
 * @param {} 
 */
	Function.prototype.bind = function() {
	  var __method = this;
	  var args= new Array();
	  for (var i=0; i < arguments.length; i++ ) {
	  	args.push(arguments[i]);
	  }
	  var object = args.shift();
	  return function() {
	    return __method.apply(object, arguments);
	  }
	}
}

if (!Array.prototype.indexOf){
  Array.prototype.indexOf = function(elt /*, from*/){
    var len = this.length;

    var from = Number(arguments[1]) || 0;
    from = (from < 0)
         ? Math.ceil(from)
         : Math.floor(from);
    if (from < 0)
      from += len;

    for (; from < len; from++){
      if (from in this &&
          this[from] === elt)
        return from;
    }
    return -1;
  };
}

/**
 * roundNumber()
 * Attempt at reliably rounding decimals
 * @param {Float}	p_fNumber	Float to be rounded
 * @param {Integer}	p_nLength	Integer indicating how many decimals in the result is needed 
 */
function roundNumber(p_fNumber,p_nLength){
	//make sure the arguments hold numbers, if not then 0
	if(isNaN(p_fNumber)) return 0;

	var nDefaultLength = 10;
	var nMinusOperator = (p_fNumber < 0 ? -1 : 1); //detect if number is negative
	var fNumber = Math.abs(p_fNumber); //convert number to positive if needed
	var nLength = (!isNaN(p_nLength) ? p_nLength : 0);

	//if desired length is smaller then the default length, calculate the difference, otherwise use default
	var nDiffLength = ( (nLength < nDefaultLength) ? nDefaultLength - nLength : nDefaultLength ) + 1;

	//do roundNumber nDiffLength times
	for(var nIndex = 0; nIndex < nDiffLength; nIndex++){
		//round fNumber to (defaultlength - current cycle) and store result in itself

		//fix a bug in javascript rounding characters between 8192 and 10484
		if( (fNumber > 8191)  && (fNumber < 10485) ){
			fNumber = fNumber - 5000;
			var fNumber = Math.round(fNumber * Math.pow(10,nDefaultLength - nIndex))/Math.pow(10,nDefaultLength - nIndex);
			fNumber = fNumber + 5000;
		} else {
			var fNumber = Math.round(fNumber * Math.pow(10,nDefaultLength - nIndex))/Math.pow(10,nDefaultLength - nIndex);
		}

	}

	//restore abs state of number
	fNumber *= nMinusOperator;
	
	return fNumber;
}

function formatPrijs(p_fBedrag,p_sNewSplit){
	var fBedrag = ( !isNaN(parseFloat(p_fBedrag)) ? parseFloat(p_fBedrag) : 0.00 );
	var sMinus = ( fBedrag < 0 ? '-' : '');
	var sResult = new String();
	var sNewSplit = new String();

	fBedrag = roundNumber(fBedrag,2);

	if(p_sNewSplit){
		sNewSplit = p_sNewSplit;
	} else {
		sNewSplit = ",";
	}

	fBedrag = Math.abs(fBedrag);
	fBedrag = parseInt((fBedrag + .005) * 100);
	fBedrag = fBedrag / 100;
	sResult = new String(fBedrag);
	if(sResult.indexOf(".") < 0){
		sResult += ".00";
	}
	if(sResult.indexOf(".") == (sResult.length - 2)){
		sResult += "0";
	}
	sResult = sMinus + sResult;
	sResult = sResult.replace(/\./gi,sNewSplit);

	return sResult;
}

/**
 * AJAX functions below
 */
function createXMLHttpRequest() {
	var oRequest = null;
	try {
		oRequest = new XMLHttpRequest();
	} catch (e) {
		try {
			oRequest = new ActiveXObject("Msxml2.XMLHTTP");
		} catch (e) {
			try {
				oRequest = new ActiveXObject("Msxml3.XMLHTTP");
			} catch (e) {
				try {
					oRequest = new ActiveXObject("MicroSoft.XMLHTTP");
				} catch (e) {
					oRequest = null;
					alert("Could not create XMLHttpRequest");
				}
			}
		}
	}
	return oRequest;
}

function sendXMLHttpRequest(p_sUrl,p_oCallBack,p_sPostData) {
	var oRequest = null;
	var sUrl = p_sUrl;
	var sMethod = (p_sPostData) ? "POST" : "GET" ;
	var sPostData = (typeof(p_sPostData) != 'undefined') ? p_sPostData : null;

	try {
		oRequest = createXMLHttpRequest();

		oRequest.open(sMethod, sUrl, true);

		oRequest.setRequestHeader('User-Agent','XMLHTTP/1.0');

		if( sPostData ){
			oRequest.setRequestHeader('Content-type','application/x-www-form-urlencoded');
		}

		oRequest.onreadystatechange = function () {
				var mxReadyState = oRequest.readyState;
				if( typeof(mxReadyState) == 'string' ) mxReadyState.toLowerCase();
				if( (mxReadyState != 4) && (mxReadyState != 'complete') ) return;

			    var nStatus = getXMLHttpRequestStatus(oRequest);
			    if( !nStatus || (nStatus >= 200 && nStatus < 300) ){
					p_oCallBack.callbackFunction(oRequest,p_oCallBack.callbackArguments);
				}
			}

		oRequest.send(sPostData);
	} catch(e) {
		alert("sendXMLHttpRequest - " + e.name + ", " + e.message);
		oRequest = null;
	}
	return oRequest;
}

function updateXMLHttpRequest(p_sUpdateTarget,p_sUrl,p_sPostData){
	var oUpdateFunction = function(p_oRequest){
		var oUpdateTarget = getDOMElementById(p_sUpdateTarget);
		oUpdateTarget.innerHTML = p_oRequest.responseText; 
	}

	oRequest = sendXMLHttpRequest(p_sUrl,{callbackFunction: oUpdateFunction, callbackArguments: null},p_sPostData);
}

function getXMLHttpRequestStatus( oXMLHttpRequest ){
	try {
		return oXMLHttpRequest.status || 0;
	} catch (e) { return 0 }
}

/**
 * DOM Functions below
 */

/** 
 * 
 * getDOMElementById()
 * Returns an object by it's ID or false if the object was not found
 * 
 * @param {Object} p_oId String or Object pointing to the target element
 * @param {Object} p_oDocument node containing the getElementById function, if none specified, document (root) will be used
 * @return {mixed} Element or false
 */
function getDOMElementById(p_oId,p_oDocument){
	var mixResult = false;
	var oDocument = document;
	
	if( (typeof(p_oDocument) != 'undefined') ){
		oDocument = p_oDocument;
	}
	
	if( oDocument && oDocument.getElementById ){
		switch( typeof(p_oId) ){
		case 'string':
			mixResult = oDocument.getElementById(p_oId);
			break;
		case 'object':
			mixResult = p_oId;
			break;
		default:
			break
		}
	}
	
	return mixResult;
}

function getFormElementByType(p_sFormId,p_sTypeName,p_oDocument){
	var mixResult = false;
	var oDocument = document;
	var oForm = null;
	var nFormCount = 0;
	var aElements = new Array();
	
	if( (typeof(p_oDocument) != 'undefined') ){
		oDocument = p_oDocument;
	}
	
	if( oDocument && oDocument.getElementById ){
		oForm = oDocument.getElementById(p_sFormId);
		nFormCount = oForm.elements.length;
		if( oForm ){
			for(var nIndex = 0; nIndex < nFormCount; nIndex++){
				if( p_sTypeName == oForm.elements[nIndex].type ) aElements.push(oForm.elements[nIndex]);
			}

			if( aElements.length ) mixResult = aElements;
		}
	}
	
	return mixResult;
}

function doNothing(){
	//do nothing
}
/**
 * doFormSubmit()
 * Submits form data and jumps to a specified URL after a successfull submit
 * 
 * @param {String} p_sFormId		String holding the id of the form
 * @param {String} p_sUrl			String with URL used to jump to after a successfull submit
 * @param {Object} p_oValueCheck	Function used to check the values in the form
 */
function doFormSubmit(p_sFormId, p_sUrl, p_oValueCheck){
	var oElement = getDOMElementById(p_sFormId);

	if (p_oValueCheck() && oElement) {
		oElement.request({
			onSuccess: function(){
				window.location = p_sUrl;
			}
		});
	}
}

function isArray(p_oObject) {
	var bResult = false;

	if( p_oObject && (typeof(p_oObject) == 'object') ){
		bResult = ( (typeof(p_oObject.splice) != 'undefined') && (typeof(p_oObject.join) != 'undefined') );
	}
	
	return bResult;
}

function inArray(p_aHaystack,p_varNeedle){
	var bFound = false;

	for(var nIndex = 0, nLength = p_aHaystack.length; (nIndex<nLength) && !bFound; nIndex++){
		if(p_aHaystack[nIndex] === p_varNeedle){
			bFound = true;
		}
	}
	
	return bFound;
}

function launchPopupWindow(p_sTitle,p_sWindowOptions,p_sUrl){
	var bResult = false;

	try{
		var oWindow = window.open(p_sUrl,p_sTitle,p_sWindowOptions);
		if(oWindow == null){
			alert('Er kon geen venster geopend worden.<br>');
		} else {
			bResult = true;
		}
	} catch(e) {
		alert('Er deed zich een onbekende fout voor.<br>');
		//e.message error
	}
	
	return bResult;
}

function setCookie( name, value, expires, path, domain, secure ) {
	// set time, it's in milliseconds
	var today = new Date();
	today.setTime( today.getTime() );
	
	// if the expires variable is set, make the correct 
	// expires time, the current script below will set 
	// it for x number of days, to make it for hours, 
	// delete * 24, for minutes, delete * 60 * 24
	if ( expires ) {
		expires = expires * 1000 * 60 * 60 * 24;
	}

	var expires_date = new Date( today.getTime() + (expires) );
	
	document.cookie = name + "=" +escape( value ) +
		( ( expires ) ? ";expires=" + expires_date.toGMTString() : "" ) + 
		( ( path ) ? ";path=" + path : "" ) + 
		( ( domain ) ? ";domain=" + domain : "" ) +
		( ( secure ) ? ";secure" : "" );
}

function getCookie( check_name ) {
	// first we'll split this cookie up into name/value pairs
	// note: document.cookie only returns name=value, not the other components
	var a_all_cookies = document.cookie.split( ';' );
	var a_temp_cookie = '';
	var cookie_name = '';
	var cookie_value = '';
	var b_cookie_found = false; // set boolean t/f default f
	
	for ( i = 0; i < a_all_cookies.length; i++ )
	{
		// now we'll split apart each name=value pair
		a_temp_cookie = a_all_cookies[i].split( '=' );
		
		
		// and trim left/right whitespace while we're at it
		cookie_name = a_temp_cookie[0].replace(/^\s+|\s+$/g, '');
	
		// if the extracted name matches passed check_name
		if ( cookie_name == check_name )
		{
			b_cookie_found = true;
			// we need to handle case where cookie has no value but exists (no = sign, that is):
			if ( a_temp_cookie.length > 1 )
			{
				cookie_value = unescape( a_temp_cookie[1].replace(/^\s+|\s+$/g, '') );
			}
			// note that in cases where cookie is initialized but no value, null is returned
			return cookie_value;
			break;
		}
		a_temp_cookie = null;
		cookie_name = '';
	}
	if ( !b_cookie_found )
	{
		return null;
	}
}

function deleteCookie( name, path, domain ) {
	if ( getCookie( name ) ) document.cookie = name + "=" +
		( ( path ) ? ";path=" + path : "") +
		( ( domain ) ? ";domain=" + domain : "" ) +
		";expires=Thu, 01-Jan-1970 00:00:01 GMT";
}

//this function can be used to add events to for instance the window
//using 'load' as eventname and window as the object
function addEvent(p_oObject, p_sEventName, p_oFunction){ 
	var mixResult = false;

	if( p_oObject.addEventListener ){ 
		p_oObject.addEventListener(p_sEventName, p_oFunction, false); 
		mixResult = true; 
	} else if( p_oObject.attachEvent ){ 
		mixResult = p_oObject.attachEvent("on"+p_sEventName, p_oFunction); 
	}

	return mixResult;
}

function selectJump(p_oTarget,p_oSource,p_bReset){
	var oTarget = getDOMElementById(p_oTarget);
	var oSource = getDOMElementById(p_oSource);

	if(oSource && oTarget && oTarget.location){
		oTarget.location.href = oSource.value; //eval(p_sTarget+".location='"+oSource.value+"'");
		if (p_bReset) oSource.selectedIndex = 0;
	}
}

function confirmJump(p_sQuestion,p_sHyperlink){
	if(confirm(p_sQuestion)){
		location.href = p_sHyperlink;
	}
}

function changeNodeClass(p_oNode,p_sId){
	var oNode = null;

	if( p_oNode) oNode = getDOMElementById(p_oNode);
	if(oNode && p_sId.length) oNode.className = p_sId;

	return oNode;
}

function toggleDisplay(p_oNode,p_sDisplay){
	var oNode = null;

	if( (p_sDisplay == undefined) || !p_sDisplay.length ) p_sDisplay = "inline";
	if( p_oNode ) oNode = getDOMElementById(p_oNode);
	if( oNode && oNode.style ){
		var sDisplay = oNode.style.display;
		oNode.style.display = (sDisplay != "none") ? "none" : p_sDisplay;
	}
	
	return oNode;
}

function toggleVisibility(p_oNode,p_sVisibility){
	var oNode = null;

	if( (p_sVisibility == undefined) || !p_sVisibility.length ) p_sVisibility = "visible";
	if( p_oNode ) oNode = getDOMElementById(p_oNode);
	if( oNode && oNode.style ){
		var sVisibility = oNode.style.visibility;
		oNode.style.visibility = (sVisibility != "hidden") ? "hidden" : p_sVisibility;
	}
	
	return oNode;
}

function setVisibility(p_oNode,p_sVisibility){
	var oNode = null;

	if( (p_sVisibility == undefined) || !p_sVisibility.length ) p_sVisibility = "visible";
	if( p_oNode ) oNode = getDOMElementById(p_oNode);
	if( oNode && oNode.style ) oNode.style.visibility = p_sVisibility;
	
	return oNode;
}

function autoResizeFrame(p_oFrameElement,p_nDefaultHeight) {
	var nNewHeight = (!isNaN(p_nDefaultHeight)?p_nDefaultHeight:0) + 'px';
	var nOffset = 0;
	var oFrameElement = null;

	if(p_oFrameElement){
		if(typeof(p_oFrameElement) == 'object'){
			oFrameElement = p_oFrameElement;
		} else if(parent && parent.document && parent.document.getElementById){
			oFrameElement = parent.document.getElementById(p_oFrameElement);
		} else if(parent && parent.document && parent.document.all){
			oFrameElement = parent.document.all[p_oFrameElement];
		}
	}

	if(oFrameElement){
		oFrameElement.style.display = "block";
		
		if(document && document.body && document.body.offsetHeight){
			nNewHeight = document.body.offsetHeight;
		}

		oFrameElement.style.height = (nNewHeight+nOffset)+'px';
	}
}

function changeFrameContents(p_sTarget,p_sSource,p_nWidth,p_nHeight){
	var oFrame = getDOMElementById(p_sTarget);
	var oSource = getDOMElementById(p_sSource);
	var sUrl = '';

	if( ((oSource === null) || (oSource === undefined)) && p_sSource.length){
		//p_sSource is not a known element, so must be an url string
		sUrl = p_sSource;
	} else if(oSource && (oSource.value !== undefined) ){
		//p_sSource was found, using the node pointer
		sUrl = oSource.value;
	}

	if( oFrame && (oFrame.src !== undefined ) ){
		if(!isNaN(p_nWidth)){
			oFrame.width = p_nWidth;
			oFrame.style.width = p_nWidth + 'px';
		}
		if(!isNaN(p_nHeight)){
			oFrame.height = p_nHeight
			oFrame.style.height = p_nHeight + 'px';
		}
		if(sUrl.length) oFrame.src = sUrl;
	}
}

/**
 * addDOMElement()
 * @version 1.1
 * @author Alex van Niel - Pantamedia
 * @param {Object} p_oArguments	This object consists of several members that make up the arguments for creating a DOM element
 * 
 * These arguments are:
 * @param {String} type			defining what kind of DOM element needs to be created
 * @param {Object} document		used to create the new DOM element, defaults to the document of the current window
 * @param {Object} parent		defines the object to which the newly created DOM element needs to be appended
 * @param {Object} attributes	should contain a list of attributes that need to be assigned to the new DOM element
 * @param {String} text			if param type is 'text', this parameter should contain the text to be added as a textNode
 * 
 */
function addDOMElement(p_oArguments){
	var oNewElement = null;
	//see if the new element needs to be created in document or somewhere else
	var oDocument = ( (typeof(p_oArguments.document) != 'undefined') && p_oArguments.document?p_oArguments.document:document);

	if(p_oArguments.type){
		switch(p_oArguments.type){
			case 'text' :
				if( typeof(p_oArguments.text) != 'undefined' ) oNewElement = oDocument.createTextNode(p_oArguments.text);
				break;
			default :
				oNewElement = oDocument.createElement(p_oArguments.type);
				break;
		}
	} 
	
	if( oNewElement && p_oArguments.attributes && (typeof(p_oArguments.attributes) == 'object') ){
		for(sKey in p_oArguments.attributes){
			switch(sKey){
				case 'style' :
					//oNewElement.setAttribute("style",p_oArguments.attributes[sKey]);
					oNewElement.style.cssText = p_oArguments.attributes[sKey];
					break;
				case 'onmousedown' :
					oNewElement.onmousedown = p_oArguments.attributes[sKey];
					break;
				case 'onmouseenter' :
					oNewElement.onmouseenter = p_oArguments.attributes[sKey];
					break;
				case 'onmouseover' :
					oNewElement.onmouseover = p_oArguments.attributes[sKey];
					break;
				case 'onmouseup'	:
					oNewElement.onmouseup = p_oArguments.attributes[sKey];
					break;
				case 'onmousemove'	:
					oNewElement.onmousemove = p_oArguments.attributes[sKey];
					break;
				case 'onmouseout'	:
					oNewElement.onmouseout = p_oArguments.attributes[sKey];
					break;
				case 'onclick'	:
					oNewElement.onclick = p_oArguments.attributes[sKey];
					break;
				case 'ondblclick'	:
					oNewElement.ondblclick = p_oArguments.attributes[sKey];
					break;
				case 'onfocus'	:
					oNewElement.onfocus = p_oArguments.attributes[sKey];
					break;
				case 'onblur'	:
					oNewElement.onblur = p_oArguments.attributes[sKey];
					break;
				case 'onkeypress'	:
					oNewElement.onkeypress = p_oArguments.attributes[sKey];
					break;
				case 'onkeydown'	:
					oNewElement.onkeydown = p_oArguments.attributes[sKey];
					break;
				case 'onkeyup'	:
					oNewElement.onkeyup = p_oArguments.attributes[sKey];
					break;
				case 'onsubmit'	:
					oNewElement.onsubmit = p_oArguments.attributes[sKey];
					break;
				case 'onselect'	:
					oNewElement.onselect = p_oArguments.attributes[sKey];
					break;
				case 'onchange'	:
					oNewElement.onchange = p_oArguments.attributes[sKey];
					break;
				case 'checked' :
					oNewElement.checked = p_oArguments.attributes[sKey];
					break;
				case 'className' :
					oNewElement.className = p_oArguments.attributes[sKey];
				default :
					oNewElement.setAttribute(sKey,p_oArguments.attributes[sKey]);
			}
		}
	}

	if(oNewElement && p_oArguments.parent && p_oArguments.parent.appendChild ) p_oArguments.parent.appendChild(oNewElement);

	return oNewElement;
}

function clearNode(p_oNode){
	var bResult = false;
	var oNode = getDOMElementById(p_oNode);

	//try to execute code
	try {
		//check if node is not null
		if(oNode){
			//loop while there are children to delete
			while(oNode.hasChildNodes()){
				//delete the last child
				oNode.removeChild(oNode.lastChild);
			}
			bResult = true;
		}
	} catch(e) {
		bResult = false;
	}

	return bResult;
}

function putStringInNode(p_sIdName,p_sString){
	var oNode = null;
	var sText = '';

	if(p_sIdName && (oNode = getDOMElementById(p_sIdName)) && p_sString){
		clearNode(oNode);
		sText = new String(p_sString);
		oNode.appendChild(document.createTextNode(sText))
	}
}

function getStringFromNode(p_sIdName){
	var oNode = null;
	var oChildNode = null;
	var sText = new String();
	var bResult = false;

	if( p_sIdName && (oNode = getDOMElementById(p_sIdName)) && oNode.hasChildNodes()){
		oChildNode = oNode.firstChild;

		while(oChildNode && !bResult){
			//is the node a TextNode?
			if(oChildNode.nodeType == 3){
				sText = new String(oChildNode.nodeValue);
				bResult = true;
			}
			oChildNode = oChildNode.nextSibling;
		}
	}
	
	return sText;
}

/* this function requires prototype library for $(), getInputs() and $F() */
function getRadioValue(p_oElement, p_sRadioGroup){
	var oElement = $(p_oElement);
	var bResult = false;

	if(p_oElement){
		if(oElement.type && (oElement.type.toLowerCase() == 'radio') ){
			var p_sRadioGroup = oElement.name;
			var oElement = oElement.form;
		} else if (oElement.tagName.toLowerCase() != 'form') {
			//nothing, bResult == false
		}
		bResult = $(oElement).getInputs('radio', p_sRadioGroup).find(function(p_oRadioElement){return p_oRadioElement.checked;});
	}

	return (bResult) ? $F(bResult) : null;
}

function setCheckBox(p_sIdName,p_bEnable,p_bUnCheck){
	var oNode = null;

	if(p_sIdName && (oNode = getDOMElementById(p_sIdName)) ){
		if( typeof(p_bUnCheck) != 'undefined'){
			oNode.checked = p_bUnCheck;
		}

		if(p_bEnable){
			if(oNode.getAttribute("disabled")){
				oNode.removeAttribute("disabled");
			}
		} else {
			if( typeof(p_bUnCheck) == 'undefined'){
				oNode.checked = 0;
			}
			oNode.setAttribute("disabled","true");
		}
	}
}

function toggleCheckBox(p_sIdName){
	var oNode =null;

	if(p_sIdName && (oNode = getDOMElementById(p_sIdName)) ){
		if(oNode.getAttribute("disabled")){
			oNode.removeAttribute("disabled");
		} else {
			oNode.checked = 0;
			oNode.setAttribute("disabled","true");
		}
	}
}

function validateForm(p_aControls){
	var bResult = false;

	if( typeof(p_aControls) != 'undefined' && typeof(p_aControls.length) != 'undefined' && p_aControls.length ){
		var nControlCount = p_aControls.length;
		var oControl = null;

		for(var nIndex = 0; nIndex < nControlCount; nIndex++){
			oControl = document.getElementById(p_aControls[nIndex].idname);
			if( !oControl || (typeof(oControl.value) == 'undefined') ){
				//programmer error
				alert('unexpected error occured');
				return false;
			} else if( oControl.value == '' || oControl.value == '0' || oControl == 0 ){
				alert(p_aControls[nIndex].message);
				oControl.focus();
				return false;
			} else {
				bResult = true;
			}
		}
	}

	return bResult;
}

