var Chaudakhadi = {};
var Utils = {};
Utils.Path = '';
Utils.mobileDeviceFlag = false;
var questionId = 0,startTime = 0,scoredMarks = 0,totalMarks = 100,resId,flag=false;
$(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;
    setTimeout(function() {
        Chaudakhadi.setAllImages();
        Chaudakhadi.init();
    }, 200);
});

Chaudakhadi.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');
    $('#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');
};

Chaudakhadi.init = function() {
    $('#coverPage').show();
    $('#level1,#home').hide();
	//$('#soundBtn').hide();
    $('#background').css({ 'background-image': 'url(' + Utils.Path + 'images/' + Chaudakhadi.hardCodedData['coverPage'] + ')' });
}
Chaudakhadi.getGameData = function() {
	document.getElementById("chaudakhadiInstruction").innerHTML=Chaudakhadi.instruction;
	if(flag==false){
	document.getElementById('playSound').src = Utils.Path + 'SOUND/instruction.mp3';
    document.getElementById('playSound').play();
	}
	flag=true;
    Chaudakhadi.words = [];
	Chaudakhadi.arrayOfLeftPositions=[];
	Chaudakhadi.arrayOfTopPositions=[];
	Chaudakhadi.questionFlag=false;
	 Chaudakhadi.scrollleftRight = 100, Chaudakhadi.counter = 0;
	$('#containment-wrapper').hide();
    $('#level1').show();
    $('#coverPage').hide();
    $('#background').css({ 'background-image': 'url(' + Utils.Path + 'images/' + Chaudakhadi.hardCodedData['BG'] + ')' });
    Chaudakhadi.words = Chaudakhadi.wordsData.slice();
    Chaudakhadi.addLettersToScrollBar();
}
Chaudakhadi.playInstruction=function()
{
	document.getElementById('playSound').pause();
	document.getElementById('playSound').src = Utils.Path + 'SOUND/instruction.mp3';
    document.getElementById('playSound').play();
}
Chaudakhadi.scroll = function(evt) {
    if (evt == 'scrollLeft')
        Chaudakhadi.scrollleftRight = Chaudakhadi.scrollleftRight - 100;
    else if (evt == 'scrollRight')
        Chaudakhadi.scrollleftRight = Chaudakhadi.scrollleftRight + 100;
    $('#scrollBar').scrollLeft(Chaudakhadi.scrollleftRight);
}
Chaudakhadi.addLettersToScrollBar = function() {
    var div, spanElement;
   $('#Next,#containment-wrapper').hide();
    $('#home').show();
    for (var i = 0; i < Chaudakhadi.words.length; i++) {
        div = $('<div class="alignInLine text-center"></div>');
        spanElement = $('<span style="cursor:pointer;" >' + Chaudakhadi.words[i]['suffix'].trim() + '</span>'); /*class="blink_me"*/
        $(div).append(spanElement);
		$(spanElement).on('click', Chaudakhadi.showCompleteChaudakhadi);
        $('#scrollBar').append(div);
    }
	/*$(document).mousemove(function(event){
    $("span").css("color","yellow");
	});*/
  }
