var AksharKhadi={};
var Utils={};
Utils.Path='';
var questionId=0,startTime=0,scoredMarks=0,totalMarks=90,resId;
AksharKhadi.rightcnt=0;
AksharKhadi.rightcntForSLD=0;
AksharKhadi.attempted=0;
AksharKhadi.index=0;
AksharKhadi.queArray=[];
AksharKhadi.quePos=-1;
AksharKhadi.timeStatus=0;
AksharKhadi.starcnt=1;
AksharKhadi.counter=0;
AksharKhadi.flag=-1;
$(document).ready(function(){
	if (navigator.userAgent.match(/Android|BlackBerry|iPhone|iPad|iPod|Opera Mini|IEMobile/i))
        Utils.mobileDeviceFlag = true;

	if (Utils.mobileDeviceFlag){
		//Utils.Path=Android.getMediaPath('Ab_kahan_hai');
		AksharKhadi.queArray=(Android.getTodaysLetters()).split(",");
	}
	else{ 
		//AksharKhadi.queArray=["ख","च"];
		getTodaysLetters();
	} 
	
	console.log(AksharKhadi.queArray);
	$(".se-pre-con").fadeOut("slow");
	setTimeout(function(){
		AksharKhadi.setAllImages();
		AksharKhadi.init();
		AksharKhadi.getGameDataAfterTimeOut();
	},200);
});
function getTodaysLetters()
{
	var randomIndex;
	while (AksharKhadi.queArray.length !== 2) 
	{
	randomIndex = Math.floor(Math.random()*AksharKhadi.mulAkshare.length);
	if($.inArray(AksharKhadi.mulAkshare[randomIndex].word,AksharKhadi.queArray) === -1)
	AksharKhadi.queArray.push(AksharKhadi.mulAkshare[randomIndex].word);
	}
}
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');
	$('#wrongimg1').prop('src',Utils.Path+'Images/Wrong_02.png');
	$('#wrongimg2').prop('src',Utils.Path+'Images/Wrong_01.png');
	$('#wrongImg').prop('src',Utils.Path+'Images/joker.png');
	$('#playAgain').prop('src',Utils.Path+'Images/Aksharkhadi_Play-Again.png');
};

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

AksharKhadi.getGameDataAfterTimeOut=function()
{
	document.getElementById('playSound').src=Utils.Path+'sounds/ting.mp3';
	document.getElementById('playSound').play();
	AksharKhadi.getGameData();
	AksharKhadi.createStars();
	setTimeout(function(){
		AksharKhadi.showQuestions();
	},1000);
}

