//26 march 2021
var Pictionary = {};
var Utils = {};
Utils.Path = '';
Utils.mobileDeviceFlag = false;
var questionId = 0,startTime = 0,scoredMarks = 0,resId = 0,totalMarks = 10,wrongCnt = 0,totalLength = 0,type = "word",correctCnt = 0,label="";
$(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;
    setTimeout(function() {
        $("#gamepage,#endpage,#homeImg").hide();
        $("#coverpage").show();
        Pictionary.setImages();
    }, 300);
});
Pictionary.initializeVariables=function()
{
	Pictionary.skipedQ = 0;
	Pictionary.alreadyShownObject = [];
	Pictionary.tempArr = []; //json data
	Pictionary.skipFlag = true;
	Pictionary.attemptFlag = false;
	Pictionary.objPointerFlag = true; //image clicked flag
	Pictionary.optionCnt = 0; //counter for playing optionin sequence
	Pictionary.levelNumber = 0; //false for learn & true for practice
}
Pictionary.setImages = function() {
    document.body.style.backgroundImage = "url(" + Utils.Path + Pictionary.coverImage + ")";
    document.getElementById("showMePageDiv").style.backgroundImage = "url(" + Utils.Path + "images/skin/board.png)";
    $("#homeImg").prop("src", Utils.Path + "images/skin/Home.png");
    $("#logoImg").prop("src", Utils.Path + "images/skin/logo.png");
    $("#playImg").prop("src", Utils.Path + "images/skin/Play.png");
    $("#nextImage").prop("src", Utils.Path + "images/skin/Next.png");
    $("#replayImage").prop("src", Utils.Path + "images/skin/Replay.png");
    $("#credit").prop("src", Utils.Path + "images/skin/credits.png");
    $("#sound").prop('src', Utils.Path + "images/skin/Sound.png");
}
Pictionary.playGame = function() {
	Pictionary.initializeVariables();
        document.body.style.backgroundImage = "url(" + Utils.Path + "images/skin/bg.png)";
        $("#homeImg,#gamepage").show();
        $("#coverpage").hide();
        Pictionary.createDivs(showMePageDiv, "picture", "pictureClass  noPadding col-md-3 col-xs-3 col-lg-3 col-sm-3", 3);
        $(".borderClass").css("backgroundImage", "url(images/skin/blue_pach.png)");
        Pictionary.selectLevel();
    }
    //creates No. of Divs
Pictionary.createDivs = function(parentDiv, id, className, no) { //create Divs for level page & Main game page
    var pictureDiv, img, imgDiv, textDiv, levelNo = 1;
    for (var j = 0; j < no; j++, levelNo++) {
        pictureDiv = document.createElement("div");
        pictureDiv.setAttribute("id", id + j);
        pictureDiv.setAttribute("class", className);
        parentDiv.appendChild(pictureDiv);

        img = document.createElement('img');
        img.setAttribute("id", id + "img" + j);
        img.setAttribute("class", " borderClass img-responsive col-lg-12 col-md-12 col-xs-12 col-sm-12");
        pictureDiv.appendChild(img);
        img.setAttribute("onclick", "Pictionary.checkAnswer(this)");
            imgDiv = document.createElement("div");
            imgDiv.setAttribute("class", "optionClass noPadding col-lg-12 col-md-12 col-xs-12 col-sm-12");
            pictureDiv.appendChild(imgDiv);

            subImgDiv = document.createElement("div");
            subImgDiv.setAttribute("class", "noPadding col-lg-4 col-md-4 col-xs-4 col-sm-4 col-sm-offset-4 col-lg-offset-4 col-md-offset-4 col-xs-offset-4");
            imgDiv.appendChild(subImgDiv);

            img = document.createElement('img');
            img.setAttribute("class", "img-responsive noPadding col-lg-10 col-md-10 col-xs-10 col-sm-10 col-sm-offset-1 col-lg-offset-1 col-md-offset-1 col-xs-offset-1");
            img.setAttribute("src", Utils.Path + "images/skin/option_Sound.png");
            $(img).data("ans", j);
            img.setAttribute("onclick", "Pictionary.playOptions(this)");
            subImgDiv.appendChild(img);
    }
}
Pictionary.selectLevel = function(element) { //selects level
        Pictionary.skipedQ = 0;
        Pictionary.alreadyShownObject = [];
        $("#message").css("visibility", "hidden");
        Pictionary.tempArr = JSON.parse(JSON.stringify(Pictionary.data.data));
        Pictionary.showObjects();
    }
    //Show Objects on the screen
