//TODO: Use the animate function in the JQuery core library and avoid JQuery UI to the extent possible
var newImgArray = [];
$(document).ready(function() {
	// Get the name and version of the browser
	var userAgent = navigator.userAgent.toLowerCase();
	// Figure out what browser is being used
	jQuery.browser = {
		version: (userAgent.match( /.+(?:rv|it|ra|ie|me)[\/: ]([\d.]+)/ ) || [])[1],
		chrome: /chrome/.test( userAgent ),
		safari: /webkit/.test( userAgent ) && !/chrome/.test( userAgent ),
		opera: /opera/.test( userAgent ),
		msie: /msie/.test( userAgent ) && !/opera/.test( userAgent ),
		mozilla: /mozilla/.test( userAgent ) && !/(compatible|webkit)/.test( userAgent )
	};

	// Preload all images
	$('#maskLoading').show();
	$('#loadingMainContent').show();
	$.preLoadCSSImages();
	$.preLoadImages(imageArray, function(){
		// Display the images in the content
		setupPageLayout(); // draws the menu at the top, and sets up the "special effects" on the page
		setupPageContent();
		// Shake the van only if not IE < 8.0
		if(!(jQuery.browser.msie && jQuery.browser.version < 8.0)) {
			shakeTheIceVan();
		}
		$('#maskLoading').hide();
		$('#loadingMainContent').hide();
	});
});

// ####### Constants #####
//
//          ||
//          ||
//          \/
//
// #######################
var NEXT_QUESTION_TEXT = '<img src="/recykids/images/content/next.png" alt="Next Question" title="next question"/>';
var FINISH_QUIZ_TEXT = '<img src="/recykids/images/content/end.png" alt="End of Quiz" title="End of Quiz"/>';

// ####### Functions #####
//
//          ||
//          ||
//          \/
//
// #######################

function shakeTheIceVan()
{
	// Truck shaking
	$('div#iceVan').effect(
		"shake",
		{
			direction: "up",           // up down / left right...
			distance: 1,
			times: 40                   // Doesn't matter..
		},
		70,
		function()
		{
			setTimeout(shakeTheIceVan, 40000);
		}
	);
}


/**
 * Equivalent to trim in php
 *
 * Without the second parameter, Javascript function will trim these characters:
 * ” ” (ASCII 32 (0×20)), an ordinary space.
 * “\t” (ASCII 9 (0×09)), a tab.
 * “\n” (ASCII 10 (0×0A)), a new line (line feed).
 * “\r” (ASCII 13 (0×0D)), a carriage return.
 * “\0″ (ASCII 0 (0×00)), the NUL-byte.
 * “\x0B” (ASCII 11 (0×0B)), a vertical tab.
*/
function trim(str, chars) {
		return ltrim(rtrim(str, chars), chars);
}

function ltrim(str, chars) {
		chars = chars || "\\s";
		return str.replace(new RegExp("^[" + chars + "]+", "g"), "");
}

function rtrim(str, chars) {
		chars = chars || "\\s";
		return str.replace(new RegExp("[" + chars + "]+$", "g"), "");
}

/*
*   Load the content of the clicked link
*   params :
*       - url : url of the page to load
*/
function loadContent(url) {
	// Load the HTML content of a page in the div whose id is 'mainContent'
	$.get(
		url,
		function(data)
		{
			$('#mainContent').html(data);
			// Once the content is loaded
			setupPageContent(); // Setup the content
			// Show it
			$("#mainContent").show("scale", "normal", function(){
				// We hide this loader here because show() set display block on the images
				$('#loadingFundo').hide();
				$('#loadingSchool').hide();
			}); 
		});
	// Set the url in browser
} // End loadContent

function displayContent(evt) {
	// Change the page Title
	document.title = $(this).attr("title") + " - Recykids - Support Your School";
	// Reduce the content
	$("#mainContent").hide("scale");
	// Load the new content
	loadContent($(this).attr("id"));
}

/**
 *  Set the links of the menu
 */
