Whquestion = {}; //namespace
var Utils = {};
Utils.Path = " ";
Utils.mobileDeviceFlag = false;
//global variable 
var resId = 0, questionId = 0, startTime = 0, totalMarks = 10, level = 4, scoredMarks = 0, label = "null", scoreFlag = false ,  wrongSoundDuration = 0;

$(document).ready(function () {
    $(".se-pre-con").fadeOut("slow");
    if ((navigator.userAgent.match(/Android|BlackBerry|iPhone|iPad|iPod|Opera Mini|IEMobile/i)) && !(window.location.href.includes('http')))
        Utils.mobileDeviceFlag = true;
    /* if (Utils.mobileDeviceFlag)
        Utils.Path = Android.getMediaPath("Wh-Question1"); */
    setTimeout(function () {Whquestion.Initilize(); }, 200);
});

Whquestion.Initilize = function () {
    //$("#playGame").css("bottom","4vw");
    document.body.style.backgroundImage = "url('images/skin/cover.gif')";
    Whquestion.setImage();
    document.title = Whquestion.hardcodedData.title;
    $("#nextStep").addClass("pulse");
    $("#homeDiv , #instrText").css('visibility', 'hidden');
    $("#widget").hide();
    $("#gamePage").hide();
    $("#endPage").hide();
    wrongBuzzerDuration();
   Whquestion.variableInitilization();
    Whquestion.createAcknowledgementDivs();
}
Whquestion.setImage = function () { //set All images
    document.getElementById("homeImg").src = Utils.Path + "images/skin/home.png";
    document.getElementById("logoImg").src = Utils.Path + "images/skin/logo.png";
    document.getElementById("nextStep").src = Utils.Path + "images/skin/play.png";
    document.getElementById("hintImage").src = Utils.Path + "images/skin/help.png";
    document.getElementById("soundImg").src = Utils.Path + "images/skin/sound.png";
    document.getElementById("nextImg").src = Utils.Path + "images/skin/next.png";
    document.getElementById("playAgain").src = Utils.Path + "images/skin/replay.png";
    document.getElementById("creditImg").src = Utils.Path + "images/skin/credits.png";
    document.getElementById("quesBox").style.backgroundImage = Utils.Path+"url('images/skin/grid box.png')"
    document.getElementById("gameOver").innerHTML = Whquestion.hardcodedData.gameOver;
   // document.getElementById("instrText").innerHTML = Whquestion.hardcodedData.instrText;
}
Whquestion.variableInitilization = function(){
    Whquestion.questionArray  = [] ; // 5 unique ques
    Whquestion.cnt = 0 ; //current ques count
    Whquestion.wrongTimer; // wrong ans timer
    Whquestion.nextQuesTimer ; //next ques timer
    Whquestion.wrongAnsCnt = 0;
    Whquestion.soundFlag = false;
}
Whquestion.startGame = function(){
    document.body.style.backgroundImage = "url('images/skin/bg.png')";
    $("#homeDiv , #instrText").css('visibility', 'visible');
    $("#widget").show();
    $("#gamePage").show();
    $("#playGame").hide();
     Whquestion.questionArray = populate(Whquestion.data , Whquestion.questionArray , 5);
     console.log(Whquestion.questionArray);
    Whquestion.createoptionDiv();
    Whquestion.setData();
}
Whquestion.createoptionDiv = function(){
    Whquestion.playinstruction();
    var optionDiv ;
    for(var i=0;i<4;i++){
        optionDiv = document.createElement("div");
        optionDiv.setAttribute("id","optionDivId"+i);
        optionDiv.setAttribute("class","noPadding bgClass optionStyle col-sm-2 col-xs-2 col-md-2 col-lg-2 col-sm-offset-1 col-xs-offset-1 col-lg-offset-1 col-md-offset-1");
        optionDiv.setAttribute("onclick","Whquestion.checkAns(this.id)");
        optionDiv.style.backgroundImage = Utils.Path+"url('images/skin/time box.png')";
        document.getElementById("optionDiv").appendChild(optionDiv);
    }
}
Whquestion.playinstruction = function(){
    document.getElementById("playSound").pause();
    document.getElementById("playSound").src = "sound/instruction.mp3";
    document.getElementById("playSound").play();
}
Whquestion.setData = function(){
    d = new Date();  //date object
	startTime = d.getDate() + "-" + (d.getMonth() + 1) + "-" + d.getFullYear() + " " + d.getHours() + ":" + d.getMinutes() + ":" + d.getSeconds();  //to get the current date

    var optionArr = [];
    optionArr = Whquestion.data[Whquestion.questionArray[Whquestion.cnt]].optionArr
    questionId = Whquestion.data[Whquestion.questionArray[Whquestion.cnt]].questionId;
    $("#ques1").text(Whquestion.data[Whquestion.questionArray[Whquestion.cnt]].ques1);
    $("#ques2").text(Whquestion.data[Whquestion.questionArray[Whquestion.cnt]].ques);
    for(var i=0;i<4;i++){
        $("#optionDivId"+i).text(optionArr[i]);
        if(optionArr[i] == Whquestion.data[Whquestion.questionArray[Whquestion.cnt]].correctAns)
        $("#optionDivId"+i).addClass("opacityClass");
    }
}
$(".quesBoxClass").mouseover(
    function(e){
       // idspan = e.target.id
        alert(this.id);
    }
)
Whquestion.checkAns = function(clicked_option){
    clearTimeout(Whquestion.wrongTimer);
    clearTimeout(Whquestion.nextQuesTimer);
    document.getElementById("playSound").pause();
    scoreFlag = true;
    if(Whquestion.wrongTimer){
        Whquestion.wrongTimer = null ;
        clearTimeout(Whquestion.wrongTimer);
    }
   if($("#"+clicked_option).text() == Whquestion.data[Whquestion.questionArray[Whquestion.cnt]].correctAns){
        $("#"+clicked_option).addClass('checkAnsClass');
        $("#"+clicked_option).addClass('animated flash');
        scoredMarks = 10 ;
        $(".optionStyle , #soundImg , #hintImage").css("pointer-events","none");
        var ansString = Whquestion.data[Whquestion.questionArray[Whquestion.cnt]].ques1;
        ansString = ansString.replace("_ _ _ _" , Whquestion.data[Whquestion.questionArray[Whquestion.cnt]].correctAns);
        document.getElementById("ques1").innerHTML = ansString ;
        Whquestion.rightAns();
      
    }
    else{
        
        document.getElementById("playSound").src = Utils.Path+"sound/BuzzerWrong.mp3";
        document.getElementById("playSound").play();
        $("#"+clicked_option).addClass('checkwrongAnsClass');
        $("#"+clicked_option).addClass('animated shake');
        $("#"+clicked_option).css({'opacity':"0.5" , "pointer-events":"none"});
        scoredMarks = 0;
        Whquestion.wrongAnsCnt++ ;
        Whquestion.wrongTimer = setTimeout(function(){
            $(".optionStyle").removeClass('checkwrongAnsClass');
            $(".shake").removeClass('animated shake');
        },250);
        if(Whquestion.wrongAnsCnt == 2){
            $(".optionStyle ,#hintImage").css("pointer-events","none");
            Whquestion.rightAnsTimer = setTimeout(() => {
                $(".opacityClass").addClass("checkAnsClass");
                $(".optionStyle").css("opacity","0.5");
                $(".opacityClass").css("opacity","1");
                //$("#hintImage").css("pointer-events","none");
                Whquestion.rightAns();
            }, wrongSoundDuration*1000);
        }
    }
    
} 
Whquestion.rightAns = function(){
     Whquestion.soundFlag = true;
    src = Utils.Path + Whquestion.data[Whquestion.questionArray[Whquestion.cnt]].correctSound;
   Whquestion.getDuration(src);
}

