﻿/**
 * JavaScript for Raet HR Benchmark 2010 tool
 * 
 * @copyright eFocus
 * @author Klaas Dieleman (klaas[AT]efocus.nl)
 * @since 28 sep 2010
 *
 * @require MooTools 1.2.x core&more (http://www.mootools.net)
 */
window.addEvent('domready', function(){	
	objCurrentSegment = getSegmentCookie();
	intCurrentStep = getCurrentStep();
	
	handleSegmentChoice();
	encodeRadioValues();
	handleQuestionRadios();
	filterResultsBySegment();
	prefillStep();	
	
	blnResultsVisible = true;
	if(isNextStepAllowed() == false && intCurrentStep > 1 && intCurrentStep < 99) {
		hideResults();
		disableNextButton();
	}
	
	if(intCurrentStep == 8) {
		document.getElement('div.hrbenchmark_container a.button_finish').addEvent('click', function(objEvent){
			objEvent.preventDefault();
			postForm();
			location.href = document.getElement('div.hrbenchmark_container a.button_finish').get('href');
		});
	}
	
	if(intCurrentStep == 99) renderSummary();
});

/**
 * replaces values in radiobuttons with URI-encoded strings
 * for safe storage in Cookie and http-POST-string
 * 
 * @copyright eFocus
 * @author Klaas Dieleman (klaas[AT]efocus.nl)
 * @since 28 sep 2010
 */
function encodeRadioValues() {
	$$('div.hrbenchmark_container input[type=radio').each(function(item) {
		item.set('value', encodeURIComponent(item.get('value')));
	});
}

/**
 * hides result pane in a step
 * 
 * @copyright eFocus
 * @author Klaas Dieleman (klaas[AT]efocus.nl)
 * @since 28 sep 2010
 */
function hideResults() {
	intResultsHeight = document.getElement('div.result_holder').getSize().y;
	document.getElement('div.result_holder').setStyle('display', 'none');
	blnResultsVisible = false;
}

/**
 * slides open result pane in a step
 * 
 * @copyright eFocus
 * @author Klaas Dieleman (klaas[AT]efocus.nl)
 * @since 28 sep 2010
 */
function showResults() {
	window.scrollTo(window.getScroll().x, document.getElement('div.result_holder').getPosition().y + intResultsHeight);
	document.getElement('div.result_holder').setStyle('display', 'block');
	blnResultsVisible = true;
}

/**
 * writes cookie with chosen market segment name and index
 * 
 * @copyright eFocus
 * @author Klaas Dieleman (klaas[AT]efocus.nl)
 * @since 28 sep 2010
 *
 * @param intSegment - the index number of the chosen segment
 * @param strSegment - the full name of the chosen segment
 */
function setSegmentCookie(intSegment, strSegment) {
	Cookie.write('hrbenchmark_segment_index', intSegment);
	Cookie.write('hrbenchmark_segment_name', strSegment);
}

/**
 * gets stored market segment from cookie
 * 
 * @copyright eFocus
 * @author Klaas Dieleman (klaas[AT]efocus.nl)
 * @since 28 sep 2010
 *
 * @return objSegment - an object containing the integer 'index' and string 'name' of the stored market segment
 */
function getSegmentCookie() {
	var objSegment = {};
	objSegment.index = parseInt(Cookie.read('hrbenchmark_segment_index'));
	objSegment.name = Cookie.read('hrbenchmark_segment_name');
	if(isNaN(objSegment.index) || objSegment.name == null) objSegment = null;
	return objSegment;
}

/**
 * erases all cookies for this application
 * 
 * @copyright eFocus
 * @author Klaas Dieleman (klaas[AT]efocus.nl)
 * @since 28 sep 2010
 */
function clearCookies() {
	Cookie.dispose('hrbenchmark_segment_index');
	Cookie.dispose('hrbenchmark_segment_name');
	Cookie.dispose('hrbenchmark_question2');
	Cookie.dispose('hrbenchmark_question3_priority_1');
	Cookie.dispose('hrbenchmark_question3_priority_2');
	Cookie.dispose('hrbenchmark_question3_priority_3');
	Cookie.dispose('hrbenchmark_question4_priority_1');
	Cookie.dispose('hrbenchmark_question4_priority_2');
	Cookie.dispose('hrbenchmark_question4_priority_3');
	Cookie.dispose('hrbenchmark_question5');
	Cookie.dispose('hrbenchmark_question6');
	Cookie.dispose('hrbenchmark_question7');
	Cookie.dispose('hrbenchmark_question8');
}

/**
 * strips results table and swaps results graph by segment, if one is chosen before
 * 
 * @copyright eFocus
 * @author Klaas Dieleman (klaas[AT]efocus.nl)
 * @since 28 sep 2010
 */
