var ChupaRustom = {};
var Utils = {};
Utils.Path = "";
var questionId = 0, startTime = 0, scoredMarks = 0, totalMarks = 10, resId = 0, label = '', level = 1;

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

ChupaRustom.init = function () {
    $("#home").hide();
    $("#queText").css('visibility', 'hidden');
    $("#gamePage").hide();
    $("#finalPage").hide();
    document.title = ChupaRustom.hardCodedData.nameOfGame;
    document.getElementById("playImage").classList.add('pulse');
    ChupaRustom.setImages();
    ChupaRustom.initVariables();
    ChupaRustom.generateQue();
    ChupaRustom.createAcknowledgementDivs();
}

ChupaRustom.setImages = function () {
    document.body.style.backgroundImage = Utils.Path + "url('images/skin/Cover.png')";
    document.getElementById("home").src = Utils.Path + "images/skin/Home.png";
    document.getElementById("logo").src = Utils.Path + "images/skin/logo.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("playAgainBtn").src = Utils.Path + "images/skin/replay.png";
    document.getElementById("creditbtn").src = Utils.Path + "images/skin/Credits.png";
    document.getElementById("queText").style.backgroundImage = "url('images/skin/title.png')";
    document.getElementById("gameOverTextDiv").innerHTML = ChupaRustom.hardCodedData.gameOver;
}

ChupaRustom.initVariables = function () {
    ChupaRustom.questionCnt = 0;
    ChupaRustom.queArray = [];
    ChupaRustom.randomNoArray = [];
    ChupaRustom.attemptFlag = false;
    ChupaRustom.clickedOptionData = '';
    ChupaRustom.previousClickOption = ''
    ChupaRustom.correctQueTimer = null;
    ChupaRustom.wrongQuestionTimer = null;
}

ChupaRustom.play = function () {
    document.body.style.backgroundImage = Utils.Path + "url('images/skin/levelBg.png')";
    $("#home").show();
    $("#gamePage").show();
    $("#playImage").hide();
    $("#finalPage").hide();
    $("#queText").css('visibility', 'visible');
    document.getElementById("playImage").classList.remove('pulse');
    d = new Date();
    startTime = d.getDate() + "-" + (d.getMonth() + 1) + "-" + d.getFullYear() + " " + d.getHours() + ":" + d.getMinutes() + ":" + d.getSeconds();

    if (ChupaRustom.questionCnt != 5) {   //5
        ChupaRustom.showQuestion();
    }
    else {
        ChupaRustom.gameOver();
    }
}

ChupaRustom.generateQue = function () {
    var randomNo = 0, firstQueCnt = 0, totalRandomQue = 0, dragElementArray = [], secondFlag = false;

    firstRandomQueCounter = Math.floor(Math.random() * 2 + 2);	//Show firstRandomQueCounter number of image option Questions.
    firstQueCnt = firstRandomQueCounter;
    secondRandomQueCounter = 5 - firstRandomQueCounter;
    totalRandomQue = firstRandomQueCounter + secondRandomQueCounter;
    //firstRandomQueCounter = 0;
    //secondRandomQueCounter = 5;
    // while (ChupaRustom.queArray.length != 5) {	//5
    //     if (firstRandomQueCounter != 0) {
    //         randomQtype = 0;				//add 0 to dataArray if que is of addition.
    //         firstRandomQueCounter--;
    //     }
    //     else {
    //         if (secondRandomQueCounter != 0) {
    //             randomQtype = 1;			//add 1 to dataArray if que is of subtraction.
    //             secondRandomQueCounter--;
    //         }
    //     }
    for (i = 0; i < 5; i++) {
        if (i < firstRandomQueCounter)
            randomQtype = 0;
        else
            randomQtype = 1
        randomNo = Math.floor(Math.random() * ChupaRustom.dataArray[randomQtype].arrayElements.length);
        while (dragElementArray.includes(randomNo)) {
            randomNo = Math.floor(Math.random() * ChupaRustom.dataArray[randomQtype].arrayElements.length);
        }
        dragElementArray.push(randomNo)
        obj = {};
        rno = Math.floor(Math.random() * ChupaRustom.dataArray[randomQtype].arrayElements[randomNo].numbers.length);
        obj.Number = ChupaRustom.dataArray[randomQtype].arrayElements[randomNo].numbers[rno];
        obj.Image = ChupaRustom.dataArray[randomQtype].arrayElements[randomNo].images[rno];
        obj.queImg = ChupaRustom.dataArray[randomQtype].arrayElements[randomNo].queImg;

        optionArray = [];
        if (randomQtype == 0) {
            obj.queType = 0;
            obj.question = ChupaRustom.dataArray[randomQtype].arrayElements[randomNo].questionText;

            optionArray.push(obj.Image);
            for (j = 0; j < 3; j++) {
                rno = Math.floor(Math.random() * ChupaRustom.dataArray[randomQtype].arrayElements[randomNo].images.length);
                img = ChupaRustom.dataArray[randomQtype].arrayElements[randomNo].images[rno];
                while (optionArray.includes(img)) {
                    rno = Math.floor(Math.random() * ChupaRustom.dataArray[randomQtype].arrayElements[randomNo].images.length);
                    img = ChupaRustom.dataArray[randomQtype].arrayElements[randomNo].images[rno];
                }
                optionArray.push(img)

            }

        }
        else {
            obj.queType = 1;
            obj.question = ChupaRustom.dataArray[randomQtype].arrayElements[randomNo].questionText;
            optionArray.push(obj.Number);
            for (j = 0; j < 3; j++) {
                rno = Math.floor(Math.random() * ChupaRustom.dataArray[randomQtype].arrayElements[randomNo].numbers.length);
                num = ChupaRustom.dataArray[randomQtype].arrayElements[randomNo].numbers[rno];
                while (optionArray.includes(img)) {
                    rno = Math.floor(Math.random() * ChupaRustom.dataArray[randomQtype].arrayElements[randomNo].numbers.length);
                    num = ChupaRustom.dataArray[randomQtype].arrayElements[randomNo].numbers[rno];
                }
                optionArray.push(num)
            }
        }
        shuffle(optionArray);
        obj.options = optionArray.slice(0);
        ChupaRustom.queArray.push(obj);

        if (dragElementArray.length == firstQueCnt && secondFlag == false) {
            secondFlag = true;
            dragElementArray = [];
        }
    }
    console.log(ChupaRustom.queArray);
    dragElementArray = [];
}

