var Barakhadi = {};
var Utils = {};
Utils.Path = '';
Utils.mobileDeviceFlag = false;
var questionId = 0,
    startTime = 0,
    scoredMarks = 0,
    totalMarks = 50,
    resId = 0,
    type = "letter";

$(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("Barakhadi"); 
    setTimeout(function() {
        Barakhadi.setAllImages();
        Barakhadi.init();
    }, 200);
});

Barakhadi.setAllImages = function() {

    $('#playGame').prop('src', Utils.Path + 'IMAGES/Barakhadi_play.png');
    $('#scrollLeft').prop('src', Utils.Path + 'IMAGES/previous.png');
    $('#scrollRight').prop('src', Utils.Path + 'IMAGES/next.png');
    $('#Hammer').prop('src', Utils.Path + 'IMAGES/emoticons_02.png');
    $('#FinalOk').prop('src', Utils.Path + 'IMAGES/emoticons_01.png');
    $('#Next').prop('src', Utils.Path + 'IMAGES/Barakhadi_Next.png');
    $('#logo').prop('src', Utils.Path + 'IMAGES/logo.png');
};

Barakhadi.init = function() {
    $('#coverPage').show();
    $('#level1,#home').hide();
    Barakhadi.scrollleftRight = 100, Barakhadi.counter = 0, Barakhadi.answerCounter = 0;
    Barakhadi.arrayOfTopPositions = [], Barakhadi.arrayOfLeftPositions = [];
    Barakhadi.correctCounter = 0;
    Barakhadi.seconds = 0;
    $('#background').css({ 'background-image': 'url(' + Utils.Path + 'IMAGES/' + Barakhadi.hardCodedData['coverPage'] + ')' });
}

Barakhadi.getGameData = function() {
    Barakhadi.words = [];
    $('#level1').show();
    $('#coverPage,#FinalOk').hide();
    $('#background').css({ 'background-image': 'url(' + Utils.Path + 'IMAGES/' + Barakhadi.hardCodedData['BG'] + ')' });
    Barakhadi.words = Barakhadi.wordsData.slice();
    Barakhadi.addLettersToScrollBar();
}

Barakhadi.scroll = function(evt) {
    if (evt == 'scrollLeft')
        Barakhadi.scrollleftRight = Barakhadi.scrollleftRight - 100;
    else if (evt == 'scrollRight')
        Barakhadi.scrollleftRight = Barakhadi.scrollleftRight + 100;
    $('#scrollBar').scrollLeft(Barakhadi.scrollleftRight);
}

Barakhadi.addLettersToScrollBar = function() {
    var div, spanElement;
    $('#Next,#Hammer,#containment-wrapper').hide();
    $('#home').show();
    for (var i = 0; i < Barakhadi.words.length; i++) {
        div = $('<div class="alignInLine text-center"></div>');
        spanElement = $('<span style="cursor:pointer;" class="blink_me">' + Barakhadi.words[i]['suffix'].trim() + '</span>');
        $(div).append(spanElement);
        $(spanElement).on('click', Barakhadi.showCompleteBarakhadi);
        $('#scrollBar').append(div);
    }
}

Barakhadi.searchWord = function(evt) {
    for (var i = 0; i < Barakhadi.words.length; i++) {
        if (Barakhadi.words[i]['suffix'].trim() == $(evt).text().trim()) {
            break;
        }
    }
    Barakhadi.ltrForbarakhadi = Barakhadi.words[i];
    console.log(Barakhadi.ltrForbarakhadi);
}

Barakhadi.showCompleteBarakhadi = function() {
    Barakhadi.gameOpened = false;
    //questionId++;
    var d = new Date();
    startTime = d.getDate() + "-" + (d.getMonth() + 1) + "-" + d.getFullYear() + " " + d.getHours() + ":" + d.getMinutes() + ":" + d.getSeconds();
    Barakhadi.ltrForbarakhadi = 0;
    scoredMarks = 0;
    Barakhadi.searchWord(this);
    Barakhadi.addSpacesForBarakhadi();
    $('#Next,#Hammer').show();
    $('#Hammer').addClass('blink_me');
    $('#scrollbarDiv').hide();
    $('#barakhadiDiv').removeClass('magictime puffIn');
    //Barakhadi.addSoundSource();
    //Barakhadi.playSoundAndHighlight();
    Barakhadi.skipReading();
}