function filterResultsBySegment() {
	
	if(objCurrentSegment) {
		stripResultsTable();
		var intStepGraph = intCurrentStep;
		$$('div.hrbenchmark_container div.graph_segment img').each(function(elGraph) {
			if(intCurrentStep == 99) {
				intStepGraph = parseInt(elGraph.getParent('li').getElement('a').get('text'));
			}
			swapSegmentGraph(elGraph, intStepGraph);
		});
	} else {
		$$('div.hrbenchmark_container div.graph_segment').dispose();
	}

}

/**
 * hijacks clicks on segment-choice links in step 1 for cookie storage
 * 
 * @copyright eFocus
 * @author Klaas Dieleman (klaas[AT]efocus.nl)
 * @since 28 sep 2010
 */
function handleSegmentChoice() {
	$$('div.hrbenchmark_container ul.segment_choice a').each(function(elItem, intIndex) {
		elItem.addEvent('click', function(objEvent) {
			objEvent.preventDefault();
			clearCookies();

			setSegmentCookie(intIndex + 1, elItem.get('text'));
			location.href = elItem.get('href');
		});
	});
}

/**
 * handles checking of radiobuttons in question-steps,
 * storing choice in a cookie, swapping results graphs and unlocking next-button, if allowed
 * 
 * @copyright eFocus
 * @author Klaas Dieleman (klaas[AT]efocus.nl)
 * @since 28 sep 2010
 */
function handleQuestionRadios() {
	$$('div.hrbenchmark_container input[type=radio]').each(function(elItem, intIndex) {
		elItem.addEvents({
			'click': function() {
				
				//if(!((intCurrentStep == 3 || intCurrentStep == 4) && $$('input[type=radio]:checked').length != 3) && isNextStepAllowed == false) {
				Cookie.write(elItem.get('name'), elItem.get('value'));
				
				if(isNextStepAllowed() && blnResultsVisible == false) {
					enableNextButton();
					showResults();
				}
				
				
				
				var intAnswerIndex = $$('div.hrbenchmark_container input[type=radio]').indexOf(elItem) + 1;
				var elSegmentGraph = document.getElement('div.hrbenchmark_container div.graph_segment img');
				var elTotalGraph = document.getElement('div.hrbenchmark_container div.graph_total img');
				if(elSegmentGraph) swapAnswerGraph(elSegmentGraph, intAnswerIndex);
				if(elTotalGraph) swapAnswerGraph(elTotalGraph, intAnswerIndex);
				
			}
		});
	});
}

/**
 * pre-checks radiobutton in step and swaps matching results graphs,
 * if a session-stored choice is found
 * 
 * @copyright eFocus
 * @author Klaas Dieleman (klaas[AT]efocus.nl)
 * @since 28 sep 2010
 */
function prefillStep() {
	var intAnswerIndex = 1;
	var arrAnswerCookies = [];
	arrAnswerCookies.include('hrbenchmark_question' + intCurrentStep.toString());
	arrAnswerCookies.include('hrbenchmark_question' + intCurrentStep.toString() + '_priority_1');
	arrAnswerCookies.include('hrbenchmark_question' + intCurrentStep.toString() + '_priority_2');
	arrAnswerCookies.include('hrbenchmark_question' + intCurrentStep.toString() + '_priority_3');
	
	arrAnswerCookies.each(function(strCookieName) {
		
		var strAnswerValue = Cookie.read(strCookieName);
		if(strAnswerValue) {
			$$('input[type=radio][name=' + strCookieName + '][value="' + strAnswerValue + '"]').set('checked', 'checked');
			intAnswerIndex = parseInt(strAnswerValue.split('_', 2)[0]);
		}
	});
	
	var elSegmentGraph = document.getElement('div.hrbenchmark_container div.graph_segment img');
	var elTotalGraph = document.getElement('div.hrbenchmark_container div.graph_total img');
	
	if(elSegmentGraph) swapAnswerGraph(elSegmentGraph, intAnswerIndex);
	if(elTotalGraph) swapAnswerGraph(elTotalGraph, intAnswerIndex);
}

/**
 * gets current step from steps-list
 * 
 * @copyright eFocus
 * @author Klaas Dieleman (klaas[AT]efocus.nl)
 * @since 28 sep 2010
 *
 * @return intCurrentStep - current step number, 99 if in final step summary
 */
function getCurrentStep() {
	var intCurrentStep = $$('div.hrbenchmark_container ul.steps li').indexOf(document.getElement('div.hrbenchmark_container ul.steps li.active')) + 1;
	if(intCurrentStep == 0 && document.getElement('ul.results_final')) intCurrentStep = 99;
	return intCurrentStep;
}