Pictionary.showObjects = function() { //display  images levelwise 
    var d;
    Pictionary.optionCnt = 0;
    Pictionary.skipFlag = true;
    Pictionary.objPointerFlag = true;
    $("#acknowledgementDiv").text('');
    clearTimeout(Pictionary.optionTimer);
    clearTimeout(Pictionary.instructionTimer);
    $("#message").css("visibility", "hidden");
    d = new Date();
    startTime = d.getDate() + "-" + (d.getMonth() + 1) + "-" + d.getFullYear() + " " + d.getHours() + ":" + d.getMinutes() + ":" + d.getSeconds();
    Pictionary.uniqueImgArr = [];
    //Pictionary.uniqueImgArr = populate(Pictionary.tempArr, Pictionary.uniqueImgArr, Pictionary.hardcoded.number);
	var array=[];
	for(var i=0;i<Pictionary.hardcoded.number;)
	{
		var randomNumber=Math.floor(Math.random()*Pictionary.data.data.length);
		while(array.includes(Pictionary.data.data[randomNumber]))
		{
			randomNumber=Math.floor(Math.random()*Pictionary.data.data.length);
		}
		if(i==0)
		{
			var ranNo=Math.floor(Math.random()*Pictionary.data.data.length);
			array.push(Pictionary.data.data[randomNumber]);
			Pictionary.uniqueImgArr.push(Pictionary.data.data[randomNumber]);
			i++;
		}
		else{
			var flag=false;
			for(var j=0;j<array.length;j++)
			{
				if(array[j].name==Pictionary.data.data[randomNumber].name){
					flag=true;}
			}
			if(flag==false)
			{
				var ranNo=Math.floor(Math.random()*Pictionary.data.data.length);
				array.push(Pictionary.data.data[randomNumber]);
				Pictionary.uniqueImgArr.push(Pictionary.data.data[randomNumber]);
				i++;
			}
		}
	}
	console.log(Pictionary.uniqueImgArr);
    for (var j = 0; j < 3; j++) { //display images & set data to images
        $("#pictureimg" + j).prop("src", Utils.Path + "images/" + Pictionary.uniqueImgArr[j].imgName);
        $("#pictureimg" + j).data("ans", Pictionary.uniqueImgArr[j].name);
    }
    Pictionary.uniqueQue = Math.floor(Math.random() * (Pictionary.uniqueImgArr.length)); //get unique Question
    while ($.inArray(Pictionary.uniqueImgArr[Pictionary.uniqueQue].name, Pictionary.alreadyShownObject) !== -1)
        Pictionary.uniqueQue = Math.floor(Math.random() * (Pictionary.uniqueImgArr.length));
    Pictionary.alreadyShownObject.push(Pictionary.uniqueImgArr[Pictionary.uniqueQue].name);
    questionId = parseInt(Pictionary.uniqueImgArr[Pictionary.uniqueQue].questionId);
    Pictionary.playInstruction();
}
Pictionary.playOptions = function(element) { //plays perticular sound for image
    clearTimeout(Pictionary.instructionTimer);
    clearTimeout(Pictionary.optionTimer);
    $("#soundDiv").css({ "pointer-events": "auto" });
    $(".borderClass").removeClass("animated zoomIn");
    var data = $(element).data("ans");
    document.getElementById('playSound').pause();
    document.getElementById('playSound').src = Utils.Path + 'sounds/' + Pictionary.uniqueImgArr[data].sound;
    document.getElementById('playSound').play();
}
Pictionary.playInstruction = function() { // plays sound of instruction/options
    Pictionary.soundFlag = true;
    $(".optionClass").css("pointer-events", "none");
    if (Pictionary.objPointerFlag)
        $(".borderClass").css({ "pointer-events": "none" });
    if (Pictionary.levelName)
        getDuration(Utils.Path + 'sounds/' + Pictionary.uniqueImgArr[Pictionary.uniqueQue].instruction, "playInstruction");
    else {
        if (Pictionary.optionCnt < 3)
            getDuration(Utils.Path + 'sounds/' + Pictionary.uniqueImgArr[Pictionary.optionCnt].sound, "play");
        else{
           getDuration(Utils.Path + 'sounds/' + Pictionary.uniqueImgArr[Pictionary.uniqueQue].instruction, "playInstruction");
		}
    }
}

