var hideuntilbrickid = false;
var hideuntildocid = false;
var rembrickid = false;
var remdocid = false;
var hideRest = false;
var inAdmin = false;
var readonlyBricks = new Object();
var hiddenBricks = new Object();
var firstSurveyAnswer = true;
var addClientSideAnswers = true;

var finished = new Array();
var _timer = false;
var goto_url = false;
var skippedDocs = new Object();
var handleDuplicateNames = false;
var firstSave = true;

/*
debugout = function (str) {
	if (typeof inspectwindow != 'object')
		inspectwindow = window.open ('', '', 'width=700,height=500,resizable=yes,scrollbars=yes,fullscreen=no');
	
	 try {
		 inspectwindow.document.body.innerHTML +=(str+ "<br>\n");
		 inspectwindow.document.body.innerHTML +=("--------------------------------------------------------------------------------<br>\n");
	 } catch (e) {
		 try {
	 		inspectwindow = window.open ('', '', 'width=700,height=500,resizable=yes,scrollbars=yes,fullscreen=no');
	
	 		inspectwindow.document.write(str);
		 } catch (e) {
	 		alert ('debugger: unable to open debug-window, debugger disabled');
		 }
	 }
}
*/

var conditionalShows = new Object();
var toberemovedANDAND = new Object();

var defaultnextdocid = false;

/**
 * Function: checkPageValidation
 *     Checks that all questions on the page have been answered in a valid manner
 *
 * Parameters:
 *     showErrors - boolean set to true if invalid answers should have an error shown
 *
 * Returns:
 *     true - if all questions have been answer correctly
 *     false - if one or more questions have been answered incorrectly
 */
function checkPageValidation(showErrors){
	//alert("IN checkPageValidation "+showErrors);
	//Get all the question bricks on the current page
	var questionBrickTypeEls = document.getElementsByName("brick_type");
	var isvalid = true;
	var alertString = "";
	//For each question on the current page....
	for(var i = 0; i < questionBrickTypeEls.length; i++){
		var qBrickTypeEl = questionBrickTypeEls[i];
		//If the question has not been skipped....
		//alert(qBrickTypeEl.innerText);	
		//FX comp
		var bid = qBrickTypeEl.getAttribute('brickid');
		if (typeof readonlyBricks[bid] !== "undefined" || typeof hiddenBricks[bid] !== "undefined")
			continue;
		//FX comp
		
		if(typeof bid !== "undefined" && typeof numbers != "undefined" && typeof numbers[bid] != "undefined" && typeof numbers[bid].skipped != "undefined" && numbers[bid].skipped == false){
			if(qBrickTypeEl.parentNode.style.display != "hidden"){
				//See if the question is compulsory....
				//We check these seperatly as these are the only type that can have data validation rules attached to them
				var mandatory = isMandatory(qBrickTypeEl.parentNode);
				if(mandatory != false){
					//If the question is an open question....
					if(qBrickTypeEl.innerText == "openvraag" || qBrickTypeEl.innerText == "autoaanvullen_veld"){
						for(var x = 0; x < qBrickTypeEl.parentNode.childNodes.length; x++){
							if(typeof qBrickTypeEl.parentNode.childNodes[x].id != "undefined"){
								if(qBrickTypeEl.parentNode.childNodes[x].id == "answerbox"){
									//answerboxElement will be the html input field (or text area)....
									var answerboxElement = qBrickTypeEl.parentNode.childNodes[x];
									if(answerboxElement.childNodes.length == 1){
										var element =  answerboxElement.childNodes[0];
										var validationRules = element.getAttribute("validationrules");
										//If there are some validation rules attached to the question...
										if(typeof validationRules !== "undefined" && validationRules !=""){
											//If its a date, first format the date...
											if(showErrors && validationRules.indexOf("Date") >= 0){
												element.value = formatDate(element.value);
											}
											//See if the given answer is valid...
											//alert("test4");
											cont = PPElementValidation(element, showErrors);
											if(cont == false){
												isvalid = false;
											}
										}
									}
									break;
								}
							}
						}
					}
					//If the question is NOT an open question....
					else{
						//If we want to show the errors to the user...
						if(showErrors){
							//If they have not answered the question (and its a mandatpry question so they should have)...
							if(typeof givenAnswers[bid] == "undefined"){
								//Try giving the error by placing it in the HTML 
								var err = giveError(bid, mandatory);
								isvalid = false;
								//If no place was defined in the template to show the error,
								//giveit as an alert instead.
								if(err != false){
									alertString = alertString + err;
								}
							}
							//Otherwise there's an answer give, so clear the error if one existed previously
							else if(qBrickTypeEl.innerText == "combilikertschaalvraag"){
								var hidden_stellingen = false;
								var hidden_meningen = false;
								var hidden_meningtoondetails = false;
								
								for(var x = 0; x < qBrickTypeEl.parentNode.childNodes.length; x++){
									if(typeof qBrickTypeEl.parentNode.childNodes[x].id != "undefined"){
										if(qBrickTypeEl.parentNode.childNodes[x].id == "hidden_stellingen"){
												hidden_stellingen = qBrickTypeEl.parentNode.childNodes[x];
										} else if(qBrickTypeEl.parentNode.childNodes[x].id == "hidden_meningen"){
												hidden_meningen = qBrickTypeEl.parentNode.childNodes[x];
										} else if(qBrickTypeEl.parentNode.childNodes[x].id == "hidden_meningtoondetails"){
												hidden_meningtoondetails = qBrickTypeEl.parentNode.childNodes[x];
										}
									}
								}
								
								if (hidden_stellingen != false){
									if (hidden_stellingen.innerText.indexOf("#####") > 0) {
										var arr = hidden_stellingen.innerText.split("#####");
										var arr_hidden_meningen = hidden_meningen.innerText.split("#####");
										var arr_hidden_meningtoondetails = hidden_meningtoondetails.innerText.split("#####");
										
										for (var el in arr) {
											if (typeof givenAnswers[bid][arr[el]] === "undefined"){
												isvalid = false;
												break;
											} else {
												var stelling_answer = givenAnswers[bid][arr[el]];
												var arr_stelling_answer = stelling_answer.split("#####");
												
												//check left side of combilikert question
													if (arr_stelling_answer[0] === "" || arr_stelling_answer[1] === ""){
													isvalid = false;
													break;
													}
												
												//check right side of combilikert question
												for (var el2 in arr_hidden_meningen) {
													if (arr_hidden_meningen[el2] === arr_stelling_answer[1]){
														//if right side is displayed
														if (arr_hidden_meningtoondetails[el2] === "ja"){
															if (arr_stelling_answer[2] === "" || arr_stelling_answer[3] === ""){
																isvalid = false;
																break;
																}			
														}
														break;
													}
												}
											}
										}
									}
								}
								
								if (isvalid){
									clearError(bid);
								} else {
									//Try giving the error by placing it in the HTML 
									var err = giveError(bid, mandatory);
									isvalid = false;
									//If no place was defined in the template to show the error,
									//giveit as an alert instead.
									if(err != false){
										alertString = alertString + err;
									}
								}
							} else {
								clearError(bid);
							}
						}
					}
				}
				//For all NOT mandatory questions....
				else{
					//We only need to check open questions as they are the only ones which need validating....
					//We validate as above...
					if(qBrickTypeEl.innerText == "openvraag" || qBrickTypeEl.innerText == "autoaanvullen_veld"){
						for(var x = 0; x < qBrickTypeEl.parentNode.childNodes.length; x++){
							if(typeof qBrickTypeEl.parentNode.childNodes[x].id != "undefined"){
								if(qBrickTypeEl.parentNode.childNodes[x].id == "answerbox"){
									var answerboxElement = qBrickTypeEl.parentNode.childNodes[x];
									if(answerboxElement.childNodes.length == 1){
										var element =  answerboxElement.childNodes[0];
										var validationRules = element.getAttribute("validationrules");
										if(typeof validationRules !== "undefined" && validationRules !="" && element.value != ""){
											if(showErrors && validationRules.indexOf("Date")>=0){
												element.value = formatDate(element.value);
											}
											cont = PPElementValidation(element, showErrors);
											if(cont == false){
												isvalid = false;
											}
										}
										else if(element.value == ""){
											if(showErrors == true){
												clearError(bid);
											}
										}
									}
									break;
								}
							}
						}
					}
				}
			}
		}
	}
	//Add any errors to the HTML or show alert
	//We do this here, so we only get one error alert per page
	//Rather than per error/question
	if(showErrors == true){
		if(alertString != ""){
			alert(alertString);
		}
		var errorEl = document.getElementById("wizarderror");
		if(errorEl != null && errorEl != false){
			for(var i = 0; i < errorEl.childNodes.length; i++){
				if(errorEl.childNodes[i].tagName !== "BR"){
					isvalid = false;
				}
			}
		}
		//See if we need to highlight the question that is invalid
		//These two settings are set in the config and then passed from the php to javascript
		if(typeof highlightClass !== "undefined" && typeof nonHighlightClass !== "undefined"){
			highlightErrors(nonHighlightClass, highlightClass);
		}
	}
	return isvalid;
}

/**
 * Function: checkMandatoryQuestionsOnPage
 *     Checks if all the compulsory questions on a page have been answered
 *
 * Parameters:
 *     none
 *
 * Returns:
 *     true - if all questions have an answer
 *     false - if one or more questions does not have an answer
 */
function checkMandatoryQuestionsOnPage(){
	var retVal = true;
	//Get all the question bricks on the page
	var questionBrickTypeEls = document.getElementsByName("brick_type");
	//For each question brick...
	for(var i = 0; i < questionBrickTypeEls.length; i++){
		var qBrickTypeEl = questionBrickTypeEls[i];
		//If it is a mandatory question
		
		// FX compat
		var bid =  qBrickTypeEl.getAttribute('brickid');
		// FX compat
		
		var brick_type = qBrickTypeEl.innerHTML;

		if(typeof bid !== "undefined" && typeof numbers != "undefined" && typeof numbers[bid] != "undefined" && typeof numbers[bid].skipped != "undefined" && numbers[bid].skipped == false){
			//If the question is not hidden (i.e. skipped)
			if(qBrickTypeEl.parentNode.style.display != "hidden"){
				//Check if it has an answer...
				var mandatory = isMandatory(qBrickTypeEl.parentNode);
				if(mandatory != false){
					
					if(typeof givenAnswers[bid] == "undefined"){
						return false;
					}
					
					// check if open parten of closed answer is filled in
					if (brick_type == "geslotenvraag") {
						var hiddenAnswersEl = dom.childNodeBy(qBrickTypeEl.parentNode,"id=hidden_answers",true);
						var openQuestionsEl = dom.childNodeBy(qBrickTypeEl.parentNode,"id=hidden_openquestions",true);
						if (hiddenAnswersEl != false && openQuestionsEl != false && openQuestionsEl.length) {
							var openQuestions = openQuestionsEl.innerText.split("#####");
							var hiddenAnswers = hiddenAnswersEl.innerText.split("#####");
							for(var j in hiddenAnswers){
								if ( openQuestions[j] == "ja" && typeof givenAnswers[bid] !== "undefined" && typeof givenAnswers[bid][hiddenAnswers[j]] !== "undefined" && givenAnswers[bid][hiddenAnswers[j]] == "") {
									return false;
								}
							}
						}
					} else if (brick_type == "likerdschaal" || brick_type == "likertschaalvraag" || brick_type == "tweevoudiglikertschaal"){
						//check if only one "stelling" is required for this brick, if not check if all "stellingen" are answered
						if (typeof likertWithOneRequiredQuestionBricks == "undefined" || (typeof likertWithOneRequiredQuestionBricks["all"] != "undefined" && likertWithOneRequiredQuestionBricks["all"] != true) || (typeof likertWithOneRequiredQuestionBricks[bid] != "undefined" && likertWithOneRequiredQuestionBricks[bid] != true)){
							var hidden_stellingen = false;
							var hidden_meningen = false;
							
							for(var x = 0; x < qBrickTypeEl.parentNode.childNodes.length; x++){
								if(typeof qBrickTypeEl.parentNode.childNodes[x].id != "undefined"){
									if(qBrickTypeEl.parentNode.childNodes[x].id == "hidden_stellingen"){
											hidden_stellingen = qBrickTypeEl.parentNode.childNodes[x];
									} else if(qBrickTypeEl.parentNode.childNodes[x].id == "hidden_meningen"){
											hidden_meningen = qBrickTypeEl.parentNode.childNodes[x];
									}	
								}
							}
							
							if (hidden_stellingen != false){
								if (hidden_stellingen.innerText.indexOf("#####") > 0) {
									var arr = hidden_stellingen.innerText.split("#####");
									var arr_hidden_meningen = hidden_meningen.innerText.split("#####");
									
	                for (var el in arr) {
	                	if (typeof givenAnswers[bid][arr[el]] === "undefined"){
	                		return false;
	                	} else {
	                		var stelling_answer = givenAnswers[bid][arr[el]];
	                		var arr_stelling_answer = stelling_answer.split("#####");
	                		
	                		//check left side of combilikert question
	            				if (arr_stelling_answer[0] === "" || arr_stelling_answer[1] === ""){
	                			return false;
	            				}
	                	}
	                }
	            	}
							}
						}
					}
					
					//check for empty tabelvraag bouwstenen
					var legeTabelvraagPattern = new RegExp("^(-----|====)+$");
					for(key in givenAnswers[bid]){
						if(legeTabelvraagPattern.test(key)){
							return false;
						}
					}
				}
			}
		}
	}
	return true;
}

/**
 * Function: highlightErrors
 *     Changes the html class of the question text for any questions with invalid answers
 *
 * Parameters:
 *     nonHighlightClass - an indexed array of html class names used if there is no error
 *     highlightClass  - an indexed array of html class names used if there is an error, the indexes of which match the first array
 *
 * Returns:
 *     nothing 
 */
function highlightErrors(nonHighlightClass, highlightClass){

	var brickswitherror = new Object();
	//find the errors hteml element
	var errorEl = document.getElementById("wizarderror");
	if(errorEl != null && errorEl != false){
		//for each error in the error html element
		for(var i  = 0; i< errorEl.childNodes.length; i++){
			//if the child has an id
			if(typeof errorEl.childNodes[i].id != "undefined"){
				//if that id is a brickid
				if(typeof numbers[errorEl.childNodes[i].id] != "undefined"){
					//store page as having an error
						brickswitherror[errorEl.childNodes[i].id] = true;
				}
			}
		}
	}
	//get all the question bricks on the current page...
	var questionBrickTypeEls = document.getElementsByName("brick_type");

	for(var i = 0; i < questionBrickTypeEls.length; i++) {
		var qBrickTypeEl = questionBrickTypeEls[i];
		
		//FX compat

		if (typeof qBrickTypeEl !== "undefined") {
			var bid = qBrickTypeEl.getAttribute('brickid');
		}else {
			break;
		}
		//FX compat

		if(typeof bid !== "undefined"){
			var brickid = bid;
			//if the brick has an error...
			if(typeof brickswitherror[brickid] !== "undefined"){
				var brickEl = qBrickTypeEl.parentNode;
				for(var j = 0; j < brickEl.childNodes.length;j++){
					var childEl = brickEl.childNodes[j];
					//Set any HTML element within the question to the error class
					for(var nonHighlightClassKey in nonHighlightClass){
						var nonHighlightClassVal = nonHighlightClass[nonHighlightClassKey];
						var highlightClassVal = highlightClass[nonHighlightClassKey];
						
						if(childEl.className == nonHighlightClassVal){
							childEl.className = highlightClassVal;
						}
					}
				}
			}
			else{ //no error
				var brickEl = qBrickTypeEl.parentNode;
				for(var j = 0; j < brickEl.childNodes.length;j++){
					var childEl = brickEl.childNodes[j];
					//Set any HTML element within the question to the NON error class
					for(var nonHighlightClassKey in nonHighlightClass){
						var nonHighlightClassVal = nonHighlightClass[nonHighlightClassKey];
						var highlightClassVal = highlightClass[nonHighlightClassKey];
						if(childEl.className == highlightClassVal){
							childEl.className = nonHighlightClassVal;
						}
					}
				}
			}
		}
	}
}

/**
 * Function: setOriginalAnswers
 *     When the form is initially loaded this function can be called to fill in answers previously given.
 *     To do this in the html.php file from the site, yuo need to make sure that the originalAnswers javascript array is constructed
 *     Also that this function is called in the javascipt generated from php
 *    (See assurantiebouwstenen/polix as an example)
 * 
 * Parameters:
 *     none
 *
 * Returns:
 *     nothing 
 */

function setOriginalAnswers(){
	//alert("setOriginalAnswers");
	//If the array has been defined (in the php part which generated the javascript to initalise the form)
	
	if(typeof originalAnswers != "undefined"){
		//for each answer that we need to set...
		
		for(var id in originalAnswers){
			//For each brick in the form (not only on current page - but all pages)
			for(var brickid in numbers){
                //if (id == "PP.PV.PV_ERB" && brickid==580) alert('stop');
				var match = false; //set to true when we find a match
				//If there unique id's match then we need have found the right question that needs its answer setting
                if(typeof numbers[brickid]['uniqueId'] != "undefined"){
					if(numbers[brickid]['uniqueId'] == id){
						match = true;
					}
                    else{
						var indexOfHekje = numbers[brickid]['uniqueId'].indexOf("#");
						if (indexOfHekje > 0) {
	                        var brickname = numbers[brickid]['uniqueId'].substring(0, indexOfHekje);
	                        if (brickname == id) {
	                            match = true;
	                        }
						}
                    }
				}
				else if(numbers[brickid]['questionText'] == id){
					match = true;
				}
				//if we found the question which needs setting...
				if(match == true){
					if (typeof readonlyQuestions !== "undefined" && typeof readonlyQuestions[id] !== "undefined") {
						readonlyBricks[brickid] = id;
					}
					//set the answer as it the user has already answered it
					if(typeof valToText != "undefined" && typeof valToText[brickid] != "undefined" && typeof valToText[brickid][originalAnswers[id]] != "undefined"){
						originalAnswers[id] = valToText[brickid][originalAnswers[id]];
					}
					givenAnswers[brickid] = new Object();
					if (originalAnswers[id].indexOf("#####") > 0) {
						var arr = originalAnswers[id].split("#####");
                        for (var el in arr) {
                            if (arr[el].indexOf("=====") > 0) {
                                var answerarr = arr[el].split("=====");
                                givenAnswers[brickid][answerarr[0]] = answerarr[1] + "#####" + answerarr[2] + "#####" + answerarr[3] + "#####" + answerarr[4];
                            } else {
								var idx = arr[el].indexOf("##");
								if (idx > 0) {
	                                givenAnswers[brickid][arr[el].substring(0,idx)] = arr[el].substring(idx+2);
								} else {
                                	givenAnswers[brickid][arr[el]] = "";
								}
                            }
                        }
					} else {
						//answeredQuestion(element)
						if (originalAnswers[id].indexOf("##") > 0) {
							var idx = originalAnswers[id].indexOf("##");
							givenAnswers[brickid][originalAnswers[id].substring(0,idx)] = originalAnswers[id].substring(idx+2);
						} else {
							givenAnswers[brickid][originalAnswers[id]] = "";
						}
						defaultAnswers[brickid] = new Object();
						defaultAnswers[brickid][originalAnswers[id]] = "";
						//alert(brickid + "=" + originalAnswers[id]);
					}
				}
			}
		}
	}
}


/**
 * Function: findFirstPageWithError
 *     Finds the first page in th eform that has an error on it
 *     So far this is being used when we need to do extermnal validation of the whole form
 *     Rather than page at a time, and then if there are any errors, we want to take the user to the
 * first page that has an error so that they can fix the answer.
 * 
 * Parameters:
 *     none
 *
 * Returns:
 *     docid - of which page has the first error / invalid answer in the form
 * 		false - if there are no errors in the form 
 */
function findFirstPageWithError () {
	
	//alert("IN findFirstPageWithError");
	var brickswitherror = new Object();
	//find the errors hteml element
	var errorEl = document.getElementById("wizarderror");
	if(errorEl != null && errorEl != false){
		//for each error in the error html element
		for(var i  = 0; i< errorEl.childNodes.length; i++){
			//if the child has an id
			if(typeof errorEl.childNodes[i].id != "undefined"){
				//if that id is a brickid
				if(typeof numbers[errorEl.childNodes[i].id] != "undefined"){
					//store page as having an error
						brickswitherror[errorEl.childNodes[i].id] = true;
				}
			}
		}
	}
	//the allQuestions list the bricks in the correct order and also knows which docid each brick is on
	//so loop through this array and find the first error and then we know the page
	for(var bid in allQuestions){
		if(typeof brickswitherror[bid] != "undefined" && brickswitherror[bid] == true){
			return allQuestions[bid];
		}
	}
	
	//No errors found
	return false;
}

/**
 * Function: clearAllErrors
 *     Removed all errors that are displayed on the page
 * 
 * Parameters:
 *     none
 *
 * Returns:
 *     nothing
 */
function clearAllErrors(){
	//alert("IN clearError");
	var errorEl = document.getElementById("wizarderror");
	if(errorEl != null && errorEl != false){
		for(var i  = 0; i< errorEl.childNodes.length; i++){
			errorEl.removeChild(errorEl.childNodes[i]);
			//errorEl.childNodes[i].removeNode(true);
		}
	}
	
	if(typeof highlightClass !== "undefined" && typeof nonHighlightClass !== "undefined"){
		highlightErrors(nonHighlightClass, highlightClass);
	}
}

/**
 * Function: clearError
 *     Removed all errors that are displayed on the page
 * 
 * Parameters:
 *     brickid - the brick id of the question whoses answer should no longer be displayed
 *
 * Returns:
 *     nothing
 */
function clearError(brickid) {
	//alert("IN clearError");
	//Get the error HTML
	var errorEl = document.getElementById("wizarderror");
	if(errorEl != null && errorEl != false){
		//For every error in the above HTML
		for(var i  = 0; i< errorEl.childNodes.length; i++){
			if(typeof errorEl.childNodes[i].id != "undefined"){
				//If it matches the correct brickid remove it
				if(errorEl.childNodes[i].id == brickid){
					errorEl.removeChild(errorEl.childNodes[i]);
				}
			}
		}
	}
}

/**
 * Function: handleErrorsFromServer
 *     Handles any errors passed from the server
 *     This can be used when we can not do client side validation (for example with the black box)
 * 
 * Parameters:
 *     errsArr - an array containing the information needed to display the errors
 *
 * Returns:
 *     true - if the errors were displayed correctly
 *     false - if the errors were not displayed correctly (there was a problem like it coudlnt find which question)
 */