function setAjaxMenuLinks() {
	$("div.menu a").click(displayContent);
	$("div.compSign a").click(displayContent);
	$("div.footer a").click(displayContent);
	// Open all external links in a new windows (Terms and conditions)
	$("div.footer a[rel='external']").unbind('click');
	$("div.footer a[rel='external']").attr('target','_blank');
}// End set ajax Menu links


/**
 *  Set the links displayed in the content
 */
function setupAjaxContentLinks() {
	 $("#mainContent a[href=\"javascript:void(0);\"][id]").click(displayContent);
} // End setupAjaxContentLinks


/**
 *     Infinite shaking element
 *     params :
 *          - elementSelector : jquery selector of an element (ex : #truck => id="truck")
 */
function shakeInfinite(elementSelector){
	$(elementSelector).effect(
		"shake",
		 {
			 direction: "up",           // up down / left right...
			 distance: "2",
			 times: 10                   // Doesn't matter..
		 },
		 70,                            // speed
		 function(){
			shakeInfinite(elementSelector);
		 } // Infinite loop, function calls itself
	);
} // End of shakeInfinite

/**
 *  Setup the page layout (Elements always displayed)
 */
function setupPageLayout(){
	// Links for the menu
	setAjaxMenuLinks();

}// End setupPageLayout()

/**
 *  Load a question in the quiz
 *  params :
 *      - data : (JSON Object) 
 *      	{
 *      		question: <string>, 
 *      		answers: []
 *      	}
 */
function loadQuestion(data){
	if (data.question.step_number == 1 && $('#quizSection').css('display') == 'none')
	{
		$('#quizSection').show('scale', 'normal');
		$('#quizIntro').hide();
	}
	
	$('#numberOfTheStep').text(data.question.step_number);
	// Load the question
	$('#question').text(data.question.question);
	// Empty Answers
	$('#answers').empty();
	// Empty Feedback
	$('div#feedback p.explanation').empty();
	$('div#feedback div').hide();
	
	// Add new data
	$.each(data.answers, function(i,answer){
		stringQuestion = '';
		stringQuestion += '<li class="answerStyle" >';
		stringQuestion +=     '<input type="radio" id="answer' + answer.id + '" name="answer" value="' + answer.id + '"/>';
		stringQuestion +=     '<label for="answer' + answer.id + '">' + answer.answer + '</label>';
		stringQuestion += '</li>';
		// Add the answers
		$('#answers').append(stringQuestion);
		// Explanation, Careful the day they add explanation for the wrong answers...
		if(answer.explanation != ''){
			$('div#feedback p.explanation').append(answer.explanation);
		}
	});
	// Hidden fields
	// Number of the step
	$('#hdnStep').val(data.question.step_number);
	// Id of the good answer
	$('#hdnGoodAnswer').val(data.question.good_answer_id);

	// Set the link for the next question (or end of the quiz)
	if ($('#quizIntro'))
	{
		setNextQuestionLink();
		// Set the feedback of the question (according to the answer selected)
		showFeedbackForAnswer();
		// Show the next question
		$('#mainContent').show('slide', {
			direction: 'right'
		});
	}
		$('#nextStep').hide();
}

/**
*   Load the JSON object of a question by AJAX
*   params :
*       - quiz_id : Id of the quiz
*       - step : Step number
*/
function getQuestionData(quiz_id, step){
	$.ajax({
		type: "GET",
		url: "index.php/quiz/ajaxQuestion/" + quiz_id + "/" + step,
		data: null, // We transmit the params in that way because of codeIgniter (get variable in the url sometimes killed)
		success: loadQuestion, // callback : loadQuestion function
		dataType: "json"
	 });
}

/**
 * Called when the user clicks the "Finish the quiz" link
*/
function endTheQuiz()
{
	// Reduce the content
	$("#mainContent").hide("scale");
	// Load the congratulations page with the form
	loadContent('index.php/quiz/congratulations');
	return false;
}


/**
 * Called when the user clicks the "next question" link
 */
