var AksharKhadi={};
var Utils={};
Utils.Path='';
Utils.mobileDeviceFlag=false;
var questionId=0,startTime=0,scoredMarks=0,totalMarks=90,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("PointMeOut"); 
	setTimeout(function(){
		AksharKhadi.setAllImages();
		AksharKhadi.init();
	},200);
});


AksharKhadi.setAllImages=function()
{
	$('#playGame').prop('src',Utils.Path+'Images/Aksharkhadi_Play.png');
	$('#home').prop('src',Utils.Path+'Images/Aksharkhadi_Home.png');
	$('#speaker').prop('src',Utils.Path+'Images/Aksharkhadi_Sound.png');
	$('#next').prop('src',Utils.Path+'Images/Aksharkhadi_Next.png');
	$('#logo').prop('src',Utils.Path+'Images/logo.png');
	$('#wrongImg').prop('src',Utils.Path+'Images/joker.png');
	$('#playAgain').prop('src',Utils.Path+'Images/Aksharkhadi_Play-Again.png');
};

AksharKhadi.init=function(){
	AksharKhadi.score=0;
	AksharKhadi.keyValue='word';
	$('#playGame').text(AksharKhadi.hardCodeddata.play);
	$('#Flip').hide();
	$('#coverPage').show();
	$('#background').css({'backgroundImage':'url('+Utils.Path+'Images/'+AksharKhadi.hardCodeddata['coverPage']+')'});
};

AksharKhadi.getGameDataAfterTimeOut=function()
{
	AksharKhadi.getGameData();
	setTimeout(function(){
		AksharKhadi.showQuestions();
	},500);
}

AksharKhadi.getGameData=function()
{
	AksharKhadi.gameOpened=false;
	scoredMarks=0;
	$('#background').css({'backgroundImage':'url('+Utils.Path+'Images/'+AksharKhadi.hardCodeddata['BG']+')'});
	$('#Flip').show();
	$('#coverPage').hide();
	$('#next,#homeDiv,#home,#speaker').show();
	$('#wrongimg1,#wrongimg2').hide();
	var randomIndex=0,tempArray=[];
	AksharKhadi.counter=0,AksharKhadi.correctAnswerCount=0;
	AksharKhadi.arrOfSelectedWords=[];
	$('.optionForFlip').css({'display':'block'});
	$('.flipItout').css({'pointer-events': 'none'});
	$('.defaultImage').removeClass('flipIt');
	$('#lastGamePage,#divContainingFullImage').hide();
	$('#soundDiv,#homeDiv,#divContainingSplitImages').fadeIn('slow');
	AksharKhadi.arrOfSelectedWords=populate(AksharKhadi.wordsData,AksharKhadi.arrOfSelectedWords, 9);
	AksharKhadi.arrOfSelectedWords=shuffleArray(AksharKhadi.arrOfSelectedWords);
	AksharKhadi.tempArray=AksharKhadi.arrOfSelectedWords.slice();
	AksharKhadi.fillGrid();
}

function populate(array1, array2, length)
{
	var randomIndex;
	while (array2.length !== length) 
	{
		randomIndex = Math.floor(Math.random()*array1.length);
		if($.inArray(array1[randomIndex],array2) === -1)
		array2.push(array1[randomIndex]);
	}
	return array2;
}

function shuffleArray(array)
{
	var i,j,temp;
	for (i = array.length - 1; i > 0; i--) 
	{
	    j = Math.floor(Math.random() * (i + 1));
	    temp = array[i];
	    array[i] = array[j];
	    array[j] = temp;
	}
	return array;
}

AksharKhadi.playSoundAgain=function()
{
	$("#speaker").css("pointer-events","none");
	if(Utils.mobileDeviceFlag)
		Android.playTts(AksharKhadi.tempArray[AksharKhadi.randomQuestion][AksharKhadi.keyValue]);
	else 
		saySomething(AksharKhadi.tempArray[AksharKhadi.randomQuestion][AksharKhadi.keyValue]);
	//document.getElementById('playSound').play();
	//Android.audioPlayer('ICDSBarakhadiGame/sounds/'+AksharKhadi.tempArray[AksharKhadi.randomQuestion]['sound']);
	setTimeout(function()
	{
		$("#speaker").css("pointer-events","auto");
	},1300);
};

