/*Global functionalities and configuration*/
blnWioDebug = false; //Debugging messages in alert mode
blnCheckFields = true; //Check the validaty of the fields
intwioCheckFieldsFromScreen = 1; // to start checking form values as of a certain screen 
// AJAX Urls - relative to /<lang>/index.php
strURLCheckNewUser = "checknewuser.php"; //URL which takes email, first and lastname to see if the user is not already in the database
strURLConfirmation = "confirmationqueries.php"; // URL which takes full form input and returns confirmation/email string + SQL Queries
strURLHandleForm = "sendemailupdatedatabase.php"; // URL which takes confirmation string and SQL queries, sends email and updates database

function wioDebug(strMsg){
	if (blnWioDebug){ alert(strMsg);}
}

//Include browser specific stylesheet
function BrowserCheck() {
	var b = navigator.appName
	if (b=="Netscape") this.b = "ns"
	else if (b=="Microsoft Internet Explorer") this.b = "ie"
	else this.b = b
	this.v = parseInt(navigator.appVersion)
	this.ns = (this.b=="ns" && this.v>=4)
	this.ns4 = (this.b=="ns" && this.v==4)
	this.ns5 = (this.b=="ns" && this.v>=5)
	this.ie = (this.b=="ie" && this.v>=4)
	this.ie4 = (navigator.userAgent.indexOf('MSIE 4')>0)
	this.ie5 = (navigator.userAgent.indexOf('MSIE 5')>0)
	if (this.ie5) this.v = 5
	this.min = (this.ns||this.ie)
}

var brw = new BrowserCheck();
if (brw.ns){
		document.write('<link rel="stylesheet" type="text/css" href="/includes/ns.css"/>');
}
else {
		document.write('<link rel="stylesheet" type="text/css" href="/includes/ie.css"/>')
}


//Language switch
function switchLanguage(strLang){
	var arrPosLang = new Array("en","fr","nl");
	//Check language to swith to
	var blnNewLangOK = false;
	for (var j=0; j <arrPosLang.length; j++){
		if (arrPosLang[j].toUpperCase() == strLang.toUpperCase()){
			blnNewLangOK = true
			break;
		}		
	}
	if (!blnNewLangOK){
		alert('Illegal language to switch to: ' + strLang);
		return;
	}
	
	//Variables
	var strCurURL, strCurLang, strNewURL, intBegin, intEnd,blnLangFound, strURLBegin, strURLEnd;
	blnLangFound = false;
	
	//Determine current language
	strCurURL = self.location.href.toUpperCase();
	strRealURL = self.location.href;
	for (var i=0; i< arrPosLang.length; i++){
		var strSearch = "/" + arrPosLang[i].toUpperCase() + "/";
		if(strCurURL.indexOf(strSearch) >= 0){
			strCurLang = arrPosLang[i];
			blnLangFound = true;
			break;
		}
	}
	
	//Determine new URL
	if (blnLangFound){
		strSearch = "/" + strCurLang + "/";
		intBegin = strCurURL.toUpperCase().indexOf(strSearch.toUpperCase());
		intEnd = intBegin + strSearch.length;
		strURLBegin = strRealURL.substring(0,intBegin);
		strURLEnd = strRealURL.substring(intEnd);
		strNewURL = strURLBegin + "/" + strLang + "/" + strURLEnd;
		self.location.href = strNewURL;
		
	}else{
        	alert('Could not determine current language.'); 
                return; 
	}	
}

/* Returns language from URL in directorystructure */
function detectLanguage(){
	var arrPosLang = new Array("en","fr","nl");
	strCurURL = self.location.href.toUpperCase();
	strRealURL = self.location.href;
	strCurLang = "unknown";
	for (var i=0; i< arrPosLang.length; i++){
		var strSearch = "/" + arrPosLang[i].toUpperCase() + "/";
		if(strCurURL.indexOf(strSearch) >= 0){
			strCurLang = arrPosLang[i];
			break;
		}
	}
	return strCurLang;
}

/* Mouseover img function, replaces 'on' to 'of' or vice versa */
function switchImg(objImage){
	var curSource = objImage.src;
	if ((curSource.search(/_on\./i)  >= 0) || (curSource.search(/_of\./i) >= 0) ){
		if (curSource.search(/_on\./i) >= 0){
			//SWITCH OF
			var newSource = curSource.replace(/_on\./i, "_of.");
		}else{
			//SWITCH ON
			var newSource = curSource.replace(/_of\./i, "_on.");
		}
		objImage.src = newSource;
	}else{
		alert('Image source needs to end in either _of. or _on.');
		return;
	}
}

