
// vars
var totalForms = 0;
var totalQuestions = 0;
var currentQuestion = 0;
var currentQuestionId = "";
var currentForm = 0;
var nextQuestion = 0;
var highestForm = 0;
var previousQuestion = 0;
var keepValue = new Array();
var keepQuestion = new Array();
var formQuestionsNames = new Array();
	
// array for all the input data
var formData = new Array();

// array for the questions
var formQuestions = new Array();

// replace the ,
function replaceComma(value){
	var str = value.replace(/,/g, "[COMMA]");
	return str;
}

// Date functions
function dateChooser(questionnr,inputid)
{
	currentQuestion = parseInt(questionnr);
	currentQuestionId = inputid;
	
	var objEarlyDate = new Date();
		objEarlyDate.setFullYear(objEarlyDate.getFullYear()-100);
	var objLateDate = new Date();
		objLateDate.setMonth(objLateDate.getMonth());

	var dateField = document.getElementById(inputid);
	dateField.DateChooser = new DateChooser();

	dateField.DateChooser.setCloseTime(200);
	dateField.DateChooser.setXOffset(10);
	dateField.DateChooser.setYOffset(10);
	dateField.DateChooser.setEarliestDate(objEarlyDate);
	dateField.DateChooser.setLatestDate(objLateDate);
	dateField.DateChooser.setUpdateFunction(updateDate);
	document.getElementById(inputid).onclick = dateField.DateChooser.display;
}

function updateDate(objDate)
{
	document.getElementById(currentQuestionId).value = objDate.getPHPDate('d-m-Y');
	parseValue(currentQuestion, currentQuestionId);
}
// e:date functions

function parseValue(questionnr,inputid) {

	currentQuestion = parseInt(questionnr);
	currentQuestionId = inputid;
	nextQuestion = (currentQuestion + 1);
	
	// remove all data from the further questions from this page and set the display to none
	if (currentQuestion != (totalQuestions - 1)) {
	
		for (i = totalQuestions - 1; i > currentQuestion; i--) {
		
			var questionInputBlock = document.getElementById('inputBlock[' + i + ']');
			var questionInputBlockId = questionInputBlock.getElementsByTagName('label')[0].htmlFor;
			
			// get type
			if (questionInputBlock.getElementsByTagName('select')[0]) {
				document.getElementById(questionInputBlockId).value = 'onbekend';
			}
			else if (questionInputBlock.getElementsByTagName('textarea')[0]) {
				document.getElementById(questionInputBlockId).value = "";
			}
			else if (questionInputBlock.getElementsByTagName('input')[0].getAttribute('type') == 'radio') {
				if (formData[currentForm][i] != null) {
					if(document.getElementById(questionInputBlockId + '[' + formData[currentForm][i] + ']')) {
						document.getElementById(questionInputBlockId + '[' + formData[currentForm][i] + ']').checked = false;
					}
				}
			}
			else {
				document.getElementById(questionInputBlockId).value = "";
			}
			
			// set the display from the question to none
			if (questionInputBlock.style.display == 'block') {
				questionInputBlock.style.display = 'none';
			}
		}
		
		if (document.getElementById('button').style.display == 'block') {
			document.getElementById('button').style.display = 'none';
		}
	}
	
	var oldValue = formData[currentForm][i];
	
	var nextQuestionVisible = checkField(inputid);
	if (nextQuestionVisible) {
		
		var newValue = formData[currentForm][i];
		
		// if a field changes remove all further questions from the array's
		if(oldValue != newValue) {
			for(i=totalQuestions; i>currentQuestion; i--) {
				if (formData[currentForm][i]) {
					formData[currentForm].splice(i, 1);
				}
				
				if (formQuestions[currentForm][i]) {
					formQuestions[currentForm].splice(i, 1);
				}
			}
		}
	
		// all questions
		if(nextQuestion < totalQuestions) {
			if (document.getElementById('inputBlock[' + nextQuestion + ']').style.display == 'none') {
				document.getElementById('inputBlock[' + nextQuestion + ']').style.display = 'block';
			}
		}
		
		// final question
		if(nextQuestion == totalQuestions) {
			document.getElementById('button').style.display = 'block';
		}
	}
	else {
		for (i = totalQuestions - 1; i > currentQuestion; i--) {
			
			// remove data from array
			if (formData[currentForm][i]) {
				formData[currentForm].splice(i, 1);
			}
		}
	}
	previousQuestion = currentQuestion;
}

