//startingDate:30-08-2019
var Singular = {};
var Utils = {};
Utils.Path = '';
Utils.mobileDeviceFlag = false;
var questionId = 0,
    startTime = 0,
    scoredMarks = 0,
    totalMarks = 4,
    resId = 0,
    level = 1,
    label = '';
var totalJsonQueCount, wordType = "word",
    ansWord = [];
Singular.questionCtr = 0;
Singular.isPracticeFlag = false;
Singular.soundFlag = false;
uniqueRuleArr = []; //for practice to store 4 rules.
$(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("Singular");  */
    if (Utils.mobileDeviceFlag) {
        Singular.isPracticeFlag = Android.isPractice();
    }
    setTimeout(function () {
        Singular.init();
    }, 100);
});

Singular.init = function () {
    document.title = Object.values(Singular.AcknowledgementPageData)[0];
    $("#coverPage").show();
    $("#gamePage").hide();
    $("#endPage").hide();
    $("#rulePage").hide();
    totalJsonQueCount = Singular.data.length;
    $(".header").not("#logo").css("visibility", "hidden");
    document.body.style.backgroundImage = "url(" + Utils.Path + "images/skin/" + Singular.wordData.coverPage + ")";
    //Singular.initializeVariables();
    Singular.setAllImages();
    Singular.createDivs();
    Singular.createToggleButtons();
    Singular.createAcknowledgementDivs();
    Singular.initializeVariables();
}

Singular.initializeVariables = function () {
    Singular.uniqueArr = [];
    Singular.counter = 0;
    Singular.firstFlag = true;
    Singular.wordArr = [];
    Singular.wordCounter = 0;
    Singular.attemptCtr = 0;

}
Singular.setAllImages = function () {
    document.getElementById("homeImage").src = Utils.Path + "images/skin/Home.png";
    document.getElementById("logoImage").src = Utils.Path + "images/skin/logo.png";
    document.getElementById("playImg").src = Utils.Path + "images/skin/play.png";
    document.getElementById("oneText").innerHTML = Singular.wordData.one;
    document.getElementById("manyText").innerHTML = Singular.wordData.many;
    document.getElementById("skipImg").src = Utils.Path + "images/skin/skip.png";
    document.getElementById("checkImg").src = Utils.Path + "images/skin/check.png";
    document.getElementById("nextImg").src = Utils.Path + "images/skin/Next.png";
    document.getElementById("replayImg").src = Utils.Path + "images/skin/PlayAgain.png";
    document.getElementById("creditImg").src = Utils.Path + "images/skin/credit.png";
    document.getElementById("gameOver").innerHTML = Singular.wordData.gameOver;
    document.getElementById("oneImg").src = Utils.Path + "images/skin/one.png";
    document.getElementById("manyImg").src = Utils.Path + "images/skin/many.png";
    document.getElementById("soundImg").src = Utils.Path + "images/skin/sound.png";


}