//Retrieves the value of a form element of type text, radio, checkbox, select and hidden.
//For multivalue elements, returns a ; separated string
function getFormElementValue(objElement){
	if (objElement == null){ wioDebug('Element is null');return "";}
	var strFieldValue = "";
	var strType;
	if (objElement.length){
		strType = objElement[0].type;
	}else{
		strType = objElement.type;
	}
	switch(strType){
		case "text":
		case "textarea":
		case "hidden":
			strFieldValue = objElement.value;
			break;
		case "radio":
		case "checkbox":
			var radioLength = objElement.length;
			if(radioLength == undefined){
				if(objElement.checked){
					strFieldValue =  objElement.value;
				}else{
					strFieldValue =  "";
				}
			}
			blnFoundAValue = false;
			for(var i = 0; i < radioLength; i++) {
				if(objElement[i].checked) {
					if (blnFoundAValue){ strFieldValue += ";";}
					strFieldValue +=  objElement[i].value; //Keep += to support multiple values
					blnFoundAValue = true;
				}
			}
			break;
		case "select-multiple":
			blnFoundAValue = false;
			for (var i= 0; i < objElement.options.length; i++){
				if (objElement.options[i].selected){
					if (blnFoundAValue){ strFieldValue += ";";}
					strFieldValue += objElement.options[i].value;
					blnFoundAValue = true;
				}
			}
			break;
		case "select-one":
			strFieldValue = objElement.options[objElement.selectedIndex].value;
			break;
		default:
			//select-one is not matched
			if (objElement.type == "select-one"){
				strFieldValue = objElement.options[objElement.selectedIndex].value;
				//wioDebug("Select-one catched in default case, value [" +strFieldValue + "]");
				return strFieldValue;
			}
			wioDebug("Type [" + objElement.type + "] for [" + objElement.name + "] is not supported in getFormElementValue");
			return "";
	}
	return strFieldValue;
}

/* 
	Retrieves option text for current selected option in  given optionSelect 
	Only supports single value selec element.
*/
function getOptionText(objSelect){
	if (objSelect.type != "select-one"){ 
		wioDebug("Wrong type in function getOptionText [" + objSelect.type + "]");
		return "";
	}else{
		return  objSelect.options[objSelect.selectedIndex].text;
	}
}


/*
	Real 'parseFloat' function with support for language settings (. and , in floating points)
*/
function wioParseFloat(strFloatingPoint){
	strFloatingPoint += "";
	//first determine the floating point divider
	floatChecker = 1 / 2;
	if ((strFloatingPoint + "").length <= 0){ return 0;}
	strCorrectedFloat = /\./.test(floatChecker + "") ? strFloatingPoint.replace(/,/,".") : strFloatingPoint.replace(/\./,",") ;
	//wioDebug("Float in [" + strFloatingPoint + "] , Checker[" + floatChecker + "] corrected float [" + strCorrectedFloat + "]");
	return parseFloat(strCorrectedFloat);
}

/* checks the validate of a date in format DD-MMM-YYYY */
function isValidDate(strDate){
	if (/^([0-9]{1,2})[\/\.-]([0-9]{1,2})[\/\.-]([0-9]{4})$/.test(strDate)){
		var strDayIn = RegExp.$1;
		var strMonthIn = RegExp.$2;
		var strYearIn = RegExp.$3;
		
		//wioDebug("Day In [" + strDate + "] =? [" + strDayIn + "/" + strMonthIn + "/" + strYearIn + "]");
		
		//check basic numeric values
		
		var intDay = Number(strDayIn);
		if (isNaN(intDay)){
			wioDebug("Day in [" + strDate +"] is NaN [" + strDayIn + "]");
			return false;
		}
		//wioDebug("strDayin [" + strDayIn + "]" + " parse day value:" + intDay);
		if (intDay <=0 || intDay > 31){
			wioDebug("Day in [" + strDate +"] is in illegal range [" + strDayIn + "]" + " parse day value:" + intDay);
			return false;
		}
		
		var intMonth = Number(strMonthIn);
		if (isNaN(intMonth)){
			wioDebug("Month in [" + strDate +"] is NaN");
			return false;
		}
		if (intMonth <=0 || intMonth > 12){
			wioDebug("Month in [" + strDate +"] is in illegal range");
			return false;
		}
		//change to JavaSCript month range which is one lower
		intMonth--;
		
		var intYear = Number(strYearIn);
		if (isNaN(intYear)){
			wioDebug("Year in [" + strDate + "] is Nan");
			return false;
		}
		var datToday = new Date();
		if (intYear <= 1850 || intYear > datToday.getFullYear){
			wioDebug("Year in [" + strDate + "] is in illegal range");
			return false;
		}
		
		//Now create a date and check if the month, day and year are the same.. otherwise the date given does not exist eg: 31/2/2008
		var datTester = new Date(intYear, intMonth, intDay);
		if (datTester.getDate() != intDay){
			wioDebug("Date is impossible for day.");
			return false;
		}
		if (datTester.getMonth() != intMonth){
			wioDebug("Date is impossible for month");
			return false;
		}
		//If you get through all the checks, it's okay
		return true;
	}else{
		wioDebug("Illegal format [" + strDate + "]");
		return false;
	}
}

