var VowelConsonant_PM = {};
var Utils = {};
Utils.Path = "";
var questionId = 0, startTime = 0, scoredMarks = 0, totalMarks = 27, resId = 0, level = 0, label='', scoreFlag = false, nextBtnClick=0, k=9, currentQues=0;

$(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 () {
        VowelConsonant_PM.init();
    });
}, 200);

VowelConsonant_PM.init = function () {
    $("#home").hide();
    $("#gamePage").hide();
    $("#timerID").hide();
    $("#finalPage").hide();
    $("#selectLevelDiv").css('visibility', 'hidden');
	document.title = VowelConsonant_PM.hardcodedData.nameOfGame;
    VowelConsonant_PM.initVariables();
    VowelConsonant_PM.setImages();
    VowelConsonant_PM.makeLevelLayout();
    VowelConsonant_PM.makeQuestionLayout();
	VowelConsonant_PM.createAcknowledgementDivs();
}

VowelConsonant_PM.initVariables = function () 
{
    VowelConsonant_PM.time = 60;                //Initial VowelConsonant_PM.time.
    VowelConsonant_PM.rightAns = 0;             //total right ans out of 18 at both attempt
    VowelConsonant_PM.skipSound = 9;            //Count of Skip Questions.\
    VowelConsonant_PM.levelIndex = 0;           //Selected level index.
    VowelConsonant_PM.questionCnt = 0;          //Count of total Questions.
    VowelConsonant_PM.currentQuesSound = 0;     //ques from quesArray
    VowelConsonant_PM.homeFlag = false;
    VowelConsonant_PM.backFrontFlag = false;
    VowelConsonant_PM.totalQues = [];           //To store 27 words(Quetions).
    VowelConsonant_PM.randomSoundArray = [];    //To store current 9 Questions.
    VowelConsonant_PM.timerId = null;           //For showing VowelConsonant_PM.time.
}

VowelConsonant_PM.setImages = function () {
    document.body.style.backgroundImage = Utils.Path + "url('images/skin/CoverPage.png')";
    document.getElementById("home").src = Utils.Path + "images/skin/Home.png";
    document.getElementById("logo").src = Utils.Path + "images/skin/logo.png";
    document.getElementById("playbutton").src = Utils.Path + "images/skin/Play.png";
    document.getElementById("goImage").src = Utils.Path + "images/skin/Go.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("timerID").style.backgroundImage = Utils.Path + "url('images/skin/time box.png')";
    document.getElementById("levelDiv").style.backgroundImage = Utils.Path + "url('images/skin/rule box.png')";
    document.getElementById("selectLevelDiv").style.backgroundImage = Utils.Path + "url('images/skin/title bar.png')";
    document.getElementById("timerSpanId").innerHTML = VowelConsonant_PM.time;
}

VowelConsonant_PM.makeLevelLayout = function()
{
    for(i=0; i<4; i++)
    {
        div = document.createElement('div');
        $('#levelDiv').append(div);
        $(div).prop('id','LevelOuterDiv'+i);
        $(div).prop('class','nopadding levelOuterDivCss col-sm-5 col-lg-5 col-md-5 col-xs-5 col-sm-offset-1 col-lg-offset-1 col-md-offset-1 col-xs-offset-1');    
       
        radioBtn = document.createElement('input');
        $('#LevelOuterDiv'+i).append(radioBtn);
        $(radioBtn).prop('id','radioBtn'+i);
        $(radioBtn).prop('type','radio');
        $(radioBtn).prop('name','level');
        $(radioBtn).prop('class','nopadding radioBtnCss col-sm-4 col-lg-4 col-md-4 col-xs-4');
        radioBtn.setAttribute('onclick','VowelConsonant_PM.selectLevel(this.id)');
        $(radioBtn).prop('data','level'+i);

        div = document.createElement('div');
        $('#LevelOuterDiv'+i).append(div);
        $(div).prop('id','level'+i);
        $(div).prop('class','nopadding levelCss col-sm-8 col-lg-8 col-md-8 col-xs-8');
        div.setAttribute('onclick','VowelConsonant_PM.selectLevel(this.id)');
        $(div).text("Level "+(i+1));
    }
    //$('#radioBtn0').prop('checked','true');
}

