var UnitConversion = {}; //namespace
var Utils = {};
Utils.Path = "";
var resId = 0, questionId = 0, startTime = 0, scoredMarks = 0, totalMarks = 10, label=" ", level = 1, scroreFlag = false,ansFlag = false;

$(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("UnitConversion"); */
    setTimeout(function () { UnitConversion.Initilize(); }, 200);
});
UnitConversion.Initilize = function () {
	document.title = UnitConversion.hardCodedData.title;
    UnitConversion.setImage();
    document.getElementById("homeDiv").style.visibility = "hidden";
    document.getElementById("gamePage").style.display = "none";
    document.getElementById("endPage").style.display = "none";
    UnitConversion.variableInitilization();
    UnitConversion.createAcknowledgementDivs();
}
UnitConversion.setImage = function () {
    document.body.style.backgroundImage = "url('images/skin/Cover.png')";
    document.getElementById("logoImg").src = Utils.Path + "images/skin/logo.png";
    document.getElementById("homeImg").src = Utils.Path + "images/skin/home.png";
    document.getElementById("playImage").src = Utils.Path + "images/skin/Play.png";
    document.getElementById("soundImage").src = Utils.Path + "images/skin/sound.png";
    document.getElementById("nextImage").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("flagDiv").style.backgroundImage=Utils.Path+"url('images/skin/Board_Start.png')";
    document.getElementById("carImg").src=Utils.Path+"images/skin/Car.png";
}
UnitConversion.variableInitilization = function () {
    UnitConversion.unique_Ques = []; //QUESTION ARRAY.
	UnitConversion.randomArray = []; //random option array
    UnitConversion.optionArray = []; //final option array
    UnitConversion.quesCount = 0; // ques from unique_Ques[] array
    UnitConversion.Answer = 0; 
    UnitConversion.currentQues = 0;
	UnitConversion.totalScore = 0; //store the no. of correct ans
    UnitConversion.Question; //used to generate ques ( 4 ml, 3 ltr)
	UnitConversion.autoNexttimerid;
    UnitConversion.wrongAnswertimerid;
}
UnitConversion.startGame = function () {
    UnitConversion.unique_Ques = populate(UnitConversion.Data, UnitConversion.unique_Ques,4); //get the unique random 
   	scroreFlag = false;
    document.body.style.backgroundImage = Utils.Path + "url('images/skin/Bg.jpg')";
    document.getElementById("homeDiv").style.visibility = "visible";
    document.getElementById("coverPage").style.display = "none";
    document.getElementById("gamePage").style.display = "block";
	document.getElementById("endPage").style.display = "none";
    UnitConversion.playInstruction();
    UnitConversion.createSpanandDiv();
    UnitConversion.setQueastionandOption();
}
UnitConversion.createSpanandDiv = function () { //create ques and ans span
    document.getElementById("helpDiv").style.visibility="visible";
    var outerQuestionDiv = document.createElement("div");
	outerQuestionDiv.setAttribute("id","OuterDivId");
	outerQuestionDiv.setAttribute("class","noPadding  col-sm-11 col-xs-11 col-lg-11 col-md-11");
	document.getElementById("QuestionDiv").appendChild(outerQuestionDiv);
    for (var i = 0; i < 5; i++) {
        var spanTag = document.createElement("span");
        spanTag.setAttribute("id", "spanId" + i);
        spanTag.setAttribute("class", "spanClass");
        outerQuestionDiv.appendChild(spanTag);
    }
    for (var i = 0; i < 4; i++) {
        var divTag = document.createElement("div");
        divTag.setAttribute("id", "optionNo" + i);
        divTag.setAttribute("class", "optionClass col-sm-4 col-xs-4 col-md-4 col-lg-4 col-sm-offset-1 col-xs-offset-1 col-md-offset-1 col-lg-offset-1");
        divTag.setAttribute("onclick", "UnitConversion.checkAnswer(this.id)");
        document.getElementById("optionDiv").appendChild(divTag);
        document.getElementById("optionNo"+i).style.backgroundImage = 'url("images/skin/Box.png")';
        var spanTag = document.createElement("span");
        spanTag.setAttribute("id","spanOptId"+i);
        spanTag.setAttribute("class","noPadding  spanoptionclass");
        divTag.appendChild(spanTag); 
    }
}
UnitConversion.optionCalculation = function () {//calculate option
    UnitConversion.randomArray = populate(UnitConversion.RatioData, UnitConversion.randomArray, 4);
    for (var i = 0; i < 4; i++) {
         var option = UnitConversion.RatioData[UnitConversion.randomArray[i]].Optionratio * UnitConversion.Question; //option according to the ratio
        option = numberSplit(option);
        UnitConversion.optionArray.push(option);
    }
    UnitConversion.optionArray = shuffle(UnitConversion.optionArray);//shuffle option array
 }