function getDuration(src, functionName) {
    var duration = 0;
    if (Pictionary.soundFlag) {
        $('#playSound').on("loadedmetadata", function() {
            Pictionary.soundFlag = false;
            duration = $('#playSound').prop('duration');
            $('#playSound').unbind("loadedmetadata");
            if (functionName == "playInstruction")
                Pictionary.playNextSound(duration);
            else
                Pictionary.playOptionsInLoop(duration);
        });
        $('#playSound').prop('src', src);
    }
}
Pictionary.playOptionsInLoop = function(duration) //play option sounds in a loop
    {
        $("#pictureimg" + Pictionary.optionCnt).addClass("animated zoomIn");
        $("#soundDiv").css({ "pointer-events": "none" });
        clearTimeout(Pictionary.instructionTimer);
        document.getElementById('playSound').play();
        if (Pictionary.optionTimer) {
            clearTimeout(Pictionary.optionTimer);
            Pictionary.optionTimer = null;
        }
        Pictionary.optionTimer = setTimeout(function() {
            $("#pictureimg" + Pictionary.optionCnt).removeClass("animated zoomIn");
            Pictionary.optionCnt++;
            if (Pictionary.optionCnt > 2) {
                clearTimeout(Pictionary.optionTimer);
                setTimeout(function() { Pictionary.playInstruction(); }, 1000);
            } else
                Pictionary.playInstruction();
        }, duration * 2000);
    }
Pictionary.playNextSound = function(duration) //function for instruction
    {
        document.getElementById('playSound').play();
        if (Pictionary.instructionTimer) {
            clearTimeout(Pictionary.instructionTimer);
            Pictionary.instructionTimer = null;
        }
        Pictionary.instructionTimer = setTimeout(function() {
            document.getElementById('playSound').pause();
            //document.getElementById('playSound').src = Utils.Path + 'sounds/' + Pictionary.tempArr[Pictionary.uniqueImgArr[Pictionary.uniqueQue]].sound;
			console.log(Pictionary.tempArr);
            document.getElementById('playSound').play();
            setTimeout(function() {
                //if (Pictionary.objPointerFlag) {
                    Pictionary.objPointerFlag = false;
                    $(".borderClass").css({ "pointer-events": "auto" });
               // }
                $(".optionClass,#soundDiv").css({ "pointer-events": "auto" });
            }, duration * 400);
        }, duration * 1000);
    }
