var Barakhadi={};
var Utils={};
Utils.Path='';
Utils.mobileDeviceFlag=false;
var questionId=0,startTime=0,scoredMarks=0,totalMarks=100,resId;

$(document).ready(function(){
	$(".se-pre-con").fadeOut("slow");
	  if(navigator.userAgent.match(/Android|BlackBerry|iPhone|iPad|iPod|Opera Mini|IEMobile/i))
		Utils.mobileDeviceFlag=true;
	 if(Utils.mobileDeviceFlag)
		Utils.Path=Android.getMediaPath("ABCD");  
	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/Stop.png');
	$('#FinalOk').prop('src',Utils.Path+'IMAGES/Correct-Ans.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');
};


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

Barakhadi.getGameData=function()
{
	Barakhadi.words=[];
	$('#level1,#home').show();
	$('#coverPage,#FinalOk,#scrollbarDiv,#Next,#Hammer').hide();
	$('#background').css({'background-image':'url('+Utils.Path+'IMAGES/'+Barakhadi.hardCodedData['BG']+')'});
	Barakhadi.words=Barakhadi.wordsData.slice();
	Barakhadi.randomLetter=Math.floor(Math.random()*Barakhadi.tempArr.length);
	console.log(Barakhadi.tempArr[Barakhadi.randomLetter]);
	Barakhadi.showAllAlphabets();
}

Barakhadi.showAllAlphabets=function()
{
	Barakhadi.gameOpened=false;
	scoredMarks=0;
	questionId++;
	var d=new Date();
	startTime=d.getDate()+"-"+(d.getMonth()+1)+"-"+d.getFullYear()+" "+d.getHours()+":"+d.getMinutes()+":"+d.getSeconds();
	Barakhadi.ltrForbarakhadi=0;
	Barakhadi.addSpacesForAlphabets();
	$('#barakhadiDiv').addClass('magictime puffIn');
	$('#Next,#Hammer').show();
	$('#Hammer').addClass('blink_me');
	if(Barakhadi.timer)
	{
		clearTimeout(Barakhadi.timer);
		Barakhadi.timer = null;
	}
	Barakhadi.timer=setTimeout(function(){
		Barakhadi.playSoundAndHighlight();
	},1500);
	
}

Barakhadi.addSpacesForAlphabets=function()
{
	var div,spanElement,outerDiv,k=0;
	$('#containment-wrapper').show();
	for(var i=0;i<3;i++)
	{
		outerDiv=$('<div style="margin-top:0%;margin-bottom:2%;padding:0px !important;" class="col-lg-12 col-md-12 col-xs-12 col-sm-12"></div>');
		for(var j=0;j<9;j++)
		{
			
			if(k<Barakhadi.words.length)
			{
				div=$('<div class="align9InLine paddingZero text-center col-lg-1 col-md-1 col-xs-1 col-sm-1"></div>');
				spanElement=$('<span id="space'+k+'" class="trans text-center spaces deviceWiseSize" style="pointer-events:none;margin-left:20%;font-weight:bold;z-index:0" >'+Barakhadi.words[k][''+Barakhadi.tempArr[Barakhadi.randomLetter]]+'</span>');
				$(spanElement).data('sound',Barakhadi.words[k][''+Barakhadi.tempArr[Barakhadi.randomLetter]]);
				$(spanElement).on('click',function(){
					Barakhadi.playSoundForEachWord($(this));
				});
				$(div).css({'background-image':'url('+Utils.Path+'IMAGES/Ant_top.png)','background-repeat': 'no-repeat','background-size': '100% 60%','background-position':'left bottom'});
				$(div).append(spanElement);
				k++;
				$(outerDiv).append(div);
			}
		}
		$('#barakhadiDiv').append(outerDiv);
	}
}

Barakhadi.playSoundForEachWord=function(element)
{
	
	if(Utils.mobileDeviceFlag)
		Android.playTts($(element).data('sound'));
	else
	{
		document.getElementById('playSound').src=Utils.Path+'SOUND/'+$(element).data('sound')+".mp3";
		document.getElementById('playSound').play();
	}
}

Barakhadi.playSoundAndHighlight=function()
{
	var time,source,callBack;
	$('#barakhadiDiv').removeClass('magictime puffIn');
	if(Utils.mobileDeviceFlag)
		Android.playTts($('#space'+Barakhadi.counter).data('sound'));
	else
	{
		source=Utils.Path+'SOUND/'+Barakhadi.wordsData[Barakhadi.counter]['sound'];
		Barakhadi.loadmetaDataFlag=true;
		callBack=Barakhadi.playNextSound;
		Barakhadi.getDuration(source,callBack);
	}		
	document.getElementById('space'+Barakhadi.counter).style.color="white";
	
}
Barakhadi.getDuration=function(sound,callBack)
{
	var duration=0;
	$('#playSound').prop('src',sound);
	if(Barakhadi.loadmetaDataFlag)
	{
		$('#playSound').on("loadedmetadata", function(){
			Barakhadi.loadmetaDataFlag=false;
			$('#playSound').unbind("loadedmetadata");
			duration=$('#playSound').prop('duration');
			callBack(duration);
			}	
		);
    }
    else
		$('#playSound').unbind("loadedmetadata");
}
Barakhadi.playNextSound=function(duration)
{
	console.log(duration);
	document.getElementById('playSound').play();

	Barakhadi.timeout=setTimeout(function()
	{
		document.getElementById('space'+Barakhadi.counter).style.color="black";
		Barakhadi.counter++;
		//document.getElementById('playSound').pause();
		if(Barakhadi.counter<Barakhadi.words.length)
		{
			Barakhadi.playSoundAndHighlight();
		}
		else
		{
			$('#Hammer').hide();
			document.getElementById('playSound').src=Utils.Path+'SOUND/glassBreak.wav';
			document.getElementById('playSound').play();
			Barakhadi.dropRandomWords();
		}
	},1500*duration);
}
Barakhadi.dropRandomWords=function()
{
	var noOfWords,randomPlace,arrOfRandomPlaces=[],arrayOfInfo=[],spanElement,xy;
	Barakhadi.answerCounter=0;
	noOfWords=Math.floor(Barakhadi.words.length/2);
	$('.spaces').css({'pointer-events':'auto'});
	Barakhadi.answerCounter=Barakhadi.words.length-noOfWords;
	for(var i=0;i<noOfWords;i++)
	{
		randomPlace=Math.floor(Math.random()*Barakhadi.words.length);
		while($.inArray(randomPlace,arrOfRandomPlaces)!=-1)
		{
			randomPlace=Math.floor(Math.random()*Barakhadi.words.length);
		}
		arrOfRandomPlaces.push(randomPlace);
		arrayOfInfo.push(Barakhadi.words[randomPlace]);
	}
	for(var i=0;i<noOfWords;i++)
	{
		$('#space'+arrOfRandomPlaces[i]).css({'color':'transparent'});
		
		spanElement=$('<span id="letter'+arrOfRandomPlaces[i]+'" style="z-index:5000" class="letters text-center deviceWiseLetters">'+arrayOfInfo[i][Barakhadi.tempArr[Barakhadi.randomLetter]]+'</span>');
		$(spanElement).data('sound',arrayOfInfo[i][Barakhadi.tempArr[Barakhadi.randomLetter]]);
		$(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)
	{
		 if(Utils.mobileDeviceFlag)
		 {
			console.log(resId,questionId,scoredMarks,totalMarks,1,startTime);
			Android.addScore(resId,questionId,scoredMarks,totalMarks,1,startTime);
		
		 }
		 	Barakhadi.gameOpened=false;
	}
	setTimeout(function(){
		location.reload(true);
	},200);
}


Barakhadi.clearAllAndShowNext=function()
{
	clearTimeout(Barakhadi.timeout);
	clearTimeout(Barakhadi.timer);
	if(Barakhadi.gameOpened==true)
	{
		 if(Utils.mobileDeviceFlag)
		 {
			console.log(resId,questionId,scoredMarks,totalMarks,1,startTime);
			Android.addScore(resId,questionId,scoredMarks,totalMarks,1,startTime);
			
		 }
		 Barakhadi.gameOpened=false;
	}
	$('#FinalOk').hide();
	$('#Next').removeClass('blink_me');
	Barakhadi.counter=0;
	Barakhadi.arrayOfTopPositions=[],Barakhadi.arrayOfLeftPositions=[];
	$('.letters').remove();
	$('#barakhadiDiv').empty();
	$('#Next,#Hammer').hide();
	Barakhadi.getGameData();
	
}

Barakhadi.Handledrop=function(event,ui)
{
	
	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':'black','z-index':'0'});
		$(draggedLetter).position({
		  my: "center center",
		  at: "center center",
		  of:this
		});
		if(Barakhadi.answerCounter==Barakhadi.words.length)
		{
			scoredMarks=100;
			 if(Utils.mobileDeviceFlag)
			 {
				
				console.log(resId,questionId,scoredMarks,totalMarks,1,startTime);
				Android.addScore(resId,questionId,scoredMarks,totalMarks,1,startTime);
			 }
			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);
	clearTimeout(Barakhadi.timer);
	$('#Hammer').hide();
	document.getElementById('space'+Barakhadi.counter).style.color="black";
	document.getElementById('playSound').src=Utils.Path+'SOUND/glassBreak.wav';
	document.getElementById('playSound').play();
	Barakhadi.dropRandomWords();
}

Barakhadi.addbackgroundColours=function()
{
	$('.trans').removeClass('trans');
}