function handleErrorsFromServer (errsArr){
	//alert("IN handleErrorsFromServer");
	var retVal = false; // return value variable
	
	//For every error in the array
	for(var errValue in errsArr){
		var err = errsArr[errValue];
		//alert("GOT ERROR FOR "+errValue);
		//For every question brick in the whole form (not just current page)
		
		
		// bug fix for ordering problem of numbered objects in Chrome and Opera
		for (var _bid=0; _bid < brickidorder.length; _bid++) {
			var brickid = brickidorder[_bid];
			var tv = numbers[brickid]['uniqueId'];
			var tvArr = tv.split("#");
			var changed = false;
			if(tvArr.length > 1){
				tv = tvArr[0];
				changed = true;
			}
			if("ERR."+tv == errValue || "ERR_"+tv == errValue){
				var noError = true;
				if(changed == false || (changed == true && numbers[brickid]['skipped'] == false)){
					if(err == "Verplicht veld ontbreekt of is leeg"){
						questiontext = numbers[brickid]["questionText"];		
						noError = giveError(brickid, questiontext, true, true);
					}
					else{
						noError = giveError(brickid, err, false, true);
					}
					if(noError == false){
						retVal = true;
					}
					break;
				}
				
			}
		}		
	}
	return retVal;
}

/**
 * Function: giveError
 *     Actually creates and displays a HTML error on the page
 * 
 * Parameters:
 *     brickId - brick id of the question which needs the error displayed
 *     questiontext - text to indicate to the suer which question is incorrectly filled in
 *     changeQuestionText - if the text above does NOT need changing then is set to false
 *     addLink - if the error should be clickable by a link to got to the page where the question is displayed
 *
 * Returns:
 *     true - if the errors were displayed correctly
 *     false - if the errors were not displayed correctly (there was a problem like it coudlnt find which question)
 */
function giveError(brickId, questiontext, changeQuestionText, addLink){

	//If there was no text set then use the default text
	if (questiontext == ""){
	 questiontext = "U heeft het veld niet juist ingevuld!"
	}
	//Else there was some text set...
	else{
		//See if this text needs changing...
		if(typeof changeQuestionText == "undefined" || changeQuestionText == true){
			questiontext = createErrorMesasge(questiontext);
		}
	}
	
	//get the error HTML element
	var errorEl = document.getElementById("wizarderror");
	//If there wasnt one then return text
	if(errorEl == null || errorEl == false){
		return questiontext;
	}
	else{	
		//strErrorMsg = "<br><span id=\""+brickId+"\" >&nbsp;"+questiontext+"</span><br>";
		//create HTML if a link is needed...
		if(addLink){
			var docid = numbers[brickId]['docid'];
			strErrorMsg = "<div id=\""+brickId+"\"><img src=\"/images/wizard/alert.gif\" width=\"21\" height=\"22\" alt=\"Fout!\" border=\"0\"><p class=helpbody style=\"text-decoration: underline;cursor:hand;\" id=\""+brickId+"\" onclick=\"gotoWizardPage("+docid+",false,false)\">&nbsp;"+questiontext+"</p></div>";
		}
		//create HTML if a link is NOT needed...
		else{
			strErrorMsg = "<div id=\""+brickId+"\"><img src=\"/images/wizard/alert.gif\" width=\"21\" height=\"22\" alt=\"Fout!\" border=\"0\"><p class=helpbody id=\""+brickId+"\">&nbsp;"+questiontext+"</p></div>";
		}
		//See if error is already being displayed...
		var found = false;
		for(var i = 0; i < errorEl.childNodes.length; i++){
			if(errorEl.childNodes[i].id == brickId){
				found = true;
				break;
			}
		}
		//If error isnt already being displayed, then display it
		if(!found){
			errorEl.innerHTML = errorEl.innerHTML + strErrorMsg;
			errorEl.style.display = "block";
		}	
		return false;
	}	
	return true;		
}

/**
 * Function: isMandatory
 *     Checks if a question is compulsary
 * 
 * Parameters:
 *     brickElement - HTML element of the question brick we need to check
 *
 * Returns:
 *     returnQuestion - the text of the question, if it is mandatory
 *     false - if it is NOT mandatory
 */
function isMandatory (brickElement) {
	var returnQuestion = "";
	
	//For each html element inside the question brick
	for(var i = 0; i < brickElement.childNodes.length; i++){
		childElement = brickElement.childNodes[i];
		//get the question text if its the question element
		if(childElement.id == "question"){
			returnQuestion = childElement.innerText
		}
		//if its the hidden_mandatory_question element...
		if(childElement.id == "hidden_mandatory_question"){
			//see if the value is 'yes'
			if(childElement.innerText == "ja"){
				//return the question text...note for this to work correctly the question element of the brick
				//must come before the hidden_mandatory_question element of the brick
				return returnQuestion;
			}
		}
	}
	return false;
}

/**
 * Function: renderQuestionBricks
 *     Generates the dynamic html for all question bricks on the current page
 * 
 * Parameters:
 *     onload - boolean set to true if we are rendering because the page is being loaded
 *
 * Returns:
 *     nothing
 */
function renderQuestionBricks(onload) {
	//alert('IN renderQuestionBricks');
	inAdmin = typeof onload == "undefined"?false:true;
	//get all the question bricks on a page...
	var questionBrickTypeEls = document.getElementsByName("brick_type");
	var errorEl = document.getElementById("wizarderror");
	//for each brick...

	for(var i = 0; i < questionBrickTypeEls.length; i++){
		var qBrickTypeEl = questionBrickTypeEls[i];
		var brick_type = qBrickTypeEl.innerHTML;
		
		if(inAdmin) {
			qBrickTypeEl.parentNode.style.display = "block";
		}
		//render the various types of questions bricks

		// FX compat
		var bid = qBrickTypeEl.getAttribute('brickid');
		// FX compat

		if(brick_type == "openvraag"){
			renderOpenVraagBrick(qBrickTypeEl.parentNode, bid, errorEl);
		}
		else if(brick_type == "autoaanvullen_veld"){
			renderAutoAanvullenVeldBrick(qBrickTypeEl.parentNode, bid, errorEl);
		}
		else if(brick_type == "geslotenvraag"){
			renderGeslotenVraagBrick(qBrickTypeEl.parentNode, bid, errorEl);
		}
		else if(brick_type == "likerdschaal" || brick_type == "likertschaalvraag" || brick_type == "tweevoudiglikertschaal"){
			renderLikertschaalVraagBrick(qBrickTypeEl.parentNode, bid, errorEl);
		}
		else if(brick_type == "combilikertschaalvraag"){
			renderCombiLikertschaalVraagBrick(qBrickTypeEl.parentNode, bid, errorEl);
		}
		else if(brick_type == "semanticdiffvraag" || brick_type == "semantischedifferentiaalvraag"){
			renderSemanticdiffVraagBrick(qBrickTypeEl.parentNode, bid, errorEl);
		} 
		else if (brick_type == "procentuelevraag") {
			renderProcentueleVraagBrick(qBrickTypeEl.parentNode, bid, errorEl);
		}
		else if(brick_type == "tabelvraag"){
			renderTabelVraagBrick(qBrickTypeEl.parentNode, bid, errorEl);
		}
	}
	//render the navigation bricks
	var navEls = document.getElementsByName("navbar");
	for(var i = 0; i < navEls.length; i++){
		var navEl = navEls[i];
		renderNavigationBrick(navEl.parentNode);
	}
	//take care of the skipped questions
    toberemovedANDAND = new Object();
    handleSkips();
    removeConditionalANDs();
}

/**
 * Function: renderNavigationBrick
 *     Generates the dynamic html for a navigation brick. A navigation brick can contain up to 5 navigation buttons.
 * 
 * Parameters:
 *     BrickHTML - HTML element of the navigation brick that needs rendering
 *
 * Returns:
 *     nothing
 */
function renderNavigationBrick (BrickHTML){
	//Get all the needed brick values that are in the HTML of the brick....
	for(var i = 0; i< BrickHTML.childNodes.length; i++){
		if(typeof BrickHTML.childNodes[i].id !== "undefined"){
			//get the brickvalues we need
			var childId = BrickHTML.childNodes[i].id;
			if(childId == "b1_class") {
				var b1_class = BrickHTML.childNodes[i].innerText;
			}
			else if(childId == "b2_class") {
				var b2_class = BrickHTML.childNodes[i].innerText;
			}
			else if(childId == "b3_class") {
				var b3_class = BrickHTML.childNodes[i].innerText;
			}
			else if(childId == "b4_class") {
				var b4_class = BrickHTML.childNodes[i].innerText;
			}
			else if(childId == "b5_class") {
				var b5_class = BrickHTML.childNodes[i].innerText;
			}
			else if(childId == "b1_onclick") {
				var b1_onclick = BrickHTML.childNodes[i].innerText;
			}
			else if(childId == "b2_onclick") {
				var b2_onclick = BrickHTML.childNodes[i].innerText;
			}
			else if(childId == "b3_onclick") {
				var b3_onclick = BrickHTML.childNodes[i].innerText;
			}
			else if(childId == "b4_onclick") {
				var b4_onclick = BrickHTML.childNodes[i].innerText;
			}
			else if(childId == "b5_onclick") {
				var b5_onclick = BrickHTML.childNodes[i].innerText;
			}
			else if(childId == "b1_onload") {
				var b1_onload = BrickHTML.childNodes[i].innerText;
			}
			else if(childId == "b2_onload") {
				var b2_onload = BrickHTML.childNodes[i].innerText;
			}
			else if(childId == "b3_onload") {
				var b3_onload = BrickHTML.childNodes[i].innerText;
			}
			else if(childId == "b4_onload") {
				var b4_onload = BrickHTML.childNodes[i].innerText;
			}
			else if(childId == "b5_onload") {
				var b5_onload = BrickHTML.childNodes[i].innerText;
			}
			else if(childId == "wn_nav1") {
				var b1 = BrickHTML.childNodes[i];
			}
			else if(childId == "wn_nav2") {
				var b2 = BrickHTML.childNodes[i];
			}
			else if(childId == "wn_nav3") {
				var b3 = BrickHTML.childNodes[i];
			}
			else if(childId == "wn_nav4") {
				var b4 = BrickHTML.childNodes[i];
			}
			else if(childId == "wn_nav5") {
				var b5 = BrickHTML.childNodes[i];
			}
		}
	}
	
	//Make the 5 buttons
	renderNavigationButton(b1, b1_class, b1_onclick, b1_onload);
	renderNavigationButton(b2, b2_class, b2_onclick, b2_onload);
	renderNavigationButton(b3, b3_class, b3_onclick, b3_onload);
	renderNavigationButton(b4, b4_class, b4_onclick, b4_onload);
	renderNavigationButton(b5, b5_class, b5_onclick, b5_onload);

	var isPageComplete = checkMandatoryQuestionsOnPage();
	enableNexts(isPageComplete);
}

/**
 * Function: renderNavigationBrick
 *     Generates the dynamic html for a navigation button within the navigation brick
 * 
 * Parameters:
 *     buttonEl - HTML element of the navigation button that needs rendering
 *     buttonClass - class of the button which is linked to the css thus controlling the look and feel of the button
 *                   this should be set to 'wn_next' if a button needs to act as a next button (see dev.handleidingen)
 *     buttonOnclick - javascript that needs to be executed when the button is clicked
 *     buttonOnload - javascript that needs to be executed when the button is loaded, i.e. now.
 *
 * Returns:
 *     nothing
 */
function renderNavigationButton(buttonEl, buttonClass, buttonOnclick, buttonOnload){
	//alert("class="+buttonClass+" onclick="+buttonOnclick+" inAdmin="+inAdmin);
	
	//Firstly we execute the javascript in the 4th parameter if it is set
	//asthis may change the values of the other values...
	if(buttonOnload != ""){
		try{
			//execute javascript. we expect an array to be returned which may contain new variables for the rendering of the button
			var ret = eval(buttonOnload);
			if(typeof ret == "object"){
				//replace class if needed....
				if(typeof ret['buttonClass'] != "undefined"){
					buttonClass = ret['buttonClass'];
				}
				//replace on click javascipt if needed....
				if(typeof ret['buttonOnclick'] != "undefined"){
					buttonOnclick = ret['buttonOnclick'];
				}
				//replace button text if needed....
				if(typeof ret['buttonText'] != "undefined"){
					buttonEl.innerText = ret['buttonText'];
				}
			}
		}
		catch (err){}
	}
	
	//If there is a class defined....note that if there is no class set then there will be no button displayed
	//So if you only want say 2 out of the 5 buttons, leave 3 of the buttons classes empty.
	if(buttonClass !== ""){
		//If its a next button we handle it slighly differenly....
		if(buttonClass == "wn_next"){
			if(typeof buttonEl.className == "undefined" || buttonEl.className == ""){
				buttonEl.className = "wn_currentpage";
				buttonEl.name = buttonClass;
				buttonEl.setAttribute("isEnabled", "NO");
				buttonEl.width = "100px";
			}			
		}
		//Else we set the class name of the button element
		else{
			buttonEl.className = buttonClass;
		}
		//display button
		buttonEl.style.display = "inline";
		if(typeof inAdmin != "undefined" && inAdmin == false){
			//set onclick event
			buttonEl.onclick = function tempeval () {
				// fix for broken IE-attribute model
				buttonOnclick = buttonOnclick.replace(/buttonEl\.gotodocid/ig ,'buttonEl.getAttribute ("gotodocid")');
				
				eval(buttonOnclick);
			};
		}
	}
}

/**
 * Function: renderQuestionNumbers
 *     Generates and displays the question numbers, these can be dynamic and this is why they must be rendered now
 * 
 * Parameters:
 *     none
 *
 * Returns:
 *     nothing
 */
function renderQuestionNumbers(){
	//alert("IN renderQuestionNumbers");
	//questionClasses is a global vraible used for the dynamic numbering of questions
	if(typeof questionClasses !== "undefined"){
		var classCounter = 0;
	}
	//get all the question bricks on the page
	var questionBrickTypeEls = document.getElementsByName("brick_type");
	//for each brick
	for(var i = 0; i < questionBrickTypeEls.length; i++){
		var qBrickTypeEl = questionBrickTypeEls[i];
		var brickid = qBrickTypeEl.getAttribute('brickid');
		
		var BrickHTML = qBrickTypeEl.parentNode;
		//For each html element within the question brick...
		for(var y = 0; y< BrickHTML.childNodes.length; y++){
			//if we have the question_number element..
			if(typeof BrickHTML.childNodes[y].id != "undefined" && BrickHTML.childNodes[y].id == "question_number") {
				//Set the number...
				var question_number_ELEMENT = BrickHTML.childNodes[y];
				var questionNumber = setQuestionNumber(brickid);
				question_number_ELEMENT.innerHTML = questionNumber;
				if(questionNumber != ""){
					question_number_ELEMENT.style.display = "block";
				}
				break;
			}
			
		}
		//If the question has not been skipped...
		if(typeof numbers != "undefined" && typeof numbers[brickid] != "undefined" && typeof numbers[brickid]['skipped'] != "undefined" && numbers[brickid]['skipped'] == false){
			if(typeof questionClasses !== "undefined" && typeof questionClasses[classCounter] !== "undefined"){
				//increase the dynamic numbering of the questions
				BrickHTML.className = questionClasses[classCounter];
				classCounter++;
				if(typeof questionClasses[classCounter] == "undefined"){
					classCounter = 0;
				}
			}
		}
	}
}

/**
 * Function: renderSemanticdiffVraagBrick
 *     Generates the html for a semantic differential question brick
 * 
 * Parameters:
 *     BrickHTML - HTML element of the question brick
 *     counterid - the brick id
 *     errorEl - the html element of the error related to the question
 *
 * Returns:
 *     nothing
 */
function renderSemanticdiffVraagBrick(BrickHTML, counterid, errorEl){
	//For every child in the bricks html...
	for(var i = 0; i< BrickHTML.childNodes.length; i++){
		if(typeof BrickHTML.childNodes[i].id !== "undefined"){
			//get the brickvalues we need
			var childId = BrickHTML.childNodes[i].id;
			if(childId == "hidden_mandatory_question") {
				var hidden_mandatory_question_ELEMENT = BrickHTML.childNodes[i];
			}
			else if(childId == "hidden_stellingen") {
				var hidden_stellingen = BrickHTML.childNodes[i];
			}
			else if(childId == "hidden_meningen") {
				var hidden_meningen = BrickHTML.childNodes[i];
			}
			else if(childId == "display_answers") {
				var display_answers_ELEMENT = BrickHTML.childNodes[i];
			}
			else if(childId == "mandatory_question") {
				var mandatory_question_ELEMENT = BrickHTML.childNodes[i];
			}
			else if(childId == "hidden_questionnumber") {
				var hidden_questionnumber_ELEMENT = BrickHTML.childNodes[i];
			}
			else if(childId == "question_number") {
				var question_number_ELEMENT = BrickHTML.childNodes[i];
			}		
			else if(childId == "hidden_displaynumber") {
				var hidden_displaynumber_ELEMENT = BrickHTML.childNodes[i];
			}
			else if(childId == "hidden_displaysubnumber") {
				var hidden_displaysubnumber_ELEMENT = BrickHTML.childNodes[i];
			}
			else if(childId == "hidden_displayheader") {
				var hidden_displayheader_ELEMENT = BrickHTML.childNodes[i];
			}
			else if(childId == "brick_type") {
				var brickid = BrickHTML.childNodes[i].getAttribute('brickid');
			}
			else if(childId == "hidden_description_type") {
				var hidden_description_type_ELEMENT = BrickHTML.childNodes[i];
			}
						
			else if(childId == "description_div") {
				var description_div_ELEMENT = BrickHTML.childNodes[i];
			}
		}
	}
	//call functions to generate html using brick values and set the returned html to the correct innerHTML
	display_answers_ELEMENT.innerHTML = reallyGenerateSemanticdiffTableHTML(hidden_meningen.innerText, hidden_stellingen.innerText, hidden_displaysubnumber_ELEMENT.innerText, hidden_displayheader_ELEMENT.innerText, counterid);
	mandatory_question_ELEMENT.innerHTML = setMandatoryIndicator(hidden_mandatory_question_ELEMENT.innerText);
	var questionNumber = setQuestionNumber(brickid);
	question_number_ELEMENT.innerHTML = questionNumber;
	if(questionNumber != ""){
		question_number_ELEMENT.style.display = "block";
	}
	arrangeDescription(description_div_ELEMENT, hidden_description_type_ELEMENT.innerText);
}

/**
 * Function: renderLikertschaalVraagBrick
 *     Generates the html for a likertschaal question brick
 * 
 * Parameters:
 *     BrickHTML - HTML element of the question brick
 *     counterid - the brick id
 *     errorEl - the html element of the error related to the question
 *
 * Returns:
 *     nothing
 */
function renderLikertschaalVraagBrick(BrickHTML, counterid, errorEl){
	//For every child in the bricks html...
	for(var i = 0; i< BrickHTML.childNodes.length; i++){
		if(typeof BrickHTML.childNodes[i].id !== "undefined"){
			//get the brickvalues we need
			var childId = BrickHTML.childNodes[i].id;
			if(childId == "hidden_mandatory_question") {
				var hidden_mandatory_question_ELEMENT = BrickHTML.childNodes[i];
			}
			else if(childId == "hidden_stellingen") {
				var hidden_stellingen = BrickHTML.childNodes[i];
			}
			else if(childId == "hidden_meningen") {
				var hidden_meningen = BrickHTML.childNodes[i];
			}
			else if(childId == "display_answers") {
				var display_answers_ELEMENT = BrickHTML.childNodes[i];
			}
			else if(childId == "mandatory_question") {
				var mandatory_question_ELEMENT = BrickHTML.childNodes[i];
			}
			else if(childId == "hidden_questionnumber") {
				var hidden_questionnumber_ELEMENT = BrickHTML.childNodes[i];
			}
			else if(childId == "question_number") {
				var question_number_ELEMENT = BrickHTML.childNodes[i];
			}		
			else if(childId == "hidden_displaynumber") {
				var hidden_displaynumber_ELEMENT = BrickHTML.childNodes[i];
			}		
			else if(childId == "hidden_displaysubnumber") {
				var hidden_displaysubnumber_ELEMENT = BrickHTML.childNodes[i];
			}
			else if(childId == "brick_type") {
				var brickid = BrickHTML.childNodes[i].getAttribute('brickid');
			}
			else if(childId == "hidden_description_type") {
				var hidden_description_type_ELEMENT = BrickHTML.childNodes[i];
			}
						
			else if(childId == "description_div") {
				var description_div_ELEMENT = BrickHTML.childNodes[i];
			}
		}
	}
	//call functions to generate html using brick values and set the returned html to the correct innerHTML
	display_answers_ELEMENT.innerHTML = reallyGenerateLikerschaalTableHTML(hidden_meningen.innerText, hidden_stellingen.innerText,hidden_displaysubnumber_ELEMENT.innerText,counterid);
	mandatory_question_ELEMENT.innerHTML = setMandatoryIndicator(hidden_mandatory_question_ELEMENT.innerText);
	var questionNumber = setQuestionNumber(brickid);
	question_number_ELEMENT.innerHTML = questionNumber;
	if(questionNumber != ""){
		question_number_ELEMENT.style.display = "block";
	}
	arrangeDescription(description_div_ELEMENT, hidden_description_type_ELEMENT.innerText);
}

/**
 * Function: renderCombiLikertschaalVraagBrick
 *     Generates the html for a combilikertschaal question brick
 * 
 * Parameters:
 *     BrickHTML - HTML element of the question brick
 *     counterid - the brick id
 *     errorEl - the html element of the error related to the question
 *
 * Returns:
 *     nothing
 */
function renderCombiLikertschaalVraagBrick(BrickHTML, counterid, errorEl){
//alert('IN renderCombiLikertschaalVraagBrick');
	//For every child in the bricks html...
	for(var i = 0; i< BrickHTML.childNodes.length; i++){
		if(typeof BrickHTML.childNodes[i].id !== "undefined"){
			//get the brickvalues we need
			var childId = BrickHTML.childNodes[i].id;
			if(childId == "hidden_mandatory_question") {
				var hidden_mandatory_question_ELEMENT = BrickHTML.childNodes[i];
			}
			else if(childId == "hidden_stellingen") {
				var hidden_stellingen = BrickHTML.childNodes[i];
			}
			else if(childId == "hidden_stellingextras") {
				var hidden_stellingextras = BrickHTML.childNodes[i];
			}
			else if(childId == "hidden_meningen") {
				var hidden_meningen = BrickHTML.childNodes[i];
			}
			else if(childId == "hidden_meningtoondetails") {
				var hidden_meningtoondetails = BrickHTML.childNodes[i];
			}
			else if(childId == "hidden_detailmeningen") {
				var hidden_detailmeningen = BrickHTML.childNodes[i];
			}
			else if(childId == "display_answers") {
				var display_answers_ELEMENT = BrickHTML.childNodes[i];
			}
			else if(childId == "mandatory_question") {
				var mandatory_question_ELEMENT = BrickHTML.childNodes[i];
			}
			else if(childId == "hidden_questionnumber") {
				var hidden_questionnumber_ELEMENT = BrickHTML.childNodes[i];
			}
			else if(childId == "question_number") {
				var question_number_ELEMENT = BrickHTML.childNodes[i];
			}		
			else if(childId == "hidden_displaynumber") {
				var hidden_displaynumber_ELEMENT = BrickHTML.childNodes[i];
			}		
			else if(childId == "hidden_displaysubnumber") {
				var hidden_displaysubnumber_ELEMENT = BrickHTML.childNodes[i];
			}
			else if(childId == "brick_type") {
				var brickid = BrickHTML.childNodes[i].getAttribute('brickid');
			}
			else if(childId == "hidden_description_type") {
				var hidden_description_type_ELEMENT = BrickHTML.childNodes[i];
			}
						
			else if(childId == "description_div") {
				var description_div_ELEMENT = BrickHTML.childNodes[i];
			}
		}
	}
	//call functions to generate html using brick values and set the returned html to the correct innerHTML
	display_answers_ELEMENT.innerHTML = reallyGenerateCombiLikerschaalTableHTML(hidden_meningen.innerText,hidden_meningtoondetails.innerText,hidden_detailmeningen.innerText,hidden_stellingen.innerText,hidden_stellingextras.innerText,hidden_displaysubnumber_ELEMENT.innerText,counterid);
	mandatory_question_ELEMENT.innerHTML = setMandatoryIndicator(hidden_mandatory_question_ELEMENT.innerText);
	var questionNumber = setQuestionNumber(brickid);
	question_number_ELEMENT.innerHTML = questionNumber;
	if(questionNumber != ""){
		question_number_ELEMENT.style.display = "block";
	}
	arrangeDescription(description_div_ELEMENT, hidden_description_type_ELEMENT.innerText);
}