function sendShort()
{
	var errors = "";
	var aanhef = document.getElementById("aanhef").value;
	var naam = document.getElementById("naam").value;
	var hypotheekbedrag = document.getElementById("hypotheekbedrag").value;
	var postcode = document.getElementById("postcode").value;
	var telefoonnummer = document.getElementById("telnr").value;
	
	if(naam == "") {
		errors += 'Er is geen naam ingevuld. <br />';
		var send = false;
	}
	if(hypotheekbedrag == "") {
		errors += 'Er is geen hypotheekbedrag ingevuld. <br />';
		var send = false;
	}
	if(!checkPostcode(postcode)) {
		errors += 'De postcode in niet of niet niet juist ingevuld. <br />';
		var send = false;
	}
	if(telefoonnummer.length != 10)	{
		errors += 'Het telefoonnummer is niet of niet juist ingevuld. <br />';
		var send = false;
	}
	
	if(send != false) {
		callAHAH('/subphp/subpages/hypotheekKort.php?aanhef='+aanhef+'&naam='+naam+'&hypotheekbedrag='+hypotheekbedrag+'&postcode='+postcode+'&telnr='+telefoonnummer+'', 'module-content');
	} else {
		document.getElementById('errors').innerHTML = errors;
	}
}

function callAjax(url, pageElement) {
	document.getElementById(pageElement).innerHTML = "<img src='/images/ajax-loader.gif' /> ";
	
	try {
    	req = new XMLHttpRequest(); /* e.g. Firefox */
	} catch(e) {
   		try {
   		req = new ActiveXObject("Msxml2.XMLHTTP");  /* some versions IE */
   		} catch (e) {
     		try {
	 			req = new ActiveXObject("Microsoft.XMLHTTP");  /* some versions IE */
     		} catch (E) {
      			req = false;
     		} 
   		} 
 	}
 	req.onreadystatechange = function() {responseAjax(url, pageElement);};
 	req.open("GET",url,true);
 	req.send(null);
}

function responseAjax(url, pageElement){
	var output = '';
	if (req.readyState == 4) {
		if (req.status == 200) {
			output = req.responseText;
			document.getElementById(pageElement).innerHTML = output;
		}
	}
}

function callAHAH(url, pageElement) {
	
	document.getElementById(pageElement).innerHTML = "<img src='/images/ajax-loader.gif' /> ";
	
	try {
    	req = new XMLHttpRequest(); /* e.g. Firefox */
	} catch(e) {
   		try {
   		req = new ActiveXObject("Msxml2.XMLHTTP");  /* some versions IE */
   		} catch (e) {
     		try {
	 			req = new ActiveXObject("Microsoft.XMLHTTP");  /* some versions IE */
     		} catch (E) {
      			req = false;
     		} 
   		} 
 	}
 	req.onreadystatechange = function() {responseAHAH(url, pageElement);};
 	req.open("GET",url,true);
 	req.send(null);
}