function saySomething(whatToSay)
{
	if('speechSynthesis' in window)
	{
		var speech = new SpeechSynthesisUtterance(whatToSay);
		speech.lang = 'hi-IN'; //en-US
		//speech.rate=0.5;
		window.speechSynthesis.speak(speech);
	}
	//$("#speaker").css("pointer-events","auto");
}
function stopSomething()
{
window.speechSynthesis.cancel();
}
AksharKhadi.showQuestions=function(tempArray)
{
	$("#textDiv").css("visibility","visible");
	AksharKhadi.randomQuestion=Math.floor(Math.random()*AksharKhadi.tempArray.length);
	$('#title').data('question',AksharKhadi.tempArray[AksharKhadi.randomQuestion][AksharKhadi.keyValue].trim());
	console.log($('#title').data('question'));
	questionId=AksharKhadi.tempArray[AksharKhadi.randomQuestion]['questionId'];
	$("#textDiv").text(AksharKhadi.tempArray[AksharKhadi.randomQuestion].langWord);
	/* if(Utils.mobileDeviceFlag)
		Android.playTts(AksharKhadi.tempArray[AksharKhadi.randomQuestion][AksharKhadi.keyValue]);
	else 
		saySomething(AksharKhadi.tempArray[AksharKhadi.randomQuestion][AksharKhadi.keyValue]); */
		AksharKhadi.playSoundAgain();
	$('.flipItout').css({'pointer-events': 'auto'});
}

AksharKhadi.fillGrid=function()
{
	var i=1,imagePath;
	var d=new Date();
	startTime=d.getDate()+"-"+(d.getMonth()+1)+"-"+d.getFullYear()+" "+d.getHours()+":"+d.getMinutes()+":"+d.getSeconds();
	AksharKhadi.randomImg=Math.floor(Math.random()*AksharKhadi.imageSet.length);
	AksharKhadi.randomWord=Math.floor((Math.random()*AksharKhadi.keyValue.length));
	for(var j=1;j<4;j++)
	{
		for(var k=0;k<3;k++)
		{
			AksharKhadi.randomQuestion=Math.floor(Math.random()*AksharKhadi.arrOfSelectedWords.length);
			$('#imgDiv'+(i-1)).data('answer',AksharKhadi.arrOfSelectedWords[AksharKhadi.randomQuestion][AksharKhadi.keyValue].trim());
			imagePath=Utils.Path+''+AksharKhadi.imageSet[AksharKhadi.randomImg]['img'];
			$('#imgDiv'+(i-1)).data('backImg',imagePath+''+i+''+AksharKhadi.imageSet[AksharKhadi.randomImg]['type']);
			$('#imgDiv'+(i-1)).data('frontImg',Utils.Path+''+AksharKhadi.frontimageSet['img']+''+i+''+AksharKhadi.frontimageSet['type']);
			/*if(AksharKhadi.arrOfSelectedWords[AksharKhadi.randomQuestion]['img']=="none")
			{*/
				$('#option'+(i-1)).text(AksharKhadi.arrOfSelectedWords[AksharKhadi.randomQuestion][AksharKhadi.keyValue].trim());
				$('#img'+j+'_'+k).hide();
			/*}
			else
			{
				$('#img'+j+'_'+k).prop('src','Images/'+AksharKhadi.arrOfSelectedWords[AksharKhadi.randomQuestion]['img']);
				$('#option'+(i-1)).hide();
			}*/
			i++;
			AksharKhadi.arrOfSelectedWords.splice(AksharKhadi.randomQuestion,1);
		}
	}	
}

