if (typeof lang == 'undefined') {
	var lang = [];
	lang['language'] = 'nl';
	lang['noQuestions'] = 'Er is geen vragenlijst ingeladen. Contacteer de beheerder van de site.';
}

var curQuestion = 0;
var relatedQuestion = false;
var ranges = [6,9];
var processed = false;

jQuery.fn.extend({
	activate: function() {
		if ($(this).attr('id') == 'nextQ') {
			if ($(this).css('margin-top') != '491px') {
				$(this).show().stop().animate({
					'marginTop': '491px'
				}, 500, function(){$('#nextQclickthingy').show();});
			}
		}
		else if ($(this).css('opacity') == '0') {
			// without selecting it implicitly by id, it will also animate other buttons (?!)
			$(this).not('#nextQ').show().animate({
				'opacity': 1
			}, 500);
		}
		return $(this);
	},
	deactivate: function() {
		if ($(this).attr('id') == 'nextQ') {
			if ($(this).css('margin-top') != '422px') {
				$('#nextQclickthingy').hide();
				$(this).animate({
					'marginTop': '422px'
				}, 500, function(){
						$(this).hide()}
				);
			}
		} 
		else if ($(this).css('opacity') != '0') {
			// without selecting it implicitly by id, it will also animate other buttons (?!)
			$(this).not('#nextQ').animate({
				'opacity': 0
			}, 500).hide();

		}
		return $(this);
	}
});


// shows next/prev buttons if applicable
function showButtons(questionNum) {
	var question = questions[questionNum];
	if (typeof question.sel == 'undefined') {
		$('button#nextQ').deactivate();	
	}
	else {
		if (typeof question.related != 'undefined' && !relatedQuestion && questions[questionNum].answers[questions[questionNum].sel].salt != 0) {
			$('button#nextQ, button#prevQ').deactivate();
			if (typeof question.related[0].sel == 'undefined') {
				return false;
			}
		}
		if ((questions.length -1) == questionNum) {
			$('button#nextQ').deactivate();
			$('button#toResults').show();
		} else {
			$('button#nextQ').activate();
			$('button#toResults').hide();
		}
	}
	
	if (questionNum == 0) {
		$('button#prevQ').deactivate();
	} else {
		$('button#prevQ').activate();
	}
}

function selectAnswer(question, answer) {
	question.sel = answer;
}

function getAnswer(question, questionNum, answerNum) {
	var $htmlAnswer = $('<label class="answer">'+ question.answers[answerNum].answer +'</label>');
	// need to add name + value + checked inline because IE6 will ignore them otherways
	var $htmlRadio = $('<span name="question'+ questionNum + (relatedQuestion == true ? 'related' : '') +'" class="radio'+ (typeof question.sel != 'undefined' && question.sel == answerNum ? ' checked' : '') +'" value="'+ answerNum +'" ></span>');

	$htmlAnswer.click(function() {
		var radioElement = $(this).find('.radio');
		$(this).parents('.answers:first').find('.radio').removeClass('checked');
		radioElement.addClass('checked');
		selectAnswer(question, radioElement.attr('value'));
		if (typeof question.related != 'undefined') {
			showRelated(questionNum);
		} else {
			showButtons(questionNum);
		}
	});
	
	$htmlAnswer.prepend($htmlRadio).append('<br />');
	return $htmlAnswer;
}

function loadQuestion(questionNum) {
	var question = questions[questionNum];
	var imgPath = getImgPath(questionNum, '_big');
	
	$('#question h2').text(question.q);
	$('#question .categories').text(question.c);
	$('#test #question #catImage img').hide();
	$('#test #question #catImage img#img_'+ questionNum).show();
	
	var answerCount = question.answers.length;
	
	$('#question .answers').append('<div class="left"></div>');
	if (answerCount > 4) {
		$('#question .answers').append('<div class="left"></div>');
	}
	if (answerCount > 7) {
		$('#question .answers').append('<div class="left"></div>');
	}
	
	for (var answer in question.answers) {
		$htmlAnswer = getAnswer(question, questionNum, answer);
		if (answer <= 3) {
			$('#question .answers div.left:first').append($htmlAnswer);
		} else if (answer <= 7) {
			$('#question .answers div.left:eq(1)').append($htmlAnswer);
		} else {
			$('#question .answers div.left:eq(2)').append($htmlAnswer);
		}
	}
	showButtons(questionNum);
}