UnitConversion.setQueastionandOption = function () { //set question and option 

    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 questionType , i;
    $("#helpDiv").addClass("bounceInDown");
    scroreFlag = false;
    UnitConversion.Question = Math.floor(Math.random() * 8) + 1;
    if(UnitConversion.quesCount < 4)
    UnitConversion.currentQues = UnitConversion.unique_Ques[UnitConversion.quesCount];
    else
     UnitConversion.currentQues = UnitConversion.unique_Ques[0];
    UnitConversion.Answer = numberSplit(UnitConversion.Data[UnitConversion.currentQues].ratio * UnitConversion.Question);
    console.log(UnitConversion.Answer);
    UnitConversion.optionCalculation(); //calculating final ans
    questionType = Math.floor(Math.random() * 2);
   if (questionType == 1) //question will be higher to lower
    {
        document.getElementById("spanId0").innerHTML = UnitConversion.Question;
        document.getElementById("spanId1").innerHTML = UnitConversion.Data[UnitConversion.currentQues].Unit1;
        document.getElementById("spanId4").innerHTML = UnitConversion.Data[UnitConversion.currentQues].Unit2;
        //setOption
        for (i = 0; i < 4; i++) {
            document.getElementById("optionNo" + i).setAttribute("value", UnitConversion.optionArray[i]);
            document.getElementById("spanOptId" + i).innerHTML = UnitConversion.optionArray[i];
        }
        document.getElementById("helpDiv").innerHTML = "1"+"   "+UnitConversion.Data[UnitConversion.currentQues].Unit1+"   "+UnitConversion.hardCodedData.EqualSign+"   "+UnitConversion.Data[UnitConversion.currentQues].ratio+"   "+UnitConversion.Data[UnitConversion.currentQues].Unit2;
    }
    else {  //question will lower to higher
        //swapping  of question with ans 
        var temp;
        temp = UnitConversion.Question;
        UnitConversion.Question = UnitConversion.Answer;
        UnitConversion.Answer = temp;
        document.getElementById("spanId0").innerHTML = UnitConversion.Question;
        document.getElementById("spanId1").innerHTML = UnitConversion.Data[UnitConversion.currentQues].Unit2;
        document.getElementById("spanId4").innerHTML = UnitConversion.Data[UnitConversion.currentQues].Unit1;
        // swapping of ans with option
        var temp, value;
        value = Math.floor(Math.random() * 4);
        temp = UnitConversion.optionArray[value];
        UnitConversion.optionArray[value] = UnitConversion.Answer;
        UnitConversion.Question = temp;
        for (var i = 0; i < 4; i++) {
            document.getElementById("optionNo" + i).setAttribute("value", UnitConversion.optionArray[i]);
            document.getElementById("spanOptId" + i).innerHTML = UnitConversion.optionArray[i];
        }
        document.getElementById("helpDiv").innerHTML = UnitConversion.Data[UnitConversion.currentQues].ratio+"   "+UnitConversion.Data[UnitConversion.currentQues].Unit2+"   "+UnitConversion.hardCodedData.EqualSign+"   "+"1"+"   "+UnitConversion.Data[UnitConversion.currentQues].Unit1;
    }
    document.getElementById("spanId2").innerHTML = UnitConversion.hardCodedData.EqualSign;
    document.getElementById("spanId3").innerHTML = UnitConversion.hardCodedData.QuestionMark;
}

UnitConversion.playInstruction = function () {// sound button
    document.getElementById("playSound").src = Utils.Path + "sound/instruction/instruction.mp3";
    document.getElementById("playSound").play();
}

