/*
FIXME: merge the 'mt' and 'ps' branches somewhere in the future
*/

function mtAjax(pars)
{
	var url = '/matchingtest/';
	var saveStudent = new Ajax.Request(url,
		{
			method: 'post',
			parameters: pars,
			onComplete: showMT,
			onFailure: reportError
		});
}

function mtShow()
{
	hideIEFuckups();
	openMT();

	/*if (dhtmlHistory.isFirstLoad()) {
		// start adding history
		dhtmlHistory.add("0", "Inleiding");
	}*/

	Set_Cookie('current_test', '1');
	mtChangeBackground(-1);
	mtAjax('mt=1&vr=0');
}

function psShow()
{
	hideIEFuckups();
	openPS();

	/*if (dhtmlHistory.isFirstLoad()) {
		// start adding history
		dhtmlHistory.add("0", "Inleiding");
	}*/

	Set_Cookie('current_test', '2');
	mtAjax('mt=2&vr=0');
}

function switchPSMT()
{
	closePS();
	mtShow();
}

function switchMTPS()
{
	closeMT();
	psShow();
}

function hideIEFuckups()
{
	if(null != document.getElementById('form_aanmelden')) {
		for (var i = 0, item; item = document.getElementById('form_aanmelden').elements[i]; i++) {
			if(item.type == "select-one") {
				item.style.visibility = 'hidden';
			}
		}
	}
}

function unhideIEFuckups()
{
	if(null != document.getElementById('form_aanmelden')) {
		for (var i = 0, item; item = document.getElementById('form_aanmelden').elements[i]; i++) {
			if(item.type == "select-one") {
				item.style.visibility = 'visible';
			}
		}
	}
}

function showMT(orginalRequest)
{
	if(document.getElementById('mt_positioner').style.visibility == 'visible') {
		document.getElementById('mt_question').innerHTML = orginalRequest.responseText;
	} else {
		document.getElementById('ps_question').innerHTML = orginalRequest.responseText;
	}

	// NOTE: Search for and activate sliders after some delay. Activating too soon will cause the slider to fail in IE.
	// FIXME: sliders cause massive fuck-ups on IE 7.
	self.setTimeout('mtLaunchSliders()', 300);
}

function reportError(orginalRequest)
{
	alert('An Ajax error has occured');
}

function actualOpen(prefix)
{
	document.getElementById('mt_fade').style.visibility = 'visible';
	document.getElementById(prefix+'_positioner').style.visibility = 'visible';
}

function openMT()
{
	actualOpen('mt');
}

function openPS()
{
	actualOpen('ps');
}

function actualClose(prefix)
{
	document.getElementById('mt_fade').style.visibility = 'hidden';
	document.getElementById('mt_positioner').style.visibility = 'hidden';
	document.getElementById('mt_question').innerHTML = '';
	if(prefix == 'ps') {
		document.getElementById('ps_positioner').style.visibility = 'hidden';
		document.getElementById('ps_question').innerHTML = '';
	}

	unhideIEFuckups();
}

function closeMT()
{
	actualClose('mt');
}

function closePS()
{
	actualClose('ps');
}

function withHistoryCloseMT(historyEntryNumber)
{
	/*if (dhtmlHistory.isFirstLoad()) {
		dhtmlHistory.add(""+historyEntryNumber+"", "Close");
	}*/

	closeMT();
}

function withHistoryClosePS(historyEntryNumber)
{
	/*if (dhtmlHistory.isFirstLoad()) {
		dhtmlHistory.add(""+historyEntryNumber+"", "Close");
	}*/

	closePS();
}

function withHistoryAanmelden(historyEntryNumber)
{
	/*if (dhtmlHistory.isFirstLoad()) {
		dhtmlHistory.add(""+historyEntryNumber+"", "Close");
	}*/

	document.location.assign('/aanmelden/');

}