function showQuestion(questionNum) {
	function whatever() {
		$('#questionSub').animate({opacity: 0}, 300, function() {$(this).hide()});
		$('#question .answers').empty();
		loadQuestion(questionNum);

		// only fade if not IE
		if (jQuery.support.opacity) {
			$('#question').animate({'opacity': 1}, 300);
		}
		if (curQuestion != questionNum) {
			$('#groups div[id=group'+ curQuestion +'] img.active').hide();
			//$('#groups div[id=group'+ curQuestion +'] img.active').animate({opacity: 0}, 500);
		}
		$('#groups div[id=group'+ questionNum +'] img.active').show();
		//$('#groups div[id=group'+ questionNum +'] img.active').animate({opacity: 1}, 500);
		curQuestion = questionNum;		
	}
	
	// fix IE ****ups
	if (!jQuery.support.opacity) {
		whatever();
	} else {
		$('#question').animate({'opacity' : 0}, 300, function() {
			whatever();
		});
	}
	relatedQuestion = false;
}

function loadRelated(questionNum) {
	var question = questions[questionNum].related[0];

	if (typeof questions[questionNum].related[0].sel != 'undefined') {
		showButtons(questionNum);
	} else {
		$('button#prevQ, button#nextQ').deactivate();
	}
	$('#questionSub h2').text(question.q);

	for (var answer in question.answers) {
		$htmlAnswer = getAnswer(question, questionNum, answer);
		$('#questionSub .answers').append($htmlAnswer);
	}
}

function showRelated(questionNum) {
	if (questions[questionNum].answers[questions[questionNum].sel].salt == 0) {
		showButtons(questionNum)
	} else {
		$('#questionSub .answers').empty();
		relatedQuestion = true;
		loadRelated(questionNum);
		$('#questionSub').show().animate({opacity: 1}, 300);
	}
}

function prevQuestion() {
	if (curQuestion != 0) {
		showQuestion(parseInt(curQuestion)-1);
	}
}

function nextQuestion() {
	if ((questions.length - 1) != curQuestion) {
		showQuestion(parseInt(curQuestion)+1);
	}
}


function doTheMagicMath(question) {
	for (related in questions[question].related) {
		if (typeof questions[question].related[related].doSomething != 'undefined') {
			questions[question].related[0].doSomething();
		}
	}
}

function cutToNumDecimals(number, numDecimals) {
	var powerOfTen = parseFloat(Math.pow(10, numDecimals));
	return number = Math.round(number * powerOfTen) / powerOfTen;
}

function showDetailedResults() {
	$('#test').append($results);
}

function createProductTable(header, productsInfo) {
	var table = '<h3>%s</h3><table class="productTable" cellspacing="0"><tr><th width="170"></th><th width="50">%s</th><th width="50">%s</th></tr>%s</table>';
	var productRows = '';
	for (var k=0; k<productsInfo.length; k++) {
		var productRow = productsInfo[k];
		productRows += $.sprintf('<tr><td valign="top">%s</td><td valign="top">%s</td><td valign="top">%s</td></tr>', productRow['name'], productRow['salt'], productRow['natriumMg']);
	}	
	
	table = $.sprintf(table, header, lang['saltTH'], lang['natriumTH'], productRows);
	return table;
}