/**
 * Function: renderGeslotenVraagBrick
 *     Generates the html for a closed question brick
 * 
 * Parameters:
 *     BrickHTML - HTML element of the question brick
 *     counterid - the brick id
 *     errorEl - the html element of the error related to the question
 *
 * Returns:
 *     nothing
 */
function renderGeslotenVraagBrick(BrickHTML, counterid, errorEl){
	//For every child in the bricks html...
	for(var i = 0; i< BrickHTML.childNodes.length; i++){
		if(typeof BrickHTML.childNodes[i].id !== "undefined"){
			//get the brickvalues we need
			var childId = BrickHTML.childNodes[i].id;
			if(childId == "question") {
				var question_ELEMENT = BrickHTML.childNodes[i];
			}
			if(childId == "hidden_mandatory_question") {
				var hidden_mandatory_question_ELEMENT = BrickHTML.childNodes[i];
			}
			else if(childId == "hidden_openquestions") {
				var hidden_openquestions_ELEMENT = BrickHTML.childNodes[i];
			}
			else if(childId == "hidden_gotos") {
				var hidden_gotos_ELEMENT = BrickHTML.childNodes[i];
			}
			else if(childId == "hidden_answers") {
				var hidden_answers_ELEMENT = BrickHTML.childNodes[i];
			}
			else if(childId == "display_answers") {
				var display_answers_ELEMENT = BrickHTML.childNodes[i];
			}
			else if(childId == "type_answers") {
				var type_answers_ELEMENT = BrickHTML.childNodes[i];
			}
			else if(childId == "mandatory_question") {
				var mandatory_question_ELEMENT = BrickHTML.childNodes[i];
			}
			else if(childId == "hidden_questionnumber") {
				var hidden_questionnumber_ELEMENT = BrickHTML.childNodes[i];
			}
			else if(childId == "question_number") {
				var question_number_ELEMENT = BrickHTML.childNodes[i];
			}
			else if(childId == "hidden_antwoordregeling") {
				var hidden_antwoordregeling_ELEMENT = BrickHTML.childNodes[i];
			}			
			else if(childId == "hidden_displaynumber") {
				var hidden_displaynumber_ELEMENT = BrickHTML.childNodes[i];
			}
			else if(childId == "brick_type") {
				var brickid = BrickHTML.childNodes[i].getAttribute('brickid');
			}			
			else if(childId == "hidden_description_type") {
				var hidden_description_type_ELEMENT = BrickHTML.childNodes[i];
			}
			else if(childId == "hidden_html_values") {
				var html_values_ELEMENT = BrickHTML.childNodes[i];
			}
						
			else if(childId == "description_div") {
				var description_div_ELEMENT = BrickHTML.childNodes[i];
			}
			else if(childId == "wizardhelp") {
				var wizardhelp_div_ELEMENT = BrickHTML.childNodes[i];
			}
			else if(childId == "sub_sel_groups") {
				var selectedGroups = BrickHTML.childNodes[i];
			}
		}
	}
	var errormessage = createErrorMesasge(question_ELEMENT.innerText);
	hideQuestionmarkIfNoDescription(wizardhelp_div_ELEMENT);
	
	//call functions to generate html using brick values and set the returned html to the correct innerHTML
	display_answers_ELEMENT.innerHTML = reallyGenerateClosedAnswerHTML(hidden_answers_ELEMENT.innerText, type_answers_ELEMENT.innerText, hidden_antwoordregeling_ELEMENT.innerText, hidden_openquestions_ELEMENT.innerText, hidden_gotos_ELEMENT.innerText, html_values_ELEMENT.innerText, counterid, errorEl, errormessage, selectedGroups);
	mandatory_question_ELEMENT.innerHTML = setMandatoryIndicator(hidden_mandatory_question_ELEMENT.innerText);
	var questionNumber = setQuestionNumber(brickid);
	question_number_ELEMENT.innerHTML = questionNumber;
	if(questionNumber != ""){
		question_number_ELEMENT.style.display = "block";
	}
	arrangeDescription(description_div_ELEMENT, hidden_description_type_ELEMENT.innerText);
	if (hidden_antwoordregeling_ELEMENT.innerText == "hidden") {
		hiddenBricks[brickid] = true;
	}
}

function hideQuestionmarkIfNoDescription(wizardhelp_div_ELEMENT){
	if(typeof wizardhelp_div_ELEMENT != "undefined"){
		for(var i = 0; i< wizardhelp_div_ELEMENT.childNodes.length; i++){
			var node = wizardhelp_div_ELEMENT.childNodes[i];
			if(node.className=="wizardRow3"){
				for(var j = 0; j< node.childNodes.length; j++){
					var node2 = node.childNodes[j];
					if(node2.id == "wizardhelp"){
						for(var k = 0; k< node2.childNodes.length; k++){
							if(node2.childNodes[k].className == "helpbody" && (node2.childNodes[k].innerText == "")){
								wizardhelp_div_ELEMENT.style.visibility = "hidden";
							}
						}
					}
				}
			}
		}
	}
}

/**
 * Function: renderProcentueleVraagBrick
 *     Generates the html for a procentuele question brick
 * 
 * Parameters:
 *     BrickHTML - HTML element of the question brick
 *     counterid - the brick id
 *     errorEl - the html element of the error related to the question
 *
 * Returns:
 *     nothing
 */
function renderProcentueleVraagBrick(BrickHTML, counterid, errorEl){
	//For every child in the bricks html...
	for(var i = 0; i< BrickHTML.childNodes.length; i++){
		if(typeof BrickHTML.childNodes[i].id !== "undefined"){
			//get the brickvalues we need
			var childId = BrickHTML.childNodes[i].id;
			if(childId == "question") {
				var question_ELEMENT = BrickHTML.childNodes[i];
			}
			if(childId == "hidden_mandatory_question") {
				var hidden_mandatory_question_ELEMENT = BrickHTML.childNodes[i];
			}
			else if(childId == "hidden_openquestions") {
				var hidden_openquestions_ELEMENT = BrickHTML.childNodes[i];
			}
			else if(childId == "hidden_gotos") {
				var hidden_gotos_ELEMENT = BrickHTML.childNodes[i];
			}
			else if(childId == "hidden_answers") {
				var hidden_answers_ELEMENT = BrickHTML.childNodes[i];
			}
			else if(childId == "display_answers") {
				var display_answers_ELEMENT = BrickHTML.childNodes[i];
			}
			else if(childId == "type_answers") {
				var type_answers_ELEMENT = BrickHTML.childNodes[i];
			}
			else if(childId == "mandatory_question") {
				var mandatory_question_ELEMENT = BrickHTML.childNodes[i];
			}
			else if(childId == "hidden_questionnumber") {
				var hidden_questionnumber_ELEMENT = BrickHTML.childNodes[i];
			}
			else if(childId == "question_number") {
				var question_number_ELEMENT = BrickHTML.childNodes[i];
				question_number_ELEMENT.style.display = "block";
			}
			else if(childId == "hidden_antwoordregeling") {
				var hidden_antwoordregeling_ELEMENT = BrickHTML.childNodes[i];
			}			
			else if(childId == "hidden_displaynumber") {
				var hidden_displaynumber_ELEMENT = BrickHTML.childNodes[i];
			}
			else if(childId == "brick_type") {
				var brickid = BrickHTML.childNodes[i].getAttribute('brickid');
			}			
			else if(childId == "hidden_description_type") {
				var hidden_description_type_ELEMENT = BrickHTML.childNodes[i];
			}
			else if(childId == "hidden_html_values") {
				var html_values_ELEMENT = BrickHTML.childNodes[i];
			}
						
			else if(childId == "description_div") {
				var description_div_ELEMENT = BrickHTML.childNodes[i];
			}
		}
	}
	var errormessage = createErrorMesasge(question_ELEMENT.innerText);
	
	
	//call functions to generate html using brick values and set the returned html to the correct innerHTML
	display_answers_ELEMENT.innerHTML = reallyGeneratePercentQuestionHTML(hidden_answers_ELEMENT.innerText, type_answers_ELEMENT.innerText, hidden_antwoordregeling_ELEMENT.innerText, hidden_openquestions_ELEMENT.innerText, hidden_gotos_ELEMENT.innerText, html_values_ELEMENT.innerText, counterid, errorEl, errormessage);
	mandatory_question_ELEMENT.innerHTML = setMandatoryIndicator(hidden_mandatory_question_ELEMENT.innerText);
	var questionNumber = setQuestionNumber(brickid);
	question_number_ELEMENT.innerHTML = questionNumber;
	if(questionNumber != ""){
		question_number_ELEMENT.style.display = "block";
	}
	arrangeDescription(description_div_ELEMENT, hidden_description_type_ELEMENT.innerText);
}

/**
 * Function: renderTabelVraagBrick
 *     Generates the html for a tabelvraag question brick
 * 
 * Parameters:
 *     BrickHTML - HTML element of the question brick
 *     counterid - the brick id
 *     errorEl - the html element of the error related to the question
 *
 * Returns:
 *     nothing
 */
function renderTabelVraagBrick(BrickHTML, counterid, errorEl){
	//For every child in the bricks html...
	for(var i = 0; i< BrickHTML.childNodes.length; i++){
		if(typeof BrickHTML.childNodes[i].id !== "undefined"){
			//get the brickvalues we need
			var childId = BrickHTML.childNodes[i].id;
			if(childId == "hidden_mandatory_question") {
				var hidden_mandatory_question_ELEMENT = BrickHTML.childNodes[i];
			}
			else if(childId == "hidden_meningen") {
				var hidden_meningen = BrickHTML.childNodes[i];
			}
			else if(childId == "hidden_meningen_type") {
				var hidden_meningen_type = BrickHTML.childNodes[i];
			}
			else if(childId == "hidden_meningen_default_value") {
				var hidden_meningen_default_value = BrickHTML.childNodes[i];
			}
			else if(childId == "display_answers") {
				var display_answers_ELEMENT = BrickHTML.childNodes[i];
			}
			else if(childId == "mandatory_question") {
				var mandatory_question_ELEMENT = BrickHTML.childNodes[i];
			}
			else if(childId == "hidden_questionnumber") {
				var hidden_questionnumber_ELEMENT = BrickHTML.childNodes[i];
			}
			else if(childId == "question_number") {
				var question_number_ELEMENT = BrickHTML.childNodes[i];
			}		
			else if(childId == "hidden_displaynumber") {
				var hidden_displaynumber_ELEMENT = BrickHTML.childNodes[i];
			}		
			else if(childId == "hidden_displaysubnumber") {
				var hidden_displaysubnumber_ELEMENT = BrickHTML.childNodes[i];
			}
			else if(childId == "brick_type") {
				var brickid = BrickHTML.childNodes[i].getAttribute('brickid');
			}
			else if(childId == "hidden_description_type") {
				var hidden_description_type_ELEMENT = BrickHTML.childNodes[i];
			}
						
			else if(childId == "description_div") {
				var description_div_ELEMENT = BrickHTML.childNodes[i];
			}
			else if(childId == "hidden_minimum_rows") {
				var hidden_minimum = BrickHTML.childNodes[i];
			}
			else if(childId == "hidden_maximum_rows") {
				var hidden_maximum = BrickHTML.childNodes[i];
			}
		}
	}
	//call functions to generate html using brick values and set the returned html to the correct innerHTML
	display_answers_ELEMENT.innerHTML = reallyGenerateTabelVraagTableHTML(hidden_meningen.innerText, hidden_meningen_type.innerText,hidden_meningen_default_value.innerText,hidden_displaysubnumber_ELEMENT.innerText,counterid, hidden_minimum.innerText, hidden_maximum.innerText);
	mandatory_question_ELEMENT.innerHTML = setMandatoryIndicator(hidden_mandatory_question_ELEMENT.innerText);
	var questionNumber = setQuestionNumber(brickid);
	question_number_ELEMENT.innerHTML = questionNumber;
	if(questionNumber != ""){
		question_number_ELEMENT.style.display = "block";
	}
	arrangeDescription(description_div_ELEMENT, hidden_description_type_ELEMENT.innerText);
}

/**
 * Function: arrangeDescription
 *     Called from all the render functions of the different question bricks to display the question description
 *     This can be displayed in various ways (as seen in bureauleemans and polix - they are very different)
 * 
 * Parameters:
 *     desc_div - the DIV element from the question brick where the description html must be placed
 *     desc_type - the type of description - there are 5 possible types (text only, and text with an image (above, below, left and right)
 *
 * Returns:
 *     nothing
 */
function arrangeDescription(desc_div, desc_type){
	var needtoswap = false;
	for(var i  = 0; i < desc_div.childNodes.length; i++){
		if(desc_div.childNodes[i].id == "desc_image"){
			if(desc_type == "Tekst alleen"){
				desc_div.childNodes[i].style.display = "none";
			}
			else if(desc_type == "Tekst met afbeelding boven"){
				desc_div.childNodes[i].style.display = "block";
				//If image is 2nd child node
				if(i == 1){
					needtoswap = true;
				}
			}	
			else if(desc_type == "Tekst met afbeelding onder"){
				desc_div.childNodes[i].style.display = "block";
				//If image is 1st child node
				if(i == 0){
					needtoswap = true;
				}
			}			
			else if(desc_type == "Tekst met afbeelding rechts"){
				desc_div.childNodes[i].style.display = "inline";
				//If image is 1st child node
				if(i == 0){
					needtoswap = true;
				}
			}
			else if(desc_type == "Tekst met afbeelding links"){
				desc_div.childNodes[i].style.display = "inline";
				//If image is 2nd child node
				if(i == 1){
					needtoswap = true;
				}
			}
		}
		else if(desc_div.childNodes[i].id == "desc_text"){
			if(desc_div.childNodes[i].innerHTML == ""){
				desc_div.childNodes[i].style.display = "none";
			}
			else{		
				if(desc_type == "Tekst met afbeelding rechts"){
					desc_div.childNodes[i].style.display = "inline";
				}
				else if(desc_type == "Tekst met afbeelding links"){
					desc_div.childNodes[i].style.display = "inline";
				}
				else{
					desc_div.childNodes[i].style.display = "block";
				}
			}
		}
	}
	if(needtoswap){
		
		var first_child_clone = desc_div.childNodes[0].cloneNode(true);
		var first_child = desc_div.childNodes[0];
		var second_child_clone  = desc_div.childNodes[1].cloneNode(true);
		var second_child = desc_div.childNodes[1];
		desc_div.removeChild(first_child);
		desc_div.removeChild(second_child);
		desc_div.appendChild(second_child_clone);
		desc_div.appendChild(first_child_clone);
	}
}

/**
 * Function: renderOpenVraagBrick
 *     Generates the html for a open question brick
 * 
 * Parameters:
 *     BrickHTML - HTML element of the question brick
 *     counterid - the brick id
 *     errorEl - the html element of the error related to the question
 *
 * Returns:
 *     nothing
 */
function renderOpenVraagBrick(BrickHTML, counterid, errorEl){
	if(typeof errorEl == "undefined"){
		errorEl = false;
	}
	
	// Define date variables which could not be available
	var minPast = "";
	var maxPast = "";
	var minFuture = "";
	var maxFuture = "";
	
	//For every child in the bricks html...
	for(var i = 0; i< BrickHTML.childNodes.length; i++){
		if(typeof BrickHTML.childNodes[i].id !== "undefined"){
			//get the brickvalues we need
			var childId = BrickHTML.childNodes[i].id;
			if(childId == "hidden_mandatory_question") {
				var hidden_mandatory_question_ELEMENT = BrickHTML.childNodes[i];
			}
			if(childId == "question") {
				var question_ELEMENT = BrickHTML.childNodes[i];
			}
			else if(childId == "answerbox") {
				var answerbox_ELEMENT = BrickHTML.childNodes[i];
			}
			else if(childId == "hidden_width") {
				var hidden_width_ELEMENT = BrickHTML.childNodes[i];
			}
			else if(childId == "hidden_height") {
				var hidden_height_ELEMENT = BrickHTML.childNodes[i];
			}
			else if(childId == "display_answers") {
				var display_answers_ELEMENT = BrickHTML.childNodes[i];
			}
			else if(childId == "mandatory_question") {
				var mandatory_question_ELEMENT = BrickHTML.childNodes[i];
			}
			else if(childId == "hidden_questionnumber") {
				var hidden_questionnumber_ELEMENT = BrickHTML.childNodes[i];
			}
			else if(childId == "question_number") {
				var question_number_ELEMENT = BrickHTML.childNodes[i];
			}
			else if(childId == "hidden_displaynumber") {
				var hidden_displaynumber_ELEMENT = BrickHTML.childNodes[i];
			}
			else if(childId == "type_answers") {
				var type_answers_ELEMENT = BrickHTML.childNodes[i];
			}
			else if(childId == "brick_type") {
				var brickid = BrickHTML.childNodes[i].getAttribute('brickid');
			}
			else if(childId == "hidden_max") {
				var maxELEMENT = BrickHTML.childNodes[i];
			}
			else if(childId == "hidden_min") {
				var minELEMENT = BrickHTML.childNodes[i];
			}
			else if(childId == "hidden_maxLength") {
				var mlELEMENT = BrickHTML.childNodes[i];
			}
			else if(childId == "minPast") {
				minPast = BrickHTML.childNodes[i];
				if (typeof minPast !== "undefined") {
					minPast = minPast.innerText;
				} else {
					minPast = "";
				}
			}
			else if(childId == "maxPast") {
				maxPast = BrickHTML.childNodes[i];
				if (typeof maxPast !== "undefined") {
					maxPast = maxPast.innerText;
				} else {
					maxPast = "";
				}
			}
			else if(childId == "minFuture") {
				minFuture = BrickHTML.childNodes[i];
				if (typeof minFuture !== "undefined") {
					minFuture = minFuture.innerText;
				} else {
					minFuture = "";
				}
			}
			else if(childId == "maxFuture") {
				maxFuture = BrickHTML.childNodes[i];
				if (typeof maxFuture !== "undefined") {
					maxFuture = maxFuture.innerText;
				} else {
					maxFuture = "";
				}
			}
			else if(childId == "hidden_description_type") {
				var hidden_description_type_ELEMENT = BrickHTML.childNodes[i];
			}
						
			else if(childId == "description_div") {
				var description_div_ELEMENT = BrickHTML.childNodes[i];
			}
			else if(childId == "wizardhelp") {
				var wizardhelp_div_ELEMENT = BrickHTML.childNodes[i];
			}		
		}
	}
	
	//call functions to generate html using brick values and set the returned html to the correct innerHTML
	var errormessage = createErrorMesasge(question_ELEMENT.innerText);
	errormessage += " " + getErrorMessageByErrorType(type_answers_ELEMENT.innerText, mlELEMENT.innerText, minELEMENT.innerText, maxELEMENT.innerText);
	hideQuestionmarkIfNoDescription(wizardhelp_div_ELEMENT);
	answerbox_ELEMENT.innerHTML = setAnswerBox(counterid,hidden_width_ELEMENT.innerText, hidden_height_ELEMENT.innerText, type_answers_ELEMENT.innerText, errorEl, errormessage, maxELEMENT.innerText, minELEMENT.innerText, mlELEMENT.innerText, minPast, maxPast, minFuture, maxFuture);
	mandatory_question_ELEMENT.innerHTML = setMandatoryIndicator(hidden_mandatory_question_ELEMENT.innerText);
	var questionNumber = setQuestionNumber(brickid);
	question_number_ELEMENT.innerHTML = questionNumber;
	if(questionNumber != ""){
		question_number_ELEMENT.style.display = "block";
	}
	arrangeDescription(description_div_ELEMENT, hidden_description_type_ELEMENT.innerText);
	
}

function getErrorMessageByErrorType(validation, maxText, minNummeric, maxNummeric) {
	var errorMessage = "";
	
	if (validation == "Text" && typeof maxText != "undefined" && maxText != "") {
		errorMessage = "De waarde mag niet langer zijn dan " + maxText + " karakters.";
	} else if (validation == "Nummeric") {
		if (typeof minNummeric != "undefined" && minNummeric != "" &&
			typeof maxNummeric != "undefined" && maxNummeric != "") {
			errorMessage = "De waarde dient tussen de waarden " + minNummeric + " en " + maxNummeric + " te liggen.";
		} else if (typeof minNummeric != "undefined" && minNummeric != "") {
			errorMessage = "De waarde dient groter te zijn dan " + minNummeric + ".";
		} else if (typeof maxNummeric != "undefined" && maxNummeric != "") {
			errorMessage = "De waarde dient kleiner te zijn dan " + maxNummeric + ".";
		}
	}
	
	return errorMessage;
}

/**
 * Function: renderAutoAanvullenVeldBrick
 *     Generates the html for a auto complete field brick
 * 
 * Parameters:
 *     BrickHTML - HTML element of the field brick
 *     counterid - the brick id
 *     errorEl - the html element of the error related to the question
 *
 * Returns:
 *     nothing
 */