Singular.createDivs = function () {
    var parentDiv, i, outerDiv, wordDiv, buttonDiv, oneDiv, manyDiv, container;
    parentDiv = document.getElementById("wordAndButton");
    oneDiv = document.getElementById("oneWord");
    manyDiv = document.getElementById("manyWord");

    for (i = 1; i <= 4; i++) {

        container = document.createElement("DIV");
        container.setAttribute("id", "container" + i);
        container.setAttribute("class", "containers col-xs-6 col-md-6 col-lg-6 col-sm-6");
        if (i > 2)
            container.style.marginTop = "5vh";
        parentDiv.appendChild(container);

        outerDiv = document.createElement("DIV");
        outerDiv.setAttribute("id", "outerDiv" + i);
        outerDiv.setAttribute("class", "outers nopadding col-xs-12 col-md-12 col-lg-12 col-sm-12");
        container.appendChild(outerDiv);

        wordDiv = document.createElement("DIV");
        wordDiv.setAttribute("id", "wordDiv" + i);
        wordDiv.setAttribute("class", "wordDivs nopadding col-xs-10 col-md-10 col-lg-10 col-sm-10 col-xs-offset-1 col-md-offset-1 col-lg-offset-1 col-sm-offset-1");
        wordDiv.style.backgroundImage = "url(" + Utils.Path + "images/skin/text_box.png";
        outerDiv.appendChild(wordDiv);

        buttonDiv = document.createElement("DIV");
        buttonDiv.setAttribute("id", "buttonDiv" + i);
        buttonDiv.setAttribute("class", "buttonDivs col-xs-12 col-md-12 col-lg-12 col-sm-12");
        outerDiv.appendChild(buttonDiv);

        oneWordDiv = document.createElement("DIV");
        oneWordDiv.setAttribute("id", "oneWord" + i);
        oneWordDiv.setAttribute("class", "oneWords  col-xs-12 col-md-12 col-lg-12 col-sm-12");
        oneDiv.appendChild(oneWordDiv);

        manyWordDiv = document.createElement("DIV");
        manyWordDiv.setAttribute("id", "manyWord" + i);
        manyWordDiv.setAttribute("class", "manyWords  col-xs-12 col-md-12 col-lg-12 col-sm-12");
        manyDiv.appendChild(manyWordDiv);



        // span2 = document.createElement("SPAN");
        // span2.setAttribute("id", "secondSpan" + i);
        // span2.setAttribute("class", "many");
        // $(span2).text("MANY");
        // span2.setAttribute("onclick", "Singular.toggle();");
        // div.appendChild(span2);



        // 	onDiv = document.createElement("DIV");
        // 	onDiv.setAttribute("id", "onDiv" + i);
        // 	onDiv.setAttribute("class", "onDivs col-xs-5 col-md-5 col-lg-5 col-sm-5");
        // 	buttonDiv.appendChild(onDiv);

        // 	offDiv = document.createElement("DIV");
        // 	offDiv.setAttribute("id", "offDiv" + i);
        // 	offDiv.setAttribute("class", "offDivs col-xs-5 col-md-5 col-lg-5 col-sm-5 col-xs-offset-1 col-md-offset-1 col-lg-offset-1 col-sm-offset-1");
        // 	buttonDiv.appendChild(offDiv);
    }
}

Singular.createToggleButtons = function () {
    var i, buttonDiv;

    for (i = 1; i <= 4; i++) {
        buttonDiv = document.getElementById("buttonDiv" + i);

        label1 = document.createElement("LABEL");
        label1.setAttribute("id", "label" + i);
        label1.setAttribute("class", "switch");
        buttonDiv.appendChild(label1);

        input = document.createElement("INPUT");
        input.setAttribute("id", "togBtn" + i);
        input.setAttribute("type", "checkbox");
        label1.appendChild(input);

        div = document.createElement("DIV");
        div.setAttribute("class", "slider round");
        div.setAttribute("onclick", "Singular.toggle(this);");
        div.setAttribute("id", "toggle" + i);
        label1.appendChild(div);

        span1 = document.createElement("SPAN");
        span1.setAttribute("id", "firstSpan" + i);
        span1.setAttribute("class", "one");
        $(span1).text(Singular.wordData.one);
        div.appendChild(span1);
    }
    Singular.shuffleToggles();
}

// Singular.onPlayClick = function () {
// 	if (Singular.isPracticeFlag)
// 		Singular.playGame();
// 	else
// 		Singular.showRules();
// }
Singular.showRules = function () {
    $("#coverPage").hide();
    $("#rulePage").show();
    $("#endPage").hide();
}

Singular.getRuleNumber = function (radioId) {
    Singular.rule = document.getElementById(radioId).getAttribute("ruleNo");
    $("#goImg").css("pointer-events", "auto");
    $("#goImg").css("opacity", 1);

}

Singular.playGame = function () {
    $("#coverPage").hide();
    $("#rulePage").hide();
    $("#gamePage").show();
    $(".header").css("visibility", "visible");
    Singular.showPairs();
}