Pictionary.checkAnswer = function(element) { //Check Answer
    var randomSound;
    $(".optionClass").css("pointer-events", "auto");
    Pictionary.skipFlag = false;
    clearTimeout(Pictionary.instructionTimer);
    if (wrongCnt == 0)
        scoredMarks = 10;
    else if (wrongCnt == 1)
        scoredMarks = 5;
	console.log($(element).data('ans'));
    if (($(element).data('ans') == Pictionary.uniqueImgArr[Pictionary.uniqueQue].name)) {
        correctCnt++;
        $(element).addClass("animated zoomIn");
        randomSound = Math.floor(Math.random() * (Pictionary.correctAns.length));
        document.getElementById('playSound').src = Utils.Path + 'sounds/instruction/' + Pictionary.correctAns[randomSound];
        document.getElementById('playSound').play();

        console.log(Pictionary.uniqueImgArr[Pictionary.uniqueQue].name, totalLength, type);
        if (Utils.mobileDeviceFlag)
            Android.addLearntData(Pictionary.uniqueImgArr[Pictionary.uniqueQue].name, totalLength, type);
        Pictionary.calculateScore();
    } else {
        wrongCnt++;
        $(element).css({ "pointer-events": "none", "opacity": "0.5" });
        $(element).addClass("animated shake");
        Pictionary.attemptFlag = true;
        randomSound = Math.floor(Math.random() * (Pictionary.wrongAns.length));
        if (wrongCnt == 2)
            document.getElementById('playSound').src = Utils.Path + 'sounds/instruction/wrong_answer!_Aditi.mp3';
        else
            document.getElementById('playSound').src = Utils.Path + 'sounds/instruction/' + Pictionary.wrongAns[randomSound];
        document.getElementById('playSound').play();
        setTimeout(function() {
            $(element).removeClass("animated shake");
        }, 1500);
    }
    if (wrongCnt == 2 || correctCnt == 1) {
        $(".borderClass,.optionClass,#soundDiv").css({ "pointer-events": "none" });
        if (Pictionary.nextQ) {
            clearTimeout(Pictionary.nextQ);
            Pictionary.nextQ = null;
        }
        Pictionary.nextQ = setTimeout(function() {
            Pictionary.nextQuestion();
            $(element).removeClass("animated zoomIn");
        }, 3000);
    }
}
Pictionary.nextQuestion = function() { //Loads Next Question
    Pictionary.skipedQ++;
    clearTimeout(Pictionary.instructionTimer);
    clearTimeout(Pictionary.optionTimer);
    $(".borderClass").removeClass("animated zoomIn animated shake");
    if (Pictionary.attemptFlag) {
        scoredMarks = 0;
        Pictionary.attemptFlag = false;
        Pictionary.calculateScore();
    }
    if (Pictionary.skipFlag) {
        scoredMarks = -1;
        Pictionary.calculateScore();
    }
    wrongCnt = 0;
    correctCnt = 0;
    clearTimeout(Pictionary.nextQ);
    document.getElementById('playSound').pause();
    $(".borderClass").css({ "pointer-events": "auto", "opacity": "1" });
    Pictionary.tempArr.splice(Pictionary.uniqueImgArr[Pictionary.uniqueQue], 1);
    if (Pictionary.skipedQ == 5) {
        clearTimeout(Pictionary.instructionTimer);
        clearTimeout(Pictionary.optionTimer);
        document.getElementById('playSound').pause();
        $('#endpage').show();
        $('#gamepage,#acknowledgementDiv').hide();
        $("#message").text(Pictionary.hardcoded.gameOver);
        $("#message").css("visibility", "visible");
        Pictionary.createHardcodeddivs();
    } else
        Pictionary.showObjects();
}
Pictionary.createHardcodeddivs = function() {
    var ackDiv;
    for (var i = 0; i < Object.keys(Pictionary.acknowledgementData).length; i++) {
        ackDiv = document.createElement("div");
        ackDiv.setAttribute("id", "ack" + i);
        ackDiv.setAttribute("class", "noPadding firstLetter text-center fontClass col-sm-12 col-lg-12 col-md-12 col-xs-12");
        ackDiv.innerHTML = Object.keys(Pictionary.acknowledgementData)[i] + " : " + Object.values(Pictionary.acknowledgementData)[i];
        document.getElementById("acknowledgementDiv").appendChild(ackDiv);
    }
    div = document.createElement('div');
    div.className = "noPadding fontClass firstLetter text-center col-xs-12 col-sm-12 col-md-12 col-lg-12";
    div.innerHTML = Pictionary.hardcoded['createdOn'];
    document.getElementById("acknowledgementDiv").appendChild(div);
}
Pictionary.callHome = function() {
    Pictionary.resetAll();
    if (Pictionary.attemptFlag) {
        scoredMarks = 0;
        Pictionary.attemptFlag = false;
        Pictionary.calculateScore();
    }
    location.reload(true);
}
Pictionary.playAgain = function() {
    Pictionary.resetAll();
    $(".borderClass").removeClass("animated zoomIn animated shake");
    $("#message").css("visibility", "visible");
    $("#endpage").hide();
    $("#gamepage").show();
	document.getElementById("showMePageDiv").innerHTML="";
   Pictionary.playGame();
}
Pictionary.resetAll = function() {
    wrongCnt = 0;
    correctCnt = 0;
    Pictionary.optionCnt = 0;
    document.getElementById('playSound').pause();
    Pictionary.skipFlag = true;
    clearTimeout(Pictionary.nextQ);
    clearTimeout(Pictionary.instructionTimer);
    clearTimeout(Pictionary.optionTimer);
}
Pictionary.calculateScore = function() {
    Pictionary.attemptFlag = false;
	label=Pictionary.uniqueImgArr[Pictionary.uniqueQue].name;
    console.log(resId, questionId, scoredMarks, totalMarks, 1, startTime,label);
    if (Utils.mobileDeviceFlag)
        Android.addScore(resId, questionId, scoredMarks, totalMarks, 1, startTime,label);
}
Pictionary.showCredit = function() {
    $("#acknowledgementDiv").show();
}