/**
 * XMS standard functions
 */

var XMS = {
	
	init: function() {
	},
	
	/**
	 * Saves calendar preferences
	 * @todo Should be in XMS.XMSCalendar namespace
	 */
	savePreferences: function (block_id, categories, appointment_types, country) {
		Slik.HTTP.callHandler('setUserPreferences', {'class': 'XMSCalendarBlock', 'id':block_id, 'appointment_types':appointment_types, 'categories':categories, 'country':country}, Slik.HTTP.writeElement, 'savePreferences');
	},
	
	/**
	 * Goes to a website, logging the visit locally
	 * @todo Should be in XMS.XMSCalendar namespace
	 */
	goToWebsite: function(block_class, block_id, record_class, record_id) {
		Slik.HTTP.callHandler('goToWebsite', {'class': block_class, 'id':block_id, 'record_class':record_class, 'record_id':record_id});
	}
	
};

var XMSPortalBlock = {
	
	selectCategory: function (elm, block_class, block_id, category_id) {
		
		if(!elm){ return false; }
		
		// reset the product items list.
		XMSPortalBlock.resetCategoryLinkedItems();
		
		// set the active class on the clicked element
		if((elm.parentNode).tagName == "LI"){
			var siblings = elm.parentNode.parentNode.children;
			if(siblings){
				for(var i=0; i<siblings.length; i++) { siblings[i].className = ""; }
				elm.parentNode.className = "active";
			}
		}
		
		XMSPortalBlock.getSubCategories(block_class, block_id, category_id);
	},	
	
	selectSubCategory: function (elm, block_class, block_id, category_id) {
		
		if(!elm){ return false; }
		
		// set the active class on the clicked element
		if((elm.parentNode).tagName == "LI"){
			var siblings = elm.parentNode.parentNode.children;
			if(siblings){
				for(var i=0; i<siblings.length; i++) { siblings[i].className = ""; }
				elm.parentNode.className = "active";
			}
		}
		
		XMSPortalBlock.getCategoryLinkedItems(block_class, block_id, category_id);
	},	
		
	getSubCategories: function (block_class, block_id, category_id) {
		Slik.HTTP.callHandler('getChildCategories', {'class': block_class, 'id':block_id, 'category_id':category_id}, Slik.HTTP.getJSON, function(response){
			var container = ( document.getElementById("itemSelectionSubCategory") ) ? document.getElementById("itemSelectionSubCategory") : null;
			
			if(container){
				container.innerHTML = response.html;
				if(Cufon){ Cufon.refresh();	}
			}
		});
	},
	
	getCategoryLinkedItems: function (block_class, block_id, category_id) {
		Slik.HTTP.callHandler('getCategoriesLinkedRecords', {'class': block_class, 'id':block_id, 'category_id':category_id}, Slik.HTTP.getJSON, function(response){
			var container = ( document.getElementById("itemSelectionProduct") ) ? document.getElementById("itemSelectionProduct") : null;
			
			if(container){
				container.innerHTML = response.html;
				if(Cufon){ Cufon.refresh();	}
			}
		});
	},
	
	resetCategoryLinkedItems: function() {
		var message = (document.getElementById("choose_category_subcategory")) ? document.getElementById("choose_category_subcategory").value : null;
		var container = (document.getElementById("itemSelectionProduct")) ? document.getElementById("itemSelectionProduct") : null;
	
		if(container) {
			container.innerHTML = "<span>"+message+"</span>";
		}
	}
	
};

var XMSSurveyNavigation = {
	switchActivePage : function (newPageNumber) {
		var surveyPages = XMSSurveyNavigation.getSurveyPages();
		
		for (var i = 0; i < surveyPages.length; i++ ) {
			var page = surveyPages[i];
			page.style.display = 'none';
		}
		
		// hide the submit button unless it is the last page of the survey part
		var submitButton = document.getElementById("surveyPartSubmitButton");

		if (newPageNumber == surveyPages.length || surveyPages.length == 0) {
			submitButton.style.display='';
		}
		else {
			submitButton.style.display='none';
		}

		var newPage = document.getElementById("xmsSurveyPage_" + newPageNumber);
		if(newPage) {
			newPage.style.display = '';
		
			XMSSurveyController.currentStep = newPageNumber - 1;
			XMSSurveyController.updateProgressBar();	
		}
		
		// go to the top of the new page
		scroll(0,0);
	},
	getSurveyPages: function () {
		var pages = new Array();
		
		// find all divs
		var divs = document.getElementsByTagName("div");
		for (var i = 0; i < divs.length; i++) {
			if (divs[i].className.indexOf('xmsSurveyPage') > -1) {
				pages.push(divs[i]);
			}
		}
		return pages;
	}
};

