String.prototype.trim = function() { return this.replace(/^\s+|\s+$/, ''); };

if (typeof VYRE == "undefined"){var VYRE = {};}
if (typeof (VYRE.Utils) == "undefined"){VYRE.Utils = {};}

VYRE.Utils.Cookie = {
   create: function(name,value,days){
     if (days) {
        var date = new Date();
        date.setTime(date.getTime()+(days*24*60*60*1000));
        var expires = "; expires="+date.toGMTString();
     }
     else var expires = "";
     document.cookie = name+"="+value+expires+"; path=/";

   },
   read: function(name) {
      var nameEQ = name + "=";
      var ca = document.cookie.split(';');
      for(var i=0;i < ca.length;i++) {
        var c = ca[i];
        while (c.charAt(0)==' ') c = c.substring(1,c.length);
        if (c.indexOf(nameEQ) == 0) return c.substring(nameEQ.length,c.length);
      }
      return null;
   },
   erase: function(name) {
     createCookie(name,"",-1);
   }

};


var Timer = {
    timeInSec:0,
    timeElement:null,

    startTimer:function(){
        this.timeInSec = 0;
        this.timeElement = jQuery("#scoreblock h2.time");
        this.timeElement.removeClass("stop");
        this.updateTime();

    },

    updateTime:function(){
        if (!this.timeElement.is(".stop")) {
            this.timeInSec += 1;
            this.timeElement.text(this.getTime());
            setTimeout("Timer.updateTime()", 1000);
        }
    },

    stopTimer:function(){
        this.timeElement.addClass("stop");
    },

    getTimeInSeconds:function(){
        return this.timeInSec;
    },

    getTime:function(seconds) {
        var timeInSec = seconds || this.timeInSec;
        var min = parseInt(timeInSec/60);
        var sec = timeInSec%60;
        if (min < 10 ) {min = "0"+min;}
        if (sec < 10 ) {sec = "0"+sec;}
        return min+":"+sec;
    }
};