function renderAutoAanvullenVeldBrick(BrickHTML, counterid, errorEl){
	if(typeof errorEl == "undefined"){
		errorEl = false;
	}
	//For every child in the bricks html...
	for(var i = 0; i< BrickHTML.childNodes.length; i++){
		if(typeof BrickHTML.childNodes[i].id !== "undefined"){
			//get the brickvalues we need
			var childId = BrickHTML.childNodes[i].id;
			if(childId == "hidden_mandatory_question") {
				var hidden_mandatory_question_ELEMENT = BrickHTML.childNodes[i];
			}
			if(childId == "question") {
				var question_ELEMENT = BrickHTML.childNodes[i];
			}
			else if(childId == "answerbox") {
				var answerbox_ELEMENT = BrickHTML.childNodes[i];
			}
			else if(childId == "hidden_width") {
				var hidden_width_ELEMENT = BrickHTML.childNodes[i];
			}
			else if(childId == "hidden_height") {
				var hidden_height_ELEMENT = BrickHTML.childNodes[i];
			}
			else if(childId == "display_answers") {
				var display_answers_ELEMENT = BrickHTML.childNodes[i];
			}
			else if(childId == "mandatory_question") {
				var mandatory_question_ELEMENT = BrickHTML.childNodes[i];
			}
			else if(childId == "hidden_questionnumber") {
				var hidden_questionnumber_ELEMENT = BrickHTML.childNodes[i];
			}
			else if(childId == "question_number") {
				var question_number_ELEMENT = BrickHTML.childNodes[i];
			}
			else if(childId == "hidden_displaynumber") {
				var hidden_displaynumber_ELEMENT = BrickHTML.childNodes[i];
			}
			else if(childId == "type_answers") {
				var type_answers_ELEMENT = BrickHTML.childNodes[i];
			}
			else if(childId == "brick_type") {
				var brickid = BrickHTML.childNodes[i].getAttribute('brickid');
			}
			else if(childId == "hidden_max") {
				var maxELEMENT = BrickHTML.childNodes[i];
			}
			else if(childId == "hidden_min") {
				var minELEMENT = BrickHTML.childNodes[i];
			}
				else if(childId == "hidden_maxLength") {
				var mlELEMENT = BrickHTML.childNodes[i];
			}
			else if(childId == "hidden_description_type") {
				var hidden_description_type_ELEMENT = BrickHTML.childNodes[i];
			}
			else if(childId == "resultatenurl") {
				var resultaten_URL = BrickHTML.childNodes[i];
			}
						
			else if(childId == "description_div") {
				var description_div_ELEMENT = BrickHTML.childNodes[i];
			}
		}
	}
	//call functions to generate html using brick values and set the returned html to the correct innerHTML
	var errormessage = createErrorMesasge(question_ELEMENT.innerText);
	answerbox_ELEMENT.innerHTML = setAnswerBoxAutoAanvullen(counterid,hidden_width_ELEMENT.innerText, hidden_height_ELEMENT.innerText, type_answers_ELEMENT.innerText, errorEl, errormessage, maxELEMENT.innerText, minELEMENT.innerText, mlELEMENT.innerText);
	mandatory_question_ELEMENT.innerHTML = setMandatoryIndicator(hidden_mandatory_question_ELEMENT.innerText);
	var questionNumber = setQuestionNumber(brickid);
	question_number_ELEMENT.innerHTML = questionNumber;
	if(questionNumber != ""){
		question_number_ELEMENT.style.display = "block";
	}
	arrangeDescription(description_div_ELEMENT, hidden_description_type_ELEMENT.innerText);
    
    if (typeof resultaten_URL !== "undefined") {
        if (typeof init_list!='undefined') init_list(resultaten_URL.innerText);
    }
}

/**
 * Function: createErrorMesasge
 *     Generates the error text from the question text
 * 
 * Parameters:
 *     questionText - text of the question
 *
 * Returns:
 *     generated error text
 */
function createErrorMesasge(questionText){
	return("U heeft een verkeerd antwoord op de vraag '"+questionText+"' gegeven.");
}

//AP: Dont think is used anymore!
//function generateClosedAnswerHTML(arr, bouwsteenId){	
//	var htmlValue = reallyGenerateClosedAnswerHTML(arr['4:::brickvalue'], arr['3:::brickvalue'], arr['7:::brickvalue'],arr['9:::brickvalue'], arr['5:::brickvalue'], bouwsteenId);
//	return htmlValue;
//}

/**
 * Function: reallyGenerateSemanticdiffTableHTML
 *     Generates the table HTMl of a semantic differential question brick
 * 
 * Parameters:
 *     colnos - number of columns needed (not the total in the table, but the number of options for the user)
 *     rowstring - string containing each rows's text, joined together with a text seperator.
 *     showSubQNumbers - boolean set to true if sub numbering is required
 *     header - string containing each column's text (the top row), joined together with a text seperator.
 *     id - the brick id
 *
 * Returns:
 *     generated error text
 */
function reallyGenerateSemanticdiffTableHTML(colnos, rowstring, showSubQNumbers, header, id){
	
	//set a boolean for is we need to show the sub question numbers or not
	//(they are an extra column in the table numbered for each subitem in the table
	if(showSubQNumbers == "ja"){
		showSubQNumbers = true;
	}
	else{
		showSubQNumbers = false;
	}
	
	//split the values up to get values for each row
	var rowArray = rowstring.split("#####");
	//always goes in a table
	var htmlValue = "<table class=\"grid_table\">";
	
	//If we need to show a header column...
	if(header != "nee"){
		//start the column
		htmlValue = htmlValue +"<tr >";
		//if the sub numbers are needed, add an extra blank row
		if(showSubQNumbers){
			htmlValue = htmlValue +"<td>&nbsp;</td>";
		}
		//add another blank row
		htmlValue = htmlValue +"<td>&nbsp;</td>";
		//for each column...
		for(var j = 0; j < colnos; j++){
			//find the type of header needed and select value.
			if(header == "ja: 1 t/m x"){
				htmlValue = htmlValue +"<td class=\"tablecoltext\">"+(j+1)+"</td>";
			}
			else if(header == "ja: -x t/m -1"){
				htmlValue = htmlValue +"<td class=\"tablecoltext\">"+(j - colnos)+"</td>";
			}
			else if(header == "ja: -x t/m 0 t/m x"){
				htmlValue = htmlValue +"<td class=\"tablecoltext\">"+getheaderval(colnos, j, true)+"</td>";
			}
			else if(header == "ja: x t/m 0 t/m x"){
				htmlValue = htmlValue +"<td class=\"tablecoltext\">"+getheaderval(colnos, j, false)+"</td>";
			}		
		}
		htmlValue = htmlValue +"<td>&nbsp;</td></tr>";
	}
	//For every subitem that needs to be in the table...
	for(var j = 0; j < rowArray.length; j++){
		//split the text value into its two seperate parts (right and left)
		splitstell = rowArray[j].split("|||||");
		//create html
		htmlValue = htmlValue +"<tr>";
		if(showSubQNumbers){
			htmlValue = htmlValue +"<td class=\"subindex\">"+(j+1)+"&nbsp;&nbsp;</td>";
		}
		htmlValue = htmlValue +"<td class=\"tablerowtext\">"+splitstell[0]+"</td>";
		for(x=0; x<colnos; x++){
			var val = "";
			if(typeof givenAnswers !== "undefined"){
				if(typeof givenAnswers[id] !== "undefined"){
					if(typeof givenAnswers[id][rowArray[j]] !== "undefined"){
						if(givenAnswers[id][rowArray[j]] == x){
							val = " checked=true ";
						}
					}
				}
			}
			if(inAdmin == true){
				htmlValue = htmlValue +"<td class=\"tableradio\"><input subitemtext=\""+rowArray[j]+"\" brickid=\""+id+"\" type=\"radio\" name=\""+rowArray[j]+"_"+id+"\" value=\""+x+"\" "+val+"></td>";
			}
			else{
				htmlValue = htmlValue +"<td class=\"tableradio\"><input onclick=\"answeredQuestion(this);\" subitemtext=\""+rowArray[j]+"\" brickid=\""+id+"\" type=\"radio\" name=\""+rowArray[j]+"_"+id+"\" value=\""+x+"\" "+val+"></td>";
			}
		}
		htmlValue = htmlValue +"<td class=\"tablerowtext\">"+splitstell[1]+"</td>";
		
		htmlValue = htmlValue +"</tr>";
	}
	return htmlValue+" </table>";
}

/**
 * Function: getheaderval
 *     Gets the value used in the semantichedifferentiaal question type
 * 
 * Parameters:
 *     total - number of columns needed (not the total in the table, but the number of options for the user)
 *     val -
 *     neg -
 *
 * Returns:
 *     the header value
 */

function getheaderval(total, val, neg){
	 var halftotal = Math.floor(total/2);
	 
	 var retval = val - halftotal;
	 
	if(halftotal == Math.round(total/2)){
		if(retval > -1){
			retval++;
		}
	}
	
	if(!neg){
		retval = Math.abs(retval);
	}
	
	return(retval);
	
}

/**
 * Function: reallyGenerateLikerschaalTableHTML
 *     Generates the table HTMl of a likerschaal question brick
 * 
 * Parameters:
 *     colnos - number of columns needed (not the total in the table, but the number of options for the user)
 *     rowstring - string containing each rows's text, joined together with a text seperator.
 *     showSubQNumbers - boolean set to true if sub numbering is required
 *     id - the brick id
 *
 * Returns:
 *     nothing
 */
function reallyGenerateLikerschaalTableHTML(columnstring, rowstring, showSubQNumbers, id){
	
	if (typeof reallyGenerateLikerschaalTableAssurantiebouwstenenHTML == "function") {
		return reallyGenerateLikerschaalTableAssurantiebouwstenenHTML(columnstring, rowstring, showSubQNumbers, id);
	}
	
	if(showSubQNumbers == "ja"){
		showSubQNumbers = true;
	}
	else{
		showSubQNumbers = false;
	}
	//split strings into arrays
	var colArray = columnstring.split("#####");
	var rowArray = rowstring.split("#####");
	//starting html
	var htmlValue = "<table class=\"grid_table\"><tr><td>&nbsp;</td>";
	//if we need show the sub numbering, add a column with the row number
	if(showSubQNumbers){
			htmlValue = htmlValue +"<td>&nbsp;</td>";
		}
	//add the headers 
	for(var i = 0; i < colArray.length; i++){
		htmlValue = htmlValue +"<td style=\"vertical-align:top; width:200px\" class=\"tablecoltext\" id=\""+colArray[i]+"_"+id+"\">";
		htmlValue = htmlValue +"<div class=\"tablecoldiv\">"+colArray[i]+"</div></td>";
	}
	htmlValue = htmlValue + "</tr>";
	//make the table, row by row
	for(var j = 0; j < rowArray.length; j++){
		htmlValue = htmlValue +"<tr>";
		if(showSubQNumbers){
			htmlValue = htmlValue +"<td class=\"subindex\" style=\"float:left; vertical-align:top;\">"+(j+1)+"&nbsp;&nbsp;</td>";
		}
		
		htmlValue = htmlValue +"<td style=\"vertical-align:top; width:200px\" class=\"tablerowtext\">"+rowArray[j]+"&nbsp;&nbsp;</td>";
		for(x=0; x<i; x++){
			var val = "";
			if(typeof givenAnswers !== "undefined"){
				if(typeof givenAnswers[id] !== "undefined"){
					if(typeof givenAnswers[id][rowArray[j]] !== "undefined"){
						if(givenAnswers[id][rowArray[j]] == colArray[x]){
							val = " checked=true ";
						}
					}
				}
			}
			if(inAdmin == true){
				htmlValue = htmlValue +"<td class=\"tableradio\"><input subitemtext=\""+rowArray[j]+"\" value=\""+colArray[x]+"\" type=\"radio\" brickid=\""+id+"\" name=\""+rowArray[j]+"_"+id+"\" "+val+"></td>";
			}
			else{
				htmlValue = htmlValue +"<td class=\"tableradio\"><input onclick=\"answeredQuestion(this);\" subitemtext=\""+rowArray[j]+"\" value=\""+colArray[x]+"\" type=\"radio\" brickid=\""+id+"\" name=\""+rowArray[j]+"_"+id+"\" "+val+"></td>";
			}
		}
		htmlValue = htmlValue +"</tr>";
	}
	return htmlValue+" </table>";
}

/**
 * Function: reallyGenerateCombiLikerschaalTableHTML
 *     Generates the table HTMl of a combilikerschaal question brick
 * 
 * Parameters:
 *     colnos - number of columns needed (not the total in the table, but the number of options for the user)
 *     rowstring - string containing each rows's text, joined together with a text seperator.
 *     showSubQNumbers - boolean set to true if sub numbering is required
 *     id - the brick id
 *
 * Returns:
 *     nothing
 */
function reallyGenerateCombiLikerschaalTableHTML(columnstring, toonDetailstring, detailColumnstring, rowstring, rowExtrastring, showSubQNumbers, id){
	
	if(showSubQNumbers == "ja"){
		showSubQNumbers = true;
	}
	else{
		showSubQNumbers = false;
	}
	//split strings into arrays
	var colArray        = columnstring.split("#####");
	var toonDetailArray = toonDetailstring.split("#####");
	var detailColArray  = detailColumnstring.split("#####");
	var rowArray        = rowstring.split("#####");
	var rowExtraArray   = rowExtrastring.split("#####");
	//starting html
	var htmlValue = "<table class=\"grid_table\"><tr><td>&nbsp;</td>";/*extra stelling tekst wordt niet getoond omdat dit teveel ruimte kost<td>&nbsp;</td>";*/
	//if we need show the sub numbering, add a column with the row number
	if(showSubQNumbers){
			htmlValue = htmlValue +"<td>&nbsp;</td>";
		}
	//add the headers 
	for(var i = 0; i < colArray.length; i++){
		
		htmlValue = htmlValue +"<td style=\"vertical-align:top; width:200px\" class=\"tablecoltext\" id=\""+colArray[i]+"_"+id+"\">";
				htmlValue = htmlValue +colArray[i]+"</td>";
	}
	
	var index = i;
	
	//add the detail headers 
	for(var i = 0; i < detailColArray.length; i++){
		
		htmlValue = htmlValue +"<td style=\"vertical-align:top; width:200px\" class=\"tablecoltext\" id=\""+detailColArray[i]+"_"+id+"\">";
		htmlValue = htmlValue +detailColArray[i]+"</td>";
	}
	
	index += i;
	
	htmlValue = htmlValue + "</tr>";
	//make the table, row by row
	for(var j = 0; j < rowArray.length; j++){
		var toonDetails = false;
		
		htmlValue = htmlValue +"<tr>";
		if(showSubQNumbers){
			htmlValue = htmlValue +"<td class=\"subindex\" style=\"float:left; vertical-align:top;\">"+(j+1)+"&nbsp;&nbsp;</td>";
		}
		
		htmlValue = htmlValue +"<td class=\"tablerowtext\" style=\"float:left; vertical-align:top; width:200px\">"+rowArray[j]+"&nbsp;&nbsp;</td>";
		//extra stelling tekst wordt niet getoond omdat dit teveel ruimte kost
		//htmlValue = htmlValue +"<td class=\"tablerowtext\" style=\"float:left; vertical-align:top; width:100\">"+rowExtraArray[j]+"&nbsp;&nbsp;</td>";
		for(x=0; x<index; x++){
			var val = "";
			if(typeof givenAnswers !== "undefined"){
				if(typeof givenAnswers[id] !== "undefined"){
					if(typeof givenAnswers[id][rowArray[j]] !== "undefined"){
						var answerArr = givenAnswers[id][rowArray[j]].split("#####");
						if(x < colArray.length && answerArr[1] == colArray[x]){
							val = " checked=true ";
							
							if(toonDetailArray[x] == "ja") {
								toonDetails = true;
								colArray[x] = "=====" + colArray[x];
							}
						}
						else if(x >= colArray.length && typeof answerArr[3] != "undefined" && answerArr[3] == detailColArray[x-colArray.length]){
							val = " checked=true ";
						}
					}
				}
			}
			if(inAdmin == true){
				if(x < colArray.length ) {
					htmlValue = htmlValue +"<td class=\"tableradio\"><input subitemtext=\""+rowArray[j]+"\" value=\""+x+"#####"+colArray[x]+"\" type=\"radio\" brickid=\""+id+"\" name=\""+rowArray[j]+"_"+id+"\" "+val+"></td>";
				}
				else {
					if(toonDetails) {
						htmlValue = htmlValue +"<td class=\"tableradio\"><input subitemtext=\""+rowArray[j]+"\" value=\""+x+"#####"+detailColArray[x-colArray.length]+"\" type=\"radio\" brickid=\""+id+"\" name=\"#####"+rowArray[j]+"_"+id+"\" "+val+"></td>";
					}
					else {
						htmlValue = htmlValue +"<td class=\"tableradio\">&nbsp;</td>";
					}
				}
			}
			else{
				if(x < colArray.length ) {
					htmlValue = htmlValue +"<td class=\"tableradio\"><input title=\""+colArray[x].replace("=====","")+"\" onclick=\"answeredQuestion(this,false,"+(j+1)+");renderQuestionBricks();\" subitemtext=\""+rowArray[j]+"\" value=\""+x+"#####"+colArray[x]+"\" type=\"radio\" brickid=\""+id+"\" name=\""+rowArray[j]+"_"+id+"\" "+val+"></td>";
				}
				else {
					if(toonDetails) {
						htmlValue = htmlValue +"<td class=\"tableradio\"><input title=\""+detailColArray[x-colArray.length]+"\" onclick=\"answeredQuestion(this,false,"+(j+1)+");renderQuestionBricks();\" subitemtext=\""+rowArray[j]+"\" value=\""+x+"#####"+detailColArray[x-colArray.length]+"\" type=\"radio\" brickid=\""+id+"\" name=\"#####"+rowArray[j]+"_"+id+"\" "+val+"></td>";
					}
					else {
						htmlValue = htmlValue +"<td class=\"tableradio\">&nbsp;</td>";
					}
				}
			}
		}
			
		for(var colIndex=0; colIndex<colArray.length; colIndex++) {
			if(colArray[colIndex].substring(0, 5) == "=====") {
				colArray[colIndex] = colArray[colIndex].substring(5, colArray[colIndex].length);
			}
		}
			
		htmlValue = htmlValue +"</tr>";
	}
	return htmlValue+" </table>";
}

/**
 * Generates the HTML of the closed question brick.
 *
 * @param	answerstring	A string of the possible answers, seperated by a text seperator.
 * @param	answertype		If its a dropdown/radio button/check box closed question.
 * @param	answerdirection	If the possible answers should be listed next to each other in one 
 *							row, or one under each other in a list.
 * @param	openquestions	If any of the possible answers need an open text as extra.
 * @param	gotos			List of questions which need to be shown when a particular answer is 
 *							selected.
 * @param	values			List of values (instead of display text).
 * @param	bouwsteenId		brick id...
 * @param	errorEl			HTML error element for this questions errors to be displayed.
 * @param	errormessage	The message to be displayed if the question is answered incorrectly.
 * @param	selectedGroups	All the selected groups (seperated by answer) wich are needed to 
 *							determine (compared to the groups of the logged in user) wich 
 *							answers are shown.
 *
 * @return	The generated HTML.
 */
function reallyGenerateClosedAnswerHTML(answerstring, answertype, answerdirection, openquestions, gotos, values, bouwsteenId, errorEl, errormessage, selectedGroups){
	//alert("in reallyGenerateClosedAnswerHTML");
	var answerArray = answerstring.split("#####");
	var openArray = openquestions.split("#####");
	var valArray = values.split("#####");
	var groupsArray = new Object();
	
	if (typeof selectedGroups != "undefined") {
		groupsArray = selectedGroups.innerHTML.split("=====");
	}
	
	var gotosArray = gotos.split("#####");
	
	var htmlValue = "<table class=\"question_table\">";
		
	var disabled = "";
	if (typeof readonlyBricks !== "undefined" && typeof readonlyBricks[bouwsteenId] !== "undefined") {
		disabled = " disabled=\"true\" ";
	}

	//if(bouwsteenId==566) alert('IN reallyGenerateClosedAnswerHTML');
	//Dropdown....
	if(answertype == "lijstweergave"){
		if(inAdmin == true){
			htmlValue = htmlValue+"<tr class=\"possible_answer\"><td><select brickid=\""+bouwsteenId+"\" id=\""+bouwsteenId+"\"><option value=\"\"></option>";
		}
		else{
			htmlValue = htmlValue+"<tr class=\"possible_answer\"><td><select "+disabled+" onchange=\"answeredQuestion(this);\" brickid=\""+bouwsteenId+"\" id=\""+bouwsteenId+"\"><option value=\"\"></option>";
		}
		for(var i = 0; i < answerArray.length; i++){
			// If the admin environment (CMS) is not loaded and there are groups defined for this 
			// answer and there is no group logged in, then the answer is not shown.
			if (inAdmin == false && 
					typeof groupsArray[i] != "undefined" && 
					groupsArray[i] != "" && 
					!isGroupLoggedIn(groupsArray[i])) {
				continue;
			}
			
			var val = "";
			if(typeof givenAnswers !== "undefined"){
				if(typeof givenAnswers[bouwsteenId] !== "undefined"){
					if(typeof givenAnswers[bouwsteenId][answerArray[i]] !== "undefined" || typeof givenAnswers[bouwsteenId][ valArray[i]] !== "undefined"){
						val = " selected=true ";
					}
				}
			}
			htmlValue = htmlValue+"<option subitemtext=\""+answerArray[i]+"\"  value=\""+answerArray[i]+"\" "+val+">"+answerArray[i]+"</option>";
		}
		htmlValue = htmlValue+"</select></td></tr>";
	}
	else{
	
		if(answertype == "meerdere antwoorden"){
			answertype = "checkbox";
			if(inAdmin == true){
				answerevent = "";
			}
			else{
				answerevent = "onclick=\"answeredQuestion(this);\"";
			}
		}
		else{
			answertype = "radio";
			if(inAdmin == true){
				answerevent = "";
			}
			else{
				if(openquestions.indexOf("ja")> -1){
					answerevent = "onclick=\"disableTextFields(this);answeredQuestion(this);\"";
				}
				else{
					answerevent = "onclick=\"answeredQuestion(this);\"";
				}
			}
		}
		for(var i = 0; i < answerArray.length; i++){
			// If the admin environment (CMS) is not loaded and there are groups defined for this 
			// answer and there is no group logged in, then the answer is not shown.
			if (inAdmin == false && 
					typeof groupsArray[i] != "undefined" && 
					groupsArray[i] != "" && 
					!isGroupLoggedIn(groupsArray[i])) {
				continue;
			}
			
			var val = "";
				var openval = "";
				if(typeof givenAnswers !== "undefined"){
				//if(bouwsteenId == 432){alert("givvans");}
					if(typeof givenAnswers[bouwsteenId] !== "undefined"){
						if(typeof givenAnswers[bouwsteenId][answerArray[i]] !== "undefined"){
							val = " checked=true ";
							openval = givenAnswers[bouwsteenId][answerArray[i]];
						}
					}
				}
			if(answerdirection == "horizontale"){
				if(i == 0){
					htmlValue = htmlValue+"<tr class=\"possible_answer\">";
				}
				
				if(typeof openArray[i] == "undefined" || openArray[i] == "nee"){
					htmlValue = htmlValue+"<td><input subitemtext=\""+answerArray[i]+"\" brickid=\""+bouwsteenId+"\" type=\""+answertype+"\" "+answerevent+" value=\""+answerArray[i]+"\" name=\""+bouwsteenId+"\" "+val+"></td><td>"+answerArray[i]+"</td>";
				}
				else{
					if(inAdmin == true){
						htmlValue = htmlValue+"<td><input subitemtext=\""+answerArray[i]+"\" brickid=\""+bouwsteenId+"\" type=\""+answertype+"\" "+answerevent+" value=\""+answerArray[i]+"\" name=\""+bouwsteenId+"\" "+val+"></td><td>"+answerArray[i]+"</td><td><input subitemtext=\""+answerArray[i]+"\" brickid=\""+bouwsteenId+"\" type=\"text\" class=\"subopenquestion\" id=\"openanswer"+i+"\" value=\""+openval+"\"></td>";
					}
					else{
						htmlValue = htmlValue+"<td></td><td><input subitemtext=\""+answerArray[i]+"\" brickid=\""+bouwsteenId+"\" type=\""+answertype+"\" onclick=\"answeredQuestion(this);enableTextBox(this);\" value=\""+answerArray[i]+"\" name=\""+bouwsteenId+"\" "+val+"></td><td>"+answerArray[i]+"</td><td><input disabled = true onblur=\"answeredQuestion(this);\" onkeyup=\"doneKeyUp(this);\" subitemtext=\""+answerArray[i]+"\" brickid=\""+bouwsteenId+"\" type=\"text\" class=\"subopenquestion\" id=\"openanswer"+i+"\" value=\""+openval+"\"></td>";
					}
				}
				if(i == answerArray.length-1){
					htmlValue = htmlValue+"</tr>";
				}
			}
			else {
				if(typeof openArray[i] == "undefined" || openArray[i] == "nee"){
					htmlValue = htmlValue+"<tr class=\"possible_answer\"><td><input subitemtext=\""+answerArray[i]+"\" brickid=\""+bouwsteenId+"\" type=\""+answertype+"\" "+answerevent+"value=\""+answerArray[i]+"\" name=\""+bouwsteenId+"\" "+val+"></td><td>"+answerArray[i]+"</td></tr>";
				}
				else{
					if(inAdmin == true){
						htmlValue = htmlValue+"<tr class=\"possible_answer\"><td><input subitemtext=\""+answerArray[i]+"\" brickid=\""+bouwsteenId+"\" type=\""+answertype+"\" "+answerevent+" value=\""+answerArray[i]+"\" name=\""+bouwsteenId+"\" "+val+"><td>"+answerArray[i]+"</td><td><input subitemtext=\""+answerArray[i]+"\" brickid=\""+bouwsteenId+"\" class=\"subopenquestion\" type=\"text\" id=\"openanswer"+i+"\" value=\""+openval+"\"></td></tr>";
					}
					else{
						htmlValue = htmlValue+"<tr class=\"possible_answer\"><td><input subitemtext=\""+answerArray[i]+"\" brickid=\""+bouwsteenId+"\" type=\""+answertype+"\" onclick=\"answeredQuestion(this);enableTextBox(this);\" value=\""+answerArray[i]+"\" name=\""+bouwsteenId+"\" "+val+"><td>"+answerArray[i]+"</td><td><input  disabled = true onblur=\"answeredQuestion(this);\" onkeyup=\"doneKeyUp(this);\" subitemtext=\""+answerArray[i]+"\" brickid=\""+bouwsteenId+"\" class=\"subopenquestion\" type=\"text\" id=\"openanswer"+i+"\" value=\""+openval+"\"></td></tr>";
					}
				}
			}
		}
	}
	return htmlValue+" </table>";
}