Singular.showPairs = function () {

    var i, rno;
    document.body.style.backgroundImage = "url(" + Utils.Path + "images/skin/Bg.png";
    Singular.questionCtr++;
    $("#learnDiv").show();
    $("#questionDiv").hide();
    $("#endPage").hide();
    // if (Singular.isPracticeFlag) {
    // 	for (i = 0; i < 4; i++) {
    // 		if (i < 2)
    // 			Singular.rule = i;
    // 		else {
    // 			Singular.rule = Math.floor(Math.random() * Singular.data.length - 2) + 2;
    // 			while (uniqueRuleArr.includes(Singular.rule))
    // 				Singular.rule = Math.floor(Math.random() * Singular.data.length - 2) + 2;
    // 		}
    // 		uniqueRuleArr.push(Singular.rule);
    // 		rno = Math.floor(Math.random() * Singular.data[Singular.rule].list.length);
    // 		Singular.uniqueArr.push(rno);
    // 	}
    // 	Singular.showQuestion();
    // }
    // else {

    for (i = 0; i < 4; i++) {
        rno = Math.floor(Math.random() * Singular.data.length);
        while (Singular.uniqueArr.includes(rno))
            rno = Math.floor(Math.random() * Singular.data.length);
        Singular.uniqueArr.push(rno);
        uniqueRuleArr.push(Singular.rule);
    }
    if (Singular.isPracticeFlag) {
        Singular.showQuestion();

    } else
        Singular.playWords(Singular.uniqueArr[Singular.counter]);
}
// }
Singular.playWords = function (rno) {
    if (Singular.firstFlag) {
        document.getElementById("playSound").src = Utils.Path + "sounds/instructions/" + Singular.wordData.oneSound;
    } else {
        document.getElementById("playSound").src = Utils.Path + "sounds/instructions/" + Singular.wordData.manySound;
    }
    document.getElementById("playSound").play();
    Singular.playOneTime = setTimeout(function () {


        if (Singular.firstFlag) {
            Singular.wordCounter++;
            document.getElementById("playSound").src = Utils.Path + "sounds/" + Singular.data[rno].oneSound;
            console.log(Singular.wordCounter);
            document.getElementById("oneWord" + Singular.wordCounter).innerHTML = Singular.data[rno].one;
        } else {
            document.getElementById("playSound").src = Utils.Path + "sounds/" + Singular.data[rno].manySound;
            document.getElementById("manyWord" + Singular.wordCounter).innerHTML = Singular.data[rno].many;
        }
        document.getElementById("playSound").play();
        if (Singular.firstFlag) {
            Singular.firstFlag = false;
            Singular.playManyTime = setTimeout(function () {
                Singular.playWords(rno);
            }, 2500);
        } else {
            if (Singular.counter < 3) {
                Singular.showPairTime = setTimeout(function () {
                    // document.getElementById("oneWord").innerHTML = "";
                    // document.getElementById("manyWord").innerHTML = "";
                    Singular.firstFlag = true;
                    Singular.counter++;
                    Singular.playWords(Singular.uniqueArr[Singular.counter]);
                }, 2500);

            } else {
                setTimeout(function () {
                    Singular.showQuestion();
                }, 2500);
            }
        }
    }, 1500);

}

Singular.showQuestion = function () {

    var i, d, counter = 1,
        rnoArr = [];
    clearTimeout(Singular.showPairTime);
    clearTimeout(Singular.playOneTime);
    clearTimeout(Singular.playManyTime);
    d = new Date();
    startTime = d.getDate() + "-" + (d.getMonth() + 1) + "-" + d.getFullYear() + " " + d.getHours() + ":" + d.getMinutes() + ":" + d.getSeconds();

    document.getElementById("playSound").pause();
    // console.log(Singular.uniqueArr);
    // Singular.shuffle(Singular.uniqueArr);
    // console.log(Singular.uniqueArr);
    $("#learnDiv").hide();
    $("#questionDiv").show();
    for (i = 0; i <= 3; i++) {
        randomWord = Math.floor(Math.random() * 2);
        if (randomWord) {
            Singular.wordArr.push(Singular.data[Singular.uniqueArr[i]].one);
            document.getElementById("wordDiv" + (i + 1)).setAttribute("word", "one");
        } else {
            Singular.wordArr.push(Singular.data[Singular.uniqueArr[i]].many);
            document.getElementById("wordDiv" + (i + 1)).setAttribute("word", "many");
        }
    }
    console.log(Singular.wordArr);
    //Singular.shuffle(Singular.wordArr)
    for (i = 1; i <= 4; i++) {
        document.getElementById("wordDiv" + i).innerHTML = Singular.wordArr[i - 1];
    }
    console.log(rnoArr);
    if (Singular.soundFlag == false) {
        document.getElementById("playSound").src = Utils.Path + "sounds/instructions/instruction.mp3";
        document.getElementById("playSound").play();
        Singular.soundFlag = true;
    }

    // for (i = 0; i < Singular.uniqueArr.length; i++) {
    // 	document.getElementById("wordDiv" + counter).innerHTML = Singular.data[Singular.uniqueArr[i]].one;
    // 	document.getElementById("wordDiv" + counter).setAttribute("word", "one");
    // 	counter++;
    // 	document.getElementById("wordDiv" + counter).innerHTML = Singular.data[Singular.uniqueArr[i]].many;
    // 	document.getElementById("wordDiv" + counter).setAttribute("word", "many");
    // 	counter++;
    // }
    // $(".onDivs").text("one");
    // $(".offDivs").text("many");

    //Singular.placeImageInRandomPlaces();
}
Singular.toggle = function (element) {
    clearInterval(Singular.noResponseTimer);
    clearTimeout(Singular.timeOut);
    document.getElementById("playSound").pause();
    document.getElementById("checkImg").style.pointerEvents = "auto";
    //Singular.startTimer();

    if ($(element).children()[0].className == "one") {
        $(element).children()[0].textContent = Singular.wordData.many;
        //$(element).children()[0].prop("data-click-state", "0");
        $(element).children().removeClass('one')
        $(element).children().addClass('many')
        //if (Singular.clickedFlag == false) {
        $(element).css("background-color", "#1e8cea");
        $(element).addClass("transformClass");
        //document.getElementById(element).classList.add(".slider:before");
        //document.querySelector("#"+element+"::-webkit-scrollbar-thumb:vertical").style.background
        //$(element).parent().text = "$(element):before {transform:translateX(8.5vw)";
        //'<style>input:checked + .slider:before{transform:translateX(8.5vw);}</style>';
        //$(element).before().css("transform", "translateX(8.5vw)");
        $(element).parent().append('<style>' + ("#" + element.id) + ':before{transform:translateX(8.5vw)!important;}</style>');

        //};
    } else {
        $(element).children()[0].textContent = Singular.wordData.one;
        //$(element).children()[0].prop("data-click-state", "1");
        $(element).children().removeClass('many')
        $(element).children().addClass('one')
        //if (Singular.clickedFlag == false) {
        $(element).css("background-color", "#4b5258");
        //'<style>input:checked + .slider:before{transform:translateX(8.5vw);}</style>';
        //$(element).before().css("transform", "translateX(8.5vw)");
        $(element).parent().append('<style>' + ("#" + element.id) + ':before{transform:none!important;}</style>');
        //}
    }

}