function responseAHAH(url, pageElement){
	var output = '';
	if (req.readyState == 4) {
		if (req.status == 200) {
			output = req.responseText;
			document.getElementById(pageElement).innerHTML = output;
			
			// set the background img
			//document.getElementById(pageElement).style.background = 'url(/images/banner2.jpg) no-repeat bottom left';
			
			if (getURLVar(url, 'page') == 'send') {
				document.getElementById('stappen').innerHTML = '<h1>Uw aanvraag is succesvol verzonden</h1>';
				
				for (i = 1; i <= totalForms + 1; i++) {
					document.getElementById('stap' + i).setAttribute("class", "");
					document.getElementById('stap' + i).onclick = "";
				}
			}
			
			totalForms = parseInt(document.getElementById('numForms').value);
			totalQuestions = parseInt(document.getElementById('numQuestions').value);
			currentForm = parseInt(getURLVar(url, 'form'));
			
			if (currentForm == totalForms) {
				document.getElementById('stappen').innerHTML = '<h1>U bent bij: Aanvraag versturen</h1>';
			}
			else {
				if(currentForm==0) {
					document.getElementById('stappen').innerHTML = '<h1>U bent bij: Stap ' + (currentForm + 1) + ' <em>(Huidige situatie)</em></h1>';	
				}
				if(currentForm==1) {
					document.getElementById('stappen').innerHTML = '<h1>U bent bij: Stap ' + (currentForm + 1) + ' <em>(Inkomen)</em></h1>';
				}
				if(currentForm==2) {
					document.getElementById('stappen').innerHTML = '<h1>U bent bij: Stap ' + (currentForm + 1) + ' <em>(Financi&euml;le verplichtingen)</em></h1>';
				}
				if(currentForm==3) {
					document.getElementById('stappen').innerHTML = '<h1>U bent bij: Stap ' + (currentForm + 1) + ' <em>(Eigen gegevens)</em></h1>';
				}
			}
			
			// reserve array for the questions
			if (formQuestions[currentForm] == null) {
				formQuestions[currentForm] = new Array();
			}
			
			if (currentForm > highestForm) {
				highestForm = currentForm;
			}
			
			// make all questions invisible
			for (cnt = 1; cnt < totalQuestions; cnt++) {
				var questionBlock = document.getElementById('inputBlock[' + cnt + ']');
				if (questionBlock != null) {
					document.getElementById('inputBlock[' + cnt + ']').style.display = 'none';
				}
			}
			
			// make next button invisible
			document.getElementById('button').style.display = 'none';
			
			// reserve array for this form
			if (formData[currentForm] == null) {
				formData[currentForm] = new Array();
			}
			
			if(getURLVar(url, 'firstQuestion')) {
				formData[0][0] = getURLVar(url, 'firstQuestion');
				formQuestions[0][0] = 'form[doel]';
			}
		}
		else {
			document.getElementById(pageElement).innerHTML = 'Kan het formulier niet ophalen';
		}
		
		// update fields
		updateForm();
		
		// make tabs active
		makeTabsActive();
		
		// get an overview
		if (currentForm == totalForms) {
			overview();
		}
	}
}		

function updateForm()
{	
	//alert(print_r(formData,true));
	for (question = 0; question < formData[currentForm].length; question++) {
	
		var questionValue;
		var questionInputBlock;
		var questionInputBlockId;
		
		// if the question has no answer
		if (formData[currentForm][question] == null) {
			//
		}
		else {
			if (formData[currentForm][question] != "") {
			
				questionValue = formData[currentForm][question];
				questionInputBlock = document.getElementById('inputBlock[' + question + ']');
				questionInputBlockId = questionInputBlock.getElementsByTagName('label')[0].htmlFor;
				
				// if it is a field WITH a checkbox
				if (questionInputBlock.getElementsByTagName('input')[1] != null && questionInputBlock.getElementsByTagName('input')[1].getAttribute('type') == 'checkbox') {
					if (questionInputBlock.getElementsByTagName('input')[1].getAttribute('type') == 'checkbox') {
						if (questionValue == "onbekend" || questionValue == "N.v.t.") {
							document.getElementsByName(questionInputBlockId)[1].checked = true;
						}
						else {
							document.getElementsByName(questionInputBlockId)[0].value = questionValue;
						}
					}
				}
				else {
					// if question is a select field
					if (questionInputBlock.getElementsByTagName('select')[0]) {
						document.getElementById(questionInputBlockId).value = questionValue;
					}
					
					// if question is a textfield
					if (questionInputBlock.getElementsByTagName('textarea')[0]) {
						document.getElementById(questionInputBlockId).value = questionValue;
					}
					
					// else it is a input field
					else {
						if (questionInputBlock.getElementsByTagName('input')[0]) {
						
							// if it is a text field
							if (questionInputBlock.getElementsByTagName('input')[0].getAttribute('type') == 'text') {
								document.getElementById(questionInputBlockId).value = questionValue;
							}
							
							// if it is a radio button
							if (questionInputBlock.getElementsByTagName('input')[0].getAttribute('type') == 'radio') {
								questionInputBlockId += '[' + questionValue + ']';
								document.getElementById(questionInputBlockId).checked = true;
							}
							
							// if it is a checkbox
							if (questionInputBlock.getElementsByTagName('input')[0].getAttribute('type') == 'checkbox') {
								questionInputBlockId += '[' + questionValue + ']';
								document.getElementById(questionInputBlockId).checked = true;
							}
						}
					}
				}
				// parse the value and update the display
				parseValue(question, questionInputBlockId);
			}
		}
	}
}