/**
 * Function: reallyGeneratePercentQuestionHTML
 *     Generates the thtml of the procentuele question brick
 * 
 * Parameters:
 *     answerstring - a string of the possible answers, seperated by a text seperator
 *     answertype - if its a dropdown/radio button/check box closed question
 *     answerdirection - if the possible answers should be listed next to each other in one row, or one under each other in a list
 *     openquestions - if any of the possible answers need an open text as extra
 *     gotos - list of questions which need to be shown when a particular answer is selected
 *     values - list of values (instead of display text)
 *     bouwsteenId - brick id
 *     errorEl - html error element for this questions errors to be displayed
 *     errormessage - the message to be displayed if the question is answered incorrectly
 *
 * Returns:
 *     nothing
 */
function reallyGeneratePercentQuestionHTML(answerstring, answertype, answerdirection, openquestions, gotos, values, bouwsteenId, errorEl, errormessage){
	var answerArray = answerstring.split("#####");
	var openArray = openquestions.split("#####");
	var valArray = values.split("#####");
	
	var gotosArray = gotos.split("#####");
	var htmlValue = "<table class=\"question_table\">";
	answertype = "text";
	
	answerevent = inAdmin ? '' : "onclick=\"answeredQuestion(this);\" onfocus=\"__checkPercentage.focus(arguments[0])\"";

		
	for(var i = 0; i < answerArray.length; i++){
		
		var val = '';

		if(typeof givenAnswers !== "undefined")
			if(typeof givenAnswers[bouwsteenId] !== "undefined")
				if(typeof givenAnswers[bouwsteenId][answerArray[i]] !== "undefined")
					val = givenAnswers[bouwsteenId][answerArray[i]];
					
		
		if (answerdirection == "horizontale") {
			if (i == 0)
				htmlValue = htmlValue+"<tr class=\"possible_answer\">";
			
			htmlValue = htmlValue + "<td>"+answerArray[i]+"</td><td><input class=\"percentageInputField\" subitemtext=\""+answerArray[i]+"\" brickid=\""+bouwsteenId+"\" type=\""+answertype+"\" "+answerevent+"value=\""+val+"\" name=\""+bouwsteenId+"\" "+val+" onkeydown=\"__checkPercentage.keydown(arguments[0]);\"></td><td>%&nbsp;&nbsp;</td>";

			if(i == answerArray.length-1)
				htmlValue = htmlValue+"</tr>";
			
		}
		else {
			htmlValue = htmlValue + "<tr class=\"possible_answer\"><td>"+answerArray[i]+"</td><td><input style=\"width:50px;\" subitemtext=\""+answerArray[i]+"\" brickid=\""+bouwsteenId+"\" type=\""+answertype+"\" "+answerevent+"value=\""+val+"\" name=\""+bouwsteenId+"\" "+val+" onkeydown=\"__checkPercentage.keydown(arguments[0]);\"></td><td>%</td></tr>";
		}
	}

	return htmlValue+" </table>";
}

/**
 * Function: reallyGenerateTabelVraagTableHTML
 *     Generates the table HTMl of a tabel vraag question brick
 * 
 * Parameters:
 *     colnos - number of columns needed (not the total in the table, but the number of options for the user)
 *     typestring - string containing each rows's type, joined together with a text seperator.
 *     defaultstring - string containing each rows's default value, joined together with a text seperator.
 *     showSubQNumbers - boolean set to true if sub numbering is required
 *     id - the brick id
 *
 * Returns:
 *     nothing
 */
function reallyGenerateTabelVraagTableHTML(columnstring, typestring, defaultstring, showSubQNumbers, id, defaultNumberOfRows, maximumNumberOfRows){
	if (showSubQNumbers == "ja") {
		showSubQNumbers = true;
	} else {
		showSubQNumbers = false;
	}
	//split strings into arrays
	var colArray = columnstring.split("#####");
	var typeArray = typestring.split("#####");
	var defaultArray = defaultstring.split("#####");
	//starting html
	var htmlValue = "<table class=\"grid_table\"><tr>";
	//if we need show the sub numbering, add a column with the row number
	if (showSubQNumbers) {
		htmlValue = htmlValue +"<td>&nbsp;</td>";
	}
	//add the headers 
	for (var i = 0; i < colArray.length; i++) {
		htmlValue = htmlValue +"<td style=\"vertical-align:top\" class=\"tablecoltext\" id=\""+colArray[i]+"_"+id+"\">";
		htmlValue = htmlValue +"<div class=\"tablecoldiv\">"+colArray[i]+"</div></td>";
	}
	if (colArray.length > 0) {
		htmlValue = htmlValue +"<td style=\"vertical-align:top\" class=\"tablecoltext\" id=\"addTableVraagRow\">";
		htmlValue = htmlValue +"<div class=\"addTableVraagRow\" onclick=\"addTableVraagRow("+id+")\">+</div></td>";
	}
	htmlValue = htmlValue + "</tr>";
	
	if (typeof givenAnswers == "undefined") {
		givenAnswers = new Object();
	}
	
	if (typeof givenAnswers[id] == "undefined") {
		givenAnswers[id] = new Object();
		
		
		var subkey = "";
		
		if(typeof defaultNumberOfRows != "undefined" && !isNaN(defaultNumberOfRows)){
			//alert("test");
			for(var rowNumber = 1; rowNumber < defaultNumberOfRows; rowNumber++){
				subkey += "-----";
			}
		}
		var key = subkey;
		
		for (var colKey = 1; colKey < colArray.length; colKey++) {
			key += "====" + subkey;
		}

		givenAnswers[id][key] = "";
	}
	
	var answerArray = new Object();
	
	// First, split up the columns.
	for (givenAnswerKey in givenAnswers[id]) {
		answerArray = givenAnswerKey.split("====");
	}
	
	// Second, split the rows from each column.
	for (answerKey in answerArray) {
		var rows = answerArray[answerKey].split("-----");
		
		answerArray[answerKey] = rows;
	}
	
	// If there are no answers available, then set the default row.
	/*if (typeof answerArray.length === "undefined" || answerArray.length == 0) {
		for (defaultKey in defaultArray) {
			columnArray = defaultArray[defaultKey].split("#####");
			
			answerArray[defaultKey] = columnArray;
		}
	}*/
	
	//make the table, row by row
	for (var j = 0; j < answerArray[0].length; j++) {
		htmlValue = htmlValue +"<tr>";
		if (showSubQNumbers) {
			htmlValue = htmlValue +"<td class=\"subindex\" style=\"float:left; vertical-align:top;\">"+(j+1)+"&nbsp;&nbsp;</td>";
		}
		
		for (x=0; x<colArray.length; x++) {
			var val = "";
			
			if (typeof answerArray !== "undefined" && 
					typeof answerArray[x] !== "undefined" && 
					typeof answerArray[x][j] !== "undefined") {
				if (typeArray[x] == "radiobutton" || typeArray[x] == "checkbox") {
					if (answerArray[x][j] == "on") {
						val = " checked=true ";
					} else {
						val = "";
					}
				} else {
					val = " value=\"" + answerArray[x][j] + "\" ";
				}
			}
			
			if (inAdmin == true) {
				if (typeArray[x] == "radiobutton") {
					htmlValue = htmlValue +"<td class=\"tableradio\"><input style=\"width:100%\" subitemtext=\""+j+"\" value=\""+colArray[x]+"\" type=\"radio\" brickid=\""+id+"\" name=\""+x+"_"+id+"\" "+val+"></td>";
				} else if (typeArray[x] == "checkbox") {
					htmlValue = htmlValue +"<td class=\"tablecheckbox\"><input style=\"width:100%\" subitemtext=\""+j+"\" value=\""+colArray[x]+"\" type=\"checkbox\" brickid=\""+id+"\" name=\""+x+"_"+id+"\" "+val+"></td>";
				} else if (typeArray[x] == "openvraag") {
					htmlValue = htmlValue +"<td class=\"tableopen\"><input style=\"width:100%\" subitemtext=\""+j+"\" value=\""+defaultArray[x]+"\" type=\"input\" brickid=\""+id+"\" name=\""+x+"_"+id+"\" "+val+"></td>";
				}
			} else {
				if (typeArray[x] == "radiobutton") {
					htmlValue = htmlValue +"<td class=\"tableradio\"><input style=\"width:100%\" onclick=\"answeredQuestion(this);\" subitemtext=\""+j+"\" type=\"radio\" brickid=\""+id+"\" name=\""+x+"_"+id+"\" surveytype=\"tabelvraag\" "+val+"></td>";
				} else if (typeArray[x] == "checkbox") {
					htmlValue = htmlValue +"<td class=\"tablecheckbox\"><input style=\"width:100%\" onclick=\"answeredQuestion(this);\" subitemtext=\""+j+"\" type=\"checkbox\" brickid=\""+id+"\" name=\""+x+"_"+id+"\" surveytype=\"tabelvraag\" "+val+"></td>";
				} else if (typeArray[x] == "openvraag") {
					htmlValue = htmlValue +"<td class=\"tableopen\"><input style=\"width:100%\" onblur=\"answeredOpenQuestion(this);\"subitemtext=\""+j+"\" type=\"input\" brickid=\""+id+"\" name=\""+x+"_"+id+"\" surveytype=\"tabelvraag\" "+val+"></td>";
				}
			}
			
			if (typeArray[x] == "statisch") {
				htmlValue = htmlValue +"<td class=\"tablestatic\"><label subitemtext=\""+j+"\" brickid=\""+id+"\" name=\""+x+"_"+id+"\" "+val+">"+defaultArray[x]+"</label></td>";
			}
		}
		
		// If the current row isn't the first row, then an delete button is added.
		if (j > 0) {
			htmlValue = htmlValue +"<td class=\"tablecoltext\" id=\"removeTableVraagRow\">";
			if(typeof id != "undefined" && id != ""){
				htmlValue = htmlValue +"<div class=\"removeTableVraagRow\" onclick=\"removeTableVraagRow("+id+","+j+")\">-</div></td>";
			}else{
				//in admin
				htmlValue = htmlValue +"<div class=\"removeTableVraagRow\"\">-</div></td>";
			}
		}
		
		htmlValue = htmlValue +"</tr>";
	}
	return htmlValue+" </table>";
}

/**
 * Adds an row to an table vraag bouwsteen. The brickid is needed to determine to wich brick the 
 * row has to be added.
 *
 * @param	brickid	The ID of the brick to wich the row has to be added.
 */
function addTableVraagRow(brickid) {
//alert('IN addTableVraagRow(' + brickid + ')');
	sendAnswerRequest(brickid, "", "-1#####add#####", "", "");
	
	// Add a new row to the givenAnswers array.
	if (typeof givenAnswers != "undefined") {
		var newKey = "";
		
		if (typeof givenAnswers[brickid] == "undefined") {
			givenAnswers[brickid] = new Object();
		}
		
		for (answerKey in givenAnswers[brickid]) {
			var answerArray = answerKey.split("====");
			
			for (rowKey in answerArray) {
				answerArray[rowKey] += "-----";
			}
			
			newKey = answerArray.join("====");
		}
		
		givenAnswers[brickid] = new Object();
		givenAnswers[brickid][newKey] = "";
	}
	
	renderQuestionBricks();
	handleSkips();
	var isPageComplete = checkMandatoryQuestionsOnPage();
	enableNexts(isPageComplete);
}

/**
 * Removes an row from an table vraag bouwsteen. The brickid is needed to determine from wich 
 * brick the row has to be removed.
 *
 * @param	brickid		The ID of the brick from wich the row has to be removed.
 * @param	rowNumber	The row wich has to be removed.
 */
function removeTableVraagRow(brickid, rowNumber) {
//alert('IN removeTableVraagRow(' + brickid + ',' + rowNumber + ')');
	sendAnswerRequest(brickid, "", (-rowNumber) + "#####remove#####", "", "");
	
	// Remove the selected row from the givenAnswers array.
	if (typeof givenAnswers != "undefined") {
		if (typeof givenAnswers[brickid] == "undefined") {
			givenAnswers[brickid] = new Object();
		}
		
		var newKey = "";
		
		for (answerKey in givenAnswers[brickid]) {
			var answerArray = answerKey.split("====");
			
			for (newAnswerKey in answerArray) {
				var newAnswerArray = answerArray[newAnswerKey].split("-----");
				
				newAnswerArray.splice(rowNumber,1);
				
				answerArray[newAnswerKey] = newAnswerArray.join("-----");
			}
			
			newKey = answerArray.join("====");
		}
		
		givenAnswers[brickid] = new Object();
		givenAnswers[brickid][newKey] = "";
	}
	
	renderQuestionBricks();
	handleSkips();
	var isPageComplete = checkMandatoryQuestionsOnPage();
	enableNexts(isPageComplete);
}

/**
 * Function: enableTextBox
 *     Enables text fields which are extra to an answer of a closed question because the correct option has been selected
 * 
 * Parameters:
 *     radiobutton - which radio button text field needs enabling
 *
 * Returns:
 *     nothing
 */
function enableTextBox(radiobutton){
	//disable all other text fields of the question
	//because its a radio button closed question and can only have one anser at a time, thus only one text field enabled at a time
	disableTextFields(radiobutton, true);
	if(radiobutton.type == "radio"){
			var textfield = radiobutton.parentNode.nextSibling.nextSibling.childNodes[0];
			textfield.disabled = false;
	}
	else if(radiobutton.type == "checkbox"){
		if(typeof radiobutton.checked != "undefined" && radiobutton.checked == true){
				var textfield = radiobutton.parentNode.nextSibling.nextSibling.childNodes[0];
				textfield.disabled = false;
		}
		else if(typeof radiobutton.checked != "undefined" && radiobutton.checked == false){
				var textfield = radiobutton.parentNode.nextSibling.nextSibling.childNodes[0];
				textfield.disabled = true;
				textfield.value = "";
		}
	}

}

/**
 * Function: disableTextFields
 *     Disables text fields which are extra to an answer of a closed question because the correct option has been selected
 * 
 * Parameters:
 *     radiobutton - which radio button text field needs disabling
 *     goingtoenable - 
 *
 * Returns:
 *     nothing
 */
function disableTextFields(radiobutton, goingtoenable){
	var radioname = radiobutton.name;
	var els = document.getElementsByName(radioname);
	for(var x = 0; x < els.length; x++){
		var radioElement = els[x];
		if(radioElement.tagName == "INPUT" && radioElement.type == "radio" && radioElement.nextSibling != null){
			var nextElement = radiobutton.parentNode.nextSibling.nextSibling.childNodes[0]; 
			if(nextElement.tagName == "INPUT" && nextElement.type == "text"){
				nextElement.disabled = true;
				nextElement.value = "";
			}
		}
	}
}

/**
 * Function: setQuestionNumber
 *    Generates the question number for a question brick
 * 
 * Parameters:
 *     brickid - id of the question brick
 *
 * Returns:
 *     the question number text to be displayed
 */
function setQuestionNumber (brickid){
	//if the question brick doesnt exist in the form, no number
	if(typeof numbers == "undefined"){
		return '';
	}
	if (numbers[brickid])
		if(numbers[brickid]['value'] != false)
			return ("Vraag " + numbers[brickid]['value']);

	return '';
}

/**
 * Function: setMandatoryIndicator
 *    sets a '*' for all compulsary questions
 * 
 * Parameters:
 *     value - string that is'ja' if question is mandatory
 *
 * Returns:
 *     the text to be displayed
 */
function setMandatoryIndicator(value){
	//alert("in setMandatoryIndicator "+value);
	if(value == "ja"){
		return "*";
	}
	return "";
}

/**
 * Function: setAnswerBox
 *    generates the html for an open question - the text area or intput text field
 * 
 * Parameters:
 *     brickId - id of the open question brick
 *     width - width in number of characters the fields should be (appox)
 *     height - number of columns of text the open question should display; if 1 an input field is used, else a text area is used
 *     validation - what sort of validation should be applied to answer (eg numeric, date)
 *     errorEl - html error element for error if answer if incorrect
 *     errormessage - text error message if answer if incorrect
 *     maxNum - if its numeric validation the max value the input can be
 *     minNum -  if its numeric validation the min value the input can be
 *     maxLength - if its text, then the max num of chars the input can be
 *     minPast - the minimum of days that an date may lay in the past
 *     maxPast - the maximum of days that an date may lay in the past
 *     minFuture - the minimum of days that an date may lay in the future
 *     maxFuture - the maximum of days that an date may lay in the future
 *
 * Returns:
 *     generated html for the question text field
 */
function setAnswerBox(brickId, width, height, validation, errorEl, errormessage, maxNum, minNum, maxLength, minPast, maxPast, minFuture, maxFuture){
		//alert("IN setAnswerBox "+maxNum+" "+minNum);
		var val = "";
		if(typeof givenAnswers !== "undefined"){
			if(typeof givenAnswers[brickId] !== "undefined"){
				if(typeof givenAnswers[brickId] != "object"){
					val = givenAnswers[brickId];
				}
				else{
					for(var t in givenAnswers[brickId]){
						val = t;
						break;
					}
				}
			}
		}

		var validationrule = getValidationRule(validation);
		// If there are some validation rules attached to the question, then try to parse it 
		// in the right format.
		if(typeof validationrule !== "undefined" && validationrule !=""){
			//If its a date, first format the date...
			if(validationrule.indexOf("Date") >= 0){
				val = formatDate(val);
			}
		}
		
		if(errorEl != false && errorEl != null){
			var errortype = "txtstring";
			var errorlocation = "wizarderror";
		}
		else{
			var errortype = "alert";
			var errorlocation = "";
		}
		if(maxNum != "" && maxNum != null){
			maxNum = "maxNumber = '"+maxNum+"'";
		}
		else{
			maxNum = "";
		}
		if(minNum != "" && minNum != null){
			minNum = "minNumber = '"+minNum+"'";
		}		
		else{
			minNum = "";
		}
		var disabled = "";
		if (typeof readonlyBricks !== "undefined" && typeof readonlyBricks[brickId] !== "undefined") {
			disabled = " disabled=\"true\" ";
		}
		
		if (minPast != "" && minPast != null) {
			minPast = " minPast='" + minPast + "' ";
		} else {
			minPast = "";
		}
		if (maxPast != "" && maxPast != null) {
			maxPast = " maxPast='" + maxPast + "' ";
		} else {
			maxPast = "";
		}
		if (minFuture != "" && minFuture != null) {
			minFuture = " minFuture='" + minFuture + "' ";
		} else {
			minFuture = "";
		}
		if (maxFuture != "" && maxFuture != null) {
			maxFuture = " maxFuture='" + maxFuture + "' ";
		} else {
			maxFuture = "";
		}


		if(height > 1){
			return("<textarea "+disabled+" errorlocation=\""+errorlocation+":::"+brickId+"\" errormsg=\""+errormessage+"\" "+maxNum +" "+minNum + " " + minPast + " " + maxPast + " " + minFuture + " " + maxFuture +" validationrules=\""+validationrule+"(oElement);\" errormsgtype=\""+errortype+"\" onkeyup=\"doneKeyUp(this);\" onblur=\"answeredOpenQuestion(this);\" brickid=\""+brickId+"\" name=\"answer"+brickId+"\" cols=\""+width+"\" rows=\""+height+"\">"+val+"</textarea>");
		}
		else{
			return("<input "+disabled+" errorlocation=\""+errorlocation+":::"+brickId+"\" errormsg=\""+errormessage+"\" "+maxNum +" "+minNum + " " + minPast + " " + maxPast + " " + minFuture + " " + maxFuture +" validationrules=\""+validationrule+"(oElement);\" errormsgtype=\""+errortype+"\" onkeyup=\"doneKeyUp(this);\" onblur=\"answeredOpenQuestion(this);\" brickid=\""+brickId+"\" name=\"answer"+brickId+"\" size=\""+width+"\" value=\""+val+"\">");
		}
}

/**
 * Function: setAnswerBoxAutoAanvullen
 *    generates the html for an auto aanvullen question - the text area or intput text field
 * 
 * Parameters:
 *     brickId - id of the open question brick
 *     width - width in number of characters the fields should be (appox)
 *     height - number of columns of text the open question should display; if 1 an input field is used, else a text area is used
 *     validation - what sort of validation should be applied to answer (eg numeric, date)
 *     errorEl - html error element for error if answer if incorrect
 *     errormessage - text error message if answer if incorrect
 *     maxNum - if its numeric validation the max value the input can be
 *     minNum -  if its numeric validation the min value the input can be
 *     maxLength - if its text, then the max num of chars the input can be
 *
 * Returns:
 *     generated html for the auto aanvullen question text field
 */