Whquestion.getDuration = function(src){
    var duration = 0;
    document.getElementById("playSound").pause();
    clearTimeout(Whquestion.rightAnsTimer);
    clearTimeout(Whquestion.wrongTimer);
    clearTimeout( Whquestion.nextBtnTimer);
    Whquestion.wrongAnsCnt = 0;
    if(Whquestion.soundFlag){
        $('#playSound').on("loadedmetadata", function () {
            Whquestion.soundFlag = false;
            duration = $('#playSound').prop('duration');
            $('#playSound').unbind("loadedmetadata");
            Whquestion.nextBtnTimer = setTimeout(() => {
                $("#nextImg").addClass("bounce");
            }, duration*1000);;
        });
        document.getElementById("playSound").src = src;
        document.getElementById("playSound").play();
    }
}
Whquestion.nextQues = function(){
    clearTimeout(Whquestion.nextQuesTimer);
    clearTimeout(Whquestion.wrongTimer);
    document.getElementById("playSound").pause();
    $("#nextImg").removeClass("bounce");
    $(".opacityClass").removeClass("opacityClass");
    if(!scoreFlag)
         scoredMarks = -1;
    label = Whquestion.data[Whquestion.questionArray[Whquestion.cnt]].correctAns;
    Whquestion.scoreFunction();
    scoreFlag = false;
    $(".flash").removeClass('animated flash');
    $(".optionStyle").css({"pointer-events":"auto" , "opacity":"1"});
    $("#soundImg,#hintImage").css("pointer-events" , "auto");
    $(".optionStyle").text("");
    $(".quesStyle").text("");
    $(".checkAnsClass").removeClass("checkAnsClass");
    Whquestion.cnt++;
    if(Whquestion.cnt < 5 ){
          Whquestion.setData();
    }
    else{
        Whquestion.gameOver();
    }
}
Whquestion.replayGame = function () { //playAgain
    document.getElementById("playSound").pause();
    clearTimeout(Whquestion.nextQuestimer);
    clearTimeout(Whquestion.wrongTimer);
    Whquestion.resetVariable();
    Whquestion.questionArray = populate(Whquestion.data , Whquestion.questionArray , 5);
  
    $(".optionStyle").text("");
    $(".quesStyle").text("");
    $("#endPage").hide();
    $("#instrText").css("visibility","visible");
    $("#soundImg,#hintImage,.optionStyle").css("pointer-events" , "auto");
     $("#gamePage").show();
     Whquestion.playinstruction();
     Whquestion.setData();
}