function gotoNextQuestion()
{
	// if a choice is selected, go to the next question only if it's the right choice.
	$('#mainContent').hide('slide', // effect
		{
			direction: 'left'
		}, // direction
		function()
		{
			var nextStep = parseInt($('#hdnStep').val()) + 1;
			var quizId = $('#hdnQuiz_id').val();
			getQuestionData(quizId, nextStep);
		}
	);
}

/**
 *  Set the link for the next question in the quiz
 *
 */
function setNextQuestionLink() {
	var nextStep = parseInt($('#hdnStep').val()) + 1;
	var numberOfSteps = $('#hdnQuiz_steps').val();

	// If there is a next question
	if (nextStep < numberOfSteps) {
		// Set the text of the link
		$('#mainContent a#nextStep').empty();
		$('#mainContent a#nextStep').append(NEXT_QUESTION_TEXT);

		// there is a default link for "go to next question", 
		// but that link is enabled in the function showFeedbackForAnswer,
		// so we unbind any current event handlers for the click event
		$('#mainContent a#nextStep').unbind('click');
	}
	// If end of the quiz
	else {
		$('#mainContent a#nextStep').empty();
		$('#mainContent a#nextStep').append(FINISH_QUIZ_TEXT);
		$('#mainContent a#nextStep').one("click", endTheQuiz);
	}
} // End of setNextQuestionLin

/**
*   Set the feedback for the answers in the quiz when users click on an answer..
*/
function showFeedbackForAnswer(){
	// When click on an answer
	$('#answers input[name=answer]').click(function(){
		// Init display
		$('div#feedback div').hide();
		// Good answer
		if($(this).val() == $('#hdnGoodAnswer').val()){
			// Show the feedback
			$('div#feedback div.goodAnswer').slideDown();
			// Number of the next step
			var nextStep = parseInt($('#hdnStep').val()) + 1;
			// Total number of steps
			var numberOfSteps = $('#hdnQuiz_steps').val();
			// next question or End quiz link enabled (see if we change this link)
			if (nextStep < numberOfSteps)
				$('#nextStep').one('click', gotoNextQuestion);
			else
				$('#nextStep').one('click', endTheQuiz);
						$('#nextStep').show();
		}
		else {// Wrong answer
			// Show the feedback
			$('div#feedback div.wrongAnswer').slideDown();
			// if the user has selected a wrong answer, 
			// then disable the 'next question' / 'end the quiz' link
			$('#nextStep').unbind('click');
						$('#nextStep').hide();
		}
	});
} // End of showFeedbackForAnswer

/**
 *  Check the form participant at the end of the quiz
 */
function validateFormParticipant(){
	// Hide the feedback
	$('div.formParticipant span.error').css('display', 'none');
		$('div.feedbackFormCompetition div').css('display', 'none');


	// Get the values
	var initials = $('div.formParticipant #txtInitials').val();
	var classroom = $('div.formParticipant #txtClass').val();
	var sexOptions = $('div.formParticipant input[name=sex]:checked');
	var school_text = $('div.formParticipant #txtSchool').val();
	var school_id = $('div.formParticipant #hdnSchool').val();

	var valid = true;

	if(trim(initials) == ''){
		$('#errorInitials').css('display', 'inline');
		valid = false;
	}

	if(sexOptions.length == 0){
		$('#errorSex').css('display', 'inline');
		valid = false;
	}

	if(trim(school_text) == '' || trim(school_id) == ''){
		$('#errorSchool').css('display', 'inline');
		valid = false;
	}

		if(trim(classroom) == ''){
		$('#errorClass').css('display', 'inline');
		valid = false;
	}

	return valid;
}

/**
 *  Submit the form displayed at the end of the quiz
 */