function setAnswerBoxAutoAanvullen(brickId, width, height, validation, errorEl, errormessage, maxNum, minNum, maxLength){
		//alert("IN setAnswerBox "+maxNum+" "+minNum);
		var val = "";
		if(typeof givenAnswers !== "undefined"){
			if(typeof givenAnswers[brickId] !== "undefined"){
				if(typeof givenAnswers[brickId] != "object"){
					val = givenAnswers[brickId];
				}
				else{
					for(var t in givenAnswers[brickId]){
						val = t;
						break;
					}
				}
			}
		}

		var validationrule = getValidationRule(validation);
		if(errorEl != false && errorEl != null){
			var errortype = "txtstring";
			var errorlocation = "wizarderror";
		}
		else{
			var errortype = "alert";
			var errorlocation = "";
		}
		if(maxNum != "" && maxNum != null){
			maxNum = "maxNumber = '"+maxNum+"'";
		}
		else{
			maxNum = "";
		}
		if(minNum != "" && minNum != null){
			minNum = "minNumber = '"+minNum+"'";
		}		
		else{
			minNum = "";
		}
		
		var disabled = "";
		if (typeof readonlyBricks !== "undefined" && typeof readonlyBricks[brickId] !== "undefined") {
			disabled = " disabled=\"true\" ";
		}

		if(height > 1){
			return("<textarea "+disabled+" errorlocation=\""+errorlocation+":::"+brickId+"\" errormsg=\""+errormessage+"\" "+maxNum +" "+minNum +" validationrules=\""+validationrule+"(oElement);\" errormsgtype=\""+errortype+"\" onkeypress=\"doneKeyUp(this);\" onblur=\"answeredOpenQuestion(this);\" brickid=\""+brickId+"\" name=\"answer"+brickId+"\" cols=\""+width+"\" rows=\""+height+"\">"+val+"</textarea>");
		}
		else{
			return("<input "+disabled+" id=\"list\" errorlocation=\""+errorlocation+":::"+brickId+"\"errormsg=\""+errormessage+"\" "+maxNum +" "+minNum +" validationrules=\""+validationrule+"(oElement);\" errormsgtype=\""+errortype+"\" onkeypress=\"doneKeyUp(this);\" onblur=\"answeredOpenQuestion(this);\" brickid=\""+brickId+"\" name=\"answer"+brickId+"\" size=\""+width+"\" value=\""+val+"\">");
		}
}

function doneKeyUp(el){
	if (givenAnswers) {
		//FX comp
		var bid = el.getAttribute('brickid');
		//FX comp
		if (bid!=='') {
			givenAnswers[bid] = new Object();
			givenAnswers[bid][el.value] = "";
			
			var res1 = true;
			// Check on length for performance reasons
			if (el.value.length <= 1) {
				res1 = checkMandatoryQuestionsOnPage();
			}
			var res2 = checkPageValidation(false);
			enableNexts(res1 && res2);
		}
	}

}

function getValidationRule(format){
	if(format == "Text"){
		return "checkNotEmpty";
	}
	else if(format == "Nummeric"){
		return("checkIsNummeric");
	}
	else if(format == "Telefoonnummer"){
		return("checkTelephone");
	}
	else if(format == "E-mail adres"){
		return("checkEmail");
	}
	else if(format == "NL Postcode"){
		return("checkPostcode");
	}
	else if(format == "Datum"){
		return("checkDate");
	}
	else if(format == "Tijd"){
		return("checkTime");
	}
	else if(format == "Sofinummer"){
		return("checkSofinr");
	}
	else if(format == "NL Banknummer"){
		return("checkBanknummer");
	}
	else if(format == "Formateer Aaaaa"){
		return("checkCaps");
	}
	else if(format == "Formateer AAAAA"){
		return("checkAllCaps");
	}
	else if(format == "NL Kenteken XX-XX-XX"){
		return("checkKenteken");
	}
	else if(format == "NL Kenteken XXXXXX"){
		return("checkKentekentwee");
	}
	else if(format == "Domeinnaam"){
		return("checkDomainnameSyntax");
	}
	else if(format == "Custom"){
		return("checkCustom");
	}
	else{
		return ("check" + format);
	}
}

function wronglyAnsweredQuestion(element){
	//I guess this (textarea) is WRONG
	if(element.tagName == "TEXTAREA"){
//		var textvalue = element.value;
		var textvalue = element.innerText;
	}
	else{
		var textvalue = element.value;
	}
	
	addClientSideAnswer(element.getAttribute('brickid'), "", textvalue, "normal");
}

function answeredQuestion (element, isopen, subitemOrder) {
	isopen = isopen || false;
	//FX compat
	var brickid = element.getAttribute('brickid');
	var elementName = element.getAttribute('name');
	//FXcompat
	var eventtype = "normal";
	var cet = "normal";
	var subitemtext = "";
	addClientSideAnswers = true;
	//alert('1924: in answeredQuestion');
	if(element.tagName == "INPUT"){		
		var textvalue = element.value;
		
		var rowNumber = element.getAttribute('subitemtext');
		var columnNumber = element.getAttribute('name');
		var surveyType = element.getAttribute('surveytype');
		
		// If the answered question is called from within the tabelvraag brick.
		if (rowNumber !== null && typeof rowNumber !== "undefined" && 
				columnNumber !== null && typeof columnNumber !== "undefined" && 
				surveyType !== null && typeof surveyType !== "undefined" && 
				surveyType == "tabelvraag") {
			if (element.type == "checkbox" || 
					element.type == "radio") {
				if (element.checked == false) {
					textvalue = "";
				} else {
					textvalue = "on";
				}
			}
		
			var oldTextValue = textvalue;
			var columnNumber = columnNumber.split("_")[0];
			textvalue = rowNumber + "#####" + columnNumber + "#####" + textvalue;
			
			// Change the givenAnswers because the default funtionality will mess things up.
			addClientSideAnswers = false;
			
			if (typeof givenAnswers == "undefined") {
				givenAnswers = new Object();
			}
			
			if (typeof givenAnswers[brickid] == "undefined") {
				givenAnswers[brickid] = new Object();
			}
			
			var newKey = "";
			
			for (answerKey in givenAnswers[brickid]) {
				var answerArray = answerKey.split("====");
				
				for (colKey in answerArray) {
					var rowArray = answerArray[colKey].split("-----");
					
					if (colKey == columnNumber) {
						for (rowKey in rowArray) {
							if (rowKey == rowNumber) {
								rowArray[rowKey] = oldTextValue;
							}
						}
					}
					
					answerArray[colKey] = rowArray.join("-----");
				}
				
				newKey = answerArray.join("====");
			}
			
			givenAnswers[brickid] = new Object();
			givenAnswers[brickid][newKey] = "";
		} else if (element.type == "checkbox") {
			if(element.checked == false) {
				eventtype = "deselected";
				cet = "deselected";
			}
		}
		else if(element.type == "radio"){
			cet = "one";
			
			if(typeof element.parentNode !== "undefined"){
				if(typeof element.parentNode.className !== "undefined"){
					if(element.parentNode.className == "tableradio"){
						cet = "normal";
					}
				}
			}
			
			
			var questionBrickTypeEls = document.getElementsByName("brick_type");

			for (var i = 0; i < questionBrickTypeEls.length; i++) {
				var qBrickTypeEl = questionBrickTypeEls[i];
				var brick_type = qBrickTypeEl.innerHTML;
				var bid = qBrickTypeEl.getAttribute('brickid');
				
				// If the combi likertschaal vraag has beean found, then the selected values
				// will be determined.
				
				/**
					* Code voor de combi likertschaal vraag
					*/
				
				if (bid == brickid && (brick_type == "likerdschaal" || brick_type == "likertschaalvraag" || brick_type == "tweevoudiglikertschaal")) {
					cet = "normal";
				} else if (bid == brickid && brick_type == "combilikertschaalvraag") {
					var elementNameBid = "_" + bid;
					
					// Retrieve the element name (stelling)
					elementNameBid = elementName.substring( 0, elementName.length - elementNameBid.length );
					
					// If the selected item was an detail mening item
					if (elementNameBid.substring(0, 5) == "#####") {
						// Retrieve the old selected answers (meningnummer; mening; detail mening nummer; detail mening)
						var answerArr = givenAnswers[bid][elementNameBid.substring(5, elementNameBid.length)].split("#####");
						
						// Create the new selected value and preserve the old normal mening item
						textvalue = answerArr[0] + "#####" + answerArr[1] + "#####" + textvalue;
					}
					// Else the item was an normal mening item
					else {
						// Seperate the meningnummer from the mening
						var textvalueArr = textvalue.split("#####");	
						
						// If the selected mening must preserve the selected detail mening, then the
						// selected detail mening will be saved
						if (textvalueArr[1].substring(0, 5) == "=====") {
							// Retrieve the selected detail mening
							var answerArr = givenAnswers[bid][elementNameBid].split("#####");
							var selectedDetailMening = "#####";
							
							// Determine if there previously was an detail mening selected
							if (typeof answerArr[2] != "undefined") {
								selectedDetailMening = answerArr[2] + "#####" + answerArr[3];
							}
							
							// Create the new selected value and preserve the old normal mening item
							textvalue = textvalueArr[0] + "#####" + textvalueArr[1].substring(5, textvalueArr[1].length) + "#####" + selectedDetailMening;
						}
						// Else the detail mening will be cleared
						else {
							textvalue = textvalue + "#####" + "#####";
						}
					}
				}
				/**
				* Einde van de code voor de combi likertschaal vraag
				*/
			}
		}
	}
	else if(element.tagName == "TEXTAREA"){
//		var textvalue = element.innerHTML;
		var textvalue = element.value;
	}
	else if(element.tagName == "SELECT"){
		var subitemtext = element.value;
		var textvalue = "";
		cet = "one";
	}
	if(element.getAttribute('subitemtext') !== null){
		var subitemtext = element.getAttribute('subitemtext');
	}
	if(element.tagName == "INPUT" && element.type != "TEXT" && subitemtext == textvalue){
		textvalue = "";
	}
	
	sendAnswerRequest(brickid, subitemtext, textvalue, eventtype, subitemOrder);
	
	if (addClientSideAnswers) {
		addClientSideAnswer(brickid, subitemtext, textvalue, cet);
	}
	
	if(!isopen){
		clearError(brickid);
	}

	handleSkips();
	var isPageComplete = checkMandatoryQuestionsOnPage() && checkPageValidation(false);
	enableNexts(isPageComplete);	
}



function answeredOpenQuestion(element){
	var cont = true;
	
	//FX compat
	var vr = element.getAttribute('validationrules'); 
	var bid = element.getAttribute('brickid');
	//FX compat
	
	if(vr !== null && typeof vr !== "undefined" && vr!="" && element.value!=""){
		if(vr.indexOf("Date") >= 0)
			element.value = formatDate(element.value);
		
		cont = PPElementValidation(element);
		
	} else {
		clearError(bid);
	}

	//alert("sending answer :: "+brickid + " " + subitemtext+ " " + textvalue + " " + eventtype);
	if(cont){
		if(cont != true){
			element.value = cont;
		}
		answeredQuestion(element, true);
	}
	else{
		wronglyAnsweredQuestion(element);
	}
	if(typeof highlightClass !== "undefined" && typeof nonHighlightClass !== "undefined"){
		highlightErrors(nonHighlightClass, highlightClass);
	}
}

/**
 * This method checks to see if the currently logged in user belongs to the given groups.
 *
 * @param	groups	The groups to wich the groups of the logged in user are checked. The groups 
 *					is an string containing every group seperated with '#####'.
 *
 * @return	If the logged in user belongs to one of the groups, then the value true is returned. 
 *			In any other case the value false is returned.
 */
function isGroupLoggedIn(groups) {
	var groupLoggedIn = false;
	
	if (typeof userGroupsPPP == "undefined") {
		userGroupsPPP = new Object();
	}
	
	// Loop the groups of the logged in user to check if one of it's groups is 
	// equal to the required group.
	for (var groupKey in userGroupsPPP) {
		if (groups.indexOf(userGroupsPPP[groupKey]) >= 0) {
			groupLoggedIn = true;
		}
	}
	
	return groupLoggedIn;
}

var doneExtra = false;

function handleSkips(){

//	alert("in handleSkips: " + typeof numbers );

	if (typeof numbers === "undefined") {
		return false;
	}
	
	if(inAdmin == true) {
		return;
	}
	
	//get all the bricks...
	var questionBrickTypeEls = document.getElementsByName("brick_type");
	
	var hideGroupQuestion = new Object();
	
	// Loop every brick and check if it should be shown based on the logged in user. If the 
	// required user is not logged in, then the brick is hidden and the answers are removed.
	for (var i = 0; i < questionBrickTypeEls.length; i++) {
		var qBrickTypeEl = questionBrickTypeEls[i];
		var brickId = questionBrickTypeEls[i].getAttribute('brickid');
	
		for (var index=0; index<qBrickTypeEl.parentNode.childNodes.length; index++) {
			var child = qBrickTypeEl.parentNode.childNodes[index];
			
			// If the question has selected groups, then check if the question must be shown. In 
			// any other case the question is always shown.
			if (child.id == "sel_groups") {
				// If there are no groups, then the question is shown.
				if (child.innerHTML == "") {
					qBrickTypeEl.parentNode.style.display = "block";
					hideGroupQuestion[brickId] = false;
				} else {
					if (isGroupLoggedIn(child.innerHTML)) {
						qBrickTypeEl.parentNode.style.display = "block";
						hideGroupQuestion[brickId] = false;
					} else {
						qBrickTypeEl.parentNode.style.display = "none";
						hideGroupQuestion[brickId] = true;
					}
				}
			}
		}
	}

	var removedanswers = false;

	var needToHide = new Object();
	var condANDs = new Object();
	
	if (typeof numbers=='undefined')
		return false;
	
	if(typeof skips != "undefined"){
		//If there are some skips in the form/enquete
		for(var brickid in numbers){

			//If the current brick has some skips attached..
			if(typeof skips[brickid] != "undefined"){
				//For each possible answer of the current brick that has some skips attached...
				for(var possanswer in skips[brickid]){
					//If the user has selected this possible answer...
					if(typeof givenAnswers[brickid] != "undefined" && typeof givenAnswers[brickid][possanswer] != "undefined"){
						//show conditional questions
						for(var qid in skips[brickid][possanswer]){
							//If it depends on other given answers...
							if(skips[brickid][possanswer][qid]['type'] == "AND"){
								//if we havent set it to true already...
								if(typeof condANDs[skips[brickid][possanswer][qid]['brickid']] == "undefined"){
									//set marker to true...
									condANDs[skips[brickid][possanswer][qid]['brickid']] = new Object();
								}
								condANDs[skips[brickid][possanswer][qid]['brickid']][brickid] = true;
							}else{
								//otherwise we need to show this brick
								conditionalShows[skips[brickid][possanswer][qid]['brickid']] = true;
								needToHide[skips[brickid][possanswer][qid]['brickid']] = false;
							}
						}
					}
					//Otherwise they have not selected this possible answer
					else{
						//For every question listed to show under the current possible answer...
						for(var qid in skips[brickid][possanswer]){
							
							if(skips[brickid][possanswer][qid]['type'] == "AND"){
								if(numbers[brickid]['skipped'] !== true){
									if(typeof condANDs[skips[brickid][possanswer][qid]['brickid']] == "undefined"){
										condANDs[skips[brickid][possanswer][qid]['brickid']] = new Object();
									}
									if(typeof condANDs[skips[brickid][possanswer][qid]['brickid']][brickid] == "undefined"){
										condANDs[skips[brickid][possanswer][qid]['brickid']][brickid] = false
									}
								}
							}							
							else{
								if(typeof conditionalShows[skips[brickid][possanswer][qid]['brickid']] != "undefined"){
									//delete (conditionalShows[skips[brickid][possanswer][qid]['brickid']]);
									if(typeof needToHide[skips[brickid][possanswer][qid]['brickid']] == "undefined"){
										needToHide[skips[brickid][possanswer][qid]['brickid']] = true;
									}
								}
							}
						}
					}		
				}
			}
		}
	}
	for(var bid in condANDs) {
		var show = true;
		for(var bid2 in condANDs[bid]){
			if(condANDs[bid][bid2] == false) {
				show = false;
			}
		}
		if(show != false) {
			conditionalShows[bid] = true;
			needToHide[bid] = false;
		} else{
			conditionalShows[bid] = false;
			needToHide[bid] = true;
		}
	}

	
	var errorElement = document.getElementById("wizarderror");
	for(var bid in needToHide) {
		if(needToHide[bid] == true) {
			delete (conditionalShows[bid]);
			//Also delete error messages when a question is hidden
			if(errorElement != null){
				for(var j = 0; j < errorElement.childNodes.length; j++){
					if(errorElement.childNodes[j].id == bid){
						errorElement.removeChild(errorElement.childNodes[j]);
						break;
					}
				}
			}
		}
	}


	//for each brick...	
	for(var brickid in numbers){
		conditionType = numbers[brickid]['conditionalType'];
		//if its a conditional question
		if (conditionType == "conditional") {
			//if the question should be shown
			if (typeof conditionalShows[brickid] !== "undefined" && 
					conditionalShows[brickid] == true && 
					(typeof hideGroupQuestion[brickid] == "undefined" || hideGroupQuestion[brickid] == false)) {
				//it isnt skipped
				numbers[brickid]['skipped'] = false;
                if (typeof condANDs[brickid] !== "undefined" && condANDs[brickid]) {
                    toberemovedANDAND[brickid] = false;
                }
			} else{
				//it is skipped
				numbers[brickid]['skipped'] = true;

				//remove answers to question if previously given if it's not a fixed hidden answer
				if(typeof givenAnswers[brickid] != "undefined" && (typeof numbers[brickid]['fixedHiddenAnswer'] == "undefined" || numbers[brickid]['fixedHiddenAnswer'] !== true) ){
					if (typeof condANDs[brickid] !== "undefined" && condANDs[brickid]) {
                        toberemovedANDAND[brickid] = true;
                    } else {
                        removeAnswers(brickid);
                        removedanswers = true;
                    }
				}
			}
		}
		else{
			// If the question is allowed to be shown (based on the logged in user), then show the 
			// question. Otherwise hide/skip the question.
			if (typeof hideGroupQuestion[brickid] == "undefined" ||
				hideGroupQuestion[brickid] == false) {
				//its always shown
				numbers[brickid]['skipped'] = false;
			} else {
				numbers[brickid]['skipped'] = true;
			}
		}	
		
	}
	var addedDefault = false;
	

	//For every question in the form...
	for(var brickid in numbers){
		//If the question isnt a skiped one...
			//alert(brickid);
		if(numbers[brickid]['skipped'] == false && !skippedDocs[numbers[brickid]['docid']]){
			//If there is a default answer but no answer has been given for thw question yet...
			if(typeof defaultAnswers[brickid] != "undefined" && typeof givenAnswers[brickid] == "undefined"){
				//alert("defaultanswer");
				
				addedDefault = true;
				
				var singleDefaultAnswer = defaultAnswers[brickid];
				givenAnswers[brickid] = singleDefaultAnswer;
				if(typeof singleDefaultAnswer == "object"){
					for(var subitemvalue in singleDefaultAnswer){
						var textvalue = singleDefaultAnswer[subitemvalue];
						sendAnswerRequest(brickid, subitemvalue, textvalue);
					}
				}else{
					sendAnswerRequest(brickid, false, singleDefaultAnswer);
				}
			}
		}
	}
	

	for(var i = 0; i < questionBrickTypeEls.length; i++){
		var qBrickTypeEl = questionBrickTypeEls[i];
		var brick_type = qBrickTypeEl.innerText;
		
		// fx compat
		var brickid = qBrickTypeEl.getAttribute('brickid');
		// end of fx compat
		
		if(typeof numbers[brickid] != "undefined") {
			if(numbers[brickid]['skipped'] != false || (typeof hiddenBricks !== "undefined" && hiddenBricks[brickid] == true)) {
				qBrickTypeEl.parentNode.style.display = "none";	
			} else{
				//show it to me baby!
				qBrickTypeEl.parentNode.style.display = "block";
			}
		}
	}
	
	var c = 1;
	if(typeof numbers != "undefined"){
		for(var bid in numbers){
			if(numbers[bid]['type'] == "dynamic"){
				if(numbers[bid]['skipped'] == false){
					numbers[bid]['value']  = c;
					c++;
				} else {	
					numbers[bid]['value']  = "";
				}
			}
		}
	}
	renderQuestionNumbers();
	setNextButtonOfNavigation();
	if(addedDefault){
		renderQuestionBricks();
	}
	else if(removedanswers){
		handleSkips();
	}
	if(typeof doExtraHandlePremieDocId !== "undefined" && typeof doExtraHandlePremieAction !== "undefined" && doneExtra == false){
		removeConditionalANDs();
        toberemovedANDAND = new Object();
        doneExtra = true;
		handlePremie(doExtraHandlePremieDocId, doExtraHandlePremieAction, null, true);
	}
}

function removeConditionalANDs() {
    for(var brickid in toberemovedANDAND){
        if (typeof toberemovedANDAND[brickid] !== "undefined" && toberemovedANDAND[brickid] == true) {
            removeAnswers(brickid);
        }
    }
}

function removeAnswers(brickid){
	
	removeClientSideAnswer(brickid);
	removeServerSideAnswer(brickid);
	var questionBrickTypeEls = document.getElementsByName("brick_type");
				
	//for each brick...
	for(var i = 0; i < questionBrickTypeEls.length; i++){
		var qBrickTypeEl = questionBrickTypeEls[i];
		
		//FX compat
		if (brickid == qBrickTypeEl.getAttribute('brickid')) {
		//FX compat
			var brick_type = qBrickTypeEl.innerText;
			//render the various types of questions bricks
			if(brick_type == "openvraag"){
				renderOpenVraagBrick(qBrickTypeEl.parentNode, qBrickTypeEl.getAttribute('brickid'));
			}
			else if(brick_type == "autoaanvullen_veld"){
				renderAutoAanvullenVeldBrick(qBrickTypeEl.parentNode, qBrickTypeEl.getAttribute('brickid'));
			}
			else if(brick_type == "geslotenvraag"){
				renderGeslotenVraagBrick(qBrickTypeEl.parentNode, qBrickTypeEl.getAttribute('brickid'));
			}
			else if(brick_type == "likerdschaal" || brick_type == "likertschaalvraag" || brick_type == "tweevoudiglikertschaal"){
				renderLikertschaalVraagBrick(qBrickTypeEl.parentNode, qBrickTypeEl.getAttribute('brickid'));
			}
			else if(brick_type == "combilikertschaalvraag"){
				renderCombiLikertschaalVraagBrick(qBrickTypeEl.parentNode, qBrickTypeEl.getAttribute('brickid'));
			}
			else if(brick_type == "semanticdiffvraag" || brick_type == "semantischedifferentiaalvraag"){
				renderSemanticdiffVraagBrick(qBrickTypeEl.parentNode, qBrickTypeEl.getAttribute('brickid'));
			}
			break;
		}
	}
}


function removeClientSideAnswer(currbrickid){
	if(typeof givenAnswers !== "undefined"){
		if(typeof givenAnswers[currbrickid] !== "undefined"){
			delete(givenAnswers[currbrickid]);
		}
	}
}

function removeServerSideAnswer(currbrickid){
	if (!firstSave) {
		sendAnswerRequest(currbrickid, "", "", "remove");
	}
}