Whquestion.resetVariable = function () { //reset all variable
    $(".flash").removeClass('animated flash');
    $(".optionStyle , #hintImage").css("pointer-events","auto");
    $(".checkAnsClass").removeClass("checkAnsClass");
     scoreFlag = false;
     Whquestion.cnt = 0;
     Whquestion.wrongAnsCnt = 0 ;
     Whquestion.soundFlag = false;
     $(".opacityClass").removeClass("opacityClass");
     Whquestion.questionArray = [];
}
Whquestion.goHome = function () {
    clearTimeout(Whquestion.nextQuestimer);
    clearTimeout(Whquestion.wrongTimer);
  document.getElementById("playSound").pause();
    if(scoreFlag)
      Whquestion.scoreFunction();

    location.reload();
}

Whquestion.gameOver = function () { // game over
    document.getElementById("playSound").pause();
    clearTimeout(Whquestion.nextQuestimer);
    $("#gamePage").hide();
    $("#endPage").show();
    $("#instrText").css("visibility","hidden");
    $("#acknowledgementDiv").hide();
}

Whquestion.createAcknowledgementDivs = function () { //create Aknowlegment div
    var i = 0, div;
    for (i = 0; i < Object.keys(Whquestion.AcknowledgementPageData).length; i++) {
        div = document.createElement('div');
        div.className = "fontClass firstLetter col-xs-12 col-sm-12 col-md-12 col-lg-12";
        div.innerHTML = Object.keys(Whquestion.AcknowledgementPageData)[i] + " : " + Object.values(Whquestion.AcknowledgementPageData)[i];
        acknowledgementDiv.appendChild(div);
    }
    div = document.createElement('div');
    div.className = "fontClass firstLetter col-xs-12 col-sm-12 col-md-12 col-lg-12";
    div.style.marginBottom = "2vh";
    acknowledgementDiv.appendChild(div);
}

Whquestion.showAcknowledgement = function () { //show Aknowlegment
    $("#acknowledgementDiv").show();
}
Whquestion.showHint = function(){
    document.getElementById("playSound").pause();
    $(".optionStyle , #hintImage").css({"pointer-events":"none"})
    $(".opacityClass").addClass("checkAnsClass");
    $(".optionStyle").css("opacity","0.5");
    $(".opacityClass").css("opacity","1");
    src = Utils.Path + Whquestion.data[Whquestion.questionArray[Whquestion.cnt]].correctSound;
    document.getElementById("playSound").src = src;
    document.getElementById("playSound").play();
    $("#nextImg").addClass('bounce');
}
Whquestion.scoreFunction = function () { //score function
    console.log(resId, questionId, scoredMarks, totalMarks, level, startTime, label);
    if (Utils.mobileDeviceFlag) {
        Android.addScore(resId, questionId, scoredMarks, totalMarks, level, startTime);
    }
}
//get wrong buzzer duration
wrongBuzzerDuration = function(){
    document.getElementById("playSound").pause();
  
   $('#playSound').on("loadedmetadata", function () {
   // Whquestion.soundFlag = false;
   wrongSoundDuration = $('#playSound').prop('duration');
    $('#playSound').unbind("loadedmetadata");
    
}); 
 document.getElementById("playSound").src = Utils.Path+"sound/BuzzerWrong.mp3"; 
 
}
//function for unique Question
function populate(array1, array2, length) {

    while (array2.length < length) {
        var randomImageData = Math.floor(Math.random() * array1.length);
        if (array2.indexOf(randomImageData) == -1) {
            array2.push(randomImageData);
        }
    }
    return array2;
}
//shuffle the options
function shuffle(sarray) {

    var arrayLength = sarray.length;
    var temp, random_index;
    while (arrayLength > 0) {
        random_index = Math.floor(Math.random() * arrayLength);
        arrayLength--;
        temp = sarray[arrayLength];
        sarray[arrayLength] = sarray[random_index];
        sarray[random_index] = temp;
    }

    return (sarray);
}