function showResults() {
	if (!processed) {
		var $results = $('<div class="items">');
		var total = 0;
		var recommendations = '';
		var results = [];
		var answersSelected = [];
		for (var question in questions) {
			if (typeof questions[question].sel == 'undefined') {
				// temp
				//questions[question].sel = 1;
				$('button#toResults').hide();		
				alert(lang['incomplete']);
				showQuestion(question);
				return false;
			} else {
				curQuestion = question;
			}
		
			if (typeof questions[curQuestion].related != 'undefined') {
				doTheMagicMath(curQuestion);
			}
		
			var selected = questions[question].sel;
		
			var salt = questions[question].answers[selected].salt = questions[question].answers[selected].salt * 2.5; //convert natrium values to salt in mg
			total += salt;
			//var salt = 1;
			
			results[question] = salt;
			answersSelected[question] = {'salt': salt};
		}
		
		results.sort().reverse();

		var backgroundClass = 'odd';
		for (var i=0; i<results.length; i++) {
			for (var j=0; j<answersSelected.length; j++) {
				if (answersSelected[j].salt == results[i]) {
					
					var info = $.sprintf('<img class="right" style="margin: 25px 25px 0 0;" src="'+ getImgPath(j, '.png') +'" alt="" /><h3>%s</h3>%s', questions[j].cat, questions[j].info);
					
					var table1 = '<div class="left">' + createProductTable((questions[j].titleBadProducts) ? questions[j].titleBadProducts : lang['badProducts'], questions[j].badProducts) + '<div class="footer">'+ questions[j].labelBadProducts +'</div></div>';
					if (questions[j].goodProducts.length > 0) {
						var table2 = '<div class="left">' + createProductTable((questions[j].titleGoodProducts) ? questions[j].titleGoodProducts : lang['goodProducts'], questions[j].goodProducts) + '<div class="footer">'+ questions[j].labelGoodProducts +'</div></div>';
					} else table2 = '';

					$results.append('<div class="item '+ backgroundClass +'">' + 
						'<div class="catNum" style="display: none">'+ (parseInt(i) + 1) +'</div>' + 
						'<div class="catName">' + questions[j].cat + '</div>' + 
						'<div class="catSalt">'+  cutToNumDecimals(answersSelected[j].salt, 1) + '<span class="small" style="margin-left: 1px">g</span></div>' + 
						'<div class="details">'+ info + table1 + table2 +'</div></div>');
					if (backgroundClass == 'odd') backgroundClass = 'even';
					else backgroundClass = 'odd';
					answersSelected[j] = 'processed';
					break;
				}
			}
		}
		
		if (total <= ranges[0]) {
			recommendations = lang['lowSalt'];
			resultClass = 'good';
		} else if (total <= ranges[1]) {
			recommendations = lang['avgSalt'];
			resultClass = 'average';
		} else {
			recommendations = lang['highSalt'];
			resultClass = 'bad';
		}
		recommendations = '<div id="recommendations">' + recommendations + '</div>';
		
		$('#test').addClass(resultClass).append('<div id="resultGlobal"></div><div id="resultTable"></div>');

		$('#resultGlobal').html('<div class="left" id="resultText"><h2>'+ lang['result'] +'</h2>'+ recommendations +'</div><div id="resultVisual" class="left"><div id="saltNumber">'+ cutToNumDecimals(total, 1) +'</div>'+ lang['gram'] +'</div></button>');
		$('#resultTable').append('<div id="results"><div><strong>' +  lang['resultTableHeader'] + '</strong></div><div class="scrollable left"></div><!--<div class="prev left disabled"><img src="/images/scroll_up.png" alt="scroll up" /></div><div class="next left"><img src="/images/scroll_down.png" /></div>--></div>');
		$('#resultTable #results .scrollable').append($results);
		$('#resultTable').append('<div class="footer" style="position: absolute; width: 630px; margin-left: 255px; top: 510px">'+ lang['disclaimer'] +'</div><div class="right clear" style="margin-right: 0; margin-top: 5px"><a id="resultExplanation" style="font-size: 11px;" href="">'+ lang['resultExplanation'] +'</a></div>');
		

		$('#resultExplanation').click(function(){
			if ($('#resultExplanationText').length > 0) {
				$('#resultExplanationText').remove();
			} else {
				$('#resultExplanation').before('<div id="resultExplanationText">'+ lang['resultExplanationText'] +'<span class="right" style="margin-top: 10px;"><a href="" onclick="$(\'#resultExplanationText\').remove(); return false;">'+ lang['close'] +'</a></span></div>');
			}
			
			//var resultExplanation = window.open('/templates/result_explanation_'+ lang['language'] +'.html', '', '');
			return false;
		});


		$('#results div.item:first').addClass('active');
		$('#results div.item:first div.details').slideDown(300);
		
		$('table').each(function(){
			$(this).find("tr:nth-child(even)").addClass("even");
		});
		
		$('#results div.item div.catName').click(function(){
			$newActive = $(this);
			$('#results div.active div.details').slideUp(300, function(){
				$('#results div.active').removeClass('active');
				$newActive.parent().addClass('active');
				$newActive.siblings('div.details').slideDown(300);
			});
		});
		
		addTooltip($('dfn'));
		
		$('#results .catName').hover(function(){
			$(this).css({'font-weight': 'bold', 'font-size': '11px'});
		}, function(){
			$(this).css({'font-weight': 'normal', 'font-size': '12px'});
		});
		

		/*var scrollable = $('#resultTable #results .scrollable').scrollable({
			vertical: true,
			size: 5,
			nextPage: '.next',
			prevPage: '.prev',
			speed: 200,
			easing: 'swing'
		});*/

		//$('#test').append($results);
		// save all the results
		curQuestion = 0;
		$.post('/action/saveResults', {questions: $.toJSON(questions)});
		processed = true;
		
		
		$('button.startTest').css('display', 'none').parent().append('<button class="toResults"></button>');
		$('button.toResults').show().click(function(){
			showResults();
		});
		
	}
	
	$('button#prevQ').deactivate();
	$('button#toResults').hide();
	$('#groups div img.active').hide();
		
	$('#test #question, #test #questionSub, #introduction, #doYouKnow, #question, #pageReadMore').hide();
	$('#test #resultGlobal, #test #resultTable').show();
	$('#testBottom').css({
		'position': 'absolute',
		'top': '380px',
		'left': '0',
		'height': '739px'
	});
}