Barakhadi.addSpacesForBarakhadi = function() {
    var div, spanElement, outerDiv, k = 0;
    $('#containment-wrapper').show();
    $('#scrollbarDiv').hide();
    for (var i = 0; i < 2; i++) {
        outerDiv = $('<div style="margin-top:0%;margin-bottom:4%" class="col-lg-12 col-md-12 col-xs-12 col-sm-12"></div>');
        for (var j = 0; j < 6; j++) {
            div = $('<div class="align6InLine text-center col-lg-2 col-md-2 col-xs-2 col-sm-2" ></div>');
            if (k < Barakhadi.ltrForbarakhadi['list'].length) {
                spanElement = $('<span id="space' + k + '" class="trans text-center spaces deviceWiseSize" style="pointer-events:none" >' + Barakhadi.ltrForbarakhadi['list'][k]['word'] + '</span>');
                $(spanElement).data('sound', Utils.Path + 'SOUND/' + Barakhadi.ltrForbarakhadi['list'][k]['sound']);
                $(spanElement).on('click', function() {
                    Barakhadi.playSoundForEachWord($(this));
                });

                $(div).append(spanElement);
                k++;
            }
            $(outerDiv).append(div);
        }
        $('#barakhadiDiv').append(outerDiv);
    }
}

Barakhadi.playSoundForEachWord = function(element) {
        document.getElementById('playSound').src = $(element).data('sound');
        document.getElementById('playSound').play();
    }
    /* 
    Barakhadi.addSoundSource=function(){
    	var source;
    	source=Utils.Path+'SOUND/'+Barakhadi.ltrForbarakhadi['list'][Barakhadi.counter]['sound'];
    	Barakhadi.getDuration(source);
    }; */

Barakhadi.getDuration = function(source) {
    var duration = 0;
    $('#playSound').on('loadedmetadata', function() {
        duration = $('#playSound').prop('duration');
        $('#playSound').unbind('loadedmetadata');
        Barakhadi.playSoundAndHighlight(duration);
    });
    $('#playSound').prop('src', source);
};

Barakhadi.playSoundAndHighlight = function(duration) {
    duration = duration + 1;
    document.getElementById('playSound').play();
    document.getElementById('space' + Barakhadi.counter).style.color = "yellow";
    Barakhadi.timeout = setTimeout(function() {
        document.getElementById('space' + Barakhadi.counter).style.color = "black";
        Barakhadi.counter++;
        document.getElementById('playSound').pause();
        if (Barakhadi.counter < Barakhadi.ltrForbarakhadi['list'].length)
            Barakhadi.addSoundSource();
        else {
            $('#Hammer').hide();
            document.getElementById('playSound').src = Utils.Path + 'SOUND/glassBreak.wav';
            document.getElementById('playSound').play();
            Barakhadi.dropRandomWords();
        }
    }, duration * 1000);
}

Barakhadi.dropRandomWords = function() {
    var noOfWords = 5,
        randomPlace, arrOfRandomPlaces = [],
        arrayOfInfo = [],
        spanElement, xy;
    Barakhadi.answerCounter = 0;
    //noOfWords=Math.floor(Barakhadi.ltrForbarakhadi['list'].length/2);
    $('.spaces').css({ 'border': '3px solid black', 'color': 'green' });
    $('.spaces').css({ 'pointer-events': 'auto' });
    Barakhadi.answerCounter = Barakhadi.ltrForbarakhadi['list'].length - noOfWords;
    for (var i = 0; i < noOfWords; i++) {
        randomPlace = Math.floor(Math.random() * Barakhadi.ltrForbarakhadi['list'].length);
        while ($.inArray(randomPlace, arrOfRandomPlaces) != -1) {
            randomPlace = Math.floor(Math.random() * Barakhadi.ltrForbarakhadi['list'].length);
        }
        arrOfRandomPlaces.push(randomPlace);
        arrayOfInfo.push(Barakhadi.ltrForbarakhadi['list'][randomPlace]);
    }
    for (var i = 0; i < noOfWords; i++) {
        $('#space' + arrOfRandomPlaces[i]).css({ 'color': 'transparent' });
        spanElement = $('<span id="letter' + arrOfRandomPlaces[i] + '" class="letters text-center deviceWiseLetters">' + arrayOfInfo[i]['word'] + '</span>');
        $(spanElement).data('sound', Utils.Path + 'SOUND/' + arrayOfInfo[i]['sound']);
        $(spanElement).draggable({
            cursor: 'move',
            containment: "#containment-wrapper",
            start: function() {
                $(this).data("origPosition", $(this).position());
                Barakhadi.playSoundForEachWord($(this));
            }
        });
        $(spanElement).on('click', function() {
            Barakhadi.playSoundForEachWord($(this));
        });
        $('#containment-wrapper').append(spanElement);
        xy = Barakhadi.getPositions();
        $(spanElement).css({ "position": "absolute", "top": xy[1] + "%", "left": xy[0] + "%" });
        $('#space' + arrOfRandomPlaces[i]).droppable({
            drop: Barakhadi.Handledrop,
            dragover: Barakhadi.allowDrop
        });
    }
    console.log(noOfWords);
    Barakhadi.addbackgroundColours();
    Barakhadi.startTimer();
}