function getURLVar(url, urlVarName) 
{
	//divide the URL in half at the '?'
	var urlHalves = url.split('?');
	var urlVarValue = '';
	
	if(urlHalves[1])
	{
		//load all the name/value pairs into an array
		var urlVars = urlHalves[1].split('&');
		
		//loop over the list, and find the specified url variable
		for(i=0; i<=(urlVars.length); i++)
		{			
			if(urlVars[i])
			{
				//load the name/value pair into an array
				var urlVarPair = urlVars[i].split('=');
				
				if (urlVarPair[0] && urlVarPair[0] == urlVarName) 
				{
					//I found a variable that matches, load it's value into the return variable
					urlVarValue = urlVarPair[1];
				}
			}
		}
	}
	return urlVarValue;   
}

function makeTabsActive() {
	
	for(i = 1; i <= totalForms+1; i++) {
		if (i == currentForm) {
			document.getElementById('stap' + i).className = "currentForm";
		} else {
			document.getElementById('stap' + i).className = "";
		}
	}
	
	for(i = 0; i<=highestForm; i++) {
		document.getElementById('stap'+ (i+1) ).className = "active";
	}
		
	// set the onclick methode to the current form
	var previousForm = currentForm;
	document.getElementById('stap' + (currentForm+1) ).onclick = function() {
		callAHAH('/subphp/subpages/berekening.php?form='+ previousForm, 'module-content');
	}
	
	// set the style from the current form to activefrom
	document.getElementById('stap'+ (currentForm+1) ).className = "activeform";
}

function showInfo(questionInfoId) {
	var id = "div"+questionInfoId;
	document.getElementById(id).style.display = "block";
}

function closeInfo(questionInfoId) {
	
	var id = "div"+questionInfoId;
	document.getElementById(id).style.display = "none";
}

function checkDay(id)
{
	if(document.getElementById(id).value == "dag")
		document.getElementById(id).value = "";
}

function checkMonth(id)
{
	if(document.getElementById(id).value == "maand")
		document.getElementById(id).value = "";
}

function checkYear(id)
{
	if(document.getElementById(id).value == "jaar")
		document.getElementById(id).value = "";
}

function overview() {
	
	// remove background img
	document.getElementById('module-content').style.background = '';
	
	for(i=0; i<totalForms; i++) {
		formQuestionsNames[i] = new Array();
	}
	
	var formcontent = document.getElementById('module-content');
	var contentstr = '';

	for(i=0; i<formData.length; i++) {
		
		if(i==0) {
			contentstr += '<p class="line"><strong>Stap 1</strong> <em>(Huidige situatie) </em><img class="edit" src="/images/edit.gif" alt="Stap 1 bewerken" onclick="callAHAH(\'/subphp/subpages/berekening.php?form=0\', \'module-content\');" /></p>';		
		}
		if(i==1) {
			contentstr += '<p class="line"><strong>Stap 2</strong> <em>(Inkomen) </em><img class="edit" src="/images/edit.gif" alt="Stap 2 bewerken" onclick="callAHAH(\'/subphp/subpages/berekening.php?form=1\', \'module-content\');" /></p>';	
		}
		if(i==2) {
			contentstr += '<p class="line"><strong>Stap 3</strong> <em>(Financi&euml;le situatie) </em><img class="edit" src="/images/edit.gif" alt="Stap 3 bewerken" onclick="callAHAH(\'/subphp/subpages/berekening.php?form=2\', \'module-content\');" /></p>';	
		}
		if(i==3) {
			contentstr += '<p class="line"><strong>Stap 4</strong> <em>(Uw gegevens) </em><img class="edit" src="/images/edit.gif" alt="Stap 4 bewerken" onclick="callAHAH(\'/subphp/subpages/berekening.php?form=3\', \'module-content\');" /></p>';	
		}
				
		contentstr += '<table>';
		for(j=0; j<formData[i].length; j++) {
			if(formQuestions[i][j]) {
				var mySplitResult = formQuestions[i][j];
			
				mySplitResult = mySplitResult.split("[");
				mySplitResult = mySplitResult[1];
				mySplitResult = mySplitResult.split("]");
				mySplitResult = mySplitResult[0];
				mySplitResult = mySplitResult.replace(/\_/g, " ");
				formQuestionsNames[i][j] = mySplitResult;
				
				contentstr += '<tr><td width="200">' + mySplitResult + ':</td><td>' + formData[i][j]  + '<td /><tr />';
			}
		}
		contentstr += '</table>';
	}
	formcontent.innerHTML = contentstr;
	formcontent.innerHTML += '<br /><br />';
	
	formcontent.innerHTML += '<b>Eventuele opmerkingen:</b><br />';
	formcontent.innerHTML += '<textarea id="opmerkingen"></textarea><br /><br />';
	
	formcontent.innerHTML += 'Zijn bovenstaande gegevens juist?<br />';
	formcontent.innerHTML += '<br />Klik op \'Aanvraag versturen\' om uw aanvraag af te ronden. Na verzending wordt er zo spoedig mogelijk contact met u opgenomen.<br /><br />';
	
	formcontent.innerHTML += '<button id="button" onclick="send();"><img src="/images/versturen_btn.jpg" alt="Verstuur je gegevens" border="0" /></button><br /><br />';
}