function getImgPath(questionNum, extension) {
	var toBeReplaced = ['â','é','è',' '];
	var replacements = ['a','e','e','_'];
	var questionCat = questions[questionNum].cat;

	
	for (var i=0; i<toBeReplaced.length; i++) {
		questionCat = questionCat.replace(new RegExp(toBeReplaced[i], 'g'), replacements[i]);
	}
	
	return '/images/'+ lang['language'] +'/'+ questionCat + extension;
}


function showGroups() {
	for (var question in questions) {
		var imgPath = getImgPath(question, '.png');
		var imgPathActive = getImgPath(question, '_a.png');
		var imgPathBig = getImgPath(question, '_big.jpg');
		var htmlImageBig = '<img id="img_'+ question +'" src="'+ imgPathBig +'" alt="'+ lang['catImage'] +'" />';
		$('#test #question #catImage').append(htmlImageBig);
		var htmlImage = '<div class="group" id="group'+ question +'" imgOrig="'+ imgPath +'" imgActive="'+ imgPathActive +'" style="left: '+ categoryPos[question][0] +'px; top: '+ categoryPos[question][1] +'px"><img src="'+ imgPath +'" alt="'+ questions[question].cat +'"/><img class="active" src="'+ imgPathActive +'" alt="'+ questions[question].cat +'"/></div>';
		$('#groups').append(htmlImage);
	}
}

function initalizeTest() {
	if (typeof questions == 'undefined') {
		alert(lang['noQuestions']);
		return false;
	}
	showGroups();
	$('#test').css('display', 'block');
}

function showPageDetails() {
		$('#resultTable, #resultGlobal').hide();
		$('#introduction, #doYouKnow, #question').hide();
		$('#pageReadMore').show();
		$('#text').show();
		$('#testBottom').css({
			'position': 'relative',
			'top': '0',
			'height': '99px'
		});
		$('#logoUnilever').removeClass('small').css({
			'margin-top':'-35px',
			'margin-left': '780px'			
		});
		return false;
}

function rand( min, max ) {
    // http://kevin.vanzonneveld.net
    // +   original by: Leslie Hoare
    // +   bugfixed by: Onno Marsman
    // *     example 1: rand(1, 1);
    // *     returns 1: 1
    var argc = arguments.length;
    if (argc == 0) {
        min = 0;
        max = 2147483647;
    } else if (argc == 1) {
        throw new Error('Warning: rand() expects exactly 2 parameters, 1 given');
    }
    return Math.floor(Math.random() * (max - min + 1)) + min;
}

function addTooltip($el){	
	/* CONFIG */		
		xOffset = 10;
		yOffset = 20;		
		// these 2 variable determine popup's distance from the cursor
		// you might want to adjust to get the right result		
	/* END CONFIG */		
	/*if (e.pageX > ($(document).width()/2)+100) {
		xOffset = xOffset - 250;
		alert(xOffset);
	}*/
	$el.hover(function(e){
		this.t = this.title;
		this.title = "";									  
		$("body").append("<p id='tooltip'>"+ this.t +"</p>");
		$("#tooltip")
			.css("top",(e.pageY - yOffset) + "px")
			.css("left",(e.pageX + xOffset) + "px")
			.fadeIn("fast");		
    },
	function(){
		this.title = this.t;		
		$("#tooltip").remove();
    });
	
	$el.mousemove(function(e){
		$("#tooltip")
			.css("top",(e.pageY - xOffset) + "px")
			.css("left",(e.pageX + yOffset) + "px");
	});			
};