VowelConsonant_PM.makeQuestionLayout = function()         //Make question according to Level.
{
    var sellIndex = 0;
    for(i=1; i<=9; i++)
    {
        div = document.createElement('div');
        $('#questionDiv').append(div);
        $(div).prop('id','option'+i);
        $(div).prop('class','optionDivCSS col-xs-4 col-sm-4 col-md-4 col-lg-4');
        //document.getElementById('option'+i).setAttribute('onclick','VowelConsonant_PM.checkAnswer(this.id)');
        document.getElementById('option'+i).style.backgroundImage = "url('images/skin/grid box.png')";

        div = document.createElement('div');
        $('#option'+i).append(div);
        $(div).prop('id','optionText'+i);
        div.setAttribute("sellIndex", sellIndex);
        sellIndex++;
        $(div).prop('class','nopadding faceClass0 optionWordCss col-sm-12 col-lg-12 col-md-12 col-xs-12');
        document.getElementById('optionText'+i).setAttribute('onclick','VowelConsonant_PM.checkAnswer(this.id)');
    }
}

VowelConsonant_PM.play = function () {
    document.body.style.backgroundImage = Utils.Path + "url('images/skin/background.png')";
    $("#selectLevelDiv").css('visibility', 'visible');
    $("#home, #gamePage, #levelDiv, #goBtn").show();
    $("#widges, #coverPage, #timerID, #questionDiv, #finalPage").hide();
    $('#goBtn').css('pointer-events', 'none');
    document.getElementById("selectLevelDiv").innerHTML = VowelConsonant_PM.hardcodedData.level;
}

VowelConsonant_PM.selectLevel = function (selectLevelId)
{
    $('#goBtn').css('pointer-events', 'auto');
    switch (selectLevelId){
        case 'level0':  
        case 'radioBtn0':      
                        level = 1;
                        VowelConsonant_PM.levelIndex = 0;
                        $('#radioBtn0').prop('checked','true');
                        break;
        case 'level1':
        case 'radioBtn1':
                        level = 2;
                        VowelConsonant_PM.levelIndex = 1;
                        $('#radioBtn1').prop('checked','true');
                        break;
        case 'level2':
        case 'radioBtn2':
                        level = 3;
                        VowelConsonant_PM.levelIndex = 2;
                        $('#radioBtn2').prop('checked','true');
                        break;   
        case 'level3':
        case 'radioBtn3':
                        level = 4;
                        VowelConsonant_PM.levelIndex = 3;
                        $('#radioBtn3').prop('checked','true');
                        break;   
    }
}

VowelConsonant_PM.showQuestion = function()         //Show question according to Level. Clicked on go Button.
{
    $("#levelDiv").hide();
    $("#goBtn").hide();
    $("#widges").show();
    $("#timerID").show();
    $("#questionDiv").show();
    $('#timerID').addClass('timerCss');
    document.getElementById("selectLevelDiv").innerHTML = 'Level'+ ' ' + level;
    document.body.style.backgroundImage = Utils.Path + "url('images/skin/background.png')";
    VowelConsonant_PM.makeQuestion();
    VowelConsonant_PM.startTimer();
    
    for(i=1; i<=9; i++){
        $('#optionText'+i).text(VowelConsonant_PM.totalQues[i-1].letter);
        $('#optionText'+i).data('sound',VowelConsonant_PM.totalQues[i-1].sound);
        VowelConsonant_PM.randomSoundArray.push(VowelConsonant_PM.totalQues[i-1].sound);
        shuffle(VowelConsonant_PM.randomSoundArray);
    }		
    VowelConsonant_PM.playQuestion();
}

VowelConsonant_PM.makeQuestion = function()
{
    var randomQue = {};		
    selectedVowel = Math.floor(Math.random() * VowelConsonant_PM.VCdata[VowelConsonant_PM.levelIndex].levelData.length);
    selectVowelData = VowelConsonant_PM.VCdata[VowelConsonant_PM.levelIndex].levelData[selectedVowel];
    for(i=0; i<3; i++){
        for(j=0; j<9; j++)     
        {
            randomQue = Math.floor(Math.random() * selectVowelData.vowelData.length);
            while(VowelConsonant_PM.totalQues.includes(selectVowelData.vowelData[randomQue]))
                randomQue = Math.floor(Math.random() * selectVowelData.vowelData.length);
            VowelConsonant_PM.totalQues.push(selectVowelData.vowelData[randomQue]);
        }
    }
    console.log('VowelConsonant_PM.totalQues');
    console.log(VowelConsonant_PM.totalQues); 
}

