CQQuiz = {

	PAGE_SIZE : 20, 
	QBLOCK_SIZE : 10,
	
	View: 'question', 
	NextAction : 'question', 
	
	initializePage : function(module_id, callback) {
		//Static for now
		CQQuiz.TOP_NUMBER = 5;
		CQQuiz.ModuleID = module_id;
		
		jQuery('.cqquiz-header-topscores').html("Top " + CQQuiz.TOP_NUMBER);
		jQuery('.cqquiz-header-question').html( "Jouez au quiz sur notre cin&eacute;ma !");
		jQuery('#cqquiz-score-modifier').hide();
		
		// Set action buttons
		jQuery(".cqquiz-submit").click(function(){ CQQuiz.submitQuestion(); this.blur(); return false; });
		jQuery(".cqquiz-button-recordname").click(function(){ CQQuiz.submitRecord();return false; });
		jQuery(".cqquiz-button-cancel").click(function(){ CQQuiz.cancelRecord();return false; });

		CQQuiz.bindScores();
		CQQuiz.bindLevels(CQQuiz.startNewQuiz, callback);
		
		pageTracker._trackEvent("Quiz", "Event", "Start");
	}, 
	
	bindLevels : function(callback, afterCallback) {
		jQuery.get("/Gateway/XML/service.asmx/QuizLevels", {ModuleID : CQQuiz.ModuleID}, function(data) {
			CQQuiz.LevelsXML = data;
			var level_width = Math.floor(100 / jQuery('Level', data).length);
			var html = "<tr>";
			var lvls = jQuery('Level', data);
			lvls.each(function(i) {
				html += "<td style='width: " + level_width + "%;"
				if (i == lvls.length - 1) {
					html += 'border-right: none;';
				}
				html += "'>" + jQuery('Name', this).text() + "</td>";
			});
			html += "</tr>";
			jQuery('.cqquiz-levels-list').html(html);

			callback(afterCallback);
		});
	}, 
	
	bindScores : function(callback) {
		jQuery.get("/Gateway/XML/service.asmx/QuizTopScores", {ModuleID : CQQuiz.ModuleID}, CQQuiz.writeTopScores);
	}, 
	
	endQuiz : function () {
		var scores = jQuery('Score', CQQuiz.ScoresXML);
		var lowerbound = 0;
		if (scores.length > 0) {
			lowerbound = parseInt(jQuery(scores[scores.length - 1]).text());
		}
		if (CQQuiz.currentScore > lowerbound) {
			//Qualifies to enter the top scores
			jQuery('.cqquiz-header-question').text('Bravo!');
			CQQuiz.switchView('record');
			CQQuiz.writeScore();
		} else {
			CQQuiz.resetQuiz();
			CQQuiz.switchView('end');
			pageTracker._trackEvent("Quiz", "Event", "Quit");
		}
	}, 
	
	startNewQuiz : function (callback) {
		var lvls = jQuery("Level", CQQuiz.LevelsXML);
		if (lvls.length > 0) {
			CQQuiz.currentScore = 0;
			CQQuiz.currentLevel = {XMLRow: -1};
			CQQuiz.QOrder = new Array();
			jQuery.get("/Gateway/XML/service.asmx/QuizQuestionCount", {ModuleID : CQQuiz.ModuleID}, function(data) {
				CQQuiz.currentPosition = "1/" + jQuery("int", data).text();
				CQQuiz.startNextLevel(callback);
			});
		} else {
			CQQuiz.switchView('error');
			if(typeof(callback) != "undefined")
					callback();
		}
	}, 
	
	startNextLevel : function (callback) {
	
		callback = callback ? callback : function(){};
		
		pageTracker._trackEvent("Quiz", "Event", "ChangeLevel");
	
		var rowindex = CQQuiz.currentLevel.XMLRow + 1;
		var lvls = jQuery('Level', CQQuiz.LevelsXML);
		if (lvls.length > rowindex) {
			CQQuiz.currentLevel = {
				ID : jQuery("ID", lvls[rowindex]).text(), 
				Name : jQuery("Name", lvls[rowindex]).text(),
				PassGrade : jQuery("PassGrade", lvls[rowindex]).text(),
				FailGrade : jQuery("FailGrade", lvls[rowindex]).text(), 
				Worth : jQuery("Worth", lvls[rowindex]).text(),
				XMLRow: rowindex
			};
			jQuery('.cqquiz-levels-selectedlevel').removeClass('cqquiz-levels-selectedlevel');
			var htmllvls = jQuery('.cqquiz-levels-list td');
			htmllvls.eq(rowindex).addClass('cqquiz-levels-selectedlevel');
			var level_width = Math.floor(100 / htmllvls.length);
			var offset = level_width * (rowindex) + (level_width / 2) - 4;
			jQuery('#cqquiz-level-arrow').animate({left:offset + '%'}, 'normal', 'easeOutSine', callback);
			//if (rowindex > 0) CQQuiz.writeFeedback('pass');
			var curpos = CQQuiz.currentPosition.split('/', 2);
			var num_skip = (rowindex==0 ? 0 : 1);
			//if (CQQuiz.QOrder) num_skip = CQQuiz.QOrder.length;
			CQQuiz.currentPosition = (parseInt(curpos[0]) + num_skip) + '/' + curpos[1];
			CQQuiz.startLevel();
		} else if (CQQuiz.QOrder.length > 0) {
			//No more levels, but there are still questions left in this one, keep going
			CQQuiz.nextQuestion();
		} else {
			//No more levels, end of quiz!
			CQQuiz.endQuiz();
		}
	}, 
	
	startLevel : function () {
		CQQuiz.submitHistory = new Array();
		CQQuiz.QOrder = new Array();
		jQuery.get("/Gateway/XML/service.asmx/QuizRandomQs", { LevelID : CQQuiz.currentLevel.ID }, function(data) {
			jQuery("QID", data).each(function(i) { 
				CQQuiz.QOrder[i] = jQuery(this).text();
			});
			//CQQuiz.currentPosition = "1/" + CQQuiz.QOrder.length;
			CQQuiz.displayQuestion();
		});
	}, 

	displayQuestion : function () {
		if (CQQuiz.QOrder.length > 0) {
                        
                        jQuery('#cqquiz-submitid').hide();

			jQuery.get("/Gateway/XML/service.asmx/QuizQuestion", { QuestionID : CQQuiz.QOrder[0] }, function(data) {
				CQQuiz.currentQuestion = {
					ID : jQuery('ID', this).text(), 
					QuestionString : jQuery('QuestionString', data).text(), 
					Feedback : jQuery('AltText', data).text(), 
					Answers : new Array(), 
					ClipRef : jQuery('ClipRef', data).text()
				};

				jQuery('#cqquiz-question-text').html(CQQuiz.currentQuestion.QuestionString);
				
				var number_of_correct = 0;
				var html = "<ul class='cqquiz-answers-list'>";
				jQuery('Answer', data).each(function(i) {
					CQQuiz.currentQuestion.Answers[i] = {
						ID : jQuery('ID', this).text(), 
						AnswerString : jQuery('AnswerString', this).text(), 
						IsCorrect : jQuery('IsCorrect', this).text() == 'True'
					};
					if (CQQuiz.currentQuestion.Answers[i].IsCorrect) number_of_correct++;
					
					html += "<li>";
					html += "<input id='cqquiz-answer-" + i + "' name='answers' type='radio' value='" + CQQuiz.currentQuestion.Answers[i].ID + "' />";
					html += "<label for='cqquiz-answer-" + i + "'><strong>" + String.fromCharCode(i+97) + ".</strong> ";
					html += CQQuiz.currentQuestion.Answers[i].AnswerString + "</label>";
					html += "</li>";
				});
				html += "</ul>";
				//Replace radio buttons with checkboxes if we have many correct answers
				if (number_of_correct > 1) {
				    html = html.replace(/type='radio'/g, "type='checkbox'");
				}
				
				jQuery('#cqquiz-content-answers').html(html);
				
				jQuery('#cqquiz-submitid').show();
				
				CQQuiz.writeNumbers();
				CQQuiz.writeScore();
				CQQuiz.switchView('question');
				
				CQQuiz.loadCurrentClip();
			});
		} else {
			CQQuiz.switchView('error');
		}
	}, 
	
	nextQuestion : function () {
		CQQuiz.QOrder.shift();
		pageTracker._trackEvent("Quiz", "Event", "NextQuestion");
		
		if (CQQuiz.QOrder.length > 0) {
		    var curpos = CQQuiz.currentPosition.split('/', 2);
		    CQQuiz.currentPosition = (parseInt(curpos[0]) + 1) + '/' + curpos[1];
		    CQQuiz.displayQuestion();
		} else {
		    //New level!
		    CQQuiz.startNextLevel();
		}
	}, 
	
	writeTopScores : function(xmlData) {
		CQQuiz.ScoresXML = xmlData;
		var html = "";
		jQuery('TopScore', xmlData).each(function(i) {
			var row = "<tr>";
			row += "<td class='scores-col-name'><strong>" + jQuery('FName', this).text() + " ";
			row += jQuery('LName', this).text() + "</strong><br />";
			row += jQuery('City', this).text() + "</td>"; 
			row += "<td class='scores-col-plus'>&nbsp;&gt;</td>";
			row += "<td class='scores-col-score'><strong>" + jQuery('Score', this).text() + "</strong></td>\n";
			html += row;
		});
		jQuery('.cqquiz-topscores-list').html(html);
	}, 
	
	writeNumbers : function () {
		var curpos = CQQuiz.currentPosition.split('/', 2);
		jQuery('#cqquiz-position-current').text(curpos[0]);
		jQuery('#cqquiz-position-over').text(curpos[1]);
		//jQuery('#cqquiz-position-over').text(1000);
	}, 
	
	writeScore : function () {
		jQuery('#cqquiz-score-display').text(CQQuiz.currentScore);
		jQuery('#cqquiz-recordscore').text(CQQuiz.currentScore);
		pageTracker._trackEvent("Quiz", "Event", "TopScoreForm");
	}, 
	
	writeFeedback : function (success, msg) {
		var imgurl = "/Portals/_default/Skins/CinemaQuebecois/images/";
		imgurl += (success ? 'quiz-correct.png' : 'quiz-wrong.png');
		jQuery('#cqquiz-feedback-img').get(0).src = imgurl;
		jQuery('#cqquiz-feedback-texte').text((success ? 'Correct' : 'Incorrect'));
		
		var answer = '';
		for (var i=0; i < CQQuiz.currentQuestion.Answers.length; i++) {
			if (CQQuiz.currentQuestion.Answers[i].IsCorrect) {
				answer = String.fromCharCode(i+97) + ". " + CQQuiz.currentQuestion.Answers[i].AnswerString;
				break;
			}
		}
		//var feedback;
		var feedback = "<div style='color: #062533; font-size: 14px; font-weight: bold;'>";
		//feedback += "R&eacute;ponse: " + answer;
		//feedback += (success ? 'Correct' : 'Incorrect') + (CQQuiz.currentQuestion.Feedback.length > 0 ? ": " : "! ");
		feedback += "</div>";
		feedback += "<span class='cqquiz-msg'>" + msg + "</span>";
		feedback += CQQuiz.currentQuestion.Feedback;
		jQuery('#cqquiz-content-feedback').html(feedback);
	}, 
	
	recordSuccess : function(success) {
		if (CQQuiz.submitHistory.length >= CQQuiz.QBLOCK_SIZE) {
			CQQuiz.submitHistory.shift();
		}
		CQQuiz.submitHistory.push(success);
		if (success) {
			//CQQuiz.writeFeedback('correct');
			CQQuiz.currentScore += parseInt(CQQuiz.currentLevel.Worth);
			CQQuiz.modifier = jQuery('#cqquiz-score-modifier');
			CQQuiz.modifier.show().animate({top: '-10px'}, 200, 'easeInSine', function() {
				CQQuiz.modifier.animate({top: '0px'}, 200, 'easeOutSine', function() {
					setTimeout("CQQuiz.modifier.hide()", 500); 
				});
			});
			CQQuiz.writeScore();
		} else {
			//CQQuiz.writeFeedback('wrong');
		}
	}, 

	getUserGrade : function() {
		if (CQQuiz.submitHistory.length < CQQuiz.QBLOCK_SIZE) {
			return 0;
		}
		
		var success_count = 0;
		for (i=0; i < CQQuiz.submitHistory.length; i++) {
			if (CQQuiz.submitHistory[i]) {
				success_count++;
			}
		}
		var last_success = CQQuiz.submitHistory[CQQuiz.submitHistory.length -1];
		
    if (last_success && success_count >= CQQuiz.currentLevel.PassGrade && 
        (CQQuiz.currentLevel.XMLRow +1) < jQuery('Level', CQQuiz.LevelsXML).length) {
        //Level up if qualify and not at last level
        return 1;
		}
    
    if (!last_success && success_count <= CQQuiz.currentLevel.FailGrade) {
			var fail_count = CQQuiz.QBLOCK_SIZE - success_count;
			CQQuiz.currentScore -= fail_count * CQQuiz.currentLevel.Worth;
			return -1;
		}
		return 0;
	}, 
	
	submitQuestion : function() {
		if (CQQuiz.View == 'feedback') {
			if (CQQuiz.NextAction == 'question') {
				CQQuiz.nextQuestion();
			} else {
				CQQuiz.startNextLevel();
			}
			return;
		}
	    var arr_answers = new Array();
		for (i=0; i < CQQuiz.currentQuestion.Answers.length; i++) {
			var ans = CQQuiz.currentQuestion.Answers[i];
			arr_answers[String(ans.ID)] = ans.IsCorrect;
		}
		if (jQuery('.cqquiz-answers-list input:checked').length > 0) {
		    var success = true;
		    var options = jQuery('.cqquiz-answers-list input');
			var labeloptions = jQuery('.cqquiz-answers-list label');
			options.each(function(i) {
			    if (this.checked != arr_answers[this.value]) {
					success = false;
					labeloptions.eq(i).addClass('cqquiz-wronganswer');
				}
				if (CQQuiz.currentQuestion.Answers[i].IsCorrect) {
					labeloptions.eq(i).removeClass('cqquiz-wronganswer');
					labeloptions.eq(i).addClass("cqquiz-goodanswer");
				}
			});
			CQQuiz.recordSuccess(success);
			var res = CQQuiz.getUserGrade();
			var msg = '';
			if (res==1 || CQQuiz.QOrder.length <= 0) {
				CQQuiz.NextAction = 'level';
				msg = 'F&eacute;licitations!  Vous passez au niveau suivant.  ';
			} else if (res==-1) {
				CQQuiz.submitHistory = new Array();
				CQQuiz.NextAction = 'question';
				CQQuiz.writeScore();
				msg = '<span style="color:red">Attention!  Vous avez fait trop d\'erreurs; votre pointage a diminu&eacute;!</span>';
			} else {
				CQQuiz.NextAction = 'question';
			}
			CQQuiz.writeFeedback(success, msg);
			CQQuiz.switchView('feedback');
		} else {
			//CQQuiz.writeFeedback('nosel');
		}
	}, 
	
	submitRecord : function() {
		var FName = jQuery('#cqquiz-record-txtFirst').val();
		var LName = jQuery('#cqquiz-record-txtLast').val();
		var City = jQuery('#cqquiz-record-txtCity').val();
		if (!FName || FName=='' || !LName || LName=='' || !City || City=='') {
			jQuery('#cqquiz-record-validator').text("Vous devez remplir tous les champs!");
			return;
		}
		jQuery.post('/Gateway/XML/service.asmx/QuizSubmitScore', {
				ModuleID : CQQuiz.ModuleID, 
				FName : FName, 
				LName : LName, 
				City : City, 
				Score : CQQuiz.currentScore, 
				Limit : CQQuiz.TOP_NUMBER }, 
			function(data) {
				CQQuiz.writeTopScores(data);
				CQQuiz.resetQuiz();
				CQQuiz.switchView('end');
				pageTracker._trackEvent("Quiz", "Event", "TopScoreSubmit");
			});
	}, 
	
	cancelRecord : function() {
		CQQuiz.resetQuiz();
		CQQuiz.switchView('end');
	}, 
	
	switchView : function(view) {
		CQQuiz.View = view;
//		var imgurl = (view == 'feedback' ? 'quiz-next.png' : 'quiz-validate.png');
//		imgurl = "/Portals/_default/Skins/CinemaQuebecois/images/" + imgurl;
//		jQuery('#cqquiz-submitid').get(0).src = imgurl;
		jQuery("#cqquiz-bouton-text").text((view == 'feedback' ? 'Question suivante' : 'Validez votre réponse' ));

		if (view != 'feedback') { 
				jQuery('#cqquiz-content-feedback').hide(); 
				jQuery('#cqquiz-feedback-img').hide(); 
				jQuery('#cqquiz-feedback-texte').hide(); 
				if (view == 'end') { 	
					jQuery('#cqquiz-view-end span').css('top', (jQuery('.descriptionPaneWrapper').height() / 2) - 9); 
					jQuery('#cqquiz-content').animate({opacity: .2}, {duration: 0,  easing:"easeOutSine", complete:function(){ 		setTimeout("jQuery('.descriptionPane').animate({height: 0}, {duration:500, easing:'easeOutExpo'}); Main.CurrentEpisode();", 1000); }});	
					jQuery('#cqquiz-view-end span').css('opacity', 1);
					jQuery('#cqquiz-view-end span').css('filter', 'alpha(opacity=100)');
				} else { 
					jQuery('.cqquiz-view').hide(); 
				} 
				jQuery('#cqquiz-view-' + view).show(); 
				jQuery('.cqquiz-answers-list input').removeAttr("disabled"); 
		} else { 
			jQuery('#cqquiz-content-feedback').show(); 
			jQuery('#cqquiz-feedback-img').show(); 
			jQuery('#cqquiz-feedback-texte').show(); 
			jQuery('.cqquiz-answers-list input').attr("disabled", "disabled"); 
		}

		//Adjust descriptionPane height
 		/* var height_table = jQuery('#cqquiz-content').css("height"); 
		jQuery('.descriptionPane').animate({height: height_table}, {duration:500, easing:"easeOutExpo"}); */
	},

	resetQuiz : function() {
 		CQQuiz.currentScore = 0;
 		CQQuiz.currentLevel = {};
		CQQuiz.currentQuestion = {};
		CQQuiz.QOrder = new Array();
		CQQuiz.submitHistory = new Array();
	},

	loadCurrentClip : function() {
 		var infos = CQQuiz.currentQuestion.ClipRef.split(';');
		if (infos.length >= 3 && infos[1].trim().length > 1 && infos[2].trim().length > 3)
		{
			JSFL.playVideo(infos[2], infos[1], CQQuiz.currentQuestion.QuestionString);
		}
		else { JSFL.showDefaultImage('quiz'); }
	}
};

function leadingZeros(num) {
	return String(num).length==1 ? "0" + num : num;
}