function submitFormParticipant(){
		valid = validateFormParticipant();
	if(valid){
		// Get the values
		var initials = $('div.formParticipant #txtInitials').val();
		var classroom = $('div.formParticipant #txtClass').val();
		var sex = $('div.formParticipant').find('input[name=sex]:checked').val();
		var school_id = $('div.formParticipant #hdnSchool').val();

		// AJAX request
		$.post(
			'index.php/quiz/ajaxSaveParticipant', // Url
			{ // POST DATA
				'initials': initials,
				'classroom' : classroom,
				'sex': sex,
				'school_id': school_id
			},
			function(data){
				// Callback : thanks for for your participation
								$('div.formParticipant').slideUp();
				$('div.feedbackFormCompetition p.valid').slideDown();
			}
		);
	}
		else {
			$('div.feedbackFormCompetition p.invalid').slideDown();
		}

} // End of submitFormParticipant


/**
 *  Tips for Why recycle and Top recycling
 *
 */
function tips(){
	// When a user click on a tip image
	$('div.tipTrigger').each(function(){
		$(this).click(function(){
			$('.tipTrigger').removeClass('active');
			// Set this tooltip as active
			$(this).addClass('active');
			// Empty the content of the div
			$('div.cloudTipContainer').empty();
			$('div.cloudTipContainer').append($(this).next().html());
			// Display the images in the content
			///*
			$('div.cloudTipContainer img').each(
				// preload the images for the tips section again 
				// TODO: this is something that needs to be sorted out properly later on
				function(index, domElement){
					var tempImg = new Image();
					tempImg.onload = function()
					{
						$(domElement).height(this.height + 'px')
			                     .width(this.width + 'px')
								 .attr('height', this.height)
			                     .attr('width', this.width);
					};
					tempImg.src = $(domElement).attr('src');
				}
			);
			//*/
			// Setup the links in the content
			$("div.cloudTipContainer a[href=\"javascript:void(0);\"]").click(displayContent);
		});
	});
}


function setImageAttributes(imageIndex)
{
	var tempImg = new Image();
	///*
	tempImg.onload = function()
	{
		//alert(tempImg.src);
	//*/
		//$(this).attr({'height': tempImg.height, 'width': tempImg.width});
		$(this).css('height', tempImg.height + 'px');
				$(this).css('width', tempImg.width + 'px');
				alert($(this).css('height'));
	}
	tempImg.src = $(this).attr('src');
}

function submitFormRecommend(){
	// Hide feedback
	$('#recommendForm .error').css('display', 'none');

		nameSender = $('#nameSender').val();
		emailSender = $('#emailSender').val();
		emailSchool = $('#emailSchool').val();
		message = $('#message').val();

		// Check
		var valid = true;
	// FilterEmail
	var filter = /^([a-zA-Z0-9_.-])+@(([a-zA-Z0-9-])+.)+([a-zA-Z0-9]{2,4})+$/;

	if(trim(nameSender) == ''){
		$('#errorNameSender').css('display', 'inline');
		valid = false;
	}

	if(trim(emailSender) == ''){
		$('#errorEmailSender').css('display', 'inline');
		valid = false;
	}
	else{
		if(!filter.test(emailSender)) {
			$('#errorFormatEmailSender').css('display', 'inline');
			valid = false;
		}
	}

	if(trim(emailSchool) == ''){
			$('#errorEmailSchool').css('display', 'inline');
		valid = false;
	}
	else{
		if(!filter.test(emailSchool)) {
			$('#errorFormatEmailSchool').css('display', 'inline');
			valid = false;
		}
	}

	if(trim(message) == ''){
		$('#errorMessage').css('display', 'inline');
				valid = false;
	}

	if(valid) {
		// Send
		$.post(
			"index.php/recommend/ajaxSendEmail",
			{
				name_sender: nameSender,
				email_sender: emailSender,
				email_school: emailSchool,
				message: message
			},
			function(data){
				// Email sent
				if(data.success){
					$('span.feedbackEmailRecommendFailed').css('display', 'none');
					$('span.feedbackEmailRecommendSuccess').css('display', 'inline');
				}
				// Failed
				else {
					$('span.feedbackEmailRecommendSuccess').css('display', 'none');
					$('span.feedbackEmailRecommendFailed').css('display', 'inline');
				}
			},
			'json'
		);
	}
}

 /**
 *  Setup the page content
 *  TODO : call the functions only when needed
 */
