
//19 Dec 2021
var Profession = {};
var Utils = {};
Utils.Path = "";
var questionId = 0, startTime = 0, scoredMarks = 0, totalMarks = 10, resId = 0, label = '', level = 1;
var clickflag = false, correctOptionId = '';

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

Profession.init = function () {
    $("#home,#gamePage, #finalPage, #responseBoxDiv").hide();
    $("#personPage,#frame,#finalPage,#screen3div,#home").hide();
	$("#prevScreenDiv, #clearButtonDiv, #nextScreenDiv").css("visibility", "hidden");
    document.title = Profession.hardCodedData.nameOfGame;
    document.getElementById("playImage").classList.add('pulse');
    Profession.setImages();
    Profession.initVariables();
    Profession.createButtons();         //For Screen-3
    //Profession.createPersonDivs();      //For Screen-3
    Profession.playCoverPageMusic();
    Profession.createAcknowledgementDivs();
}

Profession.playCoverPageMusic = function()
{
    document.getElementById("playSound").src = Utils.Path + "sounds/instructions/Row0.mp3";      
    document.getElementById("playSound").play();
}

Profession.setImages = function () {
    document.body.style.backgroundImage = Utils.Path + "url('images/skin/Cover.gif')";
    document.getElementById("home").src = Utils.Path + "images/skin/Home.png";
    document.getElementById("logo").src = Utils.Path + "images/skin/logo.png";
    document.getElementById("prevScreenImg").src = Utils.Path + "images/skin/pre_level.png";
    document.getElementById("nextScreenImg").src = Utils.Path + "images/skin/next_level.png";
    document.getElementById("playImage").src = Utils.Path + "images/skin/Play.png";
    document.getElementById("soundImage").src = Utils.Path + "images/skin/instructions.png";
    document.getElementById("nextImage").src = Utils.Path + "images/skin/Next.png";
    document.getElementById("muteImg").src = Utils.Path + "images/skin/sound.png";
    document.getElementById("muteBtnImg").src = Utils.Path + "images/skin/sound.png";
    document.getElementById("set").src = Utils.Path + "images/skin/Next.png";
    document.getElementById("clearButton").src = Utils.Path + "images/skin/replay.png";
    document.getElementById("playAgainBtn").src = Utils.Path + "images/skin/replay.png";
    document.getElementById("creditbtn").src = Utils.Path + "images/skin/Credits.png";
    document.getElementById("gameOverTextDiv").innerHTML = Profession.hardCodedData.gameOver;
}

Profession.initVariables = function () {
    Profession.noOfDiv = 0;
    Profession.correctCnt = 0;
    Profession.questionCnt = 0;
    Profession.soundFlag = false;
    Profession.queArray = [];
    Profession.toolsArray = [];
    Profession.randomNoArray = [];
    Profession.profShowNoArray = [];
    Profession.correctToolsNameArray = [];
    Profession.attemptFlag = false;
    Profession.correctQueTimer = null;
    Profession.wrongQuestionTimer = null;
}

Profession.play = function () {
    $("#home, #gamePage").show();
    $("#playImage, #coverPage, #finalPage").hide();
    $("#screen1Div").css('display', 'block');
    $("#prevScreenDiv, #nextScreenDiv").css("visibility", "visible");   //For Screen-2 & screen-3
    document.getElementById("playImage").classList.remove('pulse');
    d = new Date();
    startTime = d.getDate() + "-" + (d.getMonth() + 1) + "-" + d.getFullYear() + " " + d.getHours() + ":" + d.getMinutes() + ":" + d.getSeconds();

    Profession.showProfessionPage();      //Screen - 1
    //Profession.callNext();              //Screen - 2
    //Profession.playGame();              //Screen - 3
}