// Disable <enter> submission in all inputs, except for textareas
function stopEnterKey(evt) {
  var evt = (evt) ? evt : ((event) ? event : null);
  var node = (evt.target) ? evt.target : ((evt.srcElement) ? evt.srcElement : null);

  
  if ((evt.keyCode == 13) && (node.nodeName.toLowerCase()!="textarea"))  {return false;}
}

XMS.XMSSurveyPartBlock = new Object();
XMS.XMSSurveyPartBlock.questions = new Array();
XMS.XMSSurveyPartBlock.blockElement = null;
XMS.XMSSurveyPartBlock.form = null;

XMS.XMSSurveyPartBlock.getQuestionId = function(element) {
	var dom_id = element.id;
	var question_id = dom_id.substr(dom_id.lastIndexOf('_')+1);
	return question_id;
};

XMS.XMSSurveyPartBlock.init = function(form_id, block_id) {
	
	// Avoid the form to be sent when using the enter key
	document.onkeypress = stopEnterKey;
	
	XMS.XMSSurveyPartBlock.form = document.getElementById(form_id);
	XMS.XMSSurveyPartBlock.blockElement = document.getElementById(block_id);
	
	// Store indexed references to the DOM question objects
	var questions = YAHOO.util.Dom.getElementsByClassName('XMSSurveyQuestion', '', XMS.XMSSurveyPartBlock.form);
	for (var x=0; x < questions.length; x++) {
		var question_id = XMS.XMSSurveyPartBlock.getQuestionId(questions[x]);
		XMS.XMSSurveyPartBlock.questions[question_id] = questions[x];
	}
	
	//	Initialize disabled state of all questions
	XMS.XMSSurveyPartBlock.checkDisabledQuestions();
	
	/*	
	var inputs = XMS.XMSSurveyPartBlock.form.getElementsByTagName('label');
	for (var y=0;y < inputs.length; y++) {
		YAHOO.util.Event.addListener(inputs[y], "click", function(e) {
			console.log(e);
			if (e && e.target && e.target.tagName.toUpperCase() == 'input') {
				YAHOO.util.Event.stopPropagation(e);
				YAHOO.util.Event.stopEvent(e);
				YAHOO.util.Event.preventDefault(e);
			}
		});
	}
	
	var inputs = XMS.XMSSurveyPartBlock.form.getElementsByTagName('input');
	for (var y=0;y < inputs.length; y++) {
		YAHOO.util.Event.addListener(inputs[y], "click", XMS.XMSSurveyPartBlock.checkDisabledQuestions, inputs[y]);
		YAHOO.util.Event.addListener(inputs[y], "keyup", XMS.XMSSurveyPartBlock.checkDisabledQuestions, inputs[y]);		
	}
	*/
	
	YAHOO.util.Event.delegate(block_id, "click", function(e, matchedEl, container) {
		if (matchedEl.tagName.toLowerCase() == 'input' && matchedEl.disabled) {
			return false;
		}
		XMS.XMSSurveyPartBlock.checkDisabledQuestions(matchedEl);
	}, 'input');
	
	YAHOO.util.Event.delegate(block_id, "keyup", function(e, matchedEl, container) {
		XMS.XMSSurveyPartBlock.checkDisabledQuestions(matchedEl);
	}, 'input');

};