function mtMailShow(historyEntryNumber)
{
	// FIXME: move HTML formatting elsewhere
	if(document.getElementById('mt_mail_row').innerHTML.length <= 260) {
		document.getElementById('mt_mail_row').innerHTML = document.getElementById('mt_mail_row').innerHTML+'<br/><input type="text" name="mt_email" id="mt_email" size="20" /><input type="button" value="Versturen" onClick="mtEmail('+historyEntryNumber+')" />';
	}
}

function psMailShow(historyEntryNumber)
{
	if(document.getElementById('ps_mail_row').innerHTML.length <= 260) {
		document.getElementById('ps_mail_row').innerHTML = document.getElementById('ps_mail_row').innerHTML+'<br/><input type="text" name="ps_email" id="ps_email" size="20" /><input type="button" value="Versturen" onClick="psEmail('+historyEntryNumber+')" />';
	}
}

function limitTo(count, amount, thisElement)
{
	// count = # elements
	// amount = maximum # selected elements
	// thisElement = element clicked
	nrChecked = 0;
	for(var i = 0; i < count; i++) {
		var elementName = 'antwoord_'+i;
		if(document.getElementById(elementName).checked == true) {
			nrChecked++;
		}
	}

	if(nrChecked > amount) {
		document.getElementById('antwoord_'+thisElement).checked = false;
		document.getElementById('antwoord_'+thisElement).blur();
	}
}

function savePS(currentQuestion)
{
 	actualSave(currentQuestion, 'ps');
}

function saveMT(currentQuestion)
{
 	//alert(document.getElementById("mt_background_progres").style.backgroundImage);
	if(actualSave(currentQuestion, 'mt')) {
		mtChangeBackground(currentQuestion);
	}
}

function mtChangeBackground(currentQuestion)
{
	nextQ = (currentQuestion + 1);
	if(nextQ < 10) {
		nextQ = "0"+nextQ;
	}
	newURL = '/images/'+nextQ+'.gif';
	document.getElementById('mt_background_progres').style.backgroundImage="url('"+newURL+"')";
}

function actualSave(currentQuestion, prefix)
{
	nextQuestion = currentQuestion + 1;
	var parametersAll = new Array('submit=true&vr='+nextQuestion);

	// Make this script skip saving on the intro (question 0 is the intro)
	if(currentQuestion > 0) {
		for (var i = 0, item; item = document.getElementById(prefix+'_vraag').elements[i]; i++) {
		    // Do something with item
		    if(item.type == "radio") {
				if(item.checked) {
					parametersAll.push(item.name+'='+item.value);
				}
		    } else if (item.type == "checkbox") {
		    	if(item.checked) {
					parametersAll.push(item.name+'[]='+item.value);
				}
		    } else if (item.type == "text" || item.type == "textarea" || item.type == "hidden") {
				if(item.value != '') {
		    		parametersAll.push(item.name+'='+item.value);
				} else {
					parametersAll.push(item.name+'=');
				}
		    } else if (item.type == "select-one") {
		    	if(item.selectedIndex != 0) {
		    		parametersAll.push(item.name+'[]='+item.value);
		    	}
		    }
		}

		if(parametersAll.length < 2) {
			alert('Maak een keuze.');
			return false;
		}
	}

	/*if (dhtmlHistory.isFirstLoad()) {
		dhtmlHistory.add(""+nextQuestion+"", "Vraag "+nextQuestion);
	}*/
	mtAjax(parametersAll.join('&'));

	return true;
}

function actualNext(nextQuestion, prefix)
{
	var parametersAll = new Array('vr='+nextQuestion);
	/*if (dhtmlHistory.isFirstLoad()) {
		dhtmlHistory.add(""+nextQuestion+"", "Vraag "+nextQuestion);
	}*/
	mtAjax(parametersAll.join('&'));
}

function nextMT(nextQuestion)
{
	mtChangeBackground(0);
	actualNext(nextQuestion, 'mt');
}

function nextPS(nextQuestion)
{
	actualNext(nextQuestion, 'mt');
}


function initializeDHTMHistory()
{
	// initialize our DHTML history
	/*dhtmlHistory.initialize();

	// subscribe to DHTML history change
	// events
	dhtmlHistory.addListener(historyChange);*/
}