UnitConversion.checkAnswer = function (clicked_option) {//check the ans 
    var imgSrc,soundSrc,flagImg ; 
    scroreFlag = true;
    ansFlag = false;
    document.getElementById("playSound").pause();
    clearTimeout(UnitConversion.wrongAnswertimerid);
    clearTimeout(UnitConversion.autoNexttimerid);
   var clicked_answer = document.getElementById(clicked_option).getAttribute("value");
	if (UnitConversion.Answer == clicked_answer) {
        $(".optionClass,#soundlogo").css("pointer-events", "none");
        imgSrc = "images/skin/Car_correct-ANS.png";
        flagImg = "images/skin/Board_Correct.png";
        soundSrc = "sound/instruction/Congrats.mp3";
        UnitConversion.setRightWrongImg(imgSrc,flagImg,soundSrc);
        if (UnitConversion.autoNexttimerid) {
            clearTimeout(UnitConversion.autoNexttimerid);
            UnitConversion.autoNexttimerid = null;
        }
        UnitConversion.totalScore = UnitConversion.totalScore + 10;
        scoredMarks = 10;
        label = UnitConversion.Answer;
        UnitConversion.autoNexttimerid = setTimeout(function () {
            UnitConversion.nextQuestion();
        }, 2000);
    }
    else {
        ansFlag = true ; 
       imgSrc ="images/skin/Car_wrong-ANS.png";
        flagImg = 'images/skin/Board_Wrong.png';
        soundSrc = "sound/instruction/wrongSound.mp3";
        UnitConversion.setRightWrongImg(imgSrc,flagImg,soundSrc);
        if (UnitConversion.wrongAnswertimerid) {
            clearTimeout(UnitConversion.wrongAnswertimerid);
            UnitConversion.wrongAnswertimerid = null;
        }
        UnitConversion.wrongAnswertimerid = setTimeout(function () {
            document.getElementById("carImg").src=Utils.Path+"images/skin/Car.png";
            document.getElementById("flagDiv").style.backgroundImage=Utils.Path+"url('images/skin/Board_Start.png')";
            }, 1000);
    }
}
UnitConversion.setRightWrongImg = function(imgSrc,flagImg,soundSrc){
    document.getElementById("carImg").src=Utils.Path+imgSrc;
    document.getElementById("flagDiv").style.backgroundImage=Utils.Path+"url("+flagImg+")";
    document.getElementById("playSound").src = Utils.Path + soundSrc;
    document.getElementById("playSound").play();
}

UnitConversion.nextQuestion = function () {
    clearTimeout(UnitConversion.autoNexttimerid);
    clearTimeout(UnitConversion.wrongAnswertimerid);
    document.getElementById("playSound").pause();
    document.getElementById("carImg").src=Utils.Path+"images/skin/Car.png";
    document.getElementById("flagDiv").style.backgroundImage=Utils.Path+"url('images/skin/Board_Start.png')";
    $(".bounceInDown").removeClass('bounceInDown');
    $(".optionClass,#soundlogo").css("pointer-events", "auto");
    UnitConversion.quesCount++;
    UnitConversion.optionArray = [];
    UnitConversion.randomArray = [];
    if (!scroreFlag) {
        scoredMarks = -1;
        label = UnitConversion.Answer;
    }
    if((scroreFlag) && (ansFlag) ){
        scoredMarks = 0;
        label = UnitConversion.Answer;
    }
    UnitConversion.scoreFunction();
   
    if (UnitConversion.quesCount < 5) {
        UnitConversion.setQueastionandOption();
    }
    else {
        UnitConversion.gameOver();
    }
}
UnitConversion.gameOver = function () {
    document.getElementById("playSound").pause();
    document.getElementById("helpDiv").style.visibility="hidden";
    document.getElementById("gamePage").style.display = "none";
    document.getElementById("endPage").style.display = "block";
    document.getElementById("GameOver").innerHTML = UnitConversion.hardCodedData.gameovertext;
}
UnitConversion.callHome = function () {
    document.getElementById("playSound").pause();
    if(scroreFlag && !ansFlag)
        scoredMarks = 10; 
    else
        scoredMarks = 0; 
    UnitConversion.scoreFunction();
    location.reload();
}
UnitConversion.replayGame = function () {
    document.getElementById("optionDiv").innerHTML = " ";
    document.getElementById("QuestionDiv").innerHTML = " ";
    document.getElementById("GameOver").innerHTML = " ";
    document.getElementById("helpDiv").innerHTML=" ";
    UnitConversion.variableInitilization();
    UnitConversion.startGame();
}
UnitConversion.scoreFunction = function () {
    console.log(resId, questionId, scoredMarks, totalMarks, level, startTime, label);
    if (Utils.mobileDeviceFlag) {
        Android.addScore(resId, questionId, scoredMarks, totalMarks, level, startTime);
    }
}
UnitConversion.createAcknowledgementDivs = function () {//credit function
    var i = 0, div;
    for (i = 0; i < Object.keys(UnitConversion.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(UnitConversion.AcknowledgementPageData)[i] + " : " + Object.values(UnitConversion.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);
}
UnitConversion.showAcknowledgement = function () {
    $("#acknowledgementDiv").show();
}