XMS.XMSSurveyPartBlock.checkAnswers = function(form) {
	var callback = {
		success: function(o) {
			// handleCheckAnswers() returns associative array of question_id => "question name"
			try {
				var results = YAHOO.lang.JSON.parse(o.responseText);
			} catch (e) {
				alert("Er is een fout opgetreden. Probeer het nogmaals, of neem contact op via het contactformulier.");
				// reenable the submit button
				document.getElementById('surveyPartSubmitButton').disabled=false;
				return;
			}
			
			var invalid_question_ids = results['div_ids'];
			var firstErrorPage = results['first_error_page'];
			
			if (!invalid_question_ids || invalid_question_ids.length == 0) {
				return XMS.XMSSurveyPartBlock.submitAnswers(form);
			}

			// first make sure all question are not marked invalid
			var allDivs = YAHOO.util.Dom.getElementsByClassName('XMSSurveyQuestion', null, XMS.XMSSurveyPartBlock.blockElement); 
			for (var i = 0; i < allDivs.length; i++) {
				XMSUtil.removeClass(allDivs[i], "invalid");
			}

			// now mark the invalid questions as invalid
			for (var i = 0; i < invalid_question_ids.length; i++) {
				var question = document.getElementById(invalid_question_ids[i]);
				// some surveys (ACT/Batman-diary) have a different HTML-structure, so
				// we cannot find these elements and give them the 'invalid' class
				// so we ignore these and only show the alert
				if (question) {
					XMSUtil.addClass(question, "invalid");
				}
			}
			
			// activate the first page on which an error occurs
			XMSSurveyNavigation.switchActivePage(firstErrorPage);
			
			// and go to the top of the page
			scroll(0,0);
			
			//	Print a message
			var message = "Een of meer vragen zijn niet (goed) ingevuld.";
			alert(message);

			// reenable the submit button
			document.getElementById('surveyPartSubmitButton').disabled=false;
		}, 
		failure: function(o) {
			alert("Er is een fout opgetreden:\n" + o.statusText);

			// reenable the submit button
			document.getElementById('surveyPartSubmitButton').disabled=false;
		},
		argument: [form]
	};
	
	//	We post to the current URL
	//	First remove the hash and everything after it
	var href = document.location.href;
	var hashPos = href.indexOf("#");
	if (hashPos > -1) {
		href = href.substring(0, hashPos);
	}
	
	form.method.value = "checkAnswers";
	YAHOO.util.Connect.setForm(form);
	YAHOO.util.Connect.asyncRequest("POST", href, callback);
	return false;
};

XMS.XMSSurveyPartBlock.submitAnswers = function(form) {
	//	Clear form onsubmit so our checking handler does not get called any longer
	form.method.value = "submitAnswers";
	form.onsubmit = null;
	form.submit();
};

XMS.XMSSurveyPartBlock.disableInput = function(el) {
	el.disabled = true;
	YAHOO.util.Dom.addClass(el, 'disabled');	
};

XMS.XMSSurveyPartBlock.enableInput = function(el) {
	el.disabled = false;
	YAHOO.util.Dom.removeClass(el, 'disabled');	
};

XMS.XMSSurveyPartBlock.enableAll = function() {
	var form = XMS.XMSSurveyPartBlock.form;
	YAHOO.util.Dom.getElementsByClassName('disabled', 'div', form, function(obj) {
		YAHOO.util.Dom.removeClass(obj, 'disabled');
	});
	YAHOO.util.Dom.getElementsByClassName('disabled', 'tr', form, function(obj) {
		YAHOO.util.Dom.removeClass(obj, 'disabled');
	});
	YAHOO.util.Dom.getElementsByClassName('disabled', 'input', form, function(obj) {
		XMS.XMSSurveyPartBlock.enableInput(obj);
	});
};

XMS.XMSSurveyPartBlock.checkDisabledQuestions = function(e, el) {

	if (el && el.tagName.toLowerCase() == 'input' && el.disabled) {
		return;
	}

	var form = XMS.XMSSurveyPartBlock.form;
	form.method.value = "checkDisabledQuestions";
	
	// We want to post ALL answer inputs to the server.
	// Disabled inputs will not be posted by the browser, so we enable them first.
	// Keep track of which inputs were enabled.
	var was_disabled = new Array();
	YAHOO.util.Dom.getElementsByClassName('disabled', 'input', form, function(obj) {
		XMS.XMSSurveyPartBlock.enableInput(obj);
		was_disabled.push(obj);
	});
	
	// Capture the form data; setForm() returns the form input data.
	var formData = YAHOO.util.Connect.setForm(form);
	
	// Re-disable all original disabled inputs to their old status, so they don't flash visibly while the handler is being called.
	for (var i in was_disabled) {
		XMS.XMSSurveyPartBlock.disableInput(was_disabled[i]);
	}
	
	// Call the handler with all questions in the form data
	Slik.HTTP.callHandler('checkDisabledQuestions', formData, Slik.HTTP.getJSON, function(response) {
		form.method.value = 'submitAnswers';
		
		// Server has (hopefully) returned the question id's to disable.
		// First, enable everything again to start over with a clean slate.
		XMS.XMSSurveyPartBlock.enableAll();

		if (response.disabled_questions) {
			var ids = response.disabled_questions;
			for (var x in ids) {
				var question_element = XMS.XMSSurveyPartBlock.questions[ids[x]];
				if (!question_element) {
					throw new Exception(Slik.err='Error: question with id '+ids[x]+' not found');
				}
				
				//	Add "disabled" class to the containing element (div or tr)
				YAHOO.util.Dom.addClass(question_element, 'disabled');
				
				//	Disable all the inputs within this div
				var question_inputs = question_element.getElementsByTagName('input');
				for (var y=0;y < question_inputs.length; y++) {
					XMS.XMSSurveyPartBlock.disableInput(question_inputs[y]);
				}
			}
		}
	}, null, null, true);
};