function historyChange(newLocation, historyData)
{
	/*var historyMsg = historyData;
	if (newLocation == "complexObject") {
		historyMsg = JSON.stringify(historyData);
	}

	if(newLocation == '' || historyMsg == 'Close') {
		closeMT();
	} else {
		if(Get_Cookie('current_test') == '1') {
			openMT();
		} else {

		}

		if(historyMsg == "E-mail mt") {
			callMail('mail=none&mt=1&vr='+newLocation, 'mt');
		} else if (historyMsg == "E-mail ps") {
			callMail('mail=none&mt=2&vr='+newLocation, 'ps');
		} else {
			mtAjax('vr='+newLocation);
		}
	}*/
}

function actualShowButton(buttonName, buttonState, prefix)
{
	theName = prefix+"_"+buttonName;
	theSRC = "/images/"+theName+"_"+buttonState+".gif";

	document.getElementById(theName).src = theSRC;
}
function mtShowButtonGIF(buttonName, buttonState)
{
	theName = buttonName;
	theSRC = "/images/"+theName+"_"+buttonState+".gif";

	document.getElementById(theName).src = theSRC;
}

function mtShowButton(buttonName, buttonState)
{
	actualShowButton(buttonName, buttonState, 'mt');
}

function psShowButton(buttonName, buttonState)
{
	actualShowButton(buttonName, buttonState, 'ps');
}

function actualEmail(historyEntryNumber, prefix)
{
	emailFormat = /^\w+[\+\.\w-]*@([\w-]+\.)*\w+[\w-]*\.([a-z]{2,4}|\d+)$/i;

	if(!emailFormat.test($(prefix+'_email').value)) {
		alert('Voer een e-mail adres in!');
	} else {
		/*if (dhtmlHistory.isFirstLoad()) {
			dhtmlHistory.add(""+historyEntryNumber+"", "E-mail "+prefix);
		}*/
	}
}

function mtEmail(historyEntryNumber)
{
	actualEmail(historyEntryNumber, 'mt');
	callMail("mail="+$('mt_email').value+"&mt=1&vr"+(historyEntryNumber+1), 'mt');
}

function psEmail(historyEntryNumber)
{
	actualEmail(historyEntryNumber, 'ps');
	callMail("mail="+$('ps_email').value+"&mt=2&vr"+(historyEntryNumber+1), 'ps');
}

function callMail(pars, prefix)
{
	var url = '/matchingtest/mail/';
		var saveStudent = new Ajax.Request(url,
		{
			method: 'post',
			parameters: pars,
			onComplete: showMT,
			onFailure: reportError
		});
}

//---------------------------------+
//  CARPE  S l i d e r        1.5  |
//  2006 - 01 - 03                 |
//  By Tom Hermansson Snickars     |
//  Copyright CARPE Design         |
//  http://carpe.ambiprospect.com/ |
//  Contact for custom scripts     |
//  or implementation help.        |
//---------------------------------+

// Global vars. You don't need to make changes here to change your sliders.
// Changing the attributes in your (X)HTML file is enough.
var carpeDefaultSliderLength      = 100
var carpeSliderDefaultOrientation = 'horizontal'
var carpeSliderClassName          = 'carpe_slider'
var carpeSliderDisplayClassName   = 'carpe_slider_display'