function send()
{
	for (i = 0; i < formData.length; i++) {
		for (j = 0; j < formData[i].length; j++) {
			if (formData[i][j]) {
				var str = replaceComma(formData[i][j]);
				formData[i][j] = str;
			}
		}
	}
	
	formQuestionsNames[currentForm-1][formData[currentForm-1].length+1] = "opmerkingen";
	var str = replaceComma(document.getElementById("opmerkingen").value);
	formData[currentForm-1][formData[currentForm-1].length+1] = str;
	
	callAHAH('/subphp/subpages/berekening.php?page=send&values='+ formData +'&fields='+ formQuestionsNames +'', 'module-content');
}

function print_r(array, return_val){
	// Prints out or returns information about the specified variable  
	// 
	// version: 906.801
	// discuss at: http://phpjs.org/functions/print_r
	// +   original by: Michael White (http://getsprink.com)
	// +   improved by: Ben Bryan
	// +      input by: Brett Zamir (http://brett-zamir.me)
	// +      improved by: Brett Zamir (http://brett-zamir.me)
	// +   improved by: Kevin van Zonneveld (http://kevin.vanzonneveld.net)
	// -    depends on: echo
	// *     example 1: print_r(1, true);
	// *     returns 1: 1
	
	var output = "", pad_char = " ", pad_val = 4, d = this.window.document;
	var getFuncName = function(fn){
		var name = (/\W*function\s+([\w\$]+)\s*\(/).exec(fn);
		if (!name) {
			return '(Anonymous)';
		}
		return name[1];
	};
	
	var repeat_char = function(len, pad_char){
		var str = "";
		for (var i = 0; i < len; i++) {
			str += pad_char;
		}
		return str;
	};
	
	var formatArray = function(obj, cur_depth, pad_val, pad_char){
		if (cur_depth > 0) {
			cur_depth++;
		}
		
		var base_pad = repeat_char(pad_val * cur_depth, pad_char);
		var thick_pad = repeat_char(pad_val * (cur_depth + 1), pad_char);
		var str = "";
		
		if (typeof obj === 'object' && obj !== null && obj.constructor && getFuncName(obj.constructor) !== 'PHPJS_Resource') {
			str += "Array\n" + base_pad + "(\n";
			for (var key in obj) {
				if (obj[key] instanceof Array) {
					str += thick_pad + "[" + key + "] => " + formatArray(obj[key], cur_depth + 1, pad_val, pad_char);
				}
				else {
					str += thick_pad + "[" + key + "] => " + obj[key] + "\n";
				}
			}
			str += base_pad + ")\n";
		}
		else 
			if (obj === null || obj === undefined) {
				str = '';
			}
			else { // for our "resource" class
				str = obj.toString();
			}
		
		return str;
	};
	
	output = formatArray(array, 0, pad_val, pad_char);
	
	if (return_val !== true) {
		if (d.body) {
			this.echo(output);
		}
		else {
			try {
				d = XULDocument; // We're in XUL, so appending as plain text won't work; trigger an error out of XUL
				this.echo('<pre xmlns="http://www.w3.org/1999/xhtml" style="white-space:pre;">' + output + '</pre>');
			} 
			catch (e) {
				this.echo(output); // Outputting as plain text may work in some plain XML
			}
		}
		return true;
	}
	else {
		return output;
	}
}