ChupaRustom.showQuestion = function (index)      //Show Question and Answer.
{
    var optionArray = [];
    //ChupaRustom.randomQue = ChupaRustom.queArray[ChupaRustom.questionCnt];
    randomNum = Math.floor(Math.random() * ChupaRustom.queArray.length);
    while (ChupaRustom.randomNoArray.includes(randomNum))
        randomNum = Math.floor(Math.random() * ChupaRustom.queArray.length);
    ChupaRustom.randomNoArray.push(randomNum);

    ChupaRustom.randomQue = ChupaRustom.queArray[randomNum];
    document.getElementById("rustomSpan").innerHTML = ChupaRustom.hardCodedData.rustomText;
    document.getElementById("queImg").src = Utils.Path + "images/" + ChupaRustom.randomQue.queImg;

    if (ChupaRustom.randomQue.queType == 0) {
        document.getElementById("queSpan").innerHTML = ChupaRustom.randomQue.Number + " " + ChupaRustom.randomQue.question;
        document.getElementById("houseImg").style.display = "none";
    }
    else {
        document.getElementById("queSpan").innerHTML = ChupaRustom.randomQue.question;
        document.getElementById("houseImg").style.display = "inline";
        document.getElementById("houseImg").src = Utils.Path + "images/" + ChupaRustom.randomQue.Image;
    }

    optionArray = ChupaRustom.randomQue.options.slice(0);
    // shuffle(optionArray);
    //console.log(optionArray);
    for (i = 0; i < optionArray.length; i++) {
        div = document.createElement("div");
        document.getElementById("ansOptionDiv").appendChild(div);
        div.setAttribute("id", "ansDiv" + (i + 1));
        div.setAttribute('onclick', 'ChupaRustom.selectOption(this.id)')

        if (ChupaRustom.randomQue.queType == 0) {
            div.setAttribute("class", "divBorder col-xs-2 col-sm-2 col-md-2 col-lg-2 col-xs-offset-1 col-md-offset-1 col-lg-offset-1 col-sm-offset-1");
            image = document.createElement("img");
            document.getElementById("ansDiv" + (i + 1)).appendChild(image);
            image.setAttribute("id", "ansImage" + (i + 1));
            image.setAttribute("class", "imgCss img-responsive nopadding col-xs-12 col-sm-12 col-md-12 col-lg-12");
            image.src = Utils.Path + "images/" + optionArray[i];
            if (optionArray[i] == ChupaRustom.randomQue.Image)
                $("#ansDiv" + (i + 1)).data('ans', "correct");
            else
                $("#ansDiv" + (i + 1)).data('ans', "wrong");
        }
        else {
            div.setAttribute("class", "divBorder numberCss col-xs-2 col-sm-2 col-md-2 col-lg-2 col-xs-offset-1 col-md-offset-1 col-lg-offset-1 col-sm-offset-1");
            $("#ansDiv" + (i + 1)).text(optionArray[i]);
            if (optionArray[i] == ChupaRustom.randomQue.Number)
                $("#ansDiv" + (i + 1)).data('ans', "correct");
            else
                $("#ansDiv" + (i + 1)).data('ans', "wrong");
        }
    }
}

