var Identifywords = {};
var Utils = {};
Utils.Path = "";
Utils.mobileDeviceFlag = false;
var questionId = 0, startTime = 0, scoredMarks = 0, totalMarks = 0, resId = 0, level = 1, label = 'words',scoreFlag = false,nextBtnClick=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("hindiIdentifywords");
    setTimeout(function () {
        Identifywords.Initilize();
    }, 200);
});
Identifywords.Initilize = function () {//shows coverPage
    document.title = Identifywords.hardcodedData.title;
    Identifywords.setImage();
    $("#endPage").hide();
    $("#homeDiv").css("visibility","hidden");
    $("#gamePage").hide();
    $("#levelPage").hide();
    Identifywords.variableInitilization();
    Identifywords.createAcknowledgementDivs();
}
Identifywords.variableInitilization = function(){
    Identifywords.selectedRule; //selectd verb number   
    Identifywords.quesArray = []; //ques from unique Array
    Identifywords.soundQuesArr=[];
    Identifywords.soundQuesArr2 =[];
    Identifywords.backFrontFlag = true;
    Identifywords.homeFlag = false;
    Identifywords.rightAns=0;//total right ans out of 18 at both attempt
    Identifywords.queCnt=0; //ques from quesArray
    Identifywords.optionCnt=0; //read 9 words continuosly
    Identifywords.skipReadFlag=false;
    Identifywords.soundFlag = false;
}
Identifywords.setImage = function(){
     document.body.style.backgroundImage = "url('images/skin/bg.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("goImg").src = Utils.Path + "images/skin/go.png";
     document.getElementById("skip").src = Utils.Path + "images/skin/skip.png";
     document.getElementById("rulesID").style.backgroundImage =Utils.Path+"url('images/skin/swimimgTank.png')";
     document.getElementById("titleId").style.backgroundImage =Utils.Path+"url('images/skin/titleblock.png')";
     document.getElementById("ruleDiv").style.backgroundImage =Utils.Path+"url('images/skin/titleblock.png')";
     document.getElementById("titleId").innerHTML = Identifywords.hardcodedData.rulesTitle;
     document.getElementById("instructionText").innerHTML = Identifywords.hardcodedData.instruction;
    // document.getElementById("acknowledgementDiv").style.backgroundImage =Utils.Path+"url('images/skin/timebox.png')";
}
Identifywords.startGame = function(){
    $("#coverPage").hide();
    $("#homeDiv").css("visibility","visible");
    $("#levelPage").show();
    Identifywords.showRules();
    Identifywords.wordsDiv();
}
Identifywords.showRules = function(){
   var i,ruleListDiv,radioButtonDiv,ruleDiv;
    for(i=0;i< Identifywords.data.list.length;i++)
	{
		 ruleListDiv = document.createElement("div");
		 ruleListDiv.setAttribute("id","ruleListDivId"+i);
		 ruleListDiv.setAttribute("class"," rulesDivClass nopadding col-sm-10 col-xs-10 col-md-10 col-lg-10 col-sm-offset-1 col-md-offset-1 col-lg-offset-1 col-xs-offset-1");
         document.getElementById("rulesinnerID").appendChild(ruleListDiv);
         ruleListDiv.setAttribute("onclick", "Identifywords.selectRule(this.id)");
		 radioButtonDiv = document.createElement("INPUT");
		 radioButtonDiv.setAttribute("id","radioButtonId"+i);
		 radioButtonDiv.setAttribute("class","nopadding radioButtonClass checkmark col-sm-1 col-xs-1 col-md-1 col-lg-1");
		 radioButtonDiv.setAttribute("type", "radio");
		 radioButtonDiv.setAttribute("name", "verbs");
		
		 $(radioButtonDiv).data("ruleIndex",i);
		 document.getElementById("ruleListDivId"+i).appendChild(radioButtonDiv);
		 ruleDiv = document.createElement("div");
         ruleDiv.setAttribute("id","ruleDiv"+i);
         ruleDiv.setAttribute("class","nopadding ruleClass col-sm-11 col-lg-11 col-md-11 col-xs-11");
		$(ruleDiv).text();
		document.getElementById("ruleListDivId"+i).appendChild(ruleDiv);
		$(ruleDiv).text(Identifywords.data.list[i].rule);
    }
    $("#radioButtonId0").prop("checked", true);
	Identifywords.selectedRule=$("#radioButtonId0").data("ruleIndex"); 
}
Identifywords.selectRule = function(selectedRule){
   var selectedRuleId= $("#"+selectedRule).children().prop("id");
    $("#"+selectedRuleId).prop("checked", true);
    Identifywords.selectedRule = $("#"+selectedRuleId).data("ruleIndex");
    console.log(Identifywords.selectedRule);  
}
Identifywords.learningPage = function(){
    Identifywords.optionCnt=0;
    Identifywords.homeFlag=true;
	$("#instructionDivId").show();
    document.getElementById("ruleDiv").style.visibility = "visible";
    $("#levelPage,#widget").hide();
    $("#gamePage,#skipDiv").show();
    Identifywords.populateQue();
    Identifywords.changeOptions();
    document.getElementById("ruleDiv").innerHTML = Identifywords.data.list[Identifywords.selectedRule].rule; 
    document.getElementById("wordsChart").style.pointerEvents='none';
    $(".frontClass").css("pointer-events","none");
    clearTimeout(Identifywords.optionTimerOuter);
    clearTimeout(Identifywords.optionTimer);
    $("#instructionDivId").removeClass('animated fadeOutDown');
    Identifywords.playInstruction();
}
Identifywords.changeOptions = function()
{
    for(var i=0;i<9;i++)
    {
        $("#frontDiv"+i).text(Identifywords.quesArray[0][i].langWord); 
        $("#frontDiv"+i).data("sound",Identifywords.quesArray[0][i].sound);
        $("#frontDiv"+i).css("pointer-events","auto");
        $("#frontDiv"+i).css("color","aqua");
        $("#frontDiv"+i).parent().css("opacity","1");
        $("#frontDiv"+i).removeClass('animated bounceIn');
    }
}
Identifywords.playInstruction = function()//playSoundOfWords in learnSection 
{ 
    clearTimeout(Identifywords.optionTimer);
    Identifywords.optionTimer = null;
  //  Identifywords.soundFlag = true;
    Identifywords.loadmetaDataFlag = true;
    sound=Utils.Path + 'sounds/' +Identifywords.quesArray[0][Identifywords.optionCnt].sound;
    Identifywords.getDuration(sound);
}
Identifywords.getDuration = function (sound) {
	var duration = 0;
	$('#playSound').prop('src', sound);
	if (Identifywords.loadmetaDataFlag) {
		$('#playSound').on("loadedmetadata", function () {
			Identifywords.loadmetaDataFlag = false;
			$('#playSound').unbind("loadedmetadata");
			duration = $('#playSound').prop('duration');
			Identifywords.playOptionsInLoop(duration);
		}
		);
	}
	else
		$('#playSound').unbind("loadedmetadata");
}
/* function getDuration(sound) {
    var duration = 0;
    $('#playSound').prop('src', sound);
    if (Identifywords.loadmetaDataFlag)
	{
        $('#playSound').on("loadedmetadata", function () 
		{
            Identifywords.loadmetaDataFlag=false;
            $('#playSound').unbind("loadedmetadata");
            Identifywords.soundFlag = false;
            duration = $('#playSound').prop('duration');
            Identifywords.playOptionsInLoop(duration);
        });
        $('#playSound').unbind("loadedmetadata");
    }
} */
Identifywords.playOptionsInLoop = function (duration)//play words in a loop
{
    document.getElementById("playSound").play();
    Identifywords.skipReadFlag=false;
	$("#frontDiv"+(Identifywords.optionCnt)).addClass('animated bounceIn');
	if (Identifywords.playsoundTimer) {
		clearTimeout(Identifywords.playsoundTimer);
		Identifywords.playsoundTimer = null;
	}
	Identifywords.playsoundTimer = setTimeout(function () {
        Identifywords.optionCnt++;
        clearTimeout(Identifywords.optionTimer);
        if (Identifywords.optionCnt <9)
        {
            Identifywords.playInstruction();
        }
        else
        {
            document.getElementById("wordsChart").style.pointerEvents='auto';
            $(".frontClass").css("pointer-events","auto");
			for(var i=0;i<9;i++)
				$("#frontDiv"+i).removeClass('animated bounceIn');
        }
	}, 1000 * duration + 800);
}
Identifywords.skipReading=function()
{
	$("#instructionDivId").hide();
    document.getElementById("playSound").pause();
    clearTimeout(Identifywords.playsoundTimer);
    clearTimeout( Identifywords.nextSoundTimer);
    Identifywords.skipReadFlag=true;
    d = new Date();
	startTime = d.getDate() + "-" + (d.getMonth() + 1) + "-" + d.getFullYear() + " " + d.getHours() + ":" + d.getMinutes() + ":" + d.getSeconds();
    document.getElementById("wordsChart").style.pointerEvents='auto';
    shuffle(Identifywords.quesArray[0]);
    Identifywords.changeOptions();
    shuffle(Identifywords.quesArray[0]);
    $("#widget").show();
    $("#skipDiv").hide();
    Identifywords.playWord();
}
Identifywords.populateQue = function ()
{
	Identifywords.quesArray=[];
	var randomQue=Math.floor(Math.random()*Identifywords.data.list[Identifywords.selectedRule].data.length);
	Identifywords.quesArray.push(Identifywords.data.list[Identifywords.selectedRule].data[randomQue].wordsList);
	console.log(Identifywords.quesArray);
}
Identifywords.wordsDiv = function(){ //set the learning chart
     var i,wordDiv,tenseDiv;
     $(".wordsStyleClass").css("pointer-events","auto");
     for(i=0;i<9;i++){
           wordDiv = document.createElement("div");
           wordDiv.setAttribute("id","wordDivId"+i);
           wordDiv.setAttribute("class","noPadding wordDivClass col-sm-4 col-xs-4 co-lg-4 col-md-4");
          wordDiv.style.backgroundImage = Utils.Path+"url('images/skin/block.png')";
          document.getElementById("wordsChart").appendChild(wordDiv);
          tenseDiv = document.createElement("div");
		  tenseDiv.setAttribute("id","frontDiv"+i);
		  tenseDiv.setAttribute("sellIndex",i);
          tenseDiv.setAttribute("onclick","Identifywords.checkWord(this.id)");
          tenseDiv.setAttribute("class","wordsStyleClass frontClass noPadding col-sm-12 col-lg-12 col-md-12 col-xs-12");
        /*  $(tenseDiv).text(Identifywords.quesArray[0][i].name); 
         $(tenseDiv).data("sound",Identifywords.quesArray[0][i].sound);
         */ document.getElementById("wordDivId"+i).appendChild(tenseDiv);
     }
     console.log(Identifywords.soundQuesArr);
}
Identifywords.playWord = function(){
    document.getElementById("playSound").pause();
    clearTimeout( Identifywords.nextSoundTimer);
    document.getElementById("playSound").src = Utils.Path+"sounds/"+Identifywords.quesArray[0][Identifywords.queCnt].sound;
    document.getElementById("playSound").play();
}
Identifywords.checkWord = function(clicked_Words)
{
    var clickedSound = $("#"+clicked_Words).data("sound");
    if(!Identifywords.skipReadFlag)
    {
        $(".frontClass").removeClass('animated bounceIn');
        document.getElementById("playSound").src = Utils.Path+"sounds/"+clickedSound;
        document.getElementById("playSound").play();
    }
    else
    {
    $(".frontClass,#soundImage").css("pointer-events","none");
    scoreFlag=true;
    document.getElementById("playSound").pause();
    clearTimeout(Identifywords.pointerAutotimer);
    if((clickedSound) == Identifywords.quesArray[0][Identifywords.queCnt].sound)
    {      
        $("#"+clicked_Words).removeClass("frontClass");
        document.getElementById("playSound").src = Utils.Path+"sounds/instructions/Right_answer__Aditi.mp3";
        document.getElementById("playSound").play();
        Identifywords.queCnt++;
        Identifywords.rightAns++;
        document.getElementById(clicked_Words).style.color = "yellow";
        $("#"+clicked_Words).addClass('animated flash');
        $("#"+clicked_Words).css("pointer-events","none");
        $("#"+clicked_Words).parent().css("opacity","0.6");
        if(Identifywords.nextSoundTimer){
            clearTimeout( Identifywords.nextSoundTimer);
            Identifywords.nextSoundTimer = null;
         }
        Identifywords.nextSoundTimer = setTimeout(function(){
            $(".frontClass,#soundImage").css("pointer-events","auto");
           // document.getElementById(clicked_Words).style.color = "aqua";
            if(Identifywords.queCnt==5)
            {
                Identifywords.nextQuestion();
            }
            else
                Identifywords.playWord();
        },2000);
    }
    else
    {
        document.getElementById(clicked_Words).style.color = "red";
        $("#"+clicked_Words).addClass('animated shake');
        document.getElementById("playSound").src = Utils.Path+"sounds/instructions/Not_this_one__Aditi.mp3";
        document.getElementById("playSound").play();
        if(Identifywords.redcolorTimer){
            clearTimeout(Identifywords.redcolorTimer);
            Identifywords.redcolorTimer=null;
        } 
        Identifywords.redcolorTimer = setTimeout(()=>{
            document.getElementById(clicked_Words).style.color = "aqua";
            $(".shake").removeClass("shake");
            $(".frontClass,#soundImage").css("pointer-events","auto");
        },800);
    }
}
}
Identifywords.nextQuestion = function()
{   
    nextBtnClick++;
    var levelNum=Identifywords.selectedRule+1;
    if(scoreFlag)
        scoredMarks = Identifywords.rightAns*2*levelNum;
    else
        scoredMarks =-1;
    totalMarks=20*levelNum;
    Identifywords.scoreFunction();
    Identifywords.rightAns =0;
    scoreFlag = false;
    document.getElementById("playSound").pause();
    clearTimeout(Identifywords.nextSoundTimer);
    clearTimeout(Identifywords.pointerAutotimer);
    $(".wordsStyleClass").css("pointer-events","none");
    $(".shake").removeClass('shake');
    $(".flash").removeClass('flash');
    $(".blink_me").removeClass('blink_me');
    if(nextBtnClick==2){
        $("#gamePage").hide();
        Identifywords.gameover();
    }
    else{
        Identifywords.homeFlag = false;
      Identifywords.resetVar();
      $("#gamePage").hide();
      $("#levelPage").show();
    }
}
Identifywords.resetVar = function(){
    Identifywords.soundQuesArr=[];
    Identifywords.soundQuesArr2=[];
    Identifywords.quesArray=[];
    Identifywords.currentQues=0;
    Identifywords.queCnt=0;
    Identifywords.frontFaceCnt=0;
    Identifywords.backFaceCnt=0;
    Identifywords.backFrontFlag=true;
}
Identifywords.gameover = function()
{
    Identifywords.homeFlag = false;
    document.getElementById("playSound").pause();
    clearTimeout(Identifywords.nextSoundTimer);
    clearTimeout(Identifywords.pointerAutotimer);
    clearTimeout(Identifywords.optionTimerOuter);
    clearTimeout(Identifywords.optionTimer);
    $("#endPage").show()
    document.getElementById("ruleDiv").style.visibility = "hidden";
    document.getElementById("gameOver").innerHTML=Identifywords.hardcodedData.gameOverText;
    $("#acknowledgementDiv").hide();
}
Identifywords.callHome = function(){
    document.getElementById("playSound").pause();
    clearTimeout(Identifywords.optionTimerOuter);
    clearTimeout(Identifywords.optionTimer);
    document.getElementById("ruleDiv").style.visibility = "hidden";
    document.getElementById("gameOver").innerHTML=" ";
    Identifywords.resetVar();
    if(Identifywords.homeFlag)
    {
        Identifywords.homeFlag=false;
        nextBtnClick=0;
        $("#gamePage").hide();
        $("#endPage").hide();
        $("#levelPage").show();
    }
    else
        location.reload();
}
Identifywords.replayGame = function()
 {
    nextBtnClick=0;
	document.getElementById("gameOver").innerHTML = " ";
	$("#endPage").hide();
    $("#gamePage").hide();
    Identifywords.resetVar();
    Identifywords.homeFlag=false;
	$("#levelPage").show();
 }

Identifywords.createAcknowledgementDivs = function () {
    var i = 0, div;
    for (i = 0; i < Object.keys(Identifywords.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(Identifywords.AcknowledgementPageData)[i] + " : " + Object.values(Identifywords.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);
}
Identifywords.showAcknowledgement = function () {
    $("#acknowledgementDiv").show();
}
Identifywords.scoreFunction = function () {
    console.log(resId, questionId, scoredMarks, totalMarks, level, startTime, label);
    if (Utils.mobileDeviceFlag) {
        Android.addScore(resId, questionId, scoredMarks, totalMarks, level, startTime, label);
    }
}
Identifywords.closeInstruction=function()
{
    $("#instructionDivId").addClass('animated fadeOutDown');
}