Singular.checkAnswer = function () {
    var i;
    ansWord = [];
    clearInterval(Singular.noResponseTimer);
    clearTimeout(Singular.timeOut);
    document.getElementById("playSound").pause();
    Singular.correctCounter = 0;
    Singular.attemptCtr++;
    //$(".switch ").css("pointer-events", "none");
    $("#checkImg").css("pointer-events", "none");
    $(".buttonDivs").css("pointer-events", "none");
    for (i = 1; i <= 4; i++) {
        if (document.getElementById("wordDiv" + i).getAttribute("word") == document.getElementById("firstSpan" + i).className) {
            $("#wordDiv" + i).css("color", "green");
            Singular.correctCounter++;
            scoredMarks = Singular.correctCounter;
            ansWord.push(Singular.wordArr[i - 1]);

        } else {
            document.getElementById("playSound").src = Utils.Path + "sounds/instructions/Try_again.mp3";
            $("#wordDiv" + i).css("color", "red");
            scoredMarks = Singular.correctCounter;
            if (Singular.attemptCtr > 1) {
                document.getElementById("playSound").src = Utils.Path + "sounds/instructions/wrongSoundAksharkhadi.mp3";
                $("#nextDiv").addClass("blink_me");
                $("#soundImg").css("pointer-events", "none");

                // Singular.nextQuestionTimer = setTimeout(function () {
                // 	// console.log(resId, questionId, scoredMarks, totalMarks, level, startTime, label);
                // 	// if (Utils.mobileDeviceFlag)
                // 	// 	Android.addScore(resId, questionId, scoredMarks, totalMarks, level, startTime, label);
                // 	Singular.nextQuestion();
                // }, 2000);
            } else {
                setTimeout(function () {
                    $("#checkImg").css("pointer-events", "auto");
                    $(".buttonDivs").css("pointer-events", "auto");
                    $(".wordDivs").css("color", "black");
                }, 2000);
            }
        }
    }

    if (Singular.correctCounter > 3) {
        $("#nextDiv").addClass("blink_me");
        document.getElementById("playSound").src = Utils.Path + "sounds/instructions/thats_right.mp3";
        Singular.correctAns++;
        $("#soundImg").css("pointer-events", "none");
        scoredMarks = 4;
        if (Singular.attemptCtr > 1) {
            $("#checkImg").css("pointer-events", "none");
            //console.log(resId, questionId, scoredMarks, totalMarks, level, startTime, label);
            // if (Utils.mobileDeviceFlag)
            // 	Android.addScore(resId, questionId, scoredMarks, totalMarks, level, startTime, label);
            // Singular.nextQuestionTimer = setTimeout(function () {
            // 	Singular.nextQuestion();
            // }, 2000);
        }

    }
    document.getElementById("playSound").play();
}