/////////////// Custom AJAX FUNCTIONALITIES ///////////////////
/*
	make sure functions below are available and copy the lines below
	//POST
	wioSetAjaxConfig("/someurlyouwantocall.php","someJsFunctionToExecuteAfterwards()");
	POSTRequest("<input name='afield' value='Hello world'/>");
		
	//GET
	wioSetAjaxConfig("/someurlyouwantocall.php","someJsFunctionToExecuteAfterwards()");
	GETRequest("varone=Hello+World&vartwo=Bye+Bye");
	
*/


strWioAjaxUrl = "/willreturnerror404.htm"; //Set this variable to the correct URL before calling GETRequest or POSTRequest
strWioAjaxFunction = "wioDummy()"; //Set this variable to the correct URL before calling GETRequest or POSTRequest

function wioSetAjaxConfig(strUrlToCall, strJavaScriptToExecute){
	strWioAjaxUrl = strUrlToCall;
	strWioAjaxFunction = strJavaScriptToExecute;
}

function wioDummy(){
	alert("Use [wioSetAjaxConfig(strUrlToCall, strJavaScriptToExecute)] before using Ajax");
}
////////////////    STANDARD AJAX FUNCTIONALITIES ////////////////
var xmlHttp;
function createXMLHttpRequest() { 
	try{    
		// Firefox, Opera 8.0+, Safari    
		xmlHttp=new XMLHttpRequest(); 
	}catch (e){
		// Internet Explorer    
		try{
			xmlHttp=new ActiveXObject("Msxml2.XMLHTTP");      
		}catch (e){
			try{
				xmlHttp=new ActiveXObject("Microsoft.XMLHTTP");        
			}catch (e){
				wioDebug("Error creating the XMLHttpRequest object.");     
				return false;        
			}
		}    
	}
	return true;
} 

 
function GETRequest(query) {
	if (! createXMLHttpRequest()){
		return;	  
	}
	var zURL = strWioAjaxUrl + "?" + query;	
	//wioDebug("Getting URL [" + zURL + "]");
	xmlHttp.onreadystatechange = handleStateChange;
	xmlHttp.open("GET", zURL, true);
	xmlHttp.setRequestHeader("Charset", "iso-8859-1");
	xmlHttp.send(null);
}

function POSTRequest(query) {
	if (! createXMLHttpRequest()){
		wioDebug("could not create XMLHTTPobject");return;
	}
	xmlHttp.open("POST",strWioAjaxUrl, true);
	xmlHttp.onreadystatechange = handleStateChange;
	xmlHttp.setRequestHeader("Content-Type", "application/x-www-form-urlencoded");  
	xmlHttp.setRequestHeader("Charset", "iso-8859-1");
	xmlHttp.send(query);
}
    
function handleStateChange() {
	if(xmlHttp.readyState == 4) {
		if(xmlHttp.status == 200) {
			eval(strWioAjaxFunction); //function wich will be called if successfull response form strURL
		}else{
			wioDebug("AJAX call returned HTTP status [" + xmlHttp.status + "] [" + xmlHttp.statusText + "]");
		}
	}
}

/* shows error Message in overlayer which can be hidden  - Requires pre-existing DIV with id "errorpane" in page*/
function showError(strErrorMessage){
	//Transform strErrorMessage from text to HTML

	divErrorPane = document.getElementById("errorpane");
	divErrorPane.innerHTML = "<a class='erorrpaneclose' href='javascript:hideError();' onClick='hideError();return false;'>x</a>" + strErrorMessage;
	divErrorPane.style.display = "block";
}

/* hides error pane, identified by id "errorpane" */
function hideError(){
	divErrorPane = document.getElementById("errorpane");
	divErrorPane.innerHTML = "";
	divErrorPane.style.display = "none";
}