/**
 * removes columns of non-chosen market segment from results table
 * 
 * @copyright eFocus
 * @author Klaas Dieleman (klaas[AT]efocus.nl)
 * @since 28 sep 2010
 */
function stripResultsTable() {
	var arrSegmentColNumbers = [3,4,5,6];
	arrSegmentColNumbers.erase(objCurrentSegment.index + 2);
	var arrCellsToRemove = [];
	
	$$('div.hrbenchmark_container table.result tr').each(function(elTableRow) {
		arrSegmentColNumbers.each(function(n) {
			arrCellsToRemove.include(elTableRow.getElement('th:nth-child(' + n + '), td:nth-child(' + n + ')'));
		});
	});
	
	arrCellsToRemove.each(function(elTableCell) {
		elTableCell.dispose();
	});
}

/**
 * swaps results segment-graph and h3-title with correct graph for chosen market segment,
 * always taking the graph for answer number 1
 * 
 * @copyright eFocus
 * @author Klaas Dieleman (klaas[AT]efocus.nl)
 * @since 28 sep 2010
 *
 * @param elGraph - image element to swap
 * @param intQuestion - number of question/step to swap graph of
 */
function swapSegmentGraph(elGraph, intQuestion) {
	var strImagePath = elGraph.get('src').substring(0, elGraph.get('src').lastIndexOf('/') + 1);
	var strImageFilename = 'question' + intQuestion + '_segment' + objCurrentSegment.index + '_answer1.png';
	
	elGraph.set('src', strImagePath + strImageFilename);
	elGraph.set('alt', objCurrentSegment.name);
	document.getElement('div.hrbenchmark_container div.graph_segment h3').set('text', objCurrentSegment.name);
}

/**
 * swaps results graph with correct graph for chosen answer
 * 
 * @copyright eFocus
 * @author Klaas Dieleman (klaas[AT]efocus.nl)
 * @since 28 sep 2010
 *
 * @param elGraph - image element to swap
 * @param intQuestion - index number of chosen answer
 */
function swapAnswerGraph(elGraph, intAnswerIndex) {
	var strOrgSrc = elGraph.get('src');
	var strNewSrc = strOrgSrc.slice(0, strOrgSrc.length - 5) + intAnswerIndex + '.png';
	
	elGraph.set('src', strNewSrc);
}

/**
 * checks if next step is allowed
 * 
 * @copyright eFocus
 * @author Klaas Dieleman (klaas[AT]efocus.nl)
 * @since 28 sep 2010
 *
 * @return blnNextStepAllowed - true if current step is completely filled out
 */
function isNextStepAllowed() {
	var blnNextStepAllowed = true;
	var arrCookieNames = [];
	
	if(intCurrentStep == 3 || intCurrentStep == 4) {
		arrCookieNames.include('hrbenchmark_question' + intCurrentStep +'_priority_1');
		arrCookieNames.include('hrbenchmark_question' + intCurrentStep +'_priority_2');
		arrCookieNames.include('hrbenchmark_question' + intCurrentStep +'_priority_3');
	} else {
		arrCookieNames.include('hrbenchmark_question' + intCurrentStep);
	}
	
	for(var i = 0 ; i < arrCookieNames.length ; i ++) {
		if(Cookie.read(arrCookieNames[i]) == null) blnNextStepAllowed = false;
	}
	
	return blnNextStepAllowed;
}

/**
 * disables next-link, storing href value for later enabling of next-link
 * 
 * @copyright eFocus
 * @author Klaas Dieleman (klaas[AT]efocus.nl)
 * @since 28 sep 2010
 */
function disableNextButton() {
	$$('div.hrbenchmark_container a.button_next').addClass('blocked');
	$$('div.hrbenchmark_container a.button_next').store('href', $$('div.hrbenchmark_container a.button_next').get('href'));
	$$('div.hrbenchmark_container a.button_next').removeProperty('href');
}

/**
 * enables next-link, restoring stored href value
 * 
 * @copyright eFocus
 * @author Klaas Dieleman (klaas[AT]efocus.nl)
 * @since 28 sep 2010
 */
function enableNextButton() {
	$$('div.hrbenchmark_container a.button_next').removeClass('blocked');
	$$('div.hrbenchmark_container a.button_next').set('href', $$('div.hrbenchmark_container a.button_next').retrieve('href'));
}

/**
 * gets answers to all questions, including segment name
 * 
 * @copyright eFocus
 * @author Klaas Dieleman (klaas[AT]efocus.nl)
 * @since 28 sep 2010
 *
 * return strPostData - string of questions&answers as name/value pairs
 */