var XMSSurveyController = {
		
	currentStep : 0,
	
	// number of steps is set in XMSSurveyPartBlock.tpl
	numberOfSteps : 0,
	
	init : function() {
		// hide the progress bar when there is just one page
		if (XMSSurveyController.numberOfSteps == 0) {
			XMSSurveyController.hide();
		} else {
			XMSSurveyController.updateProgressBar();
		}
	},
	
	// hide the progress bar when not needed
	hide : function() {
		var progressBar = document.getElementById('surveyProgress');
		progressBar.style.display='none';
	},
	
	updateProgressBar : function() {
		var current_step = XMSSurveyController.currentStep;
		var steps = XMSSurveyController.numberOfSteps;
		
		// fill the percentages array with the right intervals
		var percentages = new Array();
		
		// (steps + 1) entries in total, starting with 0
		for (var i = 0; i < steps; i++) {
			percentages[i] = i * (100/steps);
		}
		
		// last position is always 100%
		percentages[steps] = 100;
		
		if(document.getElementById('surveyProgress').style.display != 'none') {
			
			var element_width = document.getElementById('progressBar').offsetWidth-10; // 220

			var current_prog = document.getElementById('currentProgress');
			if( current_prog && current_prog.style.display != 'none' && element_width > 0) {
				current_prog.style.width = Math.round((element_width/100)*percentages[current_step])+'px'; 
			}
			
			var potential_prog = document.getElementById('extraProgress');
			if( potential_prog && potential_prog.style.display != 'none' && element_width > 0) {	
				potential_prog.style.width = Math.round((element_width/100)*percentages[current_step+1])+'px'; 
			}
		}
		return false;
	}
};

var XMSUtil = {
		
	addClass : function(element, className) {
		var currentClasses = element.className;
		if (currentClasses.indexOf(className) == -1) {
			element.className += ' ' + className;
		}
	},
	removeClass : function(element, className) {
		var currentClasses = element.className;
		if (currentClasses.indexOf(className) > -1) {
			element.className = currentClasses.replace(className, '');
		}
	},
	toggle : function(element) {
		if(typeof(element) != 'object') {
			element = document.getElementById(element);
		}
		
		if(element.style.display == 'none') {
			element.style.display = 'block';
		} else {
			element.style.display = 'none';
		}
	}
};

var XMSAntiSpamElement = {
	
	autoFill: function(element_id) {
		
		var parent_el = document.getElementById(element_id);
		
		// Temporary test: assuming bots have no javascript yet, just set the answer to 'js_enabled'
		var inputs = parent_el.getElementsByTagName('input');
		
		parent_el.style.display = "none";
		
		for(var x in inputs) {
			if(inputs[x].name && inputs[x].name == "captcha_answer") {
				inputs[x].value = "js_enabled";
				// Good to know: setting type property throws an error in IE; display: none does the job
				// inputs[x].type = "hidden";
				inputs[x].style.display = "none";
			}
		}
		
	}
};

var XMSLoginPortalElement = {
		
	validateUserName: function() {
		
		// check if the username field exists
		var username = (document.getElementById('XMSWebUserLoginStrategy_user_name')) ? document.getElementById('XMSWebUserLoginStrategy_user_name') : null;
		if(!username || username.value == '') { return; }
		
		// remove the . from the username
		var valid_str = (username.value).replace('.', '');

		// replace the new valid username with the old one
		username.value = valid_str;
	}
		
}

var XMSContactFormBlock = {
	
	checkMessage: function(form) {
		var result = Slik.Util.checkRequiredFields(form, false);
		return result;
	}
	
};