Profession.showProfessionPage = function()      //Screen - 1  //show all profession
{
    var professionArray = [];
    clickflag = false;
    Profession.attemptFlag = false;

    document.body.style.backgroundImage = Utils.Path + "url('images/skin/BG_Level_1.jpg')";
    $("#widges").show();
    $("#nextBtn, #screen3Div").hide();
    $("#screen1Div").css('display', 'block');
    $("#screen2Div").css('display', 'none');
    $("#prevScreenDiv, #clearButtonDiv, #setButton, #soundBtn").css("visibility", "hidden");
    $("#nextScreenSpan").text('Screen 2');
    document.getElementById("playSound").pause();
    
    for(i=0; i<Profession.dataArray.length; i++){
        professionArray.push(Profession.dataArray[i]);
    }
    shuffle(professionArray);
    Profession.noOfDiv = professionArray.length;
    Profession.makeProfessionGrid(professionArray);

    for(j=0; j<Profession.profShowNoArray.length; j++)
    {
        document.getElementById('profession'+Profession.profShowNoArray[j]).setAttribute('onclick','Profession.showModal(this.id)');
        $("#profession"+Profession.profShowNoArray[j]).data('professionImg', professionArray[j].queGif);
        $("#profession"+Profession.profShowNoArray[j]).data('professionName', professionArray[j].profession);
        $("#profession"+Profession.profShowNoArray[j]).data('professionNameAudio', professionArray[j].queImgAudio);      

        $('#professionImg'+Profession.profShowNoArray[j]).prop('src',Utils.Path + "images/professionImages/" + professionArray[j].queImg);  
        $('#professionImg'+Profession.profShowNoArray[j]).css('visibility', 'hidden');
    } 
    for(i=1; i<=Profession.noOfDiv; i++){                   //Hide the Div who don't have images.
        if(!Profession.profShowNoArray.includes(i)){
            $("#profession"+i).css('visibility', 'hidden');
        }
    }  
    Profession.showLoader();
}

Profession.showLoader = function()      /* Function to check all images are loaded or not */
{
    var imgs = document.images,
    len = imgs.length,
    counter = 0;
    $(".loader").show();
	$('.loader').css('display', 'flex');
    [].forEach.call( imgs, function( img ) {
        if(img.complete)
            incrementCounter();
        else
            img.addEventListener( 'load', incrementCounter, false );
    } );
    function incrementCounter() {
        counter++;
        if ( counter === len ) {
            $(".loader").hide();
            console.log( 'All images loaded!' );
            Profession.soundFlag = true;
            $('.profImgCss').css('visibility', 'visible');
            setTimeout(() => {
                document.getElementById('playSound').src = Utils.Path + 'sounds/instructions/screen1_complete_Instr.mp3';
                document.getElementById('playSound').play();
            },1000);
            if(!muteFlag){
                document.getElementById('playSoundInLoop').src = Utils.Path + "sounds/instructions/Classical_Carnivale.mp3";
                document.getElementById('playSoundInLoop').loop = true;
                document.getElementById('playSoundInLoop').play();
            }
        }
    }
}

/* function getDuration(src) {
	var duration = 0;
    
	if (Profession.soundFlag) {
		$('#playSound').on("loadedmetadata", function () {
			Profession.soundFlag = false;
			duration = $('#playSound').prop('duration');
			$('#playSound').unbind("loadedmetadata");
			Profession.instructionTimer = setTimeout(function () {
                document.getElementById('playSound').src = Utils.Path + 'sounds/instructions/screen1_instr.mp3';
                document.getElementById('playSound').play();
            }, duration * 1200);
		});
		$('#playSound').prop('src', src);
        document.getElementById('playSound').play();
	}
}  */