Barakhadi.callHome = function() {
    if (Barakhadi.gameOpened == true) {
        console.log(resId, questionId, scoredMarks, totalMarks, 1, startTime);
        if (Utils.mobileDeviceFlag)
            Android.addScore(resId, questionId, scoredMarks, totalMarks, 1, startTime);
        Barakhadi.gameOpened = false;
    }
    setTimeout(function() {
        location.reload(true);
    }, 200);
}

Barakhadi.clearAllAndShowNext = function() {
    /* $('#responseBoxDiv').show();
    $('#questionMsg').text(Barakhadi.modalData.responseMsg);
    $('#Yes').text(Barakhadi.modalData.yes);
    $('#No').text(Barakhadi.modalData.no); */
    /* clearTimeout(Barakhadi.timeout);
    if(Barakhadi.gameOpened==true)
    {
    	console.log(resId,questionId,scoredMarks,totalMarks,1,startTime);
    	if(Utils.mobileDeviceFlag)
    		Android.addScore(resId,questionId,scoredMarks,totalMarks,1,startTime);
    	Barakhadi.gameOpened=false;
    }
    $('#FinalOk,#containment-wrapper').hide();
    $('#Next').removeClass('blink_me');
    $('#scrollbarDiv').show();
    Barakhadi.counter=0;
    Barakhadi.arrayOfTopPositions=[],Barakhadi.arrayOfLeftPositions=[];
    $('.letters').remove();
    $('#barakhadiDiv').empty();
    $('#Next,#Hammer').hide(); */

}

Barakhadi.Handledrop = function(event, ui) {
    console.log('hi');
    Barakhadi.gameOpened = true;
    var draggedLetter = ui.draggable;
    var droppedSpan = $(this);
    if ($(draggedLetter).text().trim() == $(droppedSpan).text().trim()) {
        Barakhadi.answerCounter++;
        Barakhadi.correctCounter++;
        scoredMarks = scoredMarks + 10;
        $(draggedLetter).draggable('disable');
        $(draggedLetter).css({ 'color': 'green' });
        Barakhadi.startTimer();
        $(draggedLetter).position({
            my: "center center",
            at: "center center",
            of: this
        });
        if (Barakhadi.answerCounter == Barakhadi.ltrForbarakhadi['list'].length) {
            document.getElementById('playSound').src = Utils.Path + 'SOUND/welldone.mp3';
            document.getElementById('playSound').play();
            $('#FinalOk').show();
            $('#Next').css({ 'visibility': 'hidden' });
            setTimeout(function() {
                Barakhadi.scoreFunction();
            }, 3000);
        }
    } else {
        ui.draggable.animate(ui.draggable.data("origPosition"), "slow");
        document.getElementById('playSound').src = Utils.Path + 'SOUND/BuzzerWrong.mp3';
        document.getElementById('playSound').play();
    }
}

Barakhadi.getPositions = function() {
    var y = Math.floor((Math.random() * 35) + 40);
    var x = Math.floor(Math.random() * 75);
    while ($.inArray(((y) || (y + 1) || (y + 2) || (y - 1) || (y - 2) || (y - 3)), Barakhadi.arrayOfTopPositions) >= 0) {
        y = Math.floor((Math.random() * 35) + 40);

    }
    while (($.inArray(((x) || (x + 1) || (x + 2) || (x - 1) || (x - 2) || (x - 3)), Barakhadi.arrayOfLeftPositions) >= 0)) {
        x = Math.floor(Math.random() * 75);
    }

    Barakhadi.arrayOfTopPositions.push(y);
    Barakhadi.arrayOfLeftPositions.push(x);
    return [x, y];
}
Barakhadi.startTimer = function() {
    clearTimeout(Barakhadi.soundTimer);
    if (Barakhadi.noResponseTimer) {
        clearInterval(Barakhadi.noResponseTimer);
        Barakhadi.noResponseTimer = null;
        Barakhadi.seconds = 0;
    }
    Barakhadi.noResponseTimer = setInterval(function() {
        Barakhadi.seconds++;
        if (Barakhadi.seconds >= 7) {
            clearTimeout(Barakhadi.soundTimer);
            Barakhadi.soundTimer = null;
            document.getElementById("playSound").src = Utils.Path + 'SOUND/INSTRUCTIONS/please_ans_the_ques.mp3';
            document.getElementById("playSound").play();
            clearInterval(Barakhadi.noResponseTimer);
            if (Barakhadi.timeOut) {
                clearTimeout(Barakhadi.timeOut);
                Barakhadi.timeOut = null;
            }
            Barakhadi.timeOut = setTimeout(function() {
                Barakhadi.seconds = 0;
                Barakhadi.startTimer();
            }, 2000);
        }
    }, 1000);
}