var QuizManager = {
	MAX_QUESTION:21,
	ENTER_KEY:13,
	container:"#question-container",
        currentQuestion:1,
        currentScore:0,
       	currentQuestionElement:null,
       	bonusQuestionElement:"#qBonus",
       	qNoElement:null,
       	scoreElement:null,
        cachedInputs : [],
        isBonusQuestion : false,
	
	init:function(){
		this.container= jQuery(this.container);
		this.currentQuestionElement = this.container.find("#q1");
		this.bonusQuestionElement = jQuery(this.bonusQuestionElement);
		this.qNoElement = jQuery("#scoreblock .qNo");
		this.scoreElement = jQuery("#scoreblock .qScore");
                this.attachFlyweights(this.container);
                this.addKonamiCode();
                Timer.startTimer();
	},
	addKonamiCode:function(){ 
		window['state'] = 0;
		window['konami'] = [38,38,40,40,37,39,37,39,66,65];
		jQuery(document).bind("keyup", function(e) {
			if ( e.keyCode == konami[state] ) {
				state++;
			} else {
				state = 0;
			}  
			if ( state == 10 )  {QuizManager.bonusQuestion();} 
		}); 
	},
	attachFlyweights:function(elem) {
		elem.unbind("click");
		elem.unbind("keyup");
		var self = this;

		elem.bind({
			click: function(event){
				var src = event.target;
				if (src.id == "qSkip") {
					self.nextQuestion("skip-current", self.currentQuestion);
				}
			},
			keyup: function(event) {
				var qId = self.currentQuestion;
				var val = event.target.value || "";
				if (self.isBonusQuestion == true ||self.bonusQuestionElement.is(":visible")) { qId = "0";}
				self.getAjaxResult(qId,val.toLowerCase().trim(),event.keyCode);
			}
		});
    
	},

	incrementScore:function () {
		if (this.currentScore < this.currentQuestion) {
			this.currentScore ++;
		}
	},

	nextQuestion:function(mode, questionNo) {
		var qNo = questionNo || this.currentQuestion;
		var newQuestion = jQuery("#q"+(qNo+ 1));
		var currentQuestionElement = jQuery("#q"+qNo);

                if (mode=="correct-answer" ){
                        this.incrementScore();
                }

		if (this.isBonusQuestion == true && mode== "skip-current") {
			var bonusQuestionElem = jQuery("#qBonus,#qBonus2");
			bonusQuestionElem.fadeOut("slow");
			currentQuestionElement.fadeIn("slow");
			this.isBonusQuestion = false;
		} else if ((newQuestion.length == 1) &&  (this.currentQuestion == questionNo) ) {
                        this.currentQuestion ++;
			this.updateDashboard(this.currentQuestion,this.currentScore);
			currentQuestionElement.fadeOut("slow");
			newQuestion.fadeIn("slow");
			newQuestion.find("#qAns").focus();
			this.currentQuestionElement = newQuestion;
		} else if (this.currentQuestion == this.MAX_QUESTION) {
			Timer.stopTimer();			
			VYRE.Utils.Cookie.create("brandquiz","var jsonRep = {score:"+this.currentScore+",time:"+Timer.getTimeInSeconds()+"}",1);
			location.href = "/submit-score/";
		}
	},

	updateDashboard:function(qNo, score) {
		this.qNoElement.text(qNo);
		this.scoreElement.text(score);
	},
	
	displayCorrectAnswerOrNot:function(result){ 

                if (this.isBonusQuestion == true && result == true) {
                    this.container.find("#qBonus #qResults").removeClass("incorrect").addClass("correct");
                }else if (this.isBonusQuestion == true && result == false) {
                    this.container.find("#qBonus #qResults").removeClass("correct").addClass("incorrect");
                }else if (result == true) {
                    this.currentQuestionElement.find("#qResults").removeClass("incorrect").addClass("correct");
                }else{
                    this.currentQuestionElement.find("#qResults").removeClass("correct").addClass("incorrect");
                }
	},

	getCachedUserInputResults:function(qId, val) {                
		var key = val.replace(" ","-").trim() + "_"+qId;
		return this.cachedInputs[key] || null;
	},
	
	setCachedUserInputResults:function(data) {
		var key = data.userInput.replace(" ","-").trim()+"_"+data.questionNo;
		this.cachedInputs[key] = data.result;
	},

	bonusQuestion:function() {
		var currentQuestionElement = jQuery("#q"+this.currentQuestion);
		var bonusQuestionElement = jQuery("#qBonus");
		currentQuestionElement.fadeOut("slow");
		bonusQuestionElement.fadeIn("slow");
		bonusQuestionElement.find("#qAns").focus();
		this.isBonusQuestion = true;
	},

	specialPreview:function() {
		if (this.isBonusQuestion == true) {
			jQuery("#qBonus").fadeOut("slow");
			jQuery("#qBonus2").fadeIn();
		}
	},

        getAjaxResult:function(qId, val, keyCode) {  

		var cachedResult = this.getCachedUserInputResults(qId,val);
		var self = this;
		if (val == "vyre") {this.bonusQuestion(); return ;}

		if (cachedResult != null) {
			//do  nothing
		} else if (val.length >= 2 && cachedResult ==  null ) {
			var url = "/verify-question/?qId="+qId+"&ans="+val;
			jQuery.get(url, function(data) {

				var jsonResponse = null;
				eval(data);
				self.setCachedUserInputResults(jsonResponse);

				if (jsonResponse.result == true && self.isBonusQuestion == true ) {
				    self.displayCorrectAnswerOrNot(true);
				    var funcName = "QuizManager.specialPreview()";
				    //var funcName = "QuizManager.nextQuestion('skip-current')";self.isBonusQuestion == false;
				    setTimeout(funcName, 1000);                                    
				} else if (jsonResponse.result == true && jsonResponse.questionNo == self.currentQuestion ) {
				    self.displayCorrectAnswerOrNot(true);
				    var funcName = "QuizManager.nextQuestion('correct-answer',"+jsonResponse.questionNo+")";
				    setTimeout(funcName, 1000);                                    
				}else if (jsonResponse.result == false && keyCode == self.ENTER_KEY){
				    self.displayCorrectAnswerOrNot(false);
				}

			});
		}

        }

	
};





jQuery(document).ready(function(){

 var bodyId = jQuery("body").attr("id");

 jQuery("#clickhere,#clickhere2,#clickhere3,#clickhere4").click(function(){ 
  jQuery("#vyre").slideToggle();
  return false;
 });

 if (bodyId == "quizpage") {
  QuizManager.init(); 
 }

 if (bodyId == "submitUserScore") {

 var jsonRep = null;
 var currentUsersCookie = VYRE.Utils.Cookie.read("brandquiz");
 eval(currentUsersCookie);


try {
  var score = jsonRep.score || 0;
  var timeInSeconds = jsonRep.time || 0;
 
  jQuery('#your-score').text(score+"/21");
  jQuery('#ITEM_ATT127_0').val(score);
  jQuery('#ITEM_ATT129_0').val(timeInSeconds);
}catch(e){}
 
 }

});