function setNextButtonOfNavigation(){
//	alert("In setNextButtonOfNavigation");
	//Get current doc id
	//Find the next question that IS displayed
	var foundCurrentPageQuestions = false
	var prevDocId = 0;

	// bug fix for order problem in Chrome and Opera (brickidorder)
	for (var _bid=0; _bid< brickidorder.length; _bid++) {
		var brickid = brickidorder[_bid];
		
		if(foundCurrentPageQuestions == false && !skippedDocs[numbers[brickid]['docid']] && typeof numbers[brickid] != "undefined" && numbers[brickid]['docid'] != currentdocid && numbers[brickid]['skipped'] == false){
			prevDocId = numbers[brickid]['docid'];
		}

		var brickIsHidden = (hiddenBricks[brickid] == true);
		if(foundCurrentPageQuestions == false && (numbers[brickid]['docid'] == currentdocid && !brickIsHidden)){
			foundCurrentPageQuestions = true;
		}
		else if(foundCurrentPageQuestions == true && numbers[brickid]['docid'] != currentdocid && !skippedDocs[numbers[brickid]['docid']] && !brickIsHidden){
			if(typeof numbers[brickid] != "undefined" && numbers[brickid]['skipped'] == false){
				//this is what we need to set the buttons to
				var nextElements = document.getElementsByName("wn_next");
				for(var i = 0; i < nextElements.length; i++){
					var nextElement = nextElements[i];
					nextElement.setAttribute ('gotodocid', numbers[brickid]['docid']);	
				}
				for(var i = 1; i < 6; i++){
					var nextElement = document.getElementById("wn_nav"+i);
					if(nextElement != null && typeof nextElement.name != "undefined" && nextElement.name == "wn_next"){
						nextElement.setAttribute ('gotodocid', numbers[brickid]['docid']);
						
						// alert("in setNextButtonOfNavigation to 2:"+numbers[brickid]['docid']);
					}
				}
				break;
			}
		}
		
		if (prevDocId != 0) {
			var prevElements = document.getElementsByName("wn_prev");
			for(var i = 0; i < prevElements.length; i++){
				var prevElement = prevElements[i];
				prevElement.setAttribute ('gotodocid', prevDocId);
			}
		}
	}
}

function enableNexts(enable){
	var errEl = document.getElementById("general_error");
	if(errEl != null){
			var emailButtonElement = document.getElementById("wn_nav2");
			if(emailButtonElement != null){
				emailButtonElement.className = "wn_currentpage";
				emailButtonElement.setAttribute("isEnabled", "NO");
				emailButtonElement.style.cursor= "default";
				emailButtonElement.onclick= "";
			}
			
			var nextButtonElement = document.getElementById("wn_nav3");
			if(nextButtonElement != null){
				nextButtonElement.className = "wn_currentpage";
				nextButtonElement.setAttribute("isEnabled", "NO");
				nextButtonElement.style.cursor= "default";
				nextButtonElement.onclick= "";
			}
	}
	
    var sumbitButtonElement = document.getElementById("sumbit_button");
    if(sumbitButtonElement != null){
        if(enable){
			sumbitButtonElement.className = "wn_otherpage";
			sumbitButtonElement.setAttribute("isEnabled", "YES");
			sumbitButtonElement.style.cursor= "hand";
		}
		else{
			sumbitButtonElement.className = "wn_currentpage";
			sumbitButtonElement.setAttribute("isEnabled", "NO");
			sumbitButtonElement.style.cursor= "default";
		}
    }
    
	//this is what we need to set the buttons to
	var nextElements = document.getElementsByName("wn_next");

	for(var i = 0; i < nextElements.length; i++){
		var nextElement = nextElements[i];
		if(enable){
			savedNextElement = nextElement;
			nextElement.className = "wn_otherpage";
			nextElement.setAttribute("isEnabled", "YES");
			nextElement.style.cursor= "hand";
			var oldtext = nextElement.getAttribute('oldText')
			if (oldtext)
				nextElement.innerHTML = oldtext;
			
		}
		else{
			nextElement.className = "wn_currentpage";
			nextElement.setAttribute("isEnabled", "NO");
			nextElement.style.cursor= "default";
			var oldtext = nextElement.getAttribute('oldText')
			if (oldtext)
				nextElement.innerHTML = oldtext;
		}
	}
	for(var i = 1; i < 6; i++){
		var nextElement = document.getElementById("wn_nav"+i);
		if(nextElement != null && typeof nextElement.name != "undefined" && nextElement.name == "wn_next"){
			if(enable){
				savedNextElement = nextElement;
				nextElement.className = "wn_otherpage";
				nextElement.setAttribute("isEnabled", "YES");
				nextElement.style.cursor= "hand";
			}
			else{
				nextElement.className = "wn_currentpage";
				nextElement.setAttribute("isEnabled", "NO");
				nextElement.style.cursor= "default";
			}
		}
	}
	if(typeof skipAnsweredPages != "undefined" && skipAnsweredPages == true){
		if(typeof savedNextElement != "undefined"){
			savedNextElement.onclick();
			delete savedNextElement;
		}else{
			skipAnsweredPages = false;
		}
	}
}

function addClientSideAnswer(brickid, subitemtext, textvalue, eventtype){
	//alert("in addClientSideAnswer");
	if(typeof givenAnswers != "undefined"){
		if(typeof givenAnswers[brickid] == "undefined"){
			givenAnswers[brickid] = new Object();
		}
		if(subitemtext != ""){
			if(eventtype !== "deselected"){
				if(eventtype == "one"){
					delete(givenAnswers[brickid]);
					givenAnswers[brickid] = new Object();
				}
				givenAnswers[brickid][subitemtext] = textvalue;
				
			}
			else{
				if(typeof givenAnswers[brickid][subitemtext] !== "undefined"){
					delete(givenAnswers[brickid][subitemtext]);
					var c = 0;
					for(var val in givenAnswers[brickid]){
						c++;
					}
					if(c == 0){
						delete(givenAnswers[brickid]);
					}
				}
			}
		}
		else{
			if(textvalue !== ""){
				givenAnswers[brickid] = textvalue;
			}
			else{
				delete(givenAnswers[brickid]);
			}
		}
	}
}


function sendAnswerRequest(brickid, subitemvalue, textvalue, eventtype, subitemOrder){
	firstSave = false;

	//not every wizard uses a survey database
	//if no survey database is used, this call is not needed
	//the variable noServerSideSurvey can be set anywehere, for polix it's in klant.js
	if (typeof noServerSideSurvey !== "undefined" && noServerSideSurvey === true){
		return true;
	}
	
//	if (textvalue && handleDuplicateNames) {
	if (handleDuplicateNames) {
		checkDuplicateNames(brickid, textvalue, subitemvalue);
	}

	var url = "/mappings/xml/informationobject/callToServer";

	var xml = "<module name=\"survey\">";
	xml = xml + "<function name=\"saveSurveyResponseAnswer\">";
	xml = xml + "<param name=\"brickid\">"+brickid;	
	xml = xml + "</param>";

	if (firstSurveyAnswer === true) {
		xml = xml + "<param name=\"newSurvey\">true</param>";
		if (typeof RequestHasResponse != 'undefined' && RequestHasResponse !== false) {
			xml = xml + "<param name=\"newSurveyResponseId\">"+CDATAencoder (RequestHasResponse)+"</param>";
		}
		firstSurveyAnswer = false;
		var r = http.nonCacheReq (url, false);
	}else{
		var r = http.nonCacheReq (url, true);
	}
	r.addHeader("Content-Type","text/xml; charset=UTF-8");
	
	if(subitemvalue != false && subitemvalue!= ""){
		xml = xml + "<param name=\"selectedSurveySubitemText\">"+CDATAencoder (subitemvalue);
		xml = xml + "</param>";
	}
	if( ( textvalue != false && textvalue!= "" ) || parseInt(textvalue) == "0"){
		xml = xml + "<param name=\"answerText\">"+CDATAencoder (textvalue);
		xml = xml + "</param>";
	}
	if(eventtype != false && eventtype!= ""){
		xml = xml + "<param name=\"eventType\">" + CDATAencoder (eventtype);
		xml = xml + "</param>";
	}
	if(subitemOrder !== false) {
		xml = xml + "<param name=\"subitemOrder\">" + CDATAencoder (subitemOrder);
		xml = xml + "</param>";
	}
	xml = xml + "</function>";
	xml = xml + "</module>";	
//	alert(xml);
	r.callback = function donothing() {
//		alert(r.responseObject.responsetext);
	};
//	alert("hier");
	if (typeof numbers !== "undefined" && typeof numbers[brickid] !== "undefined") {
		var theFunction = numbers[brickid]['uniqueId'].replace(/\./gi,"_") + "PostAction";
		if (typeof window[theFunction] != "undefined") {
			window[theFunction](brickid, textvalue, subitemvalue, eventtype, subitemOrder);
		}
	}	

	r.post (xml);
	
}

// N.B. Michel: evt cachen dubbele namen ivm performance
function checkDuplicateNames(brickid, textvalue, subitemvalue) {
	
	// bug fix for Deltalloyd AVO; sometimes we miss a numbers[brickid] [JV]
	if (!numbers[brickid])
		return;
		
	var brickname1 = numbers[brickid]['uniqueId']
	if (numbers[brickid]['uniqueId'].indexOf("#") > 0)
		brickname1 = numbers[brickid]['uniqueId'].substring(0, numbers[brickid]['uniqueId'].indexOf("#"));

	for(var id in numbers){
	
		var brickname2 = numbers[id]['uniqueId'];
		if (numbers[id]['uniqueId'].indexOf("#") > 0) {
			brickname2 = numbers[id]['uniqueId'].substring(0, numbers[id]['uniqueId'].indexOf("#"));
		}

		if (brickname1 == brickname2) {
//			dupNames[id] = brickname1;
			if (subitemvalue && (typeof defaultAnswers[id] == "undefined" || typeof defaultAnswers[id][subitemvalue] == "undefined")) {
				defaultAnswers[id] = new Object();
				defaultAnswers[id][subitemvalue] = "";
			} else {
				if (textvalue)
					defaultAnswers[id] = textvalue;
			}
		}
	}
}

function getAnswerByQID(qid){
    if (typeof qid == "undefined" || qid == "" || qid.indexOf('@') !== -1) {
        return qid;
    }
    
	var brickid = getBIDByQID(qid);
	if(brickid != false){
		if(typeof givenAnswers[brickid] != "undefined") {
		    if (typeof givenAnswers[brickid] == "object"){
				for (var el in givenAnswers[brickid]) {
                    if (el.indexOf('@') !== -1) {
                        return  el;
                    } else {
                        // If the answer itself was no emailaddress, the possibly the value
                        // of the answer might...
                        var questionBrickTypeEls = document.getElementsByName("brick_type");
                        
                        for(var i = 0; i < questionBrickTypeEls.length; i++){
                            var qBrickTypeEl = questionBrickTypeEls[i];
                            
                            if(qBrickTypeEl.innerText == "geslotenvraag") {
                                var answers = qBrickTypeEl.parentNode.childNodes[13].innerText.split("#####");
                                var values = qBrickTypeEl.parentNode.childNodes[20].innerText.split("#####");
                                
                                for(var j = 0; j < answers.length; j++){
                                    if(answers[j] == el && values[j].indexOf('@') !== -1) {
                                        return values[j];
                                    }
                                }
                            }
                        }
                    }
				}
			} else {
				return  givenAnswers[brickid];
			}
		}
	}
	return "";
}

function getBIDByQID(qid){
	/*
	var questionBrickTypeEls = document.getElementsByName("brick_type");

	for(questionBrickTypeElsId in questionBrickTypeEls){
		var qBrickTypeEl = questionBrickTypeEls[questionBrickTypeElsId];
		if(qBrickTypeEl.parentNode){
			for(qBrickTypeElChildId in qBrickTypeEl.parentNode.childNodes){
				qBrickTypeElChild = qBrickTypeEl.parentNode.childNodes[qBrickTypeElChildId];
				if(qBrickTypeElChild.id == "hidden_questionnumber"){
					if(qBrickTypeElChild.innerText == qid){
						return qBrickTypeEl.getAttribute('brickid');
					}
				}
			}
		}
	}*/
	for(brickid in numbers){
		brick = numbers[brickid];
		if(brick.uniqueId == qid){
			return brickid;
		}
	}
	return false;
}

function handleSumbit(button) {
//alert("IN handelSumbit");
	if (typeof enqueteSendPreAction == "function") {
	    enqueteSendPreAction();
        }

	// do not click twice on this button please
	var buttonOnclick = button.onclick;
        button.onclick = function (){return false};
	
//	MomentGeduldSetText('<b>Moment geduld a.u.b.</b><br>De gegevens worden verzonden');
//	MomentGeduldDisplay();

	var buttonOldValue = button.value;
	button.disabled = true;
	button.value = 'een moment..';
	
	//First need to check mandatory fields are correct.
	//renderQuestionBricks();
	if(typeof givenAnswers == "undefined"){
		//MomentGeduldHide();
                button.onclick = buttonOnclick;
                button.value = buttonOldValue;
                button.disabled = false;
		return false;
	}

	var reply = checkPageValidation(true);

	if(reply == false){
		//MomentGeduldHide();
                button.onclick = buttonOnclick;
                button.value = buttonOldValue;
                button.disabled = false;
		return false;
	}
	
	// Extra check to show an wait icon when neccesary.
	showWaitIconOnElement(button);

	while (true) {
		
		if (button.nextSibling) {
			button = nodes.getNextSibling (button);
		
			if (button.id == 'email_to')
				var email_to = button.innerHTML;
				
			if (button.id == 'email_cc')
				var email_cc = button.innerHTML;
			
			if (button.id == 'email_bcc')
				var email_bcc = button.innerHTML;
			
			if (button.id == 'goto_url')
				goto_url = button.innerHTML;
			
			if (button.id == 'karakterisatie_value')
				var karakterisatie_value = button.innerText;
			
			if (button.id == 'email_title')
				var email_title = button.innerHTML;
			
			if (button.id == 'autoreply_question')
				var autoreply_emailquestion = button.innerHTML;
			
			if (button.id == 'autoreply_subject')
				var autoreply_subject = button.innerHTML;
			
			if (button.id == 'autoreply_url')
				var autoreply_url = button.innerHTML;

			if (button.id == 'email_link_gotopage')
				var email_link_gotopage = button.innerHTML;
			
			if (button.id == 'jasper_template')
				var jasper_template = button.innerHTML;
			
			if (button.id == 'start_process')
				var start_process = button.innerHTML;
			
		} else {
			break;
		}
	}
	
	finished = new Array();

//	alert("autoreply_question:"+autoreply_emailquestion);
	if(email_to !== "" && (typeof jasper_template == "undefined" || jasper_template == "")){

		var url = "/mappings/xml/informationobject/callToServer";
		
        var arrEmailTo = new Array();
		var arrEmailsTo = email_to.split(';');
		for (var i in arrEmailsTo) {
			 var checkEmail = getAnswerByQID(arrEmailsTo[i]);
			 if (checkEmail.indexOf('@') !== -1)
			 	arrEmailTo[i] = checkEmail;
		}
		var emailadressTo = arrEmailTo.join(';');
        
        var arrEmailCC = new Array();
		var arrEmailsCC = email_cc.split(';');
		for (var i in arrEmailsCC) {
			 var checkEmail = getAnswerByQID(arrEmailsCC[i]);
			 if (checkEmail.indexOf('@') !== -1)
			 	arrEmailCC[i] = checkEmail;
		}
		var emailadressCC = arrEmailCC.join(';');
        
        var arrEmailBCC = new Array();
		var arrEmailsBCC = email_bcc.split(';');
		for (var i in arrEmailsBCC) {
			 var checkEmail = getAnswerByQID(arrEmailsBCC[i]);
			 if (checkEmail.indexOf('@') !== -1)
			 	arrEmailBCC[i] = checkEmail;
		}
		var emailadressBCC = arrEmailBCC.join(';');
        
		var r = http.nonCacheReq (url, true);	
		var xml = "<module name=\"data::pdl::survey\">";
		xml = xml + "<function name=\"emailEnqueteResponse\">";
		xml = xml + "<param name=\"email_to\">"+emailadressTo;				
		xml = xml + "</param>";
		xml = xml + "<param name=\"email_cc\">"+emailadressCC;				
		xml = xml + "</param>";
		xml = xml + "<param name=\"email_bcc\">"+emailadressBCC;				
		xml = xml + "</param>";
		xml = xml + "<param name=\"email_title\">"+email_title;				
		xml = xml + "</param>";
		for(var brickid in givenAnswers){
				xml = xml + "<param name=\"bid"+brickid+"\">";
				if(typeof givenAnswers[brickid] == "object"){
					for(var subanswer in givenAnswers[brickid]){
						if(givenAnswers[brickid][subanswer] == ""){
							xml = xml + CDATAencoder(subanswer)+ "#####";
						}
						else{
							xml = xml + CDATAencoder(subanswer)+ " -> "+ givenAnswers[brickid][subanswer]+"#####";
						}
					}
				}	
				else{
					xml = xml + CDATAencoder(givenAnswers[brickid]);
				}
				xml = xml + "</param>";
		}
		
		xml = xml + "</function>";
		xml = xml + "</module>";	
		
		
		r.callback = function donothing() {
//				alert("1:"+r.responseObject.responsetext);
			finished[0] = true;
		};
		finished[0] = false;
		r.post (xml);
	}

	if(autoreply_emailquestion !== ""){
		var brickid = "";
		for(brickid in givenAnswers){
			break;
		}
		
		var arrEmail = new Array();
		var arrEmailQuestion = autoreply_emailquestion.split(';');
		for (var i in arrEmailQuestion) {
			 var checkEmail = getAnswerByQID(arrEmailQuestion[i]);
			 if (checkEmail.indexOf('@') !== -1)
			 	arrEmail[i] = checkEmail;
		}
		var emailadress = arrEmail.join(';');
		var url = "/mappings/xml/informationobject/callToServer";
							
		var r = http.nonCacheReq (url, true);
		var xml = "<module name=\"survey\">";
		xml = xml + "<function name=\"emailURL\">";
		xml = xml + "<param name=\"brickid\">"+brickid;				
		xml = xml + "</param>";
		xml = xml + "<param name=\"email_to\">"+emailadress;				
		xml = xml + "</param>";
		xml = xml + "<param name=\"email_title\">"+autoreply_subject;
		xml = xml + "</param>";
		xml = xml + "<param name=\"email_url\">"+autoreply_url;	
		xml = xml + "</param>";
		xml = xml + "<param name=\"email_link_gotopage\">"+email_link_gotopage;				
		xml = xml + "</param>";
		
		for(var brickid in givenAnswers){
				xml = xml + "<param name=\"bid"+brickid+"\">";
				if(typeof givenAnswers[brickid] == "object"){
					for(var subanswer in givenAnswers[brickid]){
						if(givenAnswers[brickid][subanswer] == ""){
							xml = xml + CDATAencoder(subanswer)+ "#####";
						}
						else{
							xml = xml + CDATAencoder(subanswer)+ " -> "+ givenAnswers[brickid][subanswer]+"#####";
						}
					}
				}	
				else{
					xml = xml + CDATAencoder(givenAnswers[brickid]);
				}
				xml = xml + "</param>";
		}
		
		xml = xml + "</function>";
		xml = xml + "</module>";
	
		r.callback = function donothing() {
//			alert("2:"+r.responseObject.responsetext);
			finished[1] = true;
		};
		finished[1] = false;
		r.post (xml);
	}
	
	if(typeof jasper_template != "undefined" && jasper_template !== ""){
	//alert( 'IN handleSumbit (jasper_template)' );
		
		var arrEmailTo = new Array();
		var arrEmailsTo = email_to.split(';');
		for (var i in arrEmailsTo) {
			 var checkEmail = getAnswerByQID(arrEmailsTo[i]);
			 if (checkEmail.indexOf('@') !== -1)
			 	arrEmailTo[i] = checkEmail;
		}
		var emailadressTo = arrEmailTo.join(';');

	if (typeof extraEmailAddressesTo != "undefined") {
		if (emailadressTo != "" && extraEmailAddressesTo != "") {
			emailadressTo += ";";
		}

		emailadressTo += extraEmailAddressesTo;
	}
        
        var arrEmailCC = new Array();
		var arrEmailsCC = email_cc.split(';');
		for (var i in arrEmailsCC) {
			 var checkEmail = getAnswerByQID(arrEmailsCC[i]);
			 if (checkEmail.indexOf('@') !== -1)
			 	arrEmailCC[i] = checkEmail;
		}
		var emailadressCC = arrEmailCC.join(';');
        
        var arrEmailBCC = new Array();
		var arrEmailsBCC = email_bcc.split(';');
		for (var i in arrEmailsBCC) {
			 var checkEmail = getAnswerByQID(arrEmailsBCC[i]);
			 if (checkEmail.indexOf('@') !== -1)
			 	arrEmailBCC[i] = checkEmail;
		}
		var emailadressBCC = arrEmailBCC.join(';');
        
		var url = "/mappings/xml/informationobject/callToServer";

		var r = http.nonCacheReq (url, true);
		var xml = "<module name=\"data::pdl::survey\">";
		xml = xml + "<function name=\"emailPDFResponse\">";
		xml = xml + "<param name=\"jasper_template\">"+jasper_template;
		xml = xml + "</param>";
		xml = xml + "<param name=\"email_to\">"+emailadressTo;				
		xml = xml + "</param>";
		xml = xml + "<param name=\"email_cc\">"+emailadressCC;				
		xml = xml + "</param>";
		xml = xml + "<param name=\"email_bcc\">"+emailadressBCC;				
		xml = xml + "</param>";
		xml = xml + "<param name=\"email_title\">"+email_title;				
		xml = xml + "</param>";
		
		for(var brickid in givenAnswers){
				xml = xml + "<param name=\"bid"+brickid+"\">";
				if(typeof givenAnswers[brickid] == "object"){
					for(var subanswer in givenAnswers[brickid]){
						if(givenAnswers[brickid][subanswer] == ""){
							xml = xml + CDATAencoder(subanswer)+ "#####";
						}
						else{
							xml = xml + CDATAencoder(subanswer)+ " -> "+ givenAnswers[brickid][subanswer]+"#####";
						}
					}
				}	
				else{
					xml = xml + CDATAencoder(givenAnswers[brickid]);
				}
				xml = xml + "</param>";
		}
		
		xml = xml + "</function>";
		xml = xml + "</module>";


		r.callback = function donothing() {//alert(r.responseObject.responsetext);alert('test');
			finished[2] = true;
		};
		
		finished[2] = false;
		r.post (xml);
	}
	
	// Saving data for use in processdirector
	// retrieve InstanceID & StepID from url
	var instanceid  = getURLParam('processinstanceid');
	var hash = getURLParam('hash');
	if(instanceid != false && hash != false) {
		var rubriekid = getURLParam('rubriekid');
		var taskid = getURLParam('taskid');
		
		var url = "/mappings/xml/informationobject/callToServer";

		var r = http.nonCacheReq (url, true);
		var xml = "<module name=\"data::pdl::processdirector_io\">";
		xml = xml + "<function name=\"saveSchermStepResponse\">";
		xml = xml + "<param name=\"instanceid\">" + replaceSpecialChars(instanceid) + "</param>";
		xml = xml + "<param name=\"hash\">" + replaceSpecialChars(hash) + "</param>";
		xml = xml + "<param name=\"taskid\">" + replaceSpecialChars(taskid) + "</param>";
			
		for(var brickid in givenAnswers){
			xml = xml + "<param name=\"bid"+brickid+"\">";
			if(typeof givenAnswers[brickid] == "object"){
				for(var subanswer in givenAnswers[brickid]){
					if(givenAnswers[brickid][subanswer] == ""){
						xml = xml + subanswer+ "#####";
					} else {
						xml = xml + subanswer+ " -> "+ givenAnswers[brickid][subanswer]+"#####";
					}
				}
			} else {
				xml = xml + replaceSpecialChars(givenAnswers[brickid]);
			}
			xml = xml + "</param>";
		}
		
		xml = xml + "</function>";
		xml = xml + "</module>";

		r.callback = function handleResponse() {
//			var xmlDoc = new ActiveXObject("Microsoft.XMLDOM");
			var xmlDoc = http.compat.xmldoc ();
			
			xmlDoc.async="false";
			xmlDoc.loadXML(r.responseObject.responsetext);
			var response = xmlDoc.selectSingleNode("/InformationObject/data/CommandResponse/Response").nodeTypedValue;
			
			if (response != 'success') {
				alert('Opslaan mislukt: ' + response);
			}
			else {
				alert('Opslaan gelukt');
			}
			finished[3] = true;
		}

		finished[3] = false;
		r.post (xml);
	}
	
	//Start a process
	if (typeof start_process != "undefined" && start_process != "" && start_process != false && start_process != null) {
		var rubriekId = getURLParam('rubriekid');
		
		//If empty, current user will be used
		var processOwnerUserID = '';
		
		var url = "/mappings/xml/informationobject/callToServer";
		
		var r2 = http.nonCacheReq (url, true);
		var xml   = "<module name=\"data::pdl::survey\">";
		xml = xml + "<function name=\"startProcess\">";
		xml = xml + "<param name=\"processName\">" + start_process + "</param>";
		xml = xml + "<param name=\"rubriekId\">" + rubriekId + "</param>";
		xml = xml + "<param name=\"processOwnerUserID\">" + processOwnerUserID + "</param>";
		xml = xml + "</function>";
		xml = xml + "</module>";


		r2.callback = function donothing(theRequest) {
			var xmlDoc = http.compat.xmldoc ();
			
			xmlDoc.async = "false";
			xmlDoc.loadXML(theRequest.responseObject.responsetext);
			var response = xmlDoc.selectSingleNode("/InformationObject/data/CommandResponse/Response").nodeTypedValue;
			
			if (response != 'success') {
				alert("Starten van proces '" + start_process + "' is mislukt. \n\nNeem contact op met uw systeembeheerder en geef de volgende melding door: '" + response + "'.");
			}
			
			finished[4] = true;
		};
		
		finished[4] = false;
		r2.post (xml);
	}
	
	if (goto_url != "" && goto_url != false && goto_url != null) {

		var brickid = "";
		for(var brickid in givenAnswers){
			break;
		}

		var url = "/mappings/xml/informationobject/callToServer";

		var r = http.nonCacheReq (url, true);
		var xml = "<module name=\"data::pdl::survey\">";
		xml = xml + "<function name=\"getSurveyLandingPage\">";
		xml = xml + "<param name=\"brickid\">"+brickid;
		xml = xml + "</param>";
		xml = xml + "<param name=\"goto_url\">"+goto_url;
		xml = xml + "</param>";
		xml = xml + "</function>";
		xml = xml + "</module>";

		r.callback = function donothing(theRequest) {
		
		//			var xmlDoc = new ActiveXObject("Microsoft.XMLDOM");
			var xmlDoc = http.compat.xmldoc ();
			xmlDoc.async="false";
			//this is wrong(IE only):
			//xmlDoc.loadXML(theRequest.responseObject.responsetext);
			if (document.implementation && document.implementation.createDocument){
				try //Firefox, Mozilla, Opera, etc.
				{
					parser=new DOMParser();
					xmlDoc=parser.parseFromString(theRequest.responseObject.responsetext,"text/xml");
				}
				catch(e) {
					//donothing
				}		
			}else{
				try
				{
					xmlDoc.loadXML(theRequest.responseObject.responsetext);
				}catch(e){}
			}
			var cXPathString = "/InformationObject/data/CommandResponse/Response";
			if (document.implementation && document.implementation.createDocument){
				var nodes = xmlDoc.evaluate(cXPathString, xmlDoc, null, XPathResult.ANY_TYPE, null);
				var results = nodes.iterateNext();
				if(results){
					var response = results.innerText;
				}
			}else{
				var response = xmlDoc.selectSingleNode(cXPathString).nodeTypedValue;
			}

			if(response != "error") {
				var strHref = window.location.href;
				//alert("get session");
				if ( strHref.indexOf("?") > -1 ){
					var strQueryString = strHref.substr(strHref.indexOf("?")).toLowerCase();
					var aQueryString = strQueryString.split("&");
					for ( var iParam = 0; iParam < aQueryString.length; iParam++ ){
						if ( aQueryString[iParam].indexOf("sessionid=") > -1 ){
							sessionid = aQueryString[iParam];
							break;
					    }
					}
				}
				if(typeof sessionid != "undefined"){
					if ( response.indexOf("?") > -1 ){
						sessionid = "&" + sessionid;
					}else{
						sessionid = "?" + sessionid;
					}
				}else{
					sessionid = "";
				}
				
				// Safari bug fix (no clue realy)?!?
				var old_goto_url = goto_url;
				goto_url = response + sessionid;
				if (typeof goto_url== 'undefined' || goto_url == 'undefined')
					goto_url = old_goto_url;
				// end of Safari bug fix?!?
			}
			_timer = setTimeout("checkEnqueteFinished()",500);
			
		};
		
		r.post (xml);
	}
	else
	{
		_timer = setTimeout("checkEnqueteFinished()",500);
	}

	return true;		
}