VowelConsonant_PM.playQuestion = function () 
{
    d = new Date();
    startTime = d.getDate() + "-" + (d.getMonth() + 1) + "-" + d.getFullYear() + " " + d.getHours() + ":" + d.getMinutes() + ":" + d.getSeconds();
    clearTimeout(VowelConsonant_PM.pointerAutotimer);
    VowelConsonant_PM.backFrontFlag = false;
    $("#timerID").removeClass('animated rubberBand');
    if (VowelConsonant_PM.questionCnt < 18) {
        document.getElementById("playSound").src = Utils.Path + "sounds/wordSounds/" + VowelConsonant_PM.randomSoundArray[VowelConsonant_PM.currentQuesSound];
        document.getElementById("playSound").play();
        $("#playSound").data("soundData", VowelConsonant_PM.randomSoundArray[VowelConsonant_PM.currentQuesSound]);
        VowelConsonant_PM.questionCnt++;
        console.log(VowelConsonant_PM.questionCnt);
        console.log(VowelConsonant_PM.randomSoundArray[VowelConsonant_PM.currentQuesSound]);
        if (VowelConsonant_PM.pointerAutotimer) {
            clearTimeout(VowelConsonant_PM.pointerAutotimer);
            VowelConsonant_PM.pointerAutotimer = null;
        }
        VowelConsonant_PM.pointerAutotimer = setTimeout(function () {
            $(".optionDivCSS").css("pointer-events", "auto");
            $("#soundImage").css('pointer-events','auto');
        }, 1500);
        VowelConsonant_PM.startTimer();
    }
     else{
        document.getElementById("playSound").src = Utils.Path + "sounds/instructions/Congrats.mp3";
        document.getElementById("playSound").play();
        $(".optionDivCSS").css("pointer-events", "none");
        $("#nextImage").addClass("bounce_blink_me");
    }
}

VowelConsonant_PM.startTimer = function()
{
    if(VowelConsonant_PM.timerId){
        clearInterval(VowelConsonant_PM.timerId);
        VowelConsonant_PM.timerId = null;
    }
    VowelConsonant_PM.timerId = setInterval(function(){
        VowelConsonant_PM.time = VowelConsonant_PM.time-1 ;  
        document.getElementById("timerSpanId").innerHTML = VowelConsonant_PM.time;
        if(VowelConsonant_PM.time == 20)
            document.getElementById("timerID").style.color = "#ff9900";     //Orange
        else if(VowelConsonant_PM.time < 10)
            document.getElementById("timerID").style.color = "#ff2300";     //Red

        if(VowelConsonant_PM.time == 0)
           clearInterval(VowelConsonant_PM.timerId);
           return;
    },2000);
}