//show chaudakhadi
Chaudakhadi.showCompleteChaudakhadi = function() {
		$('#InstructionDiv').css('visibility','visible');
    var d = new Date();
    startTime = d.getDate() + "-" + (d.getMonth() + 1) + "-" + d.getFullYear() + " " + d.getHours() + ":" + d.getMinutes() + ":" + d.getSeconds();
    Chaudakhadi.ltrForChaudakhadi = 0;
    Chaudakhadi.searchWord(this);
	$('#Next,#containment-wrapper').show();
	Chaudakhadi.addSpacesForBarakhadi();
	//document.getElementById("mainLetter").innerHTML=Chaudakhadi.ltrForChaudakhadi.suffix;
	document.getElementById("InstructionDiv").innerHTML=Chaudakhadi.hardCodedData.instructionText;
    $('#scrollbarDiv,#chaudakhadiInstruction,#soundBtn').hide();
    Chaudakhadi.addSoundSource();
}
Chaudakhadi.searchWord = function(evt) {
    for (var i = 0; i < Chaudakhadi.words.length; i++) {
        if (Chaudakhadi.words[i]['suffix'].trim() == $(evt).text().trim()) {
            break;
        }
    }
    Chaudakhadi.ltrForChaudakhadi = Chaudakhadi.words[i];
}
Chaudakhadi.addSpacesForBarakhadi = function() {
    var div, spanElement, outerDiv, k = 0;
    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 < 7; j++) {
            div = $('<div id="Div' + j+ '" class="align6InLine text-center spaces col-lg-1 col-md-1 col-xs-1 col-sm-1" ></div>');
            if (k < Chaudakhadi.ltrForChaudakhadi['list'].length) {
                spanElement = $('<span id="space' + k + '" class="trans text-center space1 deviceWiseSize" style="pointer-events:none" >' + Chaudakhadi.ltrForChaudakhadi['list'][k]['word'] + '</span>');
                $(spanElement).data('sound', Utils.Path + 'SOUND/' + Chaudakhadi.ltrForChaudakhadi['list'][k]['sound']);
                $(spanElement).on('click', function() {
                    Chaudakhadi.playSoundForEachWord($(this));
                });

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

Chaudakhadi.addSoundSource = function() {
    var source;
    source = Utils.Path + 'SOUND/' + Chaudakhadi.ltrForChaudakhadi['list'][Chaudakhadi.counter]['sound'];
    Chaudakhadi.getDuration(source);
};

Chaudakhadi.getDuration = function(source) {
    var duration = 0;
    $('#playSound').on('loadedmetadata', function() {
        duration = $('#playSound').prop('duration');
        $('#playSound').unbind('loadedmetadata');
        Chaudakhadi.playSoundAndHighlight(duration);
    });
    $('#playSound').prop('src', source);
};
Chaudakhadi.playSoundAndHighlight = function(duration) {
    duration = duration + 1;
    document.getElementById('playSound').play();
    document.getElementById('space' + Chaudakhadi.counter).style.color = "yellow";
    Chaudakhadi.timeout = setTimeout(function() {
        document.getElementById('space' + Chaudakhadi.counter).style.color = "black";
        Chaudakhadi.counter++;
        document.getElementById('playSound').pause();
        if (Chaudakhadi.counter < Chaudakhadi.ltrForChaudakhadi['list'].length)
            Chaudakhadi.addSoundSource();
		 else {
            Chaudakhadi.dropRandomWords();
        }
    }, duration * 1000);
}
Chaudakhadi.dropRandomWords = function() {
	if(Chaudakhadi.questionFlag==false)
	{
	 document.getElementById('playSound').src = Utils.Path + 'SOUND/glassBreak.wav';
     document.getElementById('playSound').play();
	$('#InstructionDiv').css('visibility','hidden');
	Chaudakhadi.questionFlag=true;
	 clearTimeout(Chaudakhadi.timeout);
	 if( Chaudakhadi.counter<14)
	 {
     document.getElementById('space' + Chaudakhadi.counter).style.color = "black";
	 }
    var noOfWords, randomPlace, arrOfRandomPlaces = [],arrayOfInfo = [],spanElement, xy;
    Chaudakhadi.answerCounter = 0;
    noOfWords = Math.floor(Chaudakhadi.ltrForChaudakhadi['list'].length / 2);
    $('.spaces').css({ 'border': '3px solid black','backgroundColor':'#ADADC9'});
	$('.space1').css({ 'color': 'green' });
    $('.spaces').css({ 'pointer-events': 'auto' });
    Chaudakhadi.answerCounter = Chaudakhadi.ltrForChaudakhadi['list'].length - noOfWords;
    for (var i = 0; i < noOfWords; i++) {
        randomPlace = Math.floor(Math.random() * Chaudakhadi.ltrForChaudakhadi['list'].length);
        while ($.inArray(randomPlace, arrOfRandomPlaces) != -1) {
            randomPlace = Math.floor(Math.random() * Chaudakhadi.ltrForChaudakhadi['list'].length);
        }
        arrOfRandomPlaces.push(randomPlace);
        arrayOfInfo.push(Chaudakhadi.ltrForChaudakhadi['list'][randomPlace]);
    }
	console.log(arrOfRandomPlaces);
    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).draggable({
            cursor: 'move',
            containment: "html",
            start: function() {
                $(this).data("origPosition", $(this).position());
            }
        });
        $('body').append(spanElement);
        xy = Chaudakhadi.getPositions();
        $(spanElement).css({ "position": "absolute", "top": xy[1] + "vh", "left": xy[0] + "vw" });
        $('#space' + arrOfRandomPlaces[i]).droppable({
            drop: Chaudakhadi.Handledrop,
           dragover: Chaudakhadi.allowDrop
        });
		
    }
	}
	else{
		$('#containment-wrapper').hide();
    $('#scrollbarDiv,#chaudakhadiInstruction,#soundBtn').show();
    $('.letters').remove();
    $('#barakhadiDiv').empty();
    $('#Next').hide();
	document.getElementById("chaudakhadiDiv").innerHTML="";
	Chaudakhadi.getGameData();
	}
}
Chaudakhadi.allowDrop = function(event) {
    event.preventDefault();
}
Chaudakhadi.Handledrop = function(event, ui) {
    var draggedLetter = ui.draggable;
    var droppedSpan = $(this);
    if ($(draggedLetter).text().trim() == $(droppedSpan).text().trim()) {
		document.getElementById('playSound').src = Utils.Path + 'SOUND/Right_answer__Aditi.mp3';
        document.getElementById('playSound').play();
		Chaudakhadi.answerCounter++;
        $(draggedLetter).draggable('disable');
        $(draggedLetter).css({ 'color': 'green' });
        $(draggedLetter).position({
            my: "center center",
            at: "center center",
            of: this
        });
	$(draggedLetter).css({ "fontSize": "5vw"});
	//$(draggedLetter).css({ "paddingTop": "1%"});
	if (Chaudakhadi.answerCounter == Chaudakhadi.ltrForChaudakhadi['list'].length) {
            $('#Next').css({ 'visibility': 'hidden' });
            setTimeout(function() {
                document.getElementById('playSound').src = Utils.Path + 'SOUND/welldone.mp3';
                document.getElementById('playSound').play();
                $('#Next').css({ 'visibility': 'visible' });
            }, 1500);

        }
	}else{
	ui.draggable.animate(ui.draggable.data("origPosition"), "slow");
	 document.getElementById('playSound').src = Utils.Path + 'SOUND/BuzzerWrong.mp3';
     document.getElementById('playSound').play();
	//$(draggedLetter).css({ 'color': 'red' });
	//$(draggedLetter).css({ "fontSize": "4vw"});
	//$(draggedLetter).css({ "paddingTop": "0.5%"});
	}
}
Chaudakhadi.getPositions = function() {
    var y = Math.floor((Math.random() * 25) + 30);
    var x = Math.floor(Math.random() * 55);
    while ($.inArray(((y) || (y + 1) || (y + 2) || (y - 1) || (y - 2) || (y - 3)), Chaudakhadi.arrayOfTopPositions) >= 0) {
        y = Math.floor((Math.random() * 25) + 30);

    }
    while (($.inArray(((x) || (x + 1) || (x + 2) || (x - 1) || (x - 2) || (x - 3)), Chaudakhadi.arrayOfLeftPositions) >= 0)) {
        x = Math.floor(Math.random() * 35);
    }
    Chaudakhadi.arrayOfTopPositions.push(y);
    Chaudakhadi.arrayOfLeftPositions.push(x);
    return [x, y];
}
Chaudakhadi.callHome = function() {
    setTimeout(function() {
        location.reload(true);
    }, 200);
}