$(document).ready(function() {
	/*$('button#nextQ').click(function(){
			nextQuestion();
	});*/
	$(document.body).bind("click", 
		function(e) {
			var $target = $(e.target);
			if ($target.is('#prevQ')) {
				prevQuestion();
			}
			else if ($target.is('#toResults')) {
				showResults();
			}
		}); 
		
	$('#nextQclickthingy').click(function(){
		nextQuestion();
	});
	
	$('button.startTest').click(function(){
		$('#text').hide();
		$('#testBottom').css({
			'position': 'absolute',
			'top': '380px'
		});
		$('#logoUnilever').addClass('small').css({
			'margin-top': '-25px',
			'margin-left': '790px'
			});
		$('#question').show();
		showQuestion(curQuestion);
	});
	
	$('button.goBack, #header a').click(function(){
		$('#resultTable, #resultGlobal').hide();
		$('#pageReadMore, #question').hide();
		$('#text').show();
		$('#testBottom').css({
			'position': 'relative',
			'top': '0',
			'height': '99px'
		});
		$('#logoUnilever').removeClass('small').css({
			'margin-top' : '-35px',
			'margin-left': '780px'
		});
		setDoYouKnow();
		$('#text #introduction, #text #doYouKnow').show();
		return false;
	});
	
	
	//startTest();
	initalizeTest();
	
	function setDoYouKnow() {
		var doYouKnowItem = doYouKnow[rand(0,doYouKnow.length-1)];
		$('#doYouKnow').html('<img class="left" src="/images/salt.jpg" /><div class="left" style="width: 280px; margin: 40px 0 0 40px;"><strong>'+ lang['doYouKnow'] +'</strong><p style="width: auto">'+ doYouKnowItem +'</p></div>');
	}
	
	setDoYouKnow();
	
	$('#logoUnilever').html('<a href="'+ lang['unileverURL'] +'" target="_blank"><img src="/images/logo_unilever.png" alt="Unilever" /></a>');
	
	
	$('#textMoreAboutSalt').html('<a onclick="return showPageDetails();" href=""><img src="/images/'+ lang['language'] +'/txt_more_about_salt.png" alt="" /></a>');
	$('#popupTerms').html('<a href="">'+ lang['privacyLink'] +'</a>');
	$('#contact').html('<a target="_blank" href="'+ lang['contactLink'] +'">'+ lang['contact'] +'</a>');
	$('#popupTerms').click(function(){
		var popupTerms = window.open(lang['privacyPath'], '', '');
		return false;
	});
	$('#popupTermsUsage').html('<a href="">'+ lang['termsLink'] +'</a>');
	$('#popupTermsUsage').click(function(){
		var popupTerms = window.open(lang['termsPath'], '', '');
		return false;
	});
	
	$('#activateP1').click(function(){
		$(this).parent().find('.active').removeClass('active');
		$(this).addClass('active');
		$('#page2, #page3').hide();
		$('#page1').show();
	});
	$('#activateP2').click(function(){
		$(this).parent().find('.active').removeClass('active');
		$(this).addClass('active');
		$('#page1, #page3').hide();
		$('#page2').show();
	});
	$('#activateP3').click(function(){
		$(this).parent().find('.active').removeClass('active');
		$(this).addClass('active');
		$('#page2, #page1').hide();
		$('#page3').show();
	});

	addTooltip($('dfn'));
	
	
	// temp
	//$('button#toResults').css({left: '78px', top: '520px', margin: '0', position: 'relative'}).show();
	
	/*$('#groups .group').click(function() {
		showQuestion(this.id.substring(5));
	});*/
	
	// fix IE ****ups
	/*if (!jQuery.support.opacity) {
		$('button#prevQ').css('background-image', 'url(/images/'+ lang['language'] +'/btn_prev_8.png)');
	}*/

});