function setupPageContent(){
	// Set up handlers for all the links displayed on the page inside the div with id 'mainContent'
	setupAjaxContentLinks();

	// ----------- Tips Why recycle and Top recycling ----------
	tips(); // set up handlers for each element with the CSS class 'tipTrigger'

	// ----------- Fundometer -----------
	// Construct it (/scripts/fundometer.js)
	var fundo = $("div#divForTheFundometer").fundometer();
	// PIR configuration
	$.pir.options.php="../templates/supportyourschool/font/pir.php";

	
	// On change the value of the select list
	// TODO : insert the *0.75 into the library fundometer
		$('div.fundometerContainer input[name=school]').autoComplete({
			ajax : 'index.php/howismyschool/ajaxSchoolList',
			width : '283px',
			autofill: true,
			delay: 1,
			triped: 'auto-complete-striped',
			// preventEnterSubmit is already flagged true by default
			// TODO : improve the behaviour of the textfield
			// On select of a school
			onSelect: function(event, ui){
				// Display loading
				$('#loadingFundo').css('display', 'inline');
				// Set the displayed value in the textfield
				$('#txtSchool').val(ui.data.display);
				// Set the value of the hidden field with the Id of the selected school
				$('#hdnSchool').val(ui.data.value);
				// AJAX request
				$.post(
						'index.php/howismyschool/ajaxSchoolData', // Url
						{ // POST DATA
								'school_id': $('#hdnSchool').val()
						},
						function(data){
							ratioReached = data.school_raised / data.school_objective * 100;
							$.fn.fundometer.setValue(fundo, ratioReached);
							// Change the values
							$('div.targetValue span').html(' ' + data.school_objective);
							$('div.raisedValue span').html(' ' + data.school_raised);
							// Change the font
							$("div.targetValue span").pir({font: "spong3.ttf", size:10, color:"#54AE64"});
							$("div.raisedValue span").pir({font: "spong3.ttf", size:10, color:"#DF4747"});
							$('#loadingFundo').css('display', 'none');
						},
						'json'
				);
			},
			// Loading feedback
			spinner : function(event, ui){
				if(ui.active == true){
					$('#loadingFundo').css('display', 'inline');
				}
				else{
					$('#loadingFundo').css('display', 'none');
				}
			}
		});
		
		$("div.targetValue span").pir({font: "spong3.ttf", size:10, color:"#54AE64"});
		$("div.raisedValue span").pir({font: "spong3.ttf", size:10, color:"#DF4747"});

		
		// --------End of fundometer-----
		
	// ----------------------- QUIZ ---------------------
	// --------------- Auto complete school name -----------
	// Library : http://www.codenothing.com/demos/2009/auto-complete/index.html
		// Auto-complete preventing form submission, and firing onSelect function
				// A POST variable is sent, named 'value' which contain the value of the textfield
		$('div.formParticipant input[name=school]').autoComplete({
			ajax : 'index.php/quiz/ajaxSchoolList',
			width : '353px',
			// preventEnterSubmit is already flagged true by default
			// TODO : improve the behaviour of the textfield
			// On select of a school
			onSelect: function(event, ui){
			// Set the displayed value in the textfield
			$('#txtSchool').val(ui.data.display);
			// Set the value of the hidden field with the Id of the selected school
			$('#hdnSchool').val(ui.data.value);
			},
			// Loading feedback
			spinner : function(event, ui){
			if(ui.active == true){
				$('#loadingSchool').css('display', 'inline');
			}
			else{
				$('#loadingSchool').css('display', 'none');
			}
			}
		});
	// -------------End of Auto complete school name -----------

	// ----------------- Participant form -----------------
		$('div.formParticipant #btnEnter').click(function(){
			submitFormParticipant();
		});
	// -------------- End of Participant form -----------

	// ----------------- End of QUIZ -------------------

	// ----------------- Recommend form -----------------
		$('form#recommendForm #btnSubmit').click(function(){
			submitFormRecommend();
		});
	// -------------- End of recommend form -----------
}// End setupPageContent()