Profession.makeProfessionGrid = function(professionArray)       //Screen - 1 //make Grid
{
    var rowCnt = 0;
    Profession.profShowNoArray = [];

    var noOfRow = Math.ceil(Profession.dataArray.length / 3);
    for(k=0; k<noOfRow; k++){
        div = document.createElement('div');
        $(div).prop('id', 'professionRow'+(k+1));
        $(div).prop('class', 'noPadding col-sm-12 col-lg-12 col-md-12 col-xs-12');
        $('#screen1Div').append(div);
    }
    for(j=0; j<(Profession.noOfDiv); j++){
        div = document.createElement('div');
        $(div).prop('id', 'profession'+(j+1));
        $(div).prop('class', 'noPadding profDivCss col-sm-3 col-lg-3 col-md-3 col-xs-3 col-sm-offset-1 col-lg-offset-1 col-md-offset-1 col-xs-offset-1');
        if((j == 3) || (j == 6 ))      //To append next tools div to the next row
            rowCnt++;
        $('#professionRow'+(rowCnt+1)).append(div);

        img = document.createElement('img');
        $(img).prop('id', 'professionImg'+(j+1));
        $(img).prop('class', 'noPadding img-responsive profImgCss col-sm-12 col-lg-12 col-md-12 col-xs-12');
        $('#profession'+(j+1)).append(img);        
    }
    for(i=0; i<professionArray.length; i++){
        randomNum = Math.floor(Math.random() * Profession.noOfDiv) + 1;
        while (Profession.profShowNoArray.includes(randomNum))
            randomNum = Math.floor(Math.random() * Profession.noOfDiv) + 1;
        Profession.profShowNoArray.push(randomNum);
    }
    //console.log(Profession.profShowNoArray);
}

Profession.showModal = function(professionId)       //Screen - 1 //show modal
{
    clickflag = true;
    scoredMarks = 0;
    Profession.attemptFlag = true;
    $("#nextScreenDiv").css("visibility", "hidden");
    var audioData = $("#"+professionId).data('professionNameAudio');
    var imgData = $("#"+professionId).data('professionImg');
    var imgNameData = $("#"+professionId).data('professionName');
    $("#responseBoxDiv").show();
    $("#closeDiv").hide();
    clearTimeout(Profession.instructionTimer);
    document.getElementById("playSound").pause();
    $("#showProfessonImg").prop('src', Utils.Path + "images/professionImages/" + imgData);
    $("#playSound").prop('src', Utils.Path + "sounds/audios/" + audioData);
    document.getElementById("playSound").play();
    setTimeout(function(){
        $("#closeDiv").show();
    }, 800);
    label = imgNameData;
    Profession.calculateScore();
}

Profession.closeGifModal = function(){
    if(clickflag)                //When Popup is open for screen 1
    {
        //clickflag = false;
        $("#responseBoxDiv").hide();
        $(".opacityClass").css("opacity","1");
        $(".pointerClass").css("pointer-events","auto");
        $("#nextScreenDiv").css("visibility", "visible");
    }
}

//check event to close modal
/* $(document).click(function(event) {
	//if you click on anything except the modal itself close the modal
	//if (!$(event.target).closest(".modal", "#"+clickProfessionId).length) {
    if(!clickflag){
     $("#responseBoxDiv").hide();
	 $(".opacityClass").css("opacity","1");
	 $(".pointerClass").css("pointer-events","auto");
	}
    clickflag = false;
  }); */

Profession.showQueGif = function()
{
    document.getElementById("playSound").pause();
    $("#queProfessionImg").prop('src', Utils.Path + "images/professionImages/" + Profession.randomQue.queGif);
    document.getElementById("playSound").src = Utils.Path + "sounds/audios/"+ Profession.randomQue.queImgAudio;      
    document.getElementById("playSound").play();
}