Singular.nextQuestion = function () {
    clearTimeout(Singular.nextQuestionTimer);
    $("#nextDiv").removeClass("blink_me");
    $("#checkImg").css("pointer-events", "auto");
    $(".buttonDivs").css("pointer-events", "auto");
    $("#soundImg").css("pointer-events", "auto");
    console.log(resId, questionId, scoredMarks, totalMarks, level, startTime, label);
    if (Utils.mobileDeviceFlag) {
        Android.addScore(resId, questionId, scoredMarks, totalMarks, level, startTime, label);
        for (i = 0; i < ansWord.length; i++) {
            Android.addLearntData(ansWord[i], totalJsonQueCount, wordType);
        }
    }
    $(".wordDivs ").css("color", "black");
    $(".buttonDivs").empty();
    Singular.createToggleButtons();
    if (Singular.questionCtr < 3) {
        // for (var i = 0; i < 4; i++) {
        // 	document.getElementsByTagName('span')[i].className = 'one';
        // 	document.getElementsByTagName('span')[i].innerHTML = 'ONE';
        // 	document.getElementsByClassName("slider round")[i].style.backgroundColor = 'rgb(202, 34, 34)'
        // }
        Singular.initializeVariables();
        $(".oneWords").text("");
        $(".manyWords").text("");
        uniqueRuleArr = [];
        Singular.showPairs();


    } else {
        Singular.gameOver();
    }
}
Singular.gameOver = function () {
    $("#gamePage").hide();
    $("#endPage").show();
}

Singular.callHome = function () {
    if (Singular.attemptCtr) {
        console.log(resId, questionId, scoredMarks, totalMarks, level, startTime, label);
        if (Utils.mobileDeviceFlag) {
            Android.addScore(resId, questionId, scoredMarks, totalMarks, level, startTime, label);
            for (i = 0; i < ansWord.length; i++) {
                Android.addLearntData(ansWord[i], totalJsonQueCount, wordType);
            }
        }
    }
    location.reload();
}

Singular.playAgain = function () {
    Singular.questionCtr = 0;
    Singular.initializeVariables();
    $(".oneWords").text("");
    $(".manyWords").text("");
    $("#acknowledgementDiv").hide();
    $("#endPage").hide();
    $("#gamePage").show();
    if (Singular.isPracticeFlag)
        Singular.playGame();
    else
        Singular.showPairs();

}

Singular.shuffleToggles = function () {
    var i, numArr = [];
    for (i = 0; i < 2; i++) {
        rno = Math.floor(Math.random() * 4 + 1);
        while (numArr.includes(rno))
            rno = Math.floor(Math.random() * 4 + 1);
        toggle = document.getElementById("toggle" + rno);
        Singular.clickedFlag = false;
        Singular.toggle(toggle);
    }
}

Singular.onNextClick = function () {
    if (!Singular.attemptCtr)
        scoredMarks = -1;
    Singular.nextQuestion();

}








//called from Countinggame.createDiv function. places the created divs @ random positions. 
Singular.placeImageInRandomPlaces = function () {

    var containerW = $("#questionDiv").width();
    var containerH = $("#questionDiv").height();
    var positions = [];
    $(".outerDivs").each(function () {
        var coords = {
            w: $(this).outerWidth(true),
            h: $(this).outerHeight(true)
        };

        var success = false;
        while (!success) {
            coords.x = parseInt(Math.random() * (containerW - coords.w));
            coords.y = parseInt(Math.random() * (containerH - coords.h));
            var success = true;
            $.each(positions, function () {
                if (coords.x <= (this.x + this.w) &&
                    (coords.x + coords.w) >= this.x &&
                    coords.y <= (this.y + this.h) &&
                    (coords.y + coords.h) >= this.y) {
                    success = false;
                }
            });
        }
        positions.push(coords);
        $(this).css({ 'top': coords.y + 'px', 'left': coords.x + 'px' });
    });
}

Singular.shuffle = function (array) {
    var i, j, temp;
    for (i = array.length - 1; i > 0; i--) {
        j = Math.floor(Math.random() * (i + 1));
        temp = array[i];
        array[i] = array[j];
        array[j] = temp;
    }
    return array;
}

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

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

}

Singular.playInstruction = function () {
    document.getElementById("playSound").src = Utils.Path + "sounds/instructions/instruction.mp3";
    document.getElementById("playSound").play();

}