// carpeGetElementsByClass: Cross-browser function that returns
// an array with all elements that have a class attribute that
// contains className
function carpeGetElementsByClass(className)
{
	var classElements = new Array()
	var els = document.getElementsByTagName("*")
	var elsLen = els.length
	var pattern = new RegExp("\\b" + className + "\\b")
	for (i = 0, j = 0; i < elsLen; i++) {
		if ( pattern.test(els[i].className) ) {
			classElements[j] = els[i]
			j++
		}
	}
	return classElements;
}
// carpeLeft: Cross-browser version of "element.style.left"
// Returns or sets the horizontal position of an element.
function carpeLeft(elmnt, pos)
{
	if (!(elmnt = document.getElementById(elmnt))) return 0;
	if (elmnt.style && (typeof(elmnt.style.left) == 'string')) {
		if (typeof(pos) == 'number') elmnt.style.left = pos + 'px';
		else {
			pos = parseInt(elmnt.style.left);
			if (isNaN(pos)) pos = 0;
		}
	}
	else if (elmnt.style && elmnt.style.pixelLeft) {
		if (typeof(pos) == 'number') elmnt.style.pixelLeft = pos;
		else pos = elmnt.style.pixelLeft;
	}
	return pos;
}
// carpeTop: Cross-browser version of "element.style.top"
// Returns or sets the vertical position of an element.
function carpeTop(elmnt, pos)
{
	if (!(elmnt = document.getElementById(elmnt))) return 0;
	if (elmnt.style && (typeof(elmnt.style.top) == 'string')) {
		if (typeof(pos) == 'number') elmnt.style.top = pos + 'px';
		else {
			pos = parseInt(elmnt.style.top);
			if (isNaN(pos)) pos = 0;
		}
	}
	else if (elmnt.style && elmnt.style.pixelTop) {
		if (typeof(pos) == 'number') elmnt.style.pixelTop = pos;
		else pos = elmnt.style.pixelTop;
	}
	return pos;
}
// moveSlider: Handles slider and display while dragging
function moveSlider(evnt)
{
	var evnt = (!evnt) ? window.event : evnt; // The mousemove event
	if (mouseover) { // Only if slider is dragged
		x = slider.startOffsetX + evnt.screenX // Horizontal mouse position relative to allowed slider positions
		y = slider.startOffsetY + evnt.screenY // Horizontal mouse position relative to allowed slider positions
		if (x > slider.xMax) x = slider.xMax // Limit horizontal movement
		if (x < 0) x = 0 // Limit horizontal movement
		if (y > slider.yMax) y = slider.yMax // Limit vertical movement
		if (y < 0) y = 0 // Limit vertical movement
		carpeLeft(slider.id, x)  // move slider to new horizontal position
		carpeTop(slider.id, y) // move slider to new vertical position
		sliderVal = x + y // pixel value of slider regardless of orientation
		sliderPos = (slider.distance / display.valuecount) *
			Math.round(display.valuecount * sliderVal / slider.distance)
		v = Math.round((sliderPos * slider.scale + slider.from) * // calculate display value
			Math.pow(10, display.decimals)) / Math.pow(10, display.decimals)
		display.value = v // put the new value in the slider display element
		return false
	}
	return
}
// slide: Handles the start of a slider move.
function slide(evnt)
{
	if (!evnt) evnt = window.event; // Get the mouse event causing the slider activation.
	slider = (evnt.target) ? evnt.target : evnt.srcElement; // Get the activated slider element.
	dist = parseInt(slider.getAttribute('distance')) // The allowed slider movement in pixels.
	slider.distance = dist ? dist : carpeDefaultSliderLength // Deafault distance from global var.
	ori = slider.getAttribute('orientation') // Slider orientation: 'horizontal' or 'vertical'.
	orientation = ((ori == 'horizontal') || (ori == 'vertical')) ? ori : carpeSliderDefaultOrientation
		// Default orientation from global variable.
	displayId = slider.getAttribute('display') // ID of associated display element.
	display = document.getElementById(displayId) // Get the associated display element.
	display.sliderId = slider.id // Associate the display with the correct slider.
	dec = parseInt(display.getAttribute('decimals')) // Number of decimals to be displayed.
	display.decimals = dec ? dec : 0 // Default number of decimals: 0.
	val = parseInt(display.getAttribute('valuecount'))  // Allowed number of values in the interval.
	display.valuecount = val ? val : slider.distance + 1 // Default number of values: the sliding distance.
	from = parseFloat(display.getAttribute('from')) // Min/start value for the display.
	from = from ? from : 0 // Default min/start value: 0.
	to = parseFloat(display.getAttribute('to')) // Max value for the display.
	to = to ? to : slider.distance // Default number of values: the sliding distance.
	slider.scale = (to - from) / slider.distance // Slider-display scale [value-change per pixel of movement].
	if (orientation == 'vertical') { // Set limits and scale for vertical sliders.
		slider.from = to // Invert for vertical sliders. "Higher is more."
		slider.xMax = 0
		slider.yMax = slider.distance
		slider.scale = -slider.scale // Invert scale for vertical sliders. "Higher is more."
	}
	else { // Set limits for horizontal sliders.
		slider.from = from
		slider.xMax = slider.distance
		slider.yMax = 0
	}
	slider.startOffsetX = carpeLeft(slider.id) - evnt.screenX // Slider-mouse horizontal offset at start of slide.
	slider.startOffsetY = carpeTop(slider.id) - evnt.screenY // Slider-mouse vertical offset at start of slide.
	mouseover = true
	document.onmousemove = moveSlider // Start the action if the mouse is dragged.
	document.onmouseup = sliderMouseUp // Stop sliding.
	return false
}
// sliderMouseUp: Handles the mouseup event after moving a slider.
// Snaps the slider position to allowed/displayed value.
function sliderMouseUp()
{
	if (mouseover) {
		v = (display.value) ? display.value : 0 // Find last display value.
		pos = (v - slider.from)/(slider.scale) // Calculate slider position (regardless of orientation).
		if (slider.yMax == 0) {
			pos = (pos > slider.xMax) ? slider.xMax : pos
			pos = (pos < 0) ? 0 : pos
			carpeLeft(slider.id, pos) // Snap horizontal slider to corresponding display position.
		}
		if (slider.xMax == 0) {
			pos = (pos > slider.yMax) ? slider.yMax : pos
			pos = (pos < 0) ? 0 : pos
			carpeTop(slider.id, pos) // Snap vertical slider to corresponding display position.
		}
		if (document.removeEventListener) { // Remove event listeners from 'document' (W3C).
			document.removeEventListener('mousemove', moveSlider, false)
			document.removeEventListener('mouseup', sliderMouseUp, false)
		}
		else if (document.detachEvent) { // Remove event listeners from 'document' (IE).
			document.detachEvent('onmousemove', moveSlider)
			document.detachEvent('onmouseup', sliderMouseUp)
		}
	}
	mouseover = false // Stop the sliding.
}
function focusDisplay(evnt)
{
	if (!evnt) evnt = window.event; // Get the mouse event causing the display activation.
	display = (evnt.target) ? evnt.target : evnt.srcElement; // Get the activated display element.
	lock = display.getAttribute('typelock') // Is the user allowed to type into the display?
	if (lock == 'on') {
		display.blur()
	}
	return
}