Profession.showQuestion = function ()      //Screen - 2 //Show profession as Question and tools options.
{
    var rowCnt = 0;
    document.body.style.backgroundImage = Utils.Path + "url('images/skin/BG_Level_2.jpg')";
    $("#toolsDiv1, toolsDiv2, toolsDiv3, toolsDiv4, #nextBtn, #widges").show();
    $("#screen1Div").css('display', 'none');
    $("#screen2Div").css('display', 'block');
    $("#prevScreenDiv, #nextScreenDiv, #soundBtn, #muteButton").css("visibility", "visible");
    $("#clearButtonDiv, #setButton").css("visibility", "hidden");
    Profession.generateQueToolsArray();
    shuffle(Profession.toolsArray);
    Profession.randomQue = Profession.queArray[Profession.questionCnt];
    $("#queProfessionImg").prop('src', Utils.Path + "images/professionImages/" + Profession.randomQue.queImg);
    document.getElementById("playSound").src = Utils.Path + "sounds/audios/" + Profession.randomQue.queImgInstrAudio;      
    document.getElementById("playSound").play();
	if(!muteFlag){
		document.getElementById('playSoundInLoop').src = Utils.Path + "sounds/instructions/Classical_Carnivale.mp3";
		document.getElementById('playSoundInLoop').loop = true;
		document.getElementById('playSoundInLoop').play();
	}

    var noOfRow = Math.ceil(Profession.toolsArray.length / 3);
    for(k=0; k<noOfRow; k++){
        div = document.createElement('div');
        $(div).prop('id', 'toolRow'+(k+1));
        $(div).prop('class', 'noPadding col-sm-11 col-lg-11 col-md-11 col-xs-11 col-sm-offset-1 col-lg-offset-1 col-md-offset-1 col-xs-offset-1');
        $('#toolsDiv').append(div);
    }
    for(j=0; j<Profession.toolsArray.length; j++){
        div = document.createElement('div');
        $(div).prop('id', 'toolDiv'+(j+1));
        div.setAttribute('onclick','Profession.checkAnswer(this.id)');
        $(div).prop('class', 'noPadding toolsCss col-sm-4 col-lg-4 col-md-4 col-xs-4 col-sm-offset-0 col-lg-offset-0 col-md-offset-0 col-xs-offset-0');
        if((j+1) % 4 == 0)      //To append next tools div to the next row
            rowCnt++;
        $('#toolRow'+(rowCnt+1)).append(div);

        img = document.createElement('img');
        $(img).prop('id', 'toolImg'+(j+1));
        $(img).prop('class', 'toolImgCss noPadding img-responsive col-sm-12 col-lg-12 col-md-12 col-xs-12');
        $('#toolDiv'+(j+1)).append(img);
        $(img).prop('src',Utils.Path + "images/professionImages/" + Profession.toolsArray[j]);

        if(Profession.correctToolsNameArray.includes(Profession.toolsArray[j]))
            $(div).data('answer', 'correct');
        else
            $(div).data('answer', 'wrong');
    }
    Profession.questionCnt++;
}

Profession.generateQueToolsArray = function()
{
    var correctToolrandomNoArray = [], toolrandomNoArray = [];

    //Generate Question Array
    randomNum = Math.floor(Math.random() * Profession.dataArray.length);
    while (Profession.randomNoArray.includes(randomNum))
        randomNum = Math.floor(Math.random() * Profession.dataArray.length);
    Profession.randomNoArray.push(randomNum);
    toolrandomNoArray.push(randomNum);
    Profession.queArray.push(Profession.dataArray[randomNum]);

    //Generate 2 correct tools
    while(correctToolrandomNoArray.length != 2){
        Profession.randomQue = Profession.queArray[Profession.questionCnt];                 //correct random Que for correct tools
        var randomNum = Math.floor(Math.random() * Profession.randomQue.toolsImgArray.length);
        while (correctToolrandomNoArray.includes(randomNum))
            randomNum = Math.floor(Math.random() * Profession.randomQue.toolsImgArray.length);
        correctToolrandomNoArray.push(randomNum);
        Profession.correctToolsNameArray.push(Profession.randomQue.toolsImgArray[randomNum]);
        Profession.toolsArray.push(Profession.randomQue.toolsImgArray[randomNum]);          //Add first 2 correct tools in the array
    }

    //Generate other(6) wrong tools
    while(Profession.toolsArray.length != 6){                   
        randomNum = Math.floor(Math.random() * Profession.dataArray.length);        //Generate random Que for wrong tools
        while (toolrandomNoArray.includes(randomNum))     
            randomNum = Math.floor(Math.random() * Profession.dataArray.length);
        toolrandomNoArray.push(randomNum);

        randomToolNum = Math.floor(Math.random() * Profession.dataArray[randomNum].toolsImgArray.length);
        Profession.toolsArray.push(Profession.dataArray[randomNum].toolsImgArray[randomToolNum]);          //Add another 5 wrong tools in the array
    }
    correctToolrandomNoArray = [];
    
    /* console.log("Que Array");
    console.log(Profession.queArray);
    console.log("Tools Array");
    console.log(Profession.toolsArray); */

}