Barakhadi.allowDrop = function(event) {
    event.preventDefault();
}

Barakhadi.skipReading = function() {
    clearTimeout(Barakhadi.timeout);
    $('#Hammer').hide();
    document.getElementById('playSound').src = Utils.Path + 'SOUND/glassBreak.wav';
    document.getElementById('playSound').play();
    Barakhadi.dropRandomWords();
}

Barakhadi.addbackgroundColours = function() {
    $('.trans').removeClass('trans');
}
Barakhadi.showQuestion = function() {
    document.getElementById("responseBoxDiv").style.display = "none";
}
Barakhadi.NextQuestion = function(object) {
	 clearTimeout(Barakhadi.soundTimer);
    if (Barakhadi.noResponseTimer) {
        clearInterval(Barakhadi.noResponseTimer);
        Barakhadi.noResponseTimer = null;
        Barakhadi.seconds = 0;
    }
        $('#responseBoxDiv').show();
        $('#confiramtionText').text(Barakhadi.modalData.responseMsg);
        $('#Yes').text(Barakhadi.modalData.yes);
        $('#No').text(Barakhadi.modalData.no);
    }
    //score Function
Barakhadi.scoreFunction = function() {

        console.log(resId, questionId, scoredMarks, totalMarks, 1, startTime, Barakhadi.ltrForbarakhadi.suffix);
        console.log(Barakhadi.ltrForbarakhadi.suffix, Barakhadi.wordsData.length, type);
        if (Utils.mobileDeviceFlag) {
            Android.addScore(resId, questionId, scoredMarks, totalMarks, 1, startTime, Barakhadi.ltrForbarakhadi.suffix);
            Android.addLearntData(Barakhadi.ltrForbarakhadi.suffix, Barakhadi.wordsData.length, type);
        }
        $("#No").css("pointer-Events", "none");
        Barakhadi.gameOver();
    }
    //game over
Barakhadi.gameOver = function() {
        clearTimeout(Barakhadi.soundTimer);
        clearInterval(Barakhadi.noResponseTimer);
        document.getElementById("playSound").pause();
        document.getElementById("responseBoxDiv").style.display = "none";
        document.getElementById("coverPage").style.display = "none";
        document.getElementById("level1").style.display = "none";
        document.getElementById("endpage").style.display = "block";
        document.getElementById("bnext").src = Utils.Path + "IMAGES/Barakhadi_Next.png";
        document.getElementById("gameover").innerHTML = Barakhadi.modalData.message;
        Barakhadi.createStars();
        Barakhadi.giveStars();
    }
    //function which creates star divs
Barakhadi.createStars = function() {
    var newImage, newDiv, i, numberOfStars = 5;
    for (i = 1; i <= 5; i++) {
        newDiv = document.createElement("div");
        newDiv.setAttribute("id", "starDiv" + i);
        newDiv.setAttribute("class", "paddingZero  col-xs-2 col-md-2 col-lg-2 col-sm-2");
        $("#starsDiv").append(newDiv);

        newImage = document.createElement("img");
        newImage.setAttribute("id", "starImg" + i);
        newImage.setAttribute("class", "img-responsive paddingZero col-sm-12 col-lg-12 col-md-12 col-xs-12");
        newImage.setAttribute("src", Utils.Path + "IMAGES/star1.png");
        $(newDiv).append(newImage);
    }
}
Barakhadi.giveStars = function() {
    Barakhadi.queCnt = 5;
    var fractionVar, i, numberOfStars = 0,
        temp;
    Barakhadi.total_No_of_Questions = 5;
    ans = Barakhadi.total_No_of_Questions / 5;
    temp = Barakhadi.correctCounter / ans;
    numberOfStars = Math.floor(temp);
    temp = Math.round(temp);
    for (i = 1; i <= Math.floor(numberOfStars); i++)
        document.getElementById("starImg" + i).setAttribute("src", Utils.Path + "IMAGES/star2.png");
    if (numberOfStars != 0) {
        document.getElementById("playSound").src = Utils.Path + "SOUND/INSTRUCTIONS/" + "star" + numberOfStars + ".mp3";
        document.getElementById("playSound").play();
    }
    console.log(Barakhadi.correctCounter, Barakhadi.queCnt);
    if (Utils.mobileDeviceFlag)
        Android.StudentCertification(Barakhadi.correctCounter, Barakhadi.queCnt, "3");
}
Barakhadi.goNext = function() {
    if (Utils.mobileDeviceFlag)
        Android.GotoNextGame();
}