function mtLaunchSliders ()
{
	sliders = carpeGetElementsByClass(carpeSliderClassName) // Find the horizontal sliders.
	for (i = 0; i < sliders.length; i++) {
		sliders[i].onmousedown = slide // Attach event listener.
	}
	displays = carpeGetElementsByClass(carpeSliderDisplayClassName) // Find the displays.
	for (i = 0; i < displays.length; i++) {
		displays[i].onfocus = focusDisplay // Attach event listener.
	}
}

function mtCloseError()
{
	$('ps_error_text').style.visibility = 'hidden';
}

function dump (arr,level) {
	var dumped_text = "";
	if(!level) level = 0;

	//The padding given at the beginning of the line.
	var level_padding = "";

	for(var j=0;j<level+1;j++) level_padding += "    ";

	if(typeof(arr) == 'object') { //Array/Hashes/Objects
		for(var item in arr) {
			var value = arr[item];

			if(typeof(value) == 'object') { //If it is an array,
				dumped_text += level_padding + "'" + item + "' ...\n";
				dumped_text += dump(value,level+1);
			} else {
				dumped_text += level_padding + "'" + item + "' => \"" + value + "\"\n";
			}
		}
	} else { //Stings/Chars/Numbers etc.
		dumped_text = "===>"+arr+"<===("+typeof(arr)+")";
	}

	return dumped_text;
}