function getAllStepdata() {	
	var arrCookieNames = [];
	var strPostData = '';
	
	strPostData += 'hrbenchmark_segment_name';
	strPostData += '=';
	strPostData += Cookie.read('hrbenchmark_segment_name') + '&';
	
	arrCookieNames.include('hrbenchmark_question2');
	arrCookieNames.include('hrbenchmark_question3_priority_1');
	arrCookieNames.include('hrbenchmark_question3_priority_2');
	arrCookieNames.include('hrbenchmark_question3_priority_3');
	arrCookieNames.include('hrbenchmark_question4_priority_1');
	arrCookieNames.include('hrbenchmark_question4_priority_2');
	arrCookieNames.include('hrbenchmark_question4_priority_3');
	arrCookieNames.include('hrbenchmark_question5');
	arrCookieNames.include('hrbenchmark_question6');
	arrCookieNames.include('hrbenchmark_question7');
	arrCookieNames.include('hrbenchmark_question8');
	
	arrCookieNames.each(function(strCookieName, intIndex) {
		if(Cookie.read(strCookieName)) {
			strPostData += strCookieName + '=' + Cookie.read(strCookieName).split('_', 2)[1];
		} else {
			strPostData += strCookieName + '=null';
		}
		if(intIndex < arrCookieNames.length - 1) strPostData += '&';
	});
	
	return strPostData;
}

/**
 * sends all questions&answers as http-post
 * 
 * @copyright eFocus
 * @author Klaas Dieleman (klaas[AT]efocus.nl)
 * @since 28 sep 2010
 *
 * return strPostData - string of questions&answers as name/value pairs
 */
function postForm() {
	var objRequest = new Request({url:'/benchmarkpost.aspx'});
	objRequest.send(getAllStepdata());
}

/**
 * fills out summary page with all given answers,
 * strips results tables by segments and
 * swaps all graphs for segment and given answers
 * 
 * @copyright eFocus
 * @author Klaas Dieleman (klaas[AT]efocus.nl)
 * @since 28 sep 2010
 */
function renderSummary() {
	new Accordion($$('div.hrbenchmark_container ul.results_final a.number'), $$('div.hrbenchmark_container ul.results_final div.result'), {
		'alwaysHide'	: true,
		'display'		: -1,
		'onActive'		: function(elToggler) { elToggler.addClass('activenumber') },
		'onBackground'	: function(elToggler) { elToggler.removeClass('activenumber') }
	});
	
	var elSegmentGraph, elTotalGraph; 
	var arrGraphSteps = [5,6,7,8];
	var strCookieName;
	var strAnswer;

	arrGraphSteps.each(function(intStep) {
		strCookieName = ('hrbenchmark_question' + intStep.toString());
		
		if(Cookie.read(strCookieName)) {
			elSegmentGraph = $$('div.hrbenchmark_container ul.results_final > li')[intStep - 2].getElement('div.graph_segment img');
			elTotalGraph = $$('div.hrbenchmark_container ul.results_final > li')[intStep - 2].getElement('div.graph_total img');
		
			if(elSegmentGraph) swapAnswerGraph(elSegmentGraph, parseInt(Cookie.read(strCookieName).split('_', 2)[0]));
			if(elTotalGraph) swapAnswerGraph(elTotalGraph, parseInt(Cookie.read(strCookieName).split('_', 2)[0]));
		}
	});
	
	for(var intStep = 2 ; intStep <= 8 ; intStep ++) {
		if(intStep == 3 || intStep == 4) {
			if(Cookie.read('hrbenchmark_question' + intStep + '_priority_1') && Cookie.read('hrbenchmark_question' + intStep + '_priority_2') && Cookie.read('hrbenchmark_question' + intStep + '_priority_3')) {
				strAnswer = decodeURIComponent(Cookie.read('hrbenchmark_question' + intStep + '_priority_1').split('_', 2)[1]);
				strAnswer += ', ';
				strAnswer += decodeURIComponent(Cookie.read('hrbenchmark_question' + intStep + '_priority_2').split('_', 2)[1]);
				strAnswer += ', ';
				strAnswer += decodeURIComponent(Cookie.read('hrbenchmark_question' + intStep + '_priority_3').split('_', 2)[1]);
			} else {
				strAnswer = 'vraag is niet beantwoord.';
			}
		} else {
			if(Cookie.read('hrbenchmark_question' + intStep)) {
				strAnswer = decodeURIComponent(Cookie.read('hrbenchmark_question' + intStep).split('_', 2)[1]);
			} else {
				strAnswer = 'vraag is niet beantwoord.';
			}
		}
		
		$$('ul.results_final p.answer')[intStep - 2].set('html', $$('ul.results_final p.answer')[intStep - 2].get('text') + '<strong>' + strAnswer + '</strong>');
	}
	
}