AksharKhadi.getGameData=function()
{
	AksharKhadi.gameOpened=false;
	$('#background').css({'backgroundImage':'url('+Utils.Path+'Images/'+AksharKhadi.hardCodeddata['BG']+')'});
	$('#Flip').show();
	$('#coverPage').hide();
	$('#next,#speaker').show();
	$('#wrongimg1,#wrongimg2').hide();
	var randomIndex=0,tempArray=[];
	AksharKhadi.arrOfSelectedWords=[];
	$('.slide').addClass('clickable');
	$('.optionForFlip').css({'display':'block'});
	$('.clickable').css({'pointer-events': 'none'});
	$('.defaultImage').removeClass('flipIt');
	$('#lastGamePage,#divContainingFullImage').hide();
	$('#soundDiv,#divContainingSplitImages').fadeIn('slow');
	var temparr=AksharKhadi.mulAkshare.slice();
	var queNo=AksharKhadi.findIndexOfWord(temparr,AksharKhadi.queArray[AksharKhadi.index]);
	var que=temparr.splice(queNo,1);
	AksharKhadi.flag=que[0].flag;
	AksharKhadi.arrOfSelectedWords=populate(temparr,AksharKhadi.arrOfSelectedWords,8);
	AksharKhadi.arrOfSelectedWords=AksharKhadi.arrOfSelectedWords.concat(que);
	while(true){
		AksharKhadi.arrOfSelectedWords=shuffleArray(AksharKhadi.arrOfSelectedWords);
		if(AksharKhadi.findIndexOfWord(AksharKhadi.arrOfSelectedWords,que)!==AksharKhadi.quePos){
			AksharKhadi.quePos=AksharKhadi.findIndexOfWord(AksharKhadi.arrOfSelectedWords,que[0].word);
			break;
		}
	}
	AksharKhadi.tempArray=AksharKhadi.arrOfSelectedWords.slice();
	AksharKhadi.fillGrid();
};
AksharKhadi.findIndexOfWord = function(array,letter) {
    for(var i=0;i<array.length;i++){
        if(array[i].word==letter)
            return i;
    }
};
function populate(array1, array2, length)
{
	var randomIndex;
	while (array2.length !== length) 
	{
		randomIndex = Math.floor(Math.random()*array1.length);
		if($.inArray(array1[randomIndex],array2) === -1){
			if(AksharKhadi.flag==2)
			{
				if(AksharKhadi.flag!=array1[randomIndex]['flag'])
				array2.push(array1[randomIndex]);
			}
			else{
				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()
{

	clearTimeout(AksharKhadi.timeStatus);
	AksharKhadi.timeStatus=0;
	document.getElementById('playSound').src=Utils.Path+'sounds/'+"dikhao_h.mp3";
	document.getElementById('playSound').play();
	AksharKhadi.timeStatus=setTimeout(function(){
		var time=document.getElementById('playSound').duration;
		AksharKhadi.timeStatus=setTimeout(function(){
			document.getElementById('playSound').src=Utils.Path+'sounds/'+AksharKhadi.tempArray[AksharKhadi.randomQuestion]['sound'];
			document.getElementById('playSound').play();
			AksharKhadi.timeStatus=setTimeout(function(){
				time=document.getElementById('playSound').duration;
				setTimeout(function(){
					$('.clickable').css({'pointer-events': 'auto'});
				}, time*500);
			},100);
		},time*1050);
	},100);	
};


AksharKhadi.showQuestions=function(tempArray)
{
	AksharKhadi.counter++;
	$('#speaker').show();
	var d=new Date();
		startTime=d.getDate()+"-"+(d.getMonth()+1)+"-"+d.getFullYear()+" "+d.getHours()+":"+d.getMinutes()+":"+d.getSeconds();
	AksharKhadi.randomQuestion=AksharKhadi.findIndexOfWord(AksharKhadi.tempArray,AksharKhadi.queArray[AksharKhadi.index]);
	//Math.floor(Math.random()*AksharKhadi.tempArray.length);
	//AksharKhadi.findIndexOfWord(AksharKhadi.queArray[AksharKhadi.index]);
								
	document.getElementById('playSound').src=Utils.Path+'sounds/'+"dikhao_h.mp3";
	$('#title').data('question',AksharKhadi.tempArray[AksharKhadi.randomQuestion]['word'].trim());
	questionId=AksharKhadi.tempArray[AksharKhadi.randomQuestion]['questionId'];
	
	document.getElementById('playSound').play();
	AksharKhadi.timeStatus=setTimeout(function(){
		var time=document.getElementById('playSound').duration;
		AksharKhadi.timeStatus=setTimeout(function(){
			document.getElementById('playSound').src=Utils.Path+'sounds/'+AksharKhadi.tempArray[AksharKhadi.randomQuestion]['sound'];
			document.getElementById('playSound').play();
			setTimeout(function(){
				time=document.getElementById('playSound').duration;
				setTimeout(function(){
					$('.clickable').css({'pointer-events': 'auto'});
				}, time*500);
			},100);
		},time*1050);

	},100);	
}

AksharKhadi.fillGrid=function()
{
	var i=1,imagePath;
	//AksharKhadi.randomImg=Math.floor(Math.random()*AksharKhadi.imageSet.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]['word'].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]['word'].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)
{
	clearTimeout(AksharKhadi.timeStatus);
	AksharKhadi.attempted++;
	var source,frontImg,time=0;
	AksharKhadi.gameOpened=true;
	$('#next').hide();
	$('#speaker').hide();
	$('.clickable').css({'pointer-events': 'none'});
	wrongImgArray=['backWrong1.png','backWrong2.png'];
	if($('#'+evt).data('answer')==$('#title').data('question'))
	{
		AksharKhadi.rightcnt++;
		AksharKhadi.rightcntForSLD++;
		totalMarks=1;
		scoredMarks=1;
		console.log(resId,questionId,scoredMarks,totalMarks,1,startTime);
		if(Utils.mobileDeviceFlag)
			Android.addScore(resId,questionId,scoredMarks,totalMarks,1,startTime);
		document.getElementById('playSound').src="sounds/thats_right.mp3";
		setTimeout(function(){
			time=document.getElementById('playSound').duration;
			document.getElementById('playSound').play();
			setTimeout(function(){
				if((AksharKhadi.rightcnt)==3){
					$('#next').hide();
					AksharKhadi.giveStars(AksharKhadi.starcnt++);
					setTimeout(function(){
						AksharKhadi.showNextQuestion();
						$('#next').show();
					},200);
					return 0;
				}
				AksharKhadi.tempArray.splice(AksharKhadi.randomQuestion,1);
				if(AksharKhadi.nextQuestionTimer)
				{
					clearTimeout(AksharKhadi.nextQuestionTimer);
					AksharKhadi.nextQuestionTimer = null;
				}
				AksharKhadi.nextQuestionTimer=setTimeout(function()
				{	
					AksharKhadi.showQuestions();
				},200);
				if(AksharKhadi.counter>=9){
						AksharKhadi.showNextQuestion();
						$('#next').show();
						return 0;
				}
				AksharKhadi.getGameData();	
			},time*1050);
		},100);
		
	}	
	else
	{
		AksharKhadi.rightcnt=0;
		totalMarks=1;
		scoredMarks=0;
		console.log(resId,questionId,scoredMarks,totalMarks,1,startTime);
		if(Utils.mobileDeviceFlag)
			Android.addScore(resId,questionId,scoredMarks,totalMarks,1,startTime);
		$('#'+evt).addClass("shake");
		document.getElementById('playSound').src="sounds/wrongSoundAksharkhadi.mp3";
		setTimeout(function(){
			time=document.getElementById('playSound').duration;
			document.getElementById('playSound').play();
			setTimeout(function(){
				AksharKhadi.tempArray.splice(AksharKhadi.randomQuestion,1);
				if(AksharKhadi.nextQuestionTimer)
				{
					clearTimeout(AksharKhadi.nextQuestionTimer);
					AksharKhadi.nextQuestionTimer = null;
				}
				AksharKhadi.nextQuestionTimer=setTimeout(function()
				{	
					$('#'+evt).removeClass("shake");
					AksharKhadi.showQuestions();
				},200);
				if(AksharKhadi.counter>=9){
						AksharKhadi.showNextQuestion();
						$('#next').show();
						return 0;
				}
				AksharKhadi.getGameData();	
			},time*1070);
		},100);
	
	}
	
	
};

AksharKhadi.createStars=function(){
	var temp,newImage,newDiv,i,numberOfStars=2;
	for(i=1;i<=numberOfStars;i++)
	{
		newDiv= document.createElement("div");
		newDiv.setAttribute("id","starDiv"+i); 
		newDiv.setAttribute("class","noPadding stars col-xs-2 col-md-2 col-lg-2 col-sm-2 col-xs-offset-1 col-sm-offset-1 col-md-offset-1 col-lg-offset-1"); 

		newImage= document.createElement("img");
		newImage.setAttribute("id","starImg"+i); 
		newImage.setAttribute("class","img-responsive"); 
		newImage.setAttribute("src",Utils.Path+"images/star1.png");
		$(newDiv).append(newImage);
		$("#starDiv").append(newDiv);
	}
};

AksharKhadi.giveStars=function(id){
	$("#starImg"+id).prop("src",Utils.Path+"images/star2.png");
};
AksharKhadi.showNextQuestion=function()
{
	AksharKhadi.index++;
	clearTimeout(AksharKhadi.timeStatus);
	console.log( AksharKhadi.rightcntForSLD,AksharKhadi.attempted); 
	 /* if(Utils.mobileDeviceFlag)
		Android.StudentLevelDetection( AksharKhadi.rightcntForSLD,AksharKhadi.attempted);   */
	
	AksharKhadi.rightcntForSLD=0;
	AksharKhadi.counter=0;
	AksharKhadi.attempted=0;
	clearTimeout(AksharKhadi.nextQuestionTimer);
	
	var d=new Date();
	startTime=d.getDate()+"-"+(d.getMonth()+1)+"-"+d.getFullYear()+" "+d.getHours()+":"+d.getMinutes()+":"+d.getSeconds();
	if(AksharKhadi.index==2){
		AksharKhadi.shoMessage();
		return;
	}
	/*if(AksharKhadi.gameOpened==true)
	{
		console.log(resId,questionId,scoredMarks,totalMarks,1,startTime);
		//Android.addScore(resId,questionId,scoredMarks,totalMarks,1,startTime);
	}*/
	AksharKhadi.rightcnt=0;
	AksharKhadi.getGameData();
	AksharKhadi.showQuestions();
	
};

AksharKhadi.callHome=function()
{
	clearTimeout(AksharKhadi.nextQuestionTimer);
	clearTimeout(AksharKhadi.timeStatus);
	if(AksharKhadi.gameOpened==true)
	{
		//console.log(resId,questionId,scoredMarks,totalMarks,1,startTime);
		//Android.addScore(resId,questionId,scoredMarks,totalMarks,1,startTime);
	}
	setTimeout(function(){
		location.reload(true);
	},200);
}
AksharKhadi.shoMessage=function(){
	$("#game").hide();
	document.getElementById("mainGamePage").innerHTML=AksharKhadi.hardCodeddata.msg;
	document.getElementById("mainGamePage").style="font-size: 5vw; text-align:center;margin-top:12%;" ;  
}