ChupaRustom.selectOption = function (clickedOptId) {
    var clickNumber = '';
    ChupaRustom.attemptFlag = true;
    $("#" + ChupaRustom.previousClickOption).css('border', '1px solid black');
    ChupaRustom.clickedOptionData = $("#" + clickedOptId).data('ans');
    //console.log(ChupaRustom.clickedOptionData);   
    //label = $("#"+ clickedOptId).data('ansImg'); 
    ChupaRustom.previousClickOption = clickedOptId;
    // if (ChupaRustom.randomQue.questionId > 4)
    //     clickNumber = $("#" + clickedOptId).text();

    if (ChupaRustom.clickedOptionData == 'correct') {
        scoredMarks = 10;
        //document.getElementById(clickedOptId).classList.add('flash');
        $("#" + clickedOptId).css('border', '6px solid green');
        $("#ansOptionDiv").css("pointer-events", "none");
        $("#soundImage").css("pointer-events", "none");
        document.getElementById("playSound").src = Utils.Path + "sounds/instructions/thats_right.mp3";
        document.getElementById("playSound").play();

        if (ChupaRustom.correctQueTimer) {
            clearTimeout(ChupaRustom.correctQueTimer);
            ChupaRustom.correctQueTimer = null;
        }
        /* ChupaRustom.correctQueTimer = setTimeout(function () {
            document.getElementById(clickedOptId).classList.remove("flash");
            $("#"+ clickedOptId).css('border', '1px solid black');
            $("#ansOptionDiv").css("pointer-events", "auto");
            $("#soundImage").css("pointer-events", "auto");
            //ChupaRustom.callNext();
        },300); */
    }
    else {
        scoredMarks = 0;
        $("#soundImage").css("pointer-events", "none");
        //document.getElementById(clickedOptId).classList.add('shake');
        $("#" + clickedOptId).css('border', '6px solid red');
        document.getElementById("playSound").src = Utils.Path + "sounds/instructions/wrong_ans.mp3";
        document.getElementById("playSound").play();
        if (ChupaRustom.wrongQuestionTimer) {
            clearTimeout(ChupaRustom.wrongQuestionTimer);
            ChupaRustom.wrongQuestionTimer = null;
        }
        ChupaRustom.wrongQuestionTimer = setTimeout(function () {
            //document.getElementById(clickedOptId).classList.remove('shake');
            $("#" + clickedOptId).css('border', '1px solid black');
            $("#soundImage").css("pointer-events", "auto");
        }, 300);
    }
}


ChupaRustom.callNext = function () {
    if (!ChupaRustom.attemptFlag)
        scoredMarks = -1;
    console.log(resId, questionId, scoredMarks, totalMarks, level, startTime, label);
    if (Utils.mobileDeviceFlag)
        Android.addScore(resId, questionId, scoredMarks, totalMarks, level, startTime, label);

    $("#ansOptionDiv").css("pointer-events", "auto");
    $("#soundImage").css("pointer-events", "auto");
    document.getElementById("ansOptionDiv").innerHTML = '';
    ChupaRustom.attemptFlag = false;
    ChupaRustom.questionCnt++;
    ChupaRustom.play();
}

ChupaRustom.gameOver = function () {
    ChupaRustom.questionArr = [];
    $("#acknowledgementDiv").hide();
    $("#gamePage").hide();
    $("#queText").css('visibility', 'hidden');
    $("#finalPage").show();
    ChupaRustom.questionCnt = 0;
    document.getElementById("ansOptionDiv").innerHTML = '';
    //ChupaRustom.initVariables();
}

ChupaRustom.playAgain = function () {
    ChupaRustom.questionArr = [];
    $("#acknowledgementDiv").hide();
    $("#finalPage").hide();
    $("#gamePage").show();
    ChupaRustom.questionCnt = 0;
    ChupaRustom.initVariables();
    ChupaRustom.generateQue();
    ChupaRustom.play();
}

ChupaRustom.callSound = function () {
    document.getElementById("playSound").src = Utils.Path + "sounds/instructions/chooseOption_Hindi.mp3";
    document.getElementById("playSound").play();
}

ChupaRustom.callHome = function () {
    if (ChupaRustom.attemptFlag) {
        console.log(resId, questionId, scoredMarks, totalMarks, level, startTime, label);
        if (Utils.mobileDeviceFlag)
            Android.addScore(resId, questionId, scoredMarks, totalMarks, level, startTime, label);
    }
    location.reload();
}

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

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

ChupaRustom.showAcknowledgement = function () {
    $("#acknowledgementDiv").show();
}