AksharKhadi.checkAns=function(evt)
{
	var source,frontImg;
	AksharKhadi.gameOpened=true;
	AksharKhadi.counter++;
	$('.flipItout').css({'pointer-events': 'none'});
	wrongImgArray=['backWrong1.png','backWrong2.png'];
	if($('#'+evt).data('answer')==$('#title').data('question'))
	{
		$('#'+evt).css({'pointer-events': 'none'});
		$('#'+evt).removeClass('flipItout');
		AksharKhadi.correctAnswerCount++;
		$('#'+evt).find('img').show();
		$('#'+evt).find('p').hide();
		source=$('#'+evt).data('backImg');
		frontImg=$('#'+evt).data('frontImg');
		$('#'+evt).find('img').prop('src',frontImg);
		document.getElementById('playSound').src=Utils.Path+'sounds/CorrectAksharkhadi.mp3';
		document.getElementById('playSound').play();
		AksharKhadi.score+=10;
		scoredMarks+=10;
		setTimeout(function(){
			$('#'+evt).find('img').prop('src',source);
			$('#'+evt).find('img').addClass('flipIt');
		},900);
	}	
	else
	{
		scoredMarks+=0;
		$('#'+evt).addClass("shake");
		randomImg=Math.floor(Math.random()*wrongImgArray.length);
		document.getElementById('playSound').src=Utils.Path+'sounds/wrongSoundAksharkhadi.mp3';
		document.getElementById('playSound').play();
		for(var i=0;i<9;i++)
		{
			if($('#title').data('question')==$('#imgDiv'+i).data('answer'))
			{
				var offsetOfImage=$('#imgDiv'+i).offset();
				break;
			}
		}

		$('#imgDiv'+i).find('img').prop('src',Utils.Path+'Images/'+wrongImgArray[randomImg]);
		$('#imgDiv'+i).find('img').show();
		$('#imgDiv'+i).removeClass('flipItout');
		$('#imgDiv'+i).find('p').hide();
		setTimeout(function(){
				$('#'+evt).removeClass("shake");
			},900);
	}
	AksharKhadi.tempArray.splice(AksharKhadi.randomQuestion,1);
	if(AksharKhadi.nextQuestionTimer)
	{
				clearTimeout(AksharKhadi.nextQuestionTimer);
				AksharKhadi.nextQuestionTimer = null;
	}
	AksharKhadi.nextQuestionTimer=setTimeout(function()
	{
		if(AksharKhadi.counter<9)
		{	
			AksharKhadi.showQuestions();
			$('.flipItout').css({'pointer-events': 'auto'});
		}
		else
		{
			$('.flipItout').css({'pointer-events': 'none'});
			console.log(resId,questionId,scoredMarks,totalMarks,1,startTime);
			if(Utils.mobileDeviceFlag)
				Android.addScore(resId,questionId,scoredMarks,totalMarks,1,startTime);
			AksharKhadi.gameOpened=false;
			if(AksharKhadi.correctAnswerCount>8)
			{
				$('#divContainingSplitImages').fadeOut(500);
				
				setTimeout(function()
				{
					$('#soundDiv,#homeDiv').hide();
					$('#fullImage').prop('src',Utils.Path+''+AksharKhadi.imageSet[AksharKhadi.randomImg]['completeImg']);
					$('#divContainingFullImage').fadeIn(500);
					document.getElementById('playSound').src=Utils.Path+'sounds/Bell.mp3';
					document.getElementById('playSound').play();
					$('#next,#homeDiv,#home').show();
					$('#speaker').hide();
					setTimeout(function()
					{
						//AksharKhadi.showNextQuestion();
						$('#next').addClass('blink_me');
					},2500);
				},500);
			}
			else
			{
				document.getElementById('playSound').src=Utils.Path+'sounds/soundForWrong.mp3';
				document.getElementById('playSound').play();
				$("#textDiv").css("visibility","hidden");
				$('#divContainingSplitImages').fadeOut(500);
				if(AksharKhadi.tempTimer)
				{
					clearTimeout(AksharKhadi.tempTimer);
					AksharKhadi.tempTimer=null;
				}
				AksharKhadi.tempTimer=setTimeout(function()
				{
					
					$('#myModal').fadeIn(500);
					$('#soundDiv,#homeDiv').hide();
				},500);
			}
		}
	},2000);	
}

AksharKhadi.showNextQuestion=function()
{
	$('.slide').css({'pointer-events': 'auto'});
	document.getElementById('playSound').pause();
	if(Utils.mobileDeviceFlag)
		Android.stopTts();
	else
		stopSomething();
	clearTimeout(AksharKhadi.nextQuestionTimer);
	clearTimeout(AksharKhadi.tempTimer);
	if(AksharKhadi.gameOpened)
	{
		console.log(resId,questionId,scoredMarks,totalMarks,1,startTime);
		if(Utils.mobileDeviceFlag)
			Android.addScore(resId,questionId,scoredMarks,totalMarks,1,startTime);
	}
		$('#myModal').removeClass('magictime vanishIn');
		$("#myModal").fadeOut('slow');
		$('#next').removeClass('blink_me');
		AksharKhadi.getGameData();
		AksharKhadi.showQuestions();
};


AksharKhadi.callHome=function()
{
	if(Utils.mobileDeviceFlag)
	Android.stopTts();
	else
		stopSomething();
	clearTimeout(AksharKhadi.nextQuestionTimer);
	if(AksharKhadi.gameOpened)
	{
		console.log(resId,questionId,scoredMarks,totalMarks,1,startTime);
		if(Utils.mobileDeviceFlag)
			Android.addScore(resId,questionId,scoredMarks,totalMarks,1,startTime);
	}
	setTimeout(function(){
		location.reload(true);
	},200);
}