function getWeightOfQuestions(questionId, customMethodName) {
	var brickid = "";
	
	for(var brickid in givenAnswers){
		break;
	}

	var url = "/mappings/xml/informationobject/callToServer";

	var r = http.nonCacheReq (url, true);
	var xml = "<module name=\"data::pdl::survey\">";
	xml = xml + "<function name=\"getWeightOfQuestions\">";
	xml = xml + "<param name=\"brickid\">"+brickid;
	xml = xml + "</param>";
	xml = xml + "<param name=\"questionId\">"+questionId;
	xml = xml + "</param>";
	xml = xml + "</function>";
	xml = xml + "</module>";

	r.callback = function donothing() {
		var xmlDoc = http.compat.xmldoc();
		xmlDoc.async = "false";
		
		if (document.implementation && document.implementation.createDocument) {
			try { //Firefox, Mozilla, Opera, etc.
				parser = new DOMParser();
				xmlDoc = parser.parseFromString(r.responseObject.responsetext, "text/xml");
			} catch(e) { //donothing
			}		
		}else{
			try {
				xmlDoc.loadXML(r.responseObject.responsetext);
			} catch (e) {
			}
		}
		
		var cXPathString = "/InformationObject/data/CommandResponse/Response";
		
		if (document.implementation && document.implementation.createDocument) {
			var nodes = xmlDoc.evaluate(cXPathString, xmlDoc, null, XPathResult.ANY_TYPE, null);
			var results = nodes.iterateNext();
			
			if (results) {
				var response = results.innerText;
			}
		} else {
			var response = xmlDoc.selectSingleNode(cXPathString).nodeTypedValue;
		}
		
		if (eval("typeof " + customMethodName + " == \"function\"")) {
			eval(customMethodName + '(' + response + ');');
		}
		
		if (response != "error") {
			return response;
		} else {
			return 0;
		}
	};
	
	r.post (xml);
}

function checkEnqueteFinished() {
	var check = true;
	if (typeof finished !== "undefined") {
		for (var el in finished) {
			if (finished[el] == false)
				check = false;
		}
	}
	if (check) {
		clearTimeout(_timer);
	    finishEnquete();
		if (goto_url != "" && goto_url != false && goto_url != null) {
			document.location = goto_url;
		}
	} else {
		_timer = setTimeout("checkEnqueteFinished()",500);
	}
}

function getURLParam(param) {
	var s = location.search.toLowerCase().match('(?:\\?|\&)' + param + '=([^\&]*)');
	return s ? unescape(s[1].replace(/\+/g," ")) : false;
}

function replaceSpecialChars(xml) {
	s = new String(xml);
	s = s.replace(/&/g,"&amp;");
	s = s.replace(/</g,"&lt;");
	s = s.replace(/>/g,"&gt;");
	s = s.replace(/\"/g,"&quot;");
	s = s.replace(/\'/g,"&#39;");
	return s;
}

function finishEnquete() {
	// finish enquete (reset session, etc)
	var url = "/mappings/xml/informationobject/callToServer";
	var r = http.nonCacheReq (url, true);
	
	var xml = "<module name=\"survey\">";
	xml = xml + "<function name=\"finishEnquete\">";
	
	for (var brickid in givenAnswers) {
		xml = xml + "<param name=\"bid"+brickid+"\">";
		if (typeof givenAnswers[brickid] == "object") {
			for (var subanswer in givenAnswers[brickid]) {
				if (givenAnswers[brickid][subanswer] == "") {
					xml = xml + CDATAencoder (subanswer + "#####");
				} else {
					xml = xml + CDATAencoder (subanswer + " -> " + givenAnswers[brickid][subanswer]+"#####");
				}
			}
		} else {
			xml = xml + CDATAencoder (givenAnswers[brickid]);
		}
		xml = xml + "</param>";
	}
	
	xml = xml + "</function>";
	xml = xml + "</module>";
	
	r.callback = function donothing() {
		if (typeof enquetePostAction == "function") {
			enquetePostAction();
		}
	};
	
	r.post (xml);
}

function showwizardHelp (el) {
	var div = nodes.parentNodeBy(el, 'nodeName=DIV');
	var help = nodes.childNodeBy(div, 'className=wizardRow3');
	help.style.display='block';
	var titleEl = nodes.childNodeBy(help, 'id=wizardhelpquestion',true);
	
	if(titleEl != false){
		if(titleEl.innerHTML == ""){
			var wholeBrickEl = nodes.parentNodeBy(help, 'name=wholequestion');
			var questionEl = nodes.childNodeBy(wholeBrickEl, 'id=question', true);
			
			if(questionEl != false){
				titleEl.innerHTML = questionEl.innerHTML;
			}
		}
	}
	
	
	if (typeof showwizardHelp.show == 'object' && showwizardHelp.show != help) 
		showwizardHelp.show.style.display = 'none';
	
	showwizardHelp.show = help;
}

function handleFormFlow(button){
	//alert("in handleFormFlow");
	var url = "/mappings/xml/informationobject/callToServer";
	var r = http.nonCacheReq (url, true);

	var processname = false;
	var processinstanceid = false;
	var processstepname = false;
	
	if (typeof requestVars != 'undefined') {
		if (typeof requestVars ['processname'] !== 'undefined')
			processname = requestVars ['processname'];
		if (typeof requestVars ['processid'] !== 'undefined')
			processinstanceid = requestVars ['processid'];
		if (typeof requestVars ['processstepname'] !== 'undefined')
			processstepname = requestVars ['processstepname'];
	}

	if(processname === false){
		processname = 	button.nextSibling.nextSibling.innerText;
	}
	
	if(processstepname === false){
		processstepname = button.nextSibling.nextSibling.nextSibling.innerText
		if (processstepname == '' || processstepname == "initiate") {
			processstepname = "initiate";
			if(processinstanceid === false){
				processinstanceid = generateNewProcessInstanceId(processname);
			}
		}
	}

	var errStr = '';
	
	if ( processname === false){
		errStr = ' the processname';
	}

	if(processstepname === false) {
		if (errStr == '')
			errStr = ' the processstepname';
		else
			errStr += ' and the processstepname';
	}

	if ( processinstanceid === false) {
		if (errStr == '') 
			errStr = ' the processinstanceid';
		else
			errStr += ' and the processinstanceid';
	}

	if (errStr != '') {
		alert ('Fatal error: we are missing'+errStr);
		return false;
	}

	var xml = 	"<?xml version=\"1.0\" encoding=\"ISO-8859-1\" ?>";
	
	xml = xml + "<module name=\"system::wizard\">";
	xml = xml + "<function name=\"saveFormFlowData\">";
	xml = xml + "<param name=\"processinstanceid\">"+processinstanceid;
	xml = xml + "</param>";
	xml = xml + "<param name=\"processstepname\">"+processstepname;
	xml = xml + "</param>";
	xml = xml + "<param name=\"processname\">"+processname;
	xml = xml + "</param>";
	
	//alert("going to make XML");
	for(var brickid in givenAnswers){
		var uniqueid = numbers[brickid]['uniqueId'];
		xml = xml + "<param name=\""+uniqueid+"\">";
		if(typeof givenAnswers[brickid] == "object"){
			var ans = "";
			for(var subanswer in givenAnswers[brickid]){
				if(givenAnswers[brickid][subanswer] == ""){
					if(ans == ""){
						ans = subanswer;
					}
					else{
						ans = ans+";;;;;"+subanswer;
					}
				}
			}
			if(ans != ""){
				xml = xml + CDATAencoder(ans);
			}
			
		}	
		else{
			xml = xml + givenAnswers[brickid];
		}
		xml = xml + "</param>";
	}
	
	xml = xml + "</function>";
	xml = xml + "</module>";	
	var after_step_url = 	button.nextSibling.nextSibling.nextSibling.nextSibling.innerText;
	
	r.callback = function doProcessStepReq() { handleProcessStepReq(processname, processstepname,  processinstanceid, after_step_url);};
	r.post (xml);
}

function startProcess (processname) {
	var processinstanceid = generateNewProcessInstanceId(processname);
	return handleProcessStepReq(processname, 'initiate', processinstanceid);
}

function handleProcessStepReq(processname, processstepname,  processinstanceid, after_step_url){
	
	//alert("IN handleProcessStepReq :: "+processname +" :: "+ processstepname +" :: "+  processinstanceid);
	var url2 = "/mappings/xml/informationobject/processes";
							
	var r2 = http.nonCacheReq (url2, true);	
	
	var xml2 = 	"<?xml version=\"1.0\" encoding=\"ISO-8859-1\" ?><InformationObject>";
	
	//Send process request
	xml2 = xml2 + "<processsteprequest>";
	xml2 = xml2 + "<ProcessName>" + processname + "</ProcessName>";
	xml2 = xml2 + "<ProcessStepName>" + processstepname + "</ProcessStepName>";
	xml2 = xml2 + "<Action>action</Action>";
	xml2 = xml2 + "<ProcessInstanceId>" + processinstanceid + "</ProcessInstanceId>";

	xml2 = xml2 + "</processsteprequest>";
	
	xml2 = xml2 + "</InformationObject>";
	//alert(xml2);
	r2.callback = function donothing() {
		if(after_step_url != "" && after_step_url != false && after_step_url != null){
			top.location = after_step_url;
		} else {
			top.location = top.location;
		}
	};
	r2.post (xml2);

}

function generateNewProcessInstanceId(str){
	return str +"_"+new Date().getTime()+Math.floor(Math.random()*1000000);
}

/*
 * DATE FORMATTING functions
 */

 // put validation functions in the Tjip namespace
Tjip = new Object();
Tjip.Match = _Match;

function _Match( re, string )
	/* Test to see if string conforms to the given regular expression re */
{
	re = new RegExp( "^" + re + "$" );
	return re.test( string );
}

function DateObject( year, month, day )
	/* Structure for storing numerical year, month and day data. */
	/* year is from 1000 to 3000, month is from 1 to 12, day is from 1 to 31*/
{
	this.year = year;
	this.month = month;
	this.day = day;
}

function dateParser( dateString )
	/* Parses the date string (in any format supported by Meetingpoint) and returns date object */
	/* Return object with year = -1 on error. */

{

	var year = month = day = 0; // numerical representation
	var y = m = d = "0";        // string representation
	if ( Tjip.Match( "\\d{8}", dateString ) ) {
		// ddmmccyy format
		d = dateString.substring( 0, 2 );
		m = dateString.substring( 2, 4 );
		y = dateString.substring( 4, 8 );
	} else if ( Tjip.Match( "\\d{6}", dateString ) ) {
		// ddmmyy format
		d = dateString.substring( 0, 2 );
		m = dateString.substring( 2, 4 );
		y = dateString.substring( 4, 6 );
	} else {
		splitter = '';
		if ( Tjip.Match( "(\\d){1,4}-\\d{1,2}-(\\d){1,4}", dateString ) )
			splitter = '-';
		if ( !splitter && Tjip.Match( "(\\d){1,4}/\\d{1,2}/(\\d){1,4}", dateString ) )
			splitter = '/';
		if ( splitter ) {
			
			// sometimes in IE a empty dateString accurs. No clue why that is [JV]
			// bugfix: hide the error.
			try {
				list = dateString.split( splitter );
				if ( list[ 0 ].length == 4 ) {
					// ccyy-mm-dd format
					y = list[ 0 ];
					m = list[ 1 ];
					d = list[ 2 ];
				} else {
					// (d)d-(m)m-(cc)yy format
					d = list[ 0 ];
					m = list[ 1 ];
					y = list[ 2 ];
				}
			} catch (e){}
		}
	}
	year  = 1*y;
	month = 1*m;
	day   = 1*d;
	if ( year >= 0 && year < 100 && y.length == 2 ) {
		// determine how many centuries to add
		now = new Date();
		compYear = ( now.getFullYear() + 5 ) % 100;
		if ( compYear < year )
			year += 1900;
		else
			year += 2000;
		y = year.toString();
	}
	var ret;
	nDays = getDaysOfMonth( year, month );
	if ( day < 1 || day > nDays || month < 1 || month > 12 || year < 1000 || year > 3000 ||
			y.length != 4 || m.lenght < 1 || m.length > 2 || d.lenght < 1 || d.length > 2 )
		// invalid date
		return new DateObject( -1, 0, 0 );
	else
		return new DateObject( year, month, day );
}

/* Format from any valid MP date format to return mm-dd-ccyy format */
function formatDate( mpDateIn )
{
	date = dateParser( mpDateIn );
	if ( date.year == -1 ) {
		return mpDateIn; // do nothing when wrong date format is entered
	}
	return _formatDateObject( date );
}

function _formatDateObject( dateObject )
{
	d = dateObject.day;
	m = dateObject.month;
	y = dateObject.year;
	result = ( d <= 9 ? '0' : '' ) + d + '-' + ( m <= 9 ? '0' : '' ) + m + '-' + y;
	//result = y + '-' + ( m <= 9 ? '0' : '' ) + m + '-' + ( d <= 9 ? '0' : '' ) + d;
	return result;
}

function getDaysOfMonth( y, m )
	/* return number of days in month m of year y ( with 1 <= m <= 12 ); return 0 on error */
{
	days = 0;
	if ( m == 1 || m == 3 || m == 5 || m == 7 || m == 8 || m == 10 || m == 12 )
		days = 31;
	else if ( m == 4 || m == 6 || m == 9 || m == 11 )
		days = 30;
	else if ( m == 2 ) {
		if ( ( y % 4 ) == 0 && ( y % 100 ) != 0 || ( y % 400 ) == 0 )
			days = 29; // for leap years
		else
			days = 28;
	}
	return days;
}

function _IsValidDate( dateString )
	/* See if given date string parses to a valid date */
{
	d = dateParser( dateString );
	return d.year != -1;
}

/**
 * extra functions for percentage questions
 * in it's own namespace ;)
 */
var __checkPercentage = {
		focus :  function (e) {
			e = e || window.event;
			var src = e.srcElement || e.target;
			__checkPercentage.hasFocus = true;
			src.onblur = __checkPercentage.checkBlur;
		},
		keydown: function (e) {
			
			e = e || window.event;
			var src = e.srcElement || e.target;
			
			__checkPercentage.oldValue = src.value;
			__checkPercentage.src = src;
			
			window.setTimeout ( 
				function () {
					if (__checkPercentage.src.value=='') {
						//add the  user value to a global var
						answeredQuestion(src);
						return false;
					}
					
					var parent = nodes.parentNodeBy (src, 'className=' +  __checkPercentage.className);
					
					if (!parent)
						return false;
					
					var inputs = parent.getElementsByTagName('INPUT');
					
					if (!inputs)
						return false;	
					
					if (/^[0-9]+$/.test (__checkPercentage.src.value) === false)			
						__checkPercentage.src.value = __checkPercentage.oldValue;
					
					if (__checkPercentage.src.value > 100)
						__checkPercentage.src.value = 100;
										
					var total = __checkPercentage.countTotal (inputs);
					
					if(total[0]>100) {
						alert(__checkPercentage.error1)
						var _t = total[0] - parseInt(src.value);
						src.value = 100-_t;
						src.focus();
					}
					//add the  user value to a global var
					answeredQuestion(src);
				},
				1
			)
		},
	
		totals:function (parent) {
				
			var inputs = parent.getElementsByTagName('INPUT')
			
			if (!inputs)
				return false;
			
			var total = __checkPercentage.countTotal (inputs, true);
			
			if(total[0]!=100) {
				try {
					alert(__checkPercentage.error0);
					inputs[total[1]-1<0? 0: total[1]-1].focus();
				} catch (e) {}
			}
		},
	
		countTotal: function (inputs, makeZero) {
			var total = 0;
			var tmpI = 0;
			for (var i=0;i<inputs.length;i++)
				if (inputs[i].type=='text')
					if (inputs[i].value!='') {
						tmpI++;
						total += parseInt(inputs[i].value);
					}

			return [total,tmpI];
		},
		
		checkBlur: function (e) {
			__checkPercentage.hasFocus = false;
			e = e || window.event;
			var src = e.srcElement || e.target;
			var parent = nodes.parentNodeBy(src, 'className=' + __checkPercentage.className);
			
			if (!parent)
				return false;
				
			window.setTimeout ( 
				function () {
					if (__checkPercentage.hasFocus === false ) 
						__checkPercentage.totals(parent)
				},
				2
			)
		},
		
		className:'question_table',
		error0: 'het totaal van de ingevulde procentuele-vraag moet 100% zijn!',
		error1: 'Het totaal van de ingevulde vraag kan niet groter zijn dan 100%',
		hasFocus : false
	}
	
	/**
	 * This method displays an wait icon on the given element of the wizard. This icon is only 
	 * shown if the option 'useVolgendeVorigeWachtIcoon' is set in the html writer of the site and 
	 * has the value 'true'. The icon is reset when the next or previous page is shown, so it isn't 
	 * neccesary to hide the icon.
	 *
	 * @param	el	The element wich is replaced with the wait icon.
	 *
	 * @see		See Bureau Leemans for an example.
	 */
	function showWaitIconOnElement(el) {
	//alert('IN showWaitIconOnElement');
		if (typeof useVolgendeVorigeWachtIcoon != "undefined" && 
				useVolgendeVorigeWachtIcoon == true) {
			if (!el)
				return false;
			
			el.style.display = "none";
			
			var waitEl = document.getElementById("wait_icon");
			
			if (!waitEl)
				return false;
			
			waitEl.className = "waitbutton";
		}
	}

