var Sequence = {};
var Utils = {};
Utils.Path = '';
Utils.mobileDeviceFlag = false;
var questionId = 0,
    startTime = 0,
    scoredMarks = 0,
    totalMarks = 10,
    resId = 0,
    label = "";

Sequence.uniqueNumArr = [1, 2, 3, 4];
Sequence.imageArr = [];
Sequence.no = 4;
Sequence.noOfTimeQuestionAnswered = 0;
Sequence.uniqueRandomNumber = [];
Sequence.dragFlag = false;
Sequence.isCheckedFlag = false;
Sequence.ctr = 0;

//function for loader
$(document).ready(function () {
    document.title = Sequence.hardCodedData.NameoftheGame;
    $(".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("RailGadi");  */
    var randomSound = Math.floor(Math.random() * (Sequence.startTrainSound.length));
    document.getElementById('playSound').src = Utils.Path + 'sounds/' + Sequence.startTrainSound[randomSound];
    document.getElementById('playSound').play();
    setTimeout(function () {
        document.body.style.backgroundImage = "url(" + Utils.Path + Sequence.coverImage.imgname + ")";
        document.getElementById('coverpage').style.display = "block";
        document.getElementById('gamapage').style.display = "none";
        document.getElementById('endPage').style.display = "none";
        document.getElementById("home").style.display = "none";
        Sequence.setImages();
        Sequence.arrangeSequence();
    }, 300);
});

//function to set images
Sequence.setImages = function () {
    document.getElementById('logo').src = Utils.Path + "images/logo.png";
    document.getElementById('play').src = Utils.Path + "images/Play.png";
    document.getElementById('home').src = Utils.Path + "images/Home.png";
    document.getElementById("check").src = Utils.Path + "images/Done.png";
    document.getElementById("nextImage").src = Utils.Path + "images/Next.png";
    document.getElementById("normalSignal").src = Utils.Path + "images/Man_Normal.png";
    document.getElementById("trackImg").src = Utils.Path + "images/track1.png";
    document.getElementsByTagName("marquee")[0].stop();
    document.getElementById("replayImg").src = Utils.Path + "images/replay.png";
    document.getElementById("gameOver").innerHTML = Sequence.hardCodedData.gameOver;
}

function shuffleArray(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;
}

//this function will execute on play button
Sequence.playGame = function () {
    document.body.style.backgroundImage = "url('" + Utils.Path + "images/Bg-image-without-railway-track.png')";
    document.getElementById('gamapage').style.display = "block";
    document.getElementById('coverpage').style.display = "none";
    document.getElementById('home').style.display = "block";
    document.getElementById('logoDiv').style.display = "block";
    document.getElementById('play').style.display = "none";
    document.getElementById('checkDiv').style.visibility = "visible";
    document.getElementById("cloud").src = Utils.Path + "images/skyClouds.png";
    document.getElementsByTagName("marquee")[0].start();
}

//to create no of divs
Sequence.createDivs = function (parentDiv, numberOfDivs, idName, classname) {
    var temp, dropDiv;
    temp = Math.floor(10 / numberOfDivs);
    for (var i = 1; i <= numberOfDivs; i++) {
        dropDiv = document.createElement("div");
        dropDiv.setAttribute("id", "" + idName + '' + i);
        dropDiv.setAttribute("class", "" + classname + "col-xs-" + temp + " col-md-" + temp + " col-lg-" + temp + " col-sm-" + temp);
        parentDiv.appendChild(dropDiv);
    }
}

Sequence.startTrain = function () {
    var randomSound;
    Sequence.right = -55;
    answerDiv = document.getElementById('answerDiv');
    answerDiv.style.right = -55;
    randomSound = Math.floor(Math.random() * (Sequence.startTrainSound.length));
    document.getElementById('playSound').src = Utils.Path + 'sounds/' + Sequence.startTrainSound[randomSound];
    document.getElementById('playSound').play();
    if (Sequence.myVar1) {
        Sequence.myVar1 = null;
        clearInterval(Sequence.myVar1);
    }
    Sequence.myVar1 = setInterval(myTimer, 20);

    function myTimer() {
        document.getElementById('checkDiv').style.visibility = "hidden";
        document.getElementById('nextDiv').style.display = "none";
        if (Sequence.right == 8) {
            clearInterval(Sequence.myVar1);
            document.getElementById('checkDiv').style.visibility = "visible";
            document.getElementById('nextDiv').style.display = "block";
            document.getElementById('normalSignalDiv').style.display = "block";
        }
        answerDiv.style.right = (Sequence.right + 1) + '%';
        Sequence.right++;
    }
}

//function to arrange the sequence
Sequence.arrangeSequence = function () {
    clearInterval(Sequence.myVar1);
    scoredMarks = 0;
    Sequence.dragFlag = false;
    Sequence.isCheckedFlag = false;
    var tempArray = [];
    var sequenceImg, trainImg, subDiv, engineImg, randomIndex, answerDiv, engineDiv;
    Sequence.result = false;
    var d = new Date();
    startTime = d.getDate() + "-" + (d.getMonth() + 1) + "-" + d.getFullYear() + " " + d.getHours() + ":" + d.getMinutes() + ":" + d.getSeconds();
    Sequence.noOfTimeQuestionAnswered = 0;
    Sequence.startTrain();
    Sequence.imageArr = [];
    document.getElementById('answerDiv').innerHTML = "";
    answerDiv = document.getElementById('answerDiv');

    engineDiv = document.createElement("div");
    engineDiv.setAttribute("id", "engineDiv");
    engineDiv.setAttribute("class", "noPadding drop0Class col-xs-3 col-md-3 col-lg-3 col-sm-3");
    document.getElementById("answerDiv").appendChild(engineDiv);

    engineImg = document.createElement("img");
    engineImg.setAttribute("id", "engineImg");
    engineImg.setAttribute("class", "img-responsive images noPadding");
    engineImg.setAttribute("src", Utils.Path + "images/Dubblesiren.gif");
    $("#engineDiv").append(engineImg);

    Sequence.createDivs(answerDiv, 4, 'drop', '');
    for (var i = 1; i <= Sequence.no; i++)
        $("#drop" + i).addClass("dropClass");

    tempArray = Sequence.uniqueNumArr.slice();
    Sequence.uniqueArr = shuffleArray(tempArray);
    Sequence.result = Sequence.checkTwoArrays(Sequence.uniqueNumArr, Sequence.uniqueArr);
    while (Sequence.result) {
        $('#answerDiv').empty();
        clearInterval(Sequence.myVar1);
        Sequence.arrangeSequence();
        return 0;
        break;
    }
    if (!Sequence.result) {
        Sequence.addInsideImages();
    }
}
Sequence.addInsideImages = function () {
    Sequence.imageArr = Sequence.Images.slice();
    randomIndex = Sequence.uniqueImages();
    if (Sequence.uniqueRandomNumber.length >= Sequence.imageArr.length) {
        Sequence.uniqueRandomNumber = [];
        randomIndex = Sequence.uniqueImages();
    }
    for (var i = 1; i <= Sequence.no; i++) {
        subDiv = document.createElement("div");
        subDiv.setAttribute("id", "subDiv" + i);
        subDiv.setAttribute("class", "innerDivClass subDivClass col-xs-12 col-md-12 col-lg-12 col-sm-12");
        document.getElementById("drop" + i).appendChild(subDiv);
        $("#subDiv" + i).data('ans', i);

        innerDiv = document.createElement("div");
        innerDiv.setAttribute("id", "innerDiv" + i);
        innerDiv.setAttribute("class", "innerDivClass col-xs-12 col-md-12 col-lg-12 col-sm-12");
        document.getElementById("subDiv" + i).appendChild(innerDiv);
        $("#innerDiv" + i).data('answer', Sequence.uniqueArr[i - 1]);

        trainImg = document.createElement("img");
        trainImg.setAttribute("id", "trainImg" + i);
        trainImg.setAttribute("class", "img-responsive images noPadding");
        trainImg.setAttribute("src", Utils.Path + "" + Sequence.trainImages);
        $("#drop" + i).append(trainImg);

        sequenceImg = document.createElement("img");
        sequenceImg.setAttribute("id", "sequenceImg" + i);
        sequenceImg.setAttribute("class", "img-responsive images noPadding");
        sequenceImg.setAttribute("src", Utils.Path + Sequence.imageArr[randomIndex].imgname + Sequence.uniqueArr[i - 1] + Sequence.imageArr[randomIndex].imgtype);
        $("#innerDiv" + i).append(sequenceImg);

        $("#innerDiv" + i).draggable();
        $("#innerDiv" + i).draggable({ revert: "invalid" });
        $("#innerDiv" + i).data("dragFlag", 1)
        $("#subDiv" + i).data("hasChild", 1);
        $("#subDiv" + i).droppable({
            drop: Sequence.onDrop,
            dragover: allowDrop
        });
    }
    questionId = Sequence.imageArr[randomIndex].id;
}

Sequence.checkTwoArrays = function (arr1, arr2) {
    if (arr1.length !== arr2.length)
        return false;
    for (var i = arr1.length; i--;) {
        if (arr1[i] !== arr2[i])
            return false;
    }
    return true;
};

Sequence.uniqueImages = function () {
    var randomIndex = Math.floor(Math.random() * (Sequence.imageArr.length));
    while (Sequence.uniqueRandomNumber.includes(randomIndex))
        randomIndex = Math.floor(Math.random() * (Sequence.imageArr.length));
    Sequence.uniqueRandomNumber.push(randomIndex);
    return randomIndex;
}

//Function to change Images
Sequence.nextImage = function () {
    Sequence.ctr++;
    clearInterval(Sequence.myVar1);
    if (Sequence.isCheckedFlag == false && Sequence.dragFlag == true) {
        console.log(resId, questionId, scoredMarks, totalMarks, 1, startTime, label);
        if (Utils.mobileDeviceFlag)
            Android.addScore(resId, questionId, scoredMarks, totalMarks, 1, startTime, label);
    }
    if (Sequence.ctr < 5) {
        Sequence.right = -55;
        document.getElementById('playSound').pause();
        document.getElementById("normalSignal").src = Utils.Path + "images/Man_Normal.png";
        document.getElementById("engineImg").src = Utils.Path + "images/Dubblesiren.gif";
        document.getElementById('normalSignal').style.display = "block";
        document.getElementById('nextDiv').style.pointerEvents = "auto";
        document.getElementById('checkDiv').style.pointerEvents = "auto";
        Sequence.arrangeSequence();
    }
    else
        Sequence.showLastPage();
}
Sequence.showLastPage = function () {
    $("#gamapage").hide();
    $("#endPage").show();
}

Sequence.playAgain = function () {
    $("#gamapage").show();
    $("#endPage").hide();
    Sequence.ctr = 0;
    Sequence.right = -55;
    document.getElementById('playSound').pause();
    document.getElementById("normalSignal").src = Utils.Path + "images/Man_Normal.png";
    document.getElementById("engineImg").src = Utils.Path + "images/Dubblesiren.gif";
    document.getElementById('normalSignal').style.display = "block";
    document.getElementById('nextDiv').style.pointerEvents = "auto";
    document.getElementById('checkDiv').style.pointerEvents = "auto";
    Sequence.arrangeSequence();
}
//this function is executed when element is dropped
Sequence.onDrop = function (event, ui) {
    var src, srcDiv, dst, dstDiv;
    Sequence.dragFlag = true;
    document.getElementById('playSound').src = Utils.Path + 'sounds/DESK_BELL.mp3';
    document.getElementById('playSound').play();
    if ($(ui.draggable).data("dragFlag") == 1 && $(this).data("hasChild") == 1) {
        src = ui.draggable;
        srcDiv = $(src).parent();
        dstDiv = $(this);
        dst = $(dstDiv).children();
        $(dstDiv).append(src);
        $(srcDiv).append(dst);
    } else
        ui.draggable.draggable('option', 'revert', true);

    ui.draggable.position({
        at: "center",
        of: this
    });
    ui.draggable.animate({
        top: "0px",
        left: "0px"
    });
}

//to check Answer
Sequence.checkAnswer = function () {
    var randomSound, soundDuration, answerDiv, counter = 0;
    Sequence.isCheckedFlag = true;
    Sequence.right = 9;
    answerDiv = document.getElementById('answerDiv');
    Sequence.noOfTimeQuestionAnswered++;
    for (var i = 0; i < Sequence.no; i++) {
        if ($('#subDiv' + i).find('div').data('answer') === $('#subDiv' + i).data('ans'))
            counter++;
    }
    if (counter == Sequence.no) {
        $('#nextDiv').hide();
        scoredMarks = 10;
        $('.subDivClass').children().draggable('disable');
        randomSound = Math.floor(Math.random() * (Sequence.correctAns.length));

        document.getElementById('playSound').src = Utils.Path + 'sounds/' + Sequence.correctAns[randomSound];
        setTimeout(function () {
            soundDuration = document.getElementById('playSound').duration;
            document.getElementById('playSound').play();
            document.getElementById("normalSignal").src = Utils.Path + "images/Man_Happy.png";
            document.getElementById('nextDiv').style.pointerEvents = "none";
            document.getElementById('checkDiv').style.pointerEvents = "none";
            setTimeout(function () {
                Sequence.myVar = setInterval(myTimer, 50);
                document.getElementById('nextDiv').style.display = "none";
                document.getElementById('checkDiv').style.visibility = "hidden";
                document.getElementById('playSound').src = Utils.Path + 'sounds/trainpassing.mp3';
                document.getElementById('playSound').play();
                document.getElementById("engineImg").src = Utils.Path + "images/Dubblesiren.gif";
            }, soundDuration * 1000);
        }, 300);

        function myTimer() {
            if (Sequence.right == 100) {
                clearInterval(Sequence.myVar);
                Sequence.nextImage();
            }
            answerDiv.style.right = (Sequence.right + 1) + '%';
            Sequence.right++;
        }
    } else {
        scoredMarks = 0;
        randomSound = Math.floor(Math.random() * (Sequence.wrongAns.length));
        document.getElementById('playSound').pause();
        document.getElementById('playSound').src = Utils.Path + 'sounds/' + Sequence.wrongAns[randomSound];
        document.getElementById('playSound').play();
        document.getElementById("engineImg").src = Utils.Path + "images/engine.png";
        document.getElementById("normalSignal").src = Utils.Path + "images/Man_Angry.png";
        if (Sequence.timer) {
            Sequence.timer = null;
            clearTimeout(Sequence.timer);
        }
        Sequence.timer = setTimeout(function () {
            document.getElementById("normalSignal").src = Utils.Path + "images/Man_Normal.png";
        }, 2000);
    }
    if (Sequence.noOfTimeQuestionAnswered == 1) {
        console.log(resId, questionId, scoredMarks, totalMarks, 1, startTime);
        if (Utils.mobileDeviceFlag)
            Android.addScore(resId, questionId, scoredMarks, totalMarks, 1, startTime, label);
    }
}

function allowDrop(event) {
    event.preventDefault();
}
Sequence.homeClick = function () {
    if (Sequence.isCheckedFlag == false && Sequence.dragFlag == true) {
        console.log(resId, questionId, scoredMarks, totalMarks, 1, startTime);
        if (Utils.mobileDeviceFlag)
            Android.addScore(resId, questionId, scoredMarks, totalMarks, 1, startTime, label);
    }
    location.reload();
}