var Barakhadi = {};
var Utils = {};
Utils.Path = '';
Utils.mobileDeviceFlag = false;
var questionId = 0,
    startTime = 0,
    scoredMarks = 0,
    totalMarks = 100,
    resId, 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');
    $('#home').prop('src', Utils.Path + 'IMAGES/home.png');
	$('#soundBtn').prop('src', Utils.Path + 'IMAGES/option_Sound.png');
};

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

Barakhadi.getGameData = function() {
    Barakhadi.words = [];
	document.getElementById("barakhadiInstruction").innerHTML=Barakhadi.instruction;
	document.getElementById('playSound').src = Utils.Path + 'SOUND/instruction3.mp3';
    document.getElementById('playSound').play();
    $('#level1').show();
    $('#coverPage,#FinalOk').hide();
    $('#background').css({ 'background-image': 'url(' + Utils.Path + 'IMAGES/' + Barakhadi.hardCodedData['BG'] + ')' });
    Barakhadi.words = Barakhadi.wordsData.slice();
    Barakhadi.addLettersToScrollBar();
}
Barakhadi.playInstruction=function()
{
	document.getElementById('playSound').pause();
	document.getElementById('playSound').src = Utils.Path + 'SOUND/instruction3.mp3';
    document.getElementById('playSound').play();
}
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,#barakhadiInstruction,#soundBtn').hide();
    $('#barakhadiDiv').removeClass('magictime puffIn');
    Barakhadi.addSoundSource();
    //Barakhadi.playSoundAndHighlight();
}

Barakhadi.addSpacesForBarakhadi = function() {
    var div, spanElement, outerDiv, k = 0;
    $('#containment-wrapper').show();
    $('#scrollbarDiv,#barakhadiInstruction').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, 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));
        });
        $('body').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
        });
    }
    Barakhadi.addbackgroundColours();
}

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

Barakhadi.clearAllAndShowNext = function() {
    clearTimeout(Barakhadi.timeout);
    document.getElementById('playSound').pause();
    if (Barakhadi.gameOpened == true) {
        console.log(resId, questionId, scoredMarks, totalMarks, 1, startTime, Barakhadi.ltrForbarakhadi.suffix);
        if (Utils.mobileDeviceFlag)
            Android.addScore(resId, questionId, scoredMarks, totalMarks, 1, startTime.Barakhadi.ltrForbarakhadi.suffix);
        Barakhadi.gameOpened = false;
    }
    $('#FinalOk,#containment-wrapper').hide();
    $('#Next').removeClass('blink_me');
    $('#scrollbarDiv,#barakhadiInstruction,#soundBtn').show();
	//document.getElementById('playSound').src = Utils.Path + 'SOUND/instruction3.mp3';
    //document.getElementById('playSound').play();
    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++;
        $(draggedLetter).draggable('disable');
        $(draggedLetter).css({ 'color': 'green' });
        $(draggedLetter).position({
            my: "center center",
            at: "center center",
            of: this
        });
        if (Barakhadi.answerCounter == Barakhadi.ltrForbarakhadi['list'].length) {
            scoredMarks = 100;
            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);
            }

            Barakhadi.gameOpened = false;
            $('#FinalOk').show();
            $('#Next').css({ 'visibility': 'hidden' });
            setTimeout(function() {
                document.getElementById('playSound').src = Utils.Path + 'SOUND/welldone.mp3';
                document.getElementById('playSound').play();
                $('#barakhadiDiv').removeClass('magictime puffIn');
                $('#Next').css({ 'visibility': 'visible' });
                $('#Next').addClass('blink_me');
            }, 1500);

        }
    } else {
        scoredMarks = 0;
        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.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');
}