Profession.checkAnswer = function (clickedOptId) 
{    
    Profession.clickCnt++;
    Profession.attemptFlag = true;
    Profession.wrongQuestionTimer = null;
    clearTimeout(Profession.wrongQuestionTimer);
    clickedOptionData = $("#"+clickedOptId).data('answer');

    var correctSoundArr = ['are_wahh.mp3', 'bohot_acche.mp3', 'bohot_badhiya.mp3', 'bohot_khub.mp3', 'good_job.mp3', 'shabbash.mp3', 'wah_kya_baat_hain.mp3']

    if (clickedOptionData == 'correct')             //For correct answer
    {
        Profession.correctCnt++;  
        Profession.clickCnt = 0;
        correctOptionId = clickedOptId;
        $("#"+clickedOptId).css("pointer-events", "none");
        $("#"+clickedOptId).css('box-shadow', '2px 2px 22px 8px blue');
        if(Profession.correctCnt == 2){
            scoredMarks = 10;
            $("#toolsDiv").css("pointer-events", "none");
            $("#soundBtn").css("pointer-events", "none");
            $("#queProfessionDiv").css("pointer-events", "none");
            blinkTimer = setTimeout(function(){
                document.getElementById("nextBtn").classList.add('blink_me');
            },700);
            var randSound = Math.floor(Math.random() * correctSoundArr.length);
            document.getElementById("playSound").src = Utils.Path + "sounds/instructions/" + correctSoundArr[randSound];
            document.getElementById("playSound").play();
        }
        else{
            scoredMarks = 5;
            document.getElementById("playSound").src = Utils.Path + "sounds/instructions/areWahh_aurDhundiye.mp3";      
            document.getElementById("playSound").play();
        }
    }
    else {                                                  //Wrong answer
        if(scoredMarks != 5)
            scoredMarks = 0;
        $("#soundBtn").css("pointer-events", "none");
        $("#"+clickedOptId).css('box-shadow', '2px 2px 22px 8px red');
        document.getElementById("playSound").src = Utils.Path + "sounds/instructions/try_again_hindi.mp3";
        document.getElementById("playSound").play(); 
        if (Profession.wrongQuestionTimer) {
            clearTimeout(Profession.wrongQuestionTimer);
            Profession.wrongQuestionTimer = null;
        }
        Profession.wrongQuestionTimer = setTimeout(function () {
            $("#soundBtn").css("pointer-events", "auto");
            $("#" + clickedOptId).css('box-shadow', 'none');
        },300);
    } 

    if(Profession.clickCnt == 2){                       //ZoomIn the correct tools for clue
        for(i=0; i<Profession.toolsArray.length; i++){
            toolData = $("#toolDiv"+(i+1)).data('answer');
            if(toolData == 'correct' && "toolDiv"+(i+1) != correctOptionId){
                $("#toolDiv"+(i+1)).addClass("borderGlow animated zoomIn");
            }
        }
        Profession.clickCnt = 0;
        flashTimer = setTimeout(function(){
            $(".toolsCss").removeClass("borderGlow animated zoomIn");
        },500);
    }
}