VowelConsonant_PM.checkAnswer = function(clicked_Words)
{
    scoreFlag = true;
    VowelConsonant_PM.backFrontFlag = true;
    document.getElementById("playSound").pause();
    $(".optionDivCSS").css("pointer-events", "none");
    var clickedSound = $("#" + clicked_Words).data("sound");
    var playedSound = $("#playSound").data("soundData");
    
    if (clickedSound == playedSound) 
    {
        VowelConsonant_PM.rightAns++;
        clearInterval(VowelConsonant_PM.timerId);
        $('#'+clicked_Words).css('color','#56ff00');
        $("#soundImage").css('pointer-events','none');
        VowelConsonant_PM.time = VowelConsonant_PM.time + 3;
        if(VowelConsonant_PM.time > 60)
             VowelConsonant_PM.time = 60;
        if(VowelConsonant_PM.time > 10 && VowelConsonant_PM.time < 20)
            document.getElementById("timerID").style.color = "#ff9900";     //Orange
        else if(VowelConsonant_PM.time > 20)
            document.getElementById("timerID").style.color = "rgb(3 249 249)";     //Sky Blue
        else if(VowelConsonant_PM.time < 10)
            document.getElementById("timerID").style.color = "#ff2300";     //Red
        document.getElementById("timerSpanId").innerHTML = VowelConsonant_PM.time;
        $("#timerID").addClass('animated rubberBand');
        
        var idNum = document.getElementById(clicked_Words).getAttribute("sellIndex");
        $("#" + clicked_Words).addClass('animated flash');
        //$("#" + clicked_Words).parent().css("transform", "rotateX(360deg)");
        document.getElementById("playSound").src = Utils.Path + "sounds/instructions/ting.mp3";
        document.getElementById("playSound").play();
        if (VowelConsonant_PM.correctAnsTimer || VowelConsonant_PM.nextSoundTimer) {
            clearTimeout(VowelConsonant_PM.correctAnsTimer);
            clearTimeout(VowelConsonant_PM.nextSoundTimer);
            VowelConsonant_PM.nextSoundTimer = null;
            VowelConsonant_PM.correctAnsTimer = null;
        }
        if (VowelConsonant_PM.randomSoundArray.length > 0) {
            VowelConsonant_PM.correctAnsTimer = setTimeout(function () {
                $(".flash").removeClass("flash"); 
                $("#" + clicked_Words).parent().css("transform", "rotateX(360deg)");
                $('#'+ clicked_Words).css('color',"#fdea00");
                $("#"+clicked_Words).text(VowelConsonant_PM.totalQues[k].letter);
                $("#"+clicked_Words).data("sound", VowelConsonant_PM.totalQues[k].sound);
            }, 600);

            VowelConsonant_PM.randomSoundArray.push(VowelConsonant_PM.totalQues[k].sound);
            VowelConsonant_PM.randomSoundArray.splice(VowelConsonant_PM.currentQuesSound, 1);
            shuffle(VowelConsonant_PM.randomSoundArray);
        }
        VowelConsonant_PM.nextSoundTimer = setTimeout(function () {
            k++;
            VowelConsonant_PM.playQuestion();
            $("#" + clicked_Words).parent().css("transform", "");
        }, 2000);
    }
    else {
        document.getElementById(clicked_Words).style.color = "#ff2300";     //red
        $("#" + clicked_Words).addClass('animated shake');
        document.getElementById("playSound").src = Utils.Path + "sounds/instructions/wrong_ans.mp3";
        document.getElementById("playSound").play();
        if (VowelConsonant_PM.redcolorTimer) {
            clearTimeout(VowelConsonant_PM.redcolorTimer);
            VowelConsonant_PM.redcolorTimer = null;
        }
        VowelConsonant_PM.redcolorTimer = setTimeout(() => {
            document.getElementById(clicked_Words).style.color = "#fdea00";
            $(".optionDivCSS").css("pointer-events", "auto");
            $(".shake").removeClass("shake");
        }, 800);
    }
}

VowelConsonant_PM.playInstruction = function () {
    document.getElementById("playSound").pause(); 
    document.getElementById("playSound").src = Utils.Path + "sounds/wordSounds/" + VowelConsonant_PM.randomSoundArray[VowelConsonant_PM.currentQuesSound];
        document.getElementById("playSound").play();
}

VowelConsonant_PM.playNextSound = function () {     //callNext();
    console.log('Skipped');
    document.getElementById('playSound').pause();
    if(VowelConsonant_PM.questionCnt == 18){
       VowelConsonant_PM.nextQuestion();
    }
    else if(!VowelConsonant_PM.backFrontFlag)    //VowelConsonant_PM.backFrontFlag == false
    {
        VowelConsonant_PM.currentQuesSound++;
        if(VowelConsonant_PM.questionCnt == 9){
           for(i = 1; i <= 9; i++){
            $("#optionText" + i).text(VowelConsonant_PM.totalQues[VowelConsonant_PM.skipSound].letter);
            $("#optionText"+i).data("sound", VowelConsonant_PM.totalQues[VowelConsonant_PM.skipSound].sound);
            VowelConsonant_PM.randomSoundArray.push(VowelConsonant_PM.totalQues[VowelConsonant_PM.skipSound].sound);
            VowelConsonant_PM.skipSound++;
        }
        k = VowelConsonant_PM.skipSound;                                                                   
        $(".faceClass0").parent().css("transform", "rotateX(360deg)");
        var i=0;
        VowelConsonant_PM.randomSoundArray.splice(i,9);   
        shuffle(VowelConsonant_PM.randomSoundArray);
        VowelConsonant_PM.currentQuesSound=0;
       }
       VowelConsonant_PM.playQuestion();
   }
}

VowelConsonant_PM.nextQuestion = function () 
{
    if (scoreFlag)
        scoredMarks = VowelConsonant_PM.rightAns;
    else
        scoredMarks = -1;
    VowelConsonant_PM.scoreFunction();
    //nextBtnClick++;
    scoreFlag = false;
    VowelConsonant_PM.rightAns = 0;
    VowelConsonant_PM.skipSound = 0;
    VowelConsonant_PM.questionCnt = 0; 
    document.getElementById("playSound").pause();
    clearTimeout(VowelConsonant_PM.nextSoundTimer);
    clearTimeout(VowelConsonant_PM.pointerAutotimer);
    $("#nextImage").removeClass('bounce_blink_me');
    $(".shake").removeClass('shake');
    $(".flash").removeClass('flash');
    $("#gamePage").hide();
    VowelConsonant_PM.gameOver();
}

VowelConsonant_PM.resetTimer = function()
{
    clearInterval(VowelConsonant_PM.timerId);
    VowelConsonant_PM.time = 60;
    //document.getElementById("timerID").style.borderColor = "#148a06ed";
    document.getElementById("timerSpanId").innerHTML = VowelConsonant_PM.time;
}

VowelConsonant_PM.gameOver = function () 
{
    VowelConsonant_PM.homeFlag = false;
    clearInterval(VowelConsonant_PM.timerId);
    document.getElementById("playSound").pause();
    clearTimeout(VowelConsonant_PM.nextSoundTimer);
    clearTimeout(VowelConsonant_PM.pointerAutotimer);
    $("#finalPage").show()
    $("#acknowledgementDiv").hide();
    $("#selectLevelDiv").text('');
    document.getElementById('selectLevelDiv').innerHTML = VowelConsonant_PM.hardcodedData.gameOver;
}
VowelConsonant_PM.callHome = function () {
    clearInterval(VowelConsonant_PM.timerId);
    VowelConsonant_PM.resetTimer();
    document.getElementById("playSound").pause();
    document.getElementById("questionDiv").innerHTML = " ";
    VowelConsonant_PM.resetVar();
    if (VowelConsonant_PM.homeFlag) {
        //nextBtnClick = 0;
        VowelConsonant_PM.skipSound = 0;
        VowelConsonant_PM.homeFlag = false;
        $("#gamePage").hide();
        $("#finalPage").hide();
        $("#levelDiv").show();
    }
    else
        location.reload();
}

VowelConsonant_PM.resetVar = function()
{
    VowelConsonant_PM.totalQues = [];           //unique 3 node
    VowelConsonant_PM.totalQues = [];           //27 ques
    VowelConsonant_PM.randomSoundArray = []; 
    VowelConsonant_PM.rightAns = 0;             //total right ans out of 18 at both attempt
    VowelConsonant_PM.questionCnt=0;
    VowelConsonant_PM.skipSound = 0;
    VowelConsonant_PM.currentQuesSound = 0;     //ques from totalQues
}

VowelConsonant_PM.replayGame = function () 
{
    console.log('Replay Game');
    VowelConsonant_PM.time = 60;
    VowelConsonant_PM.homeFlag = false;
    clearInterval(VowelConsonant_PM.timerId);
    $('.radioBtnCss').removeAttr('checked');
    $('.optionWordCss').text('');
    $(".faceClass0").parent().css("transform", "");
    document.getElementById("timerID").style.color = "rgb(3 249 249)";
    VowelConsonant_PM.play();
    VowelConsonant_PM.initVariables();
    VowelConsonant_PM.resetTimer();
}

VowelConsonant_PM.createAcknowledgementDivs = function () {
	var i = 0, div;
	for (i = 0; i < Object.keys(VowelConsonant_PM.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(VowelConsonant_PM.AcknowledgementPageData)[i] + " : " + Object.values(VowelConsonant_PM.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 = VowelConsonant_PM.hardcodedData.createdOn;
	div.style.marginBottom = "2vh";
	acknowledgementDiv.appendChild(div);
}

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

VowelConsonant_PM.scoreFunction = function () {
    console.log(resId, questionId, scoredMarks, totalMarks, level, startTime, label);
    if (Utils.mobileDeviceFlag) {
        Android.addScore(resId, questionId, scoredMarks, totalMarks, level, startTime);
    }
}

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);
}