var DingDangDing = {};
DingDangDing.clickCnt = 0;
DingDangDing.question = 0;
DingDangDing.randomNoArr = [];
DingDangDing.slotsArray = [];
DingDangDing.randomObject = 0;
var Utils = {};
Utils.Path = '';
DingDangDing.clickFlag = false;
Utils.mobileDeviceFlag = false;
var questionId = 0,
    startTime = 0,
    scoredMarks = 0,
    totalMarks = 10,
    resId = 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;
    /* if(Utils.mobileDeviceFlag)
        Utils.Path=Android.getMediaPath("DingDangDing"); */
    setTimeout(function () {
        $('#coverPage,#homeAndLogoDiv').show();
        DingDangDing.setImages();
        DingDangDing.init();
    }, 200);
});

DingDangDing.init = function () {
    document.title = DingDangDing.hardcodedata.NameoftheGame;
    document.body.style.backgroundImage = 'url(' + Utils.Path + 'images/' + DingDangDing.hardcodedata['coverPage'] + ')';
    document.getElementById("endGame").innerHTML = DingDangDing.hardcodedata.message;
    $('#gamePage,#lastPage').hide();
    DingDangDing.randomNoArr = DingDangDing.createRandomNoArray(DingDangDing.randomNoArr, DingDangDing.cnt);
    console.log(DingDangDing.randomNoArr);
    if (DingDangDing.hardcodedata['languageFont'] != null)
        setFontFamilyForLang("fonts/" + DingDangDing.hardcodedata['languageFont']);
}

setFontFamilyForLang = function (fontFilePath) {
    var newStyle = "<style>" +
        "@font-face {  " +
        "font-family: 'CustomFontFamily';" +
        "src: url('" + fontFilePath + "') format('truetype');" +
        "}  </style>";
    $("head").append(newStyle);
    $("#endGame").css("font-family", "CustomFontFamily");
}