Profession.callNext = function () 
{
    $("#screen3Div").hide();
    $("#screen1Div").css('display', 'none');
    document.getElementById("playSound").pause();
    //var displayScreen2 = document.getElementById("screen2Div").style.display;

    if(!Profession.attemptFlag){
        scoredMarks = -1;
        label = 'null';
    } 
    

    if(Profession.questionCnt < 5) {       //Call to Screen-2
        Profession.clearScreen2();
        Profession.showQuestion();
    }
    else{
        $("#prevScreenDiv").css('visibility', 'visible');
        Profession.playGame();      //Call to MakeUp-ShakeUp game(Screen-3).
    }  
    if(!clickflag){
        clickflag = false;
        Profession.calculateScore();
        Profession.attemptFlag = false;
    }
}

Profession.clearScreen2 = function()
{
    correctOptionId = '';
    Profession.clickCnt = 0;
    Profession.correctCnt = 0;
    Profession.toolsArray = [];
    Profession.correctToolsNameArray = [];
    $("#prevScreenDiv, #nextScreenDiv").css('visibility', 'visible');
    $("#queProfessionImg").prop('src', '');
    $("#toolsDiv").css("pointer-events", "auto");
    $("#soundBtn").css("pointer-events", "auto");
    $("#queProfessionDiv").css("pointer-events", "auto");
    document.getElementById("toolsDiv").innerHTML = '';
    document.getElementById("nextBtn").classList.remove('blink_me');
    for(i=0; i< Profession.toolsArray.length; i++)
        $(".toolsCss").css('border', '');
        $(".toolsCss").data('answer', '');
}

Profession.changeScreen = function(clickBtnId){
    var displayScreen1 = document.getElementById("screen1Div").style.display;
    var displayScreen2 = document.getElementById("screen2Div").style.display;
    var displayScreen3 = document.getElementById("screen3Div").style.display;

    if(displayScreen1 == 'block'){             //When displaying Screen - 1
        if(clickBtnId == 'nextScreenImg'){
            Profession.callNext();              //Screen - 2  
        }
    }
    else if(displayScreen2 == 'block'){        //When displaying Screen - 2
        if(clickBtnId == 'prevScreenImg'){
            document.getElementById("screen1Div").innerHTML = '';
            Profession.showProfessionPage();    //Screen - 1
        }
        else{                                   //"#nextScreenImg"
            Profession.playGame();              //Screen - 3
        }
    }
    else if(displayScreen3 == 'block'){         //When displaying Screen - 3
        if(clickBtnId == 'prevScreenImg'){
            if(Profession.questionCnt == 5){
                Profession.initVariables();
                Profession.showQuestion();
            }
            Profession.callNext();    //Screen - 2
        }
    }
    else{                                   //When displaying game over page
        Profession.playGame();                  //Screen - 3
    }
}

Profession.gameOver = function () {
    $("#frame, #acknowledgementDiv").hide();
    $("#finalPage").show();
    $("#prevScreenDiv").css("visibility", "visible");
    $("#nextScreenDiv, #widgesScreen3, #setButton").css("visibility", "hidden");
    Profession.goBack = null;
	document.getElementById("playSound").pause();
	document.getElementById("playSoundInLoop").pause();
}

Profession.callHome = function () {
    document.getElementById("playSound").pause();
    document.getElementById("playSoundInLoop").pause();
    if (Profession.attemptFlag) {
        Profession.calculateScore();
        Profession.attemptFlag = false;
    }
    location.reload();
}

Profession.playAgain = function () {
    $("#finalPage, #acknowledgementDiv").hide();
    $("#gamePage").show();
    $("#soundBtn").css("visibility", "visible");
    document.getElementById("screen1Div").innerHTML = '';
    document.getElementById("nextBtn").classList.remove('blink_me');
    Profession.initVariables();
    Profession.play();
}

Profession.callSound = function () {
    var displayScreen2 = document.getElementById("screen2Div").style.display;
    if(displayScreen2 == 'block'){             //When displaying Screen - 1
        document.getElementById("playSound").src = Utils.Path + "sounds/audios/" + Profession.randomQue.queImgInstrAudio;      
        document.getElementById("playSound").play();
    }
} 

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

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

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