/****************************************************************** 
 System:	Dynamic Dialogue (DD) System File

 File:		dd_questionnaire.js

 Title:		Client part of the dd_item questionnaire.

**************************************************************** 
 Description:  
 		Script for the questionnaire item: 
 		Functions:
 			toggleHelp: shows a HelpBox
 			toggleHelpOff: hideds all helpboxes
 			addRow: add a row to a table

 History		Version		Person	Remark
 21-11-2006 	1.0			RuBr	Creator 
		Created this file
*******************************************************************/

/*GLOBAL DECLARATIONS*/
	var HelpBoxes;

/*FUNCTIONS FOR HELPBOXES*/	
	/*init HelpBoxes array*/
	function initHelpBoxes(listOfHelpBoxes){
		HelpBoxes = new Array();
		
		for(counter = 0; counter < listOfHelpBoxes.length; counter++){
			HelpBoxes[HelpBoxes.length] = listOfHelpBoxes[counter];
		}	
	}
	
	/*hide all helpboxes and show given element*/
	function toggleHelp(elementid) {
		for(counter=0; counter < HelpBoxes.length; counter++) {
			var objHide = document.getElementById(HelpBoxes[counter]);
			objHide.style.display = 'none';
		}
						
		var objVisible = document.getElementById(elementid);
		objVisible.style.display = '';
	}
					
	/*hide all helpboxes*/
	function toggleHelpOff() {
		for(counter=0; counter < HelpBoxes.length; counter++) {
			var objHide = document.getElementById(HelpBoxes[counter]);
			objHide.style.display = 'none';
		}
	}
	
/*FUNCTIONS FOR TABLE ROWS*/

	/*add row to table and fill with the list of cells*/
	function addDeelVraagRow(table_id, listOfCells, parentid){
		/*declare variables*/
		var objTable = document.getElementById(table_id);
		var row = objTable.insertRow(objTable.rows.length);					
		var cell;
		var cellHTML;
		/*loop over list of cells*/
		for(counter=0; counter < listOfCells.length; counter++) {
			
			cell = row.insertCell(counter);
			cellHTML = "<input type='hidden' name='PARENT_ID_F' value='"+parentid+"' />";
			cellHTML += "<input type='hidden' name='POSITIE_F' value='"+objTable.rows.length+"' />";
			cellHTML += "<input type='hidden' name='DEELVRAAG_ID_F' value='"+listOfCells[counter][0]+"' />";
			if(listOfCells[counter][1]!='open'){
				cellHTML += "<input type='checkbox' style='border:0px;' onclick='javascript:changeState(this,Checkbox_"+listOfCells[counter][0]+"_"+objTable.rows.length+")' />";
				cellHTML += "<input type='hidden' name='DEELVRAAG_ANTWOORD_F' id='Checkbox_"+listOfCells[counter][0]+"_"+objTable.rows.length+"' value='off'></input>";
			}
			else {
				cellHTML += "<input type='text' name='DEELVRAAG_ANTWOORD_F' />";
			}
			cell.innerHTML = cellHTML;
		}
	}
	
	function changeState(obj, obj2){
		var hiddenObj = document.getElementById(obj2);
		if(obj.checked == true){
			obj2.value = 'on';
		}
		else{
			obj2.value = 'off';
		}
	}
	
	function sliderChange(element, valueElement, itemName, markerImage, clearImage){
		//get all the element with the name names
		var items = document.getElementsByName(itemName);
		
		for (i in items){
			//set all items to clear, which have for source, markerImage
			if(items[i].src = markerImage){
				items[i].src = clearImage;
			}
		}
		//set clicked element to marked
		element.src = markerImage;
		var valueObj = document.getElementById(valueElement);
		valueObj.value = element.alt;
	}
	

	
	function textCounter(field,cntfield,maxlimit) {
		
		var val;
		if(typeof(field.getValue) == 'undefined') {
			val = field.value;
		}
		else {
			val = field.getValue();		
		}
		
		
		if (val.length > maxlimit) { // if too long...trim it!
			if(typeof(field.setValue) == 'undefined') {
				field.value = field.value.substring(0, maxlimit);
			}
			else {
				field.setValue(val.substring(0, maxlimit));
			}
		}
		else {
			cntfield.value = maxlimit - val.length;
		}		
	}
	

	function addQuestionToArray(question_id, answer, action, dst_question_id) {
		var item = new Array();
		var dst_item = new Array();
		
		dst_item['action'] = action;
		dst_item['dst_question_id'] = dst_question_id;
			
		var index = findDestQuestionInArray(question_id, answer, action);
		if(index != -1) {
			q_controls[index]['dst_item'].push(dst_item);
		} else {
			item['question_id'] = question_id
			item['answer']= answer;
			item['dst_item'] = new Array();
			item['dst_item'].push(dst_item);
			q_controls.push(item);
		}
	}
	
	function findDestQuestionInArray(question_id, answer, action) {
		for(var i=0; i<q_controls.length; i++) {
			var item = q_controls[i];
			if(item['question_id'] == question_id &&  (item['answer'] == answer || item['answer'] =='') ) {
				return i;
			}
		}
		
		return -1;
	}
	
	function initQuestionEvent() {
		for(var i=0; i<q_controls.length; i++) {
			var item = q_controls[i];
			var qels = document.getElementsByName(item['question_id']);
			
			for(var ii=0; ii < qels.length; ii++) {
				var el = qels[ii];
				
				if (el.addEventListener) {
					el.addEventListener("change", 
						function() {
							showhiddenQuestionControl(this);
						}
					, false);
				} else {
					el.attachEvent("onchange",
						function() {
							showhiddenQuestionControl(this);
						}
					);
				}
			}
		}
		
		initQuestionControls();
	}

	function initQuestionControls() {
		require(["dojo/ready"], function(ready){
	 		ready(2000,function(){ 
				var allreadinit = new Array();
				
				for(var i=0; i<q_controls.length; i++) {
					var item = q_controls[i];
					var show = false;
					
					if(allreadinit.indexOf(item['question_id']) != -1) {
						continue;
					}
					
					var qels = document.getElementsByName(item['question_id']);
					
					for(var ii=0; ii < qels.length; ii++) {
						var el = qels[ii];
						var elId = el.value.substr(0, el.value.indexOf('^^'));
					
						if((elId == item['answer'] || item['answer'] =='') && el.checked) {
							show = true;
							allreadinit.push(item['question_id']);
							break;
						}
					}
					activateDisplayRules(item['dst_item'], show, elId, true);					
				}
			});
		});
	}
	
	function showhiddenQuestionControl(el) {
		
		var elId = el.value.substr(0, el.value.indexOf('^^'));
		var elIds = el.id.split('_');
		
		
		var item = findDestQuestionById(elIds[0], elId);
		if(item == null) {
			return;
		}

		if(elId == item['answer']  || item['answer'] =='') {
			activateDisplayRules(item['dst_item'], true, elId, false);
		}
	}

	function findDestQuestionById(question_id, answer) {
		for(var i=0; i<q_controls.length; i++) {
			var item = q_controls[i];
			if(item['question_id'] == question_id && (item['answer'] == answer || item['answer'] =='')) {
				return item;
			}
		}
		
		return null;
	}
		
	function activateDisplayRules(controls, show, val, init) {
		if (!init) {
			for(var i=0; i < controls.length; i++) {
				var actionFull = controls[i]["action"];
				var action = actionFull.substr(0, actionFull.indexOf('|'));
				console.log(action);
				var params = actionFull.substr(actionFull.indexOf('|') + 1);
				console.log(params);
				
				/* define the function 'index' */
				if(action == "FromFirstToLast" && !init) {
					settagval(controls[i]["dst_question_id"], val, params);
					
				}
			}
		}
	}
	
	function settagval(targetElement, instance_id, tags) {
		require(["dijit/registry","dojo/domReady!"], function(reg) {
			try {
				if (instance_id.length > 0) {
					var resval = '';
					while (tags.length > 0) {
						var end = tags.indexOf('|');
						var tag;
						if (end == -1) {
							tag = tags;
							tags = '';
						} else {						
							tag = tags.substr(0, end);
							tags = tags.substr(end + 1);
						}
					
						var dataurl = 'cheyenne?cddid=json.instance_tag_val&cmode=json&P_TAG='+tag+'&P_INSTANCE_ID=' + instance_id
						/* Op deze wijze worden de waardes geconcateneerd. De volgorde is echter willekeurig. Dit is een uitzoekopdracht wanneer dit echt relevant wordt. */
						require(
							[ "dojo/json","dojo/request/xhr", "dojo/promise/all", "dojo/Deferred", "dojo/_base/lang","dojo/domReady!" ],
							function(JSON,xhr,all,Deffered,lang) {
								var taxonomyDefinition = xhr(dataurl, {handleAs : "json"});
		
								all([taxonomyDefinition]).then(function(results){
									var value = results[0].option.name;
									resval += ' ' + ((value) ? value : '');
									if (document.getElementById(targetElement)) {
										console.log('set value ' + resval);
										document.getElementById(targetElement).value = resval;
									} else if(reg.byId(targetElement)) {
										console.log('dijit found');
										//check dijit reg
										var dojoObj=reg.byId(targetElement);
										dojoObj.set('value',resval);
									} else if(reg.byId(targetElement + '_VALUE')) {
										console.log('dijit VALUE found');
										//check dijit reg
										var dojoObj=reg.byId(targetElement + '_VALUE');
										dojoObj.set('value',resval);
									}
								});
						});
					}

				}
			}
			catch(err) {
				
			}	
		});
	}