var MatchThePair = {};
var Utils = {};
Utils.Path = "";
Utils.mobileDeviceFlag = false;
var questionId = 0, startTime = 0, scoredMarks = 0, totalMarks = 10, resId = 0, level = 1, label = '',scoreFlag = false,questionCnt = 0,uniqueQuesArray=[],correctCounter=0,numberOfStars=0,  instructionFlag = true;; //content overall unique 35 ques;
$(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("MatchThePair");
    setTimeout(function () {
        MatchThePair.Initilize();
    }, 200);
});
MatchThePair.Initilize = function () {//shows coverPage
    document.title = MatchThePair.hardCodedData.title;
    MatchThePair.setImage();
    document.getElementById("endPage").style.display = "none";
    document.getElementById("homeDiv").style.visibility = "hidden";
	document.getElementById("gamePage").style.display = "none";
    MatchThePair.variableInitilization();
    MatchThePair.createAcknowledgementDivs();
}
MatchThePair.setImage = function () {//function to set Images
    document.body.style.backgroundImage = "url('images/skin/coverpage.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("playAgain").src = Utils.Path + "images/skin/replay.png";
    document.getElementById("creditImg").src = Utils.Path + "images/skin/Credits.png";
    document.getElementById("soundImg").src= Utils.Path+"images/skin/sound.png";
    document.getElementById("nextImg").src = Utils.Path + "images/skin/Next.png";
    document.getElementById("optionDiv2").style.backgroundImage = "url('images/skin/Option bar.png')";
    document.getElementById("acknowledgementDiv").scrollTop = '0px'; //Always scroll the slider to the Top at the beginning. 
}
MatchThePair.variableInitilization = function(){
    MatchThePair.questionArray=[]; //unique ques from json
    MatchThePair.optionArray = []; 
    MatchThePair.imageArray=[]; //number of images in quesArr
    MatchThePair.textArray=[]; // number of text in quesArr
    MatchThePair.rightAns = 0; 
    MatchThePair.total_No_of_Questions = 15;
    MatchThePair.autoNextTimer;
    MatchThePair.pointerTimer;
    MatchThePair.soundFlag=false;
     MatchThePair.instructionTimer;
}
MatchThePair.startGame = function () {//play game
    document.body.style.backgroundImage = "url('images/skin/bg.png')";
	document.getElementById("coverPage").style.display = "none";
	document.getElementById("gamePage").style.display = "block";
    document.getElementById("endPage").style.display = "none";
    document.getElementById("homeDiv").style.visibility = "visible";
    uniqueQuesArray = populate(MatchThePair.imgArr,uniqueQuesArray,35);
    console.log(uniqueQuesArray);
    MatchThePair.createMainDivs();
    MatchThePair.createElements();
}
MatchThePair.createMainDivs = function()
{
    MatchThePair.playInstruction();
     var cardDiv;
    for (i = 0; i < 3; i++) {//questionDIV
        cardDiv = document.createElement("DIV");
         cardDiv.setAttribute("id", "option" + i);
         cardDiv.setAttribute("class", "options noPadding col-xs-3 col-md-3 col-lg-3 col-sm-3 col-sm-offset-1 col-xs-offset-1 col-lg-offset-1 col-md-offset-1");
         cardDiv.style.backgroundImage = "url('images/skin/Q box.png')";
         document.getElementById("questionDiv").appendChild(cardDiv);
        }
}
MatchThePair.playInstruction = function()
{
    clearTimeout(MatchThePair.autoNextTimer);
    clearTimeout(MatchThePair.responsiveBoxTimer);
    document.getElementById("playSound").src=Utils.Path+"sounds/instruction.mp3";
    document.getElementById("playSound").play();
}
MatchThePair.createElements = function () { //create div
    d = new Date();  //date object
    startTime = d.getDate() + "-" + (d.getMonth() + 1) + "-" + d.getFullYear() + " " + d.getHours() + ":" + d.getMinutes() + ":" + d.getSeconds();  //to get the current date 

    scoreFlag = false;
    clearTimeout(MatchThePair.autoNextTimer);
    clearTimeout(MatchThePair.responsiveBoxTimer);
    clearTimeout(MatchThePair.pointerTimer);
    var randomNumber,random=0,index=0,i=0,i,j=0 ,m=0,p=0,quesDivIndex=0;
     while(MatchThePair.questionArray.length<7){ //getting 7 ques for 1 attempt
        MatchThePair.questionArray.push(uniqueQuesArray[i]);
        i++;
    }
     $("#optionDiv2").addClass('animated zoomIn');
    randomNumber = Math.floor(Math.random()*2)+1;
    while(quesDivIndex<3){
      for(var j=0;j<2;j++) { //inner 2 div 
            var innerDiv = document.createElement("div");
            innerDiv.setAttribute("id","innerDivId"+index);
            innerDiv.setAttribute("class","noPadding ansDivs col-sm-10 col-xs-10 col-md-10 col-lg-10 col-sm-offset-1 col-xs-offset-1 col-lg-offset-1 col-md-offset-1");
            innerDiv.style.backgroundImage = "url('images/skin/Q box 2.png')";
            document.getElementById("option"+quesDivIndex).appendChild(innerDiv);
            if(j==0){
       if(quesDivIndex < randomNumber)
        {
            img = document.createElement("IMG");
            img.setAttribute("id", "ansImg" + index);
            img.setAttribute("class", "img-responsive ansImages noPadding col-xs-12 col-md-12 col-lg-12 col-sm-12");
            img.src = Utils.Path+"images/"+MatchThePair.imgArr[MatchThePair.questionArray[quesDivIndex]].image;

            MatchThePair.textArray.push(MatchThePair.questionArray[quesDivIndex]);
            innerDiv.appendChild(img);
        }
        else{
            var optionSpan = document.createElement("Div");
            optionSpan.setAttribute("id","optionSpan"+index);
            optionSpan.setAttribute("class","spanClass");
            optionSpan.innerHTML = MatchThePair.imgArr[MatchThePair.questionArray[quesDivIndex]].marathiName;
            MatchThePair.imageArray.push(MatchThePair.questionArray[quesDivIndex]);
            innerDiv.appendChild(optionSpan);
        }
        index++;
    }
    else{
            $(innerDiv).addClass( "dropDiv");
            $(innerDiv).addClass("ansDivs");
        $(innerDiv).data("data",MatchThePair.imgArr[MatchThePair.questionArray[quesDivIndex]].marathiName);
        $(function(){    // Drop function
            $(".dropDiv").droppable(
            {     
                drop: MatchThePair.dropImg 
                
            });
        });
        index++;
    } 

    }
    quesDivIndex++;
}
    for(var k = 3;k<7;k++) //to put more 4 options rather than ans 
    {
        if(k<5)
           MatchThePair.imageArray.push(MatchThePair.questionArray[k]);
        else
            MatchThePair.textArray.push(MatchThePair.questionArray[k]);
    }
     MatchThePair.imageArray = shuffle(MatchThePair.imageArray);
     MatchThePair.textArray = shuffle(MatchThePair.textArray);
     if(MatchThePair.imageArray.length>MatchThePair.textArray.length)
         random = 1;
    else
         random = 0
     for(var j = 0; j < 7; j++){ //option div
        rightdiv = document.createElement("DIV");
        rightdiv.setAttribute("id", "rightDiv" + j);
        rightdiv.setAttribute("class", "noPadding ImageClass");
        rightdiv.style.backgroundImage = "url('images/skin/Option box.png')";
        if(random == 1){
            random = 0;
            if(MatchThePair.imageArray.length>m){
                optionimg = document.createElement("IMG");
            optionimg.setAttribute("id", "optionImg" + j);
            optionimg.setAttribute("class", "img-responsive dragDiv ansImages noPadding col-xs-12 col-md-12 col-lg-12 col-sm-12 col-xs-offset-12");
            optionimg.src =Utils.Path+"images/"+MatchThePair.imgArr[MatchThePair.imageArray[m]].image;
            $(optionimg).data("data",MatchThePair.imgArr[MatchThePair.imageArray[m]].marathiName);
            m++;
             }
             rightdiv.appendChild(optionimg);
        }
        else{
            random=1;
            if(MatchThePair.textArray.length>p){
                var rightSpan = document.createElement("div");
            rightSpan.setAttribute("id","rightSpanId"+j);
            rightSpan.setAttribute("class","spanClass1 dragDiv");
            rightSpan.innerHTML =MatchThePair.imgArr[MatchThePair.textArray[p]].marathiName;
            $(rightSpan).data("data",MatchThePair.imgArr[MatchThePair.textArray[p]].marathiName);
            p++;
           
            }
              rightdiv.appendChild(rightSpan);
         }
        document.getElementById("optionDiv2").appendChild(rightdiv);
        $(".loader").show();
        $('.loader').css('display', 'flex');
       var imgs = document.images, len = imgs.length, counter = 0;
       [].forEach.call( imgs, function( img )
       {
            if(img.complete)
             incrementCounter();
           else
             img.addEventListener( 'load', incrementCounter, false );
       } );
      function incrementCounter()
      {
        counter++;
        if ( counter === len )
        $(".loader").hide();
      }
        $(function () {  //function for Drag 
            $(".dragDiv").draggable({
                revert: "invalid",
                zIndex:"1",
               containment:"html"
            });
        });
        
    }
}   
MatchThePair.dropImg = function(event,ui) //fuction to drop image
{
    clearTimeout(MatchThePair.autoNextTimer);
    clearTimeout(MatchThePair.responsiveBoxTimer);
    clearTimeout(MatchThePair.pointerTimer);
    document.getElementById("playSound").pause();
    $('.shake').removeClass('animated shake');
    $('.flash').removeClass('animated flash');
    scoreFlag=true;
    var draggedData ,dropppedData , dragImg
    dragImg  = ui.draggable;
    draggedData = ui.draggable.data("data");
    dropppedData = $(this).data("data");
    if(draggedData == dropppedData)
    {
        MatchThePair.rightAns++;
        $(this).append(dragImg);
        $(this).addClass('animated flash');
        $(dragImg).css({ 'top': "0%", 'left': "0%",'width':'100%','height':'100%' });
        if($(this).children().hasClass("spanClass1"))
         $(this).children().addClass('droppedspan');
         $(".droppedspan").css({"font-size":"3vw","display":"flex" , "justify-content":"center","align-items":"center"});
        $(".dragDiv").css('pointer-events', 'none');
        $(this).children().draggable(
            {
                disabled:true
            });
        $(this).droppable({
            disabled: true
          });
         MatchThePair.checkAns();
    }
    else{
        document.getElementById("playSound").pause();
        $(".dragDiv").css('pointer-events', 'none');
        $(this).addClass('animated shake');
        document.getElementById("playSound").src = Utils.Path+"sounds/Anahhh.mp3";
       document.getElementById("playSound").play();
        $(ui.draggable).draggable("option", "revert", true);
        MatchThePair.pointerTimer = setTimeout(function(){ $(".dragDiv").css('pointer-events', 'auto'); $(".shake").removeClass('animated shake');},1000);
       }
}
MatchThePair.checkAns = function()
{
    correctCounter = correctCounter + 1;
    console.log(correctCounter);
    clearTimeout(MatchThePair.autoNextTimer);
    clearTimeout(MatchThePair.responsiveBoxTimer);
    clearTimeout(MatchThePair.pointerTimer);
    document.getElementById("playSound").pause();
    document.getElementById("playSound").src = Utils.Path+"sounds/coorrect_beat.mp3";
    document.getElementById("playSound").play();
    MatchThePair.pointerTimer = setTimeout(function(){ $(".dragDiv").css('pointer-events', 'auto');},1000);
     if(MatchThePair.rightAns == 3)
    {
        if(MatchThePair.responsiveBoxTimer){
            clearTimeout(MatchThePair.responsiveBoxTimer);
            MatchThePair.responsiveBoxTimer = null;
        }
        MatchThePair.responsiveBoxTimer=setTimeout(function(){
        document.getElementById("playSound").pause();
        document.getElementById("responseBoxDiv").style.display = "block";
        document.getElementById("playSound").src = Utils.Path+"sounds/Cheering.mp3";
        document.getElementById("playSound").play();
        },1000);
        scoredMarks = 10;
        if(MatchThePair.autoNextTimer)
        {
            clearTimeout(MatchThePair.autoNextTimer);
            MatchThePair.autoNextTimer = null;
        }
        MatchThePair.autoNextTimer = setTimeout(function(){MatchThePair.nextQuestion();},3000)
    }
}
MatchThePair.nextQuestion = function()
{
    questionCnt++;
    clearTimeout(MatchThePair.autoNextTimer);
    clearTimeout(MatchThePair.responsiveBoxTimer);
    clearTimeout(MatchThePair.pointerTimer);
    document.getElementById("playSound").pause();
    uniqueQuesArray.splice(0,7);
    if(!scoreFlag)
        scoredMarks =-1;
    if(scoreFlag && MatchThePair.rightAns < 2)
       scoredMarks=0;
    MatchThePair.scoreFunction();
    document.getElementById("responseBoxDiv").style.display = "none";
    $('.shake').removeClass('animated shake');
    $('.flash').removeClass('animated flash');
    $(".zoomIn").removeClass('animated zoomIn');
    if(questionCnt<5){
        document.getElementById("optionDiv2").innerHTML=" ";
        for (i = 0; i < 3; i++) {
            document.getElementById("option"+i).innerHTML=" ";
        }
    MatchThePair.variableInitilization();
    MatchThePair.createElements();
    }
    else
        MatchThePair.gameOver();
}
MatchThePair.gameOver = function()
{
    clearTimeout(MatchThePair.autoNextTimer);
    clearTimeout(MatchThePair.responsiveBoxTimer);
   $("#acknowledgementDiv").hide();
    document.getElementById("playSound").pause();
    document.getElementById("gamePage").style.display = "none";
    document.getElementById("endPage").style.display = "block";
    //document.getElementById("gameOver").innerHTML = MatchThePair.hardCodedData.gameOverText;
    document.getElementById("finalInstruction").innerHTML = MatchThePair.hardCodedData.instrucion;
    MatchThePair.createStars();
    MatchThePair.giveStars();
}
MatchThePair.createStars = function () {//div for stars
    clearInterval(MatchThePair.noResponseTimer);
    var newImage, newDiv, i;
    numberOfStars = 5;
    for (i = 1; i <= Math.floor(numberOfStars); i++) {
        newDiv = document.createElement("div");
        newDiv.setAttribute("id", "starDiv" + i);
        newDiv.setAttribute("class", "noPadding stars col-xs-2 col-md-2 col-lg-2 col-sm-2");
        newImage = document.createElement("img");
        newImage.setAttribute("id", "starImg" + i);
        newImage.setAttribute("class", "img-responsive noPadding col-sm-12 col-lg-12 col-md-12 col-xs-12");
        newImage.setAttribute("src", Utils.Path + "images/skin/star1.png");
        $(newDiv).append(newImage);
        $("#starsDiv").append(newDiv);
    }
}
MatchThePair.giveStars = function () {//calculate stars
    clearInterval(MatchThePair.noResponseTimer);
    var i,temp;
    numberOfStars = 0,
    ans = MatchThePair.total_No_of_Questions / 5;
    temp = correctCounter / ans;
    numberOfStars = Math.floor(temp);
    temp = Math.round(temp);
    console.log(numberOfStars);
    console.log(temp);
    for (i = 1; i <= Math.floor(numberOfStars); i++)
        document.getElementById("starImg" + i).setAttribute("src", Utils.Path + "images/skin/star2.png");
    $("#starsDiv").css("visibility", "visible");
    if(numberOfStars!=0)
      MatchThePair.finalInstruction();
    else{
        document.getElementById("playSound").src=Utils.Path+"sounds/finalInstruction.mp3";
        document.getElementById("playSound").play();
    }
    if (Utils.mobileDeviceFlag)
        Android.StudentCertification(MatchThePair.correctCounter, MatchThePair.total_No_of_Questions, "8");
}
MatchThePair.finalInstruction = function () {
    MatchThePair.soundFlag=true;
    src = Utils.Path+"sounds/"+"Star"+numberOfStars+".mp3";
    MatchThePair.getDuration(src);
}
MatchThePair.getDuration=function(src){
    var duration = 0;
	if (MatchThePair.soundFlag) {
		$('#playSound').on("loadedmetadata", function () {
			MatchThePair.soundFlag = false;
			duration = $('#playSound').prop('duration');
            $('#playSound').unbind("loadedmetadata");
               MatchThePair.playNextSound(duration);
		});
		$('#playSound').prop('src', src);
	}
}
MatchThePair.playNextSound = function (duration)//plz ans ques function call
{
    document.getElementById('playSound').play();
    if(instructionFlag){
	if (MatchThePair.instructionTimer) {
		clearTimeout(MatchThePair.instructionTimer);
		MatchThePair.instructionTimer = null;
	}
	MatchThePair.instructionTimer = setTimeout(function () {
		document.getElementById('playSound').pause();
		MatchThePair.playLastInstruction();
    }, duration * 1000);
  }
}
MatchThePair.playLastInstruction = function(){
    document.getElementById("playSound").src=Utils.Path+"sounds/finalInstruction.mp3";
    document.getElementById("playSound").play();
}
MatchThePair.replayGame = function()
{
    instructionFlag = false;
    clearTimeout(MatchThePair.autoNextTimer);
    clearTimeout(MatchThePair.responsiveBoxTimer);
    clearTimeout(MatchThePair.pointerTimer);
    clearTimeout(MatchThePair.instructionTimer);
    document.getElementById("playSound").pause();
    document.getElementById("gamePage").style.display = "block";
    document.getElementById("endPage").style.display = "none";
    //document.getElementById("gameOver").innerHTML =" ";
    document.getElementById("starsDiv").innerHTML =" ";
    document.getElementById("finalInstruction").innerHTML=" ";
    document.getElementById("acknowledgementDiv").scrollTop = '0px'; //Always scroll the slider to the Top at the beginning. 
    questionCnt =0;
    uniqueQuesArray =[];
    correctCounter=0;
    document.getElementById("optionDiv2").innerHTML=" ";
    document.getElementById("questionDiv").innerHTML=" ";
    MatchThePair.variableInitilization();
    MatchThePair.startGame();
}
MatchThePair.callHome = function()
{
    clearTimeout(MatchThePair.autoNextTimer);
    clearTimeout(MatchThePair.responsiveBoxTimer);
    clearTimeout(MatchThePair.pointerTimer);
    document.getElementById("playSound").pause();
    if(!scoreFlag)
        scoredMarks = 0;
    else
        scoredMarks=10;
        this.scoreFunction();
        location.reload();
}
MatchThePair.createAcknowledgementDivs = function () {
    var i = 0, div;
    for (i = 0; i < Object.keys(MatchThePair.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(MatchThePair.AcknowledgementPageData)[i] + " : " + Object.values(MatchThePair.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);

  /*  var extraInfo = document.createElement("div");
	$(extraInfo).prop('class', 'noPadding col-md-12 col-xs-12 col-lg-12 col-sm-12');
	$(extraInfo).css({ 'text-align': 'center', 'margin-top': '2.5vh' }); */

	for (var i = 0; i < 2; i++)
	{
		var extradiv=document.createElement("div");
		$(extradiv).prop('class', 'noPadding fontClass firstLetter col-md-12 col-xs-12 col-lg-12 col-sm-12');
		$(extradiv).text(MatchThePair.extraInfo[i]);
        $(extradiv).css("font-size","1.9vw");
		$(extraInfo).append(extradiv)
	}
//	$('#acknowledgementDiv').append(extraInfo);
}
MatchThePair.showAcknowledgement = function () {
    clearTimeout(MatchThePair.instructionTimer);
    document.getElementById("playSound").pause();
    $("#acknowledgementDiv").show();
}
MatchThePair.scoreFunction = function () {
    console.log(resId, questionId, scoredMarks, totalMarks, level, startTime, label);
    if (Utils.mobileDeviceFlag) {
        Android.addScore(resId, questionId, scoredMarks, totalMarks, level, startTime);
    }
}