DingDangDing.setImages = function () {
    document.getElementById('homeImage').src = Utils.Path + "images/Home.png";
    document.getElementById('logoImage').src = Utils.Path + "images/logo.png";
    document.getElementById('play').src = Utils.Path + "images/Play.png";
    document.getElementById('nextButton').src = Utils.Path + "images/Next.png";
    document.getElementById('lastPagehomeimg').src = Utils.Path + "images/replay.png";
}
DingDangDing.createRandomNoArray = function (array, arrlength) {
    var i = 0,
        randomNumber;
    while (i < arrlength) {
        randomNumber = Math.floor(Math.random() * arrlength) + 1;
        while ($.inArray(randomNumber, array) >= 0) {
            randomNumber = Math.floor(Math.random() * arrlength) + 1;
        }
        array.push(randomNumber);
        i++;
    }
    return array;
}
DingDangDing.playGame = function () {
    $('#coverPage').hide();
    $('#gamePage,#homeImage,#nextDiv').show(); //call reset function
    DingDangDing.showDefaultData();
}
DingDangDing.showDefaultData = function () {
    var d = new Date();
    scoredMarks = 0;
    startTime = d.getDate() + "-" + (d.getMonth() + 1) + "-" + d.getFullYear() + " " + d.getHours() + ":" + d.getMinutes() + ":" + d.getSeconds();
    DingDangDing.noOfTimeQuestionAnswered = 0; //reset
    DingDangDing.randomObject = Math.floor(Math.random() * DingDangDing.json.length - 1) + 1;
    document.body.style.backgroundImage = 'url(' + Utils.Path + 'images/' + DingDangDing.json[DingDangDing.randomObject].backgroundImg + ')';
    DingDangDing.createObjectsSlots();
    DingDangDing.setNumberDivs(DingDangDing.cnt);
    DingDangDing.getRandomSlots();
    DingDangDing.placeObjectsRandomly(DingDangDing.randomNoArr[DingDangDing.question]);
}
//slots are created to put objects in it
DingDangDing.createObjectsSlots = function () {
    var slotDiv;
    for (var i = 1; i <= DingDangDing.slotCnt; i++) {
        slotDiv = document.createElement('div'); //numberdivs created
        slotDiv.id = 'slotDiv' + i;
        slotDiv.className = 'nopadding slot col-xs-2 col-md-2 col-lg-2 col-sm-2';
        objectsDiv.appendChild(slotDiv); //change name 
    }
}
DingDangDing.getRandomSlots = function () {
    var i = 0,
        randomNumber;
    while (i < DingDangDing.randomNoArr[DingDangDing.question]) {
        randomNumber = Math.floor(Math.random() * DingDangDing.slotCnt) + 1;
        while ($.inArray(randomNumber, DingDangDing.slotsArray) >= 0) {
            randomNumber = Math.floor(Math.random() * DingDangDing.slotCnt) + 1;
        }
        DingDangDing.slotsArray.push(randomNumber);
        i++;
    }
}
DingDangDing.setNumberDivs = function (count) {
    var numberDiv, UniqueNumbers = [];
    // getting unique and random number shuffle
    UniqueNumbers = DingDangDing.randomNoArr.slice(0);
    UniqueNumbers = shuffleArray(UniqueNumbers);
    for (var i = 0; i < count; i++) {
        numberDiv = document.createElement('div'); //numberdivs created
        numberDiv.id = 'numberDiv' + i;
        numberDiv.className = 'default paraletter col-xs-1 col-md-1 col-lg-1 col-sm-1';
        $(numberDiv).data("numberId", UniqueNumbers[i]); //setting number to div data 	
        numberDiv.setAttribute('onclick', 'DingDangDing.numberClick(this.id)');
        numberDiv.style.backgroundImage = 'url(' + Utils.Path + 'images/Button.png)';
        numberDiv.innerHTML = UniqueNumbers[i];
        numbersDiv.appendChild(numberDiv);
    }
}
DingDangDing.placeObjectsRandomly = function (cnt) {
    var objectImg, objectImage = [],
        randomObjectImage, randomRotate = 0,
        randomRotateDegree = 0;
    objectImage = DingDangDing.json[DingDangDing.randomObject].objectImg.split(',');
    for (var i = 0; i < cnt; i++) {
        randomRotate = Math.floor(Math.random() * DingDangDing.rotate.length);
        randomRotateDegree = Math.floor(Math.random() * DingDangDing.rotateDegree.length);

        objectDiv = document.createElement('div');
        objectDiv.id = 'objectDiv' + i;
        objectDiv.className = 'objectsOnSlots col-xs-12 col-md-12 col-lg-12 col-sm-12';

        objectImg = document.createElement('img');
        objectImg.id = 'objectImg' + i;
        randomObjectImage = Math.floor(Math.random() * objectImage.length);
        objectImg.src = Utils.Path + "images/" + objectImage[randomObjectImage];
        if (DingDangDing.json[DingDangDing.randomObject].classname != null) {
            if (DingDangDing.json[DingDangDing.randomObject].rotate == "true")
                objectImg.className = 'nopadding img-responsive objectImg col-xs-12 col-md-12 col-lg-12 col-sm-12' + DingDangDing.rotate[randomRotate];
            else
                objectImg.className = 'nopadding img-responsive objectImg col-xs-12 col-md-12 col-lg-12 col-sm-12' + DingDangDing.rotateDegree[randomRotateDegree];
        } else
            objectImg.className = 'nopadding img-responsive objectImg col-xs-12 col-md-12 col-lg-12 col-sm-12';
        objectDiv.appendChild(objectImg);
        document.getElementById('slotDiv' + DingDangDing.slotsArray[i]).appendChild(objectDiv);
    }
    $('.objectsOnSlots').attr('onclick', 'DingDangDing.imageClick(this.id)');
}
DingDangDing.numberClick = function (clickedNo) {
    DingDangDing.clickFlag = false;
    var randomCorrectSound, randomWrongSound, numberData;
    document.getElementById('playSound').pause();
    DingDangDing.noOfTimeQuestionAnswered++;
    numberData = $("#" + clickedNo).data("numberId");
    if (numberData == DingDangDing.randomNoArr[DingDangDing.question]) {
        scoredMarks = 10;
        document.getElementById("nextDiv").style.visibility = "hidden";
        $("#" + clickedNo).addClass("animated bounce");
        $('.objectsOnSlots').css({ 'pointer-events': 'none' });
        randomCorrectSound = Math.floor(Math.random() * DingDangDing.correctSounds.length);
        document.getElementById("playSound").src = Utils.Path + "sound/" + DingDangDing.correctSounds[randomCorrectSound];
        document.getElementById('playSound').pause();
        document.getElementById('playSound').play();
        $('.default').css({ 'pointer-events': 'none' });
        //setTimeout(function(){ $('.default').css({'pointer-events':'auto'});},2000);		
        if (DingDangDing.question != DingDangDing.cnt - 1)
            setTimeout(function () { DingDangDing.resetData(); }, 2500);
        else {
            document.getElementById("gamePage").style.display = "none";
            setTimeout(function () {
                document.body.style.backgroundImage = 'url(' + Utils.Path + 'images/deep_space_4k-wide.png)';
                document.getElementById("homeImage").style.display = "none";
                document.getElementById("lastPage").style.display = "block";
            }, 1500);
        }
    } else {
        scoredMarks = 0;
        DingDangDing.clickCnt = 0;
        $("#" + clickedNo).addClass("animated shake");
        $('.objectsOnSlots').css({ 'pointer-events': 'none' });
        $('.default').css({ 'pointer-events': 'none' });
        randomWrongSound = Math.floor(Math.random() * DingDangDing.wrongSounds.length);
        document.getElementById("playSound").src = Utils.Path + "sound/" + DingDangDing.wrongSounds[randomWrongSound];
        document.getElementById('playSound').pause();
        setTimeout(function () {
            duration = document.getElementById("playSound").duration;
            document.getElementById('playSound').play();
            if (DingDangDing.timer) {
                DingDangDing.timer = null;
                clearTimeout(DingDangDing.timer);
            }
            DingDangDing.timer = setTimeout(function () {
                document.getElementById("playSound").src = Utils.Path + "sound/" + DingDangDing.sounds.countagain;
                document.getElementById('playSound').play();
                setTimeout(function () {
                    duration = document.getElementById("playSound").duration;
                    $('.objectsOnSlots').css({ 'pointer-events': 'auto' });
                    $(".objectsOnSlots").removeClass("highlight");
                    $('.default').css({ 'pointer-events': 'auto' });
                    $("#" + clickedNo).removeClass("animated shake");
                    $('.objectsOnSlots').attr('onclick', 'DingDangDing.imageClick(this.id)');
                }, duration * 1000);
            }, duration * 1000);
        }, 300);
    }
    if (DingDangDing.noOfTimeQuestionAnswered == 1) {
        console.log(resId, DingDangDing.randomNoArr[DingDangDing.question], scoredMarks, totalMarks, 1, startTime, label);
        if (Utils.mobileDeviceFlag)
            Android.addScore(resId, DingDangDing.randomNoArr[DingDangDing.question], scoredMarks, totalMarks, 1, startTime, label);
    }
}
//function for gifimage click
DingDangDing.imageClick = function (imgId) {
    if (DingDangDing.noOfTimeQuestionAnswered == 0)
        DingDangDing.clickFlag = true;
    else
        DingDangDing.clickFlag = false;

    DingDangDing.clickCnt++;
    document.getElementById('playSound').pause();
    document.getElementById("playSound").src = Utils.Path + "sound/" + DingDangDing.data[DingDangDing.clickCnt - 1].sound;
    document.getElementById('playSound').play();
    $("#" + imgId).addClass("highlight");
    document.getElementById(imgId).onclick = null;
};

DingDangDing.resetData = function () {
    DingDangDing.clickFlag = false;
    $('.default').css({ 'pointer-events': 'auto' });
    DingDangDing.slotsArray = [];
    DingDangDing.clickCnt = 0;
    $('#objectsDiv,#numbersDiv').empty();
    DingDangDing.question++;
    DingDangDing.showDefaultData();
    $('.default,.objectsOnSlots').css({ 'pointer-events': 'auto' });
    document.getElementById("nextDiv").style.visibility = "visible";
}
DingDangDing.nextQuestion = function () {
    if (DingDangDing.clickFlag == true) {
        console.log(resId, DingDangDing.randomNoArr[DingDangDing.question], scoredMarks, totalMarks, 1, startTime);
        if (Utils.mobileDeviceFlag)
            Android.addScore(resId, DingDangDing.randomNoArr[DingDangDing.question], scoredMarks, totalMarks, 1, startTime);
    }
    document.getElementById('playSound').pause();
    clearTimeout(DingDangDing.timer);
    if (DingDangDing.question != DingDangDing.cnt - 1)
        DingDangDing.resetData();
    else {
        $('#gamePage,#homeImage').hide();
        $('#lastPage').show();
        document.body.style.backgroundImage = 'url(' + Utils.Path + 'images/deep_space_4k-wide.png)';
    }
}

DingDangDing.replay = function () {
    $('#gamePage,#homeImage').show();
    $('#lastPage').hide();
    $("#objectsDiv,#numbersDiv").empty();
    DingDangDing.question = 0;
    DingDangDing.playGame();
}
DingDangDing.goToHome = function () {
    if (DingDangDing.clickFlag == true) {
        console.log(resId, DingDangDing.randomNoArr[DingDangDing.question], scoredMarks, totalMarks, 1, startTime);
        if (Utils.mobileDeviceFlag)
            Android.addScore(resId, DingDangDing.randomNoArr[DingDangDing.question], scoredMarks, totalMarks, 1, startTime);
    }
    location.reload();
}