// 8 May //
var startingLetter={};
var Utils={};
Utils.Path='';
Utils.mobileDeviceFlag=false;
var questionId=0,starstartingLetterme=0,scoredMarks=0,totalMarks=10,resId=0,totalNos=0,wordName='';
startingLetter.wordData=[];
totalQuestion=0;
startingLetter.questionCount=0;
startingLetter.skippedCnt=0;
startingLetter.attemptCnt=0;
startingLetter.totalQue=0;
startingLetter.correctCounter=0;
$(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("Starting Letter");   */
	
	setTimeout(function()
	{
		if(startingLetter.hardcodedData['languageFont']!=null)
			setFontFamilyForLang("fonts/"+startingLetter.hardcodedData['languageFont']);
		document.body.style.backgroundImage="url("+Utils.Path+"images/"+startingLetter.hardcodedData.coverImage+")";
		document.getElementById('coverpage').style.display="block";
		document.getElementById('gamepage').style.display="none";
		document.getElementById('skipDiv').style.display="none";
		startingLetter.createStars();
		startingLetter.setImage();
		startingLetter.initVariables();
	},200);
});
//Initialise variables //
startingLetter.initVariables=function()
{
	startingLetter.letterArr=[];
	startingLetter.cnt=0;
	startingLetter.soundFlag=false;
	startingLetter.attemptFlag=false;
	startingLetter.skipFlag=true;
	startingLetter.objPointerFlag=true;
	startingLetter.wrongCnt=0;
	startingLetter.seconds=0;
	
	totalNos=startingLetter.Data.length;
}
setFontFamilyForLang=function(fontFilePath){
  var newStyle = "<style>"+
            "@font-face {  "+
              "font-family: 'CustomFontFamily';"  +
                "src: url('"+fontFilePath+"') format('truetype');"+
                "}  </style>";
    $("head").append(newStyle);
    $("body").css("font-family","CustomFontFamily"); 
}
startingLetter.showInstruction=function()
{
	document.getElementById('gamepage').style.display="none";
	document.getElementById('playGame').style.display="none";
	document.body.style.backgroundImage="url("+Utils.Path+"images/"+startingLetter.hardcodedData.bgImage+")";
}
//play Game//
startingLetter.playGame=function()
{
	document.body.style.backgroundImage="url("+Utils.Path+"images/"+startingLetter.hardcodedData.bgImage+")";
	document.getElementById('gamepage').style.display="block";
	document.getElementById('coverpage').style.display="none";
	document.getElementById('wordDiv').style.visibility="visible";
	document.getElementById('skipDiv').style.display="block";
/* 	document.getElementById("playSoundBack").src=Utils.Path+"sounds/Instruction/Carpassinghorn.mp3";//bgSound
	document.getElementById("playSoundBack").loop=true;
	document.getElementById("playSoundBack").play();  */
	getUniqueValArr(startingLetter.Data,startingLetter.wordData,5);
	totalQuestion=startingLetter.wordData.length;
	startingLetter.getWord();
	startingLetter.createDiv();
}
// set Images//
startingLetter.setImage=function()
{
	document.getElementById('logo').src=Utils.Path+"images/logo.png";
	document.getElementById('play').src=Utils.Path+"images/Play.png";
	document.getElementById('home').src=Utils.Path+"images/home.png";
	document.getElementById('resultImg').src=Utils.Path+"images/Flag-Boy.gif";
	document.getElementById('skip').src=Utils.Path+"images/Skip.png";
	document.getElementById('next').src=Utils.Path+"images/Next.png";
	document.getElementById('soundImg').src=Utils.Path+"images/Sound.png";
	document.getElementById('carDivs').style.backgroundImage=Utils.Path+'url(images/road2.png)';
	document.getElementById('wordDiv').style.backgroundImage=Utils.Path+'url(images/main-text-bg.png)';
}
startingLetter.createDiv=function()
{
	shuffleArray(startingLetter.carImages);
	for(var i=0;i<=4;i++)
	{
		startingLetter.setCarAtRandomPos(carDivsInner,1,i,startingLetter.letterArr[i]);
		startingLetter.animatecar("carDiv"+i);
	}
	clearInterval(startingLetter.carInterval);
	//startingLetter.playSoundAgain();
	startingLetter.playInstruction()
	startingLetter.startTimer();
	var d=new Date();
	starstartingLetterme=d.getDate()+"-"+(d.getMonth()+1)+"-"+d.getFullYear()+" "+d.getHours()+":"+d.getMinutes()+":"+d.getSeconds();
	startingLetter.skipFlag=true;
}
// Creates Div //
startingLetter.setCarAtRandomPos=function(parentDiv,numberOfDivs,idNo,data)
{
	var carElement,letter;
    for(var i=1;i<=numberOfDivs;i++)
    {
        carElement= document.createElement("div");
        carElement.setAttribute("id","carDiv"+idNo); 
        carElement.setAttribute("class","noPaddingcls backgroundProp col-lg-2 col-md-2 col-xs-2 col-sm-2"); 
		carElement.style.backgroundImage="url("+Utils.Path+"images/"+startingLetter.carImages[idNo].imageName+")";
		carElement.setAttribute("cubeData",data);
		carElement.setAttribute("crachedData","crashcar"+startingLetter.carImages[idNo].dataId+".png");
		carElement.setAttribute("onclick","startingLetter.checkAnswer(this);");
        parentDiv.appendChild(carElement);
        letter=document.createElement("p");
        letter.setAttribute("id","letter"+idNo);
		letter.setAttribute("class","noPaddingcls paraCls text-center");
       	letter.innerHTML=data;
        carElement.appendChild(letter);
    }
}
//move vehichles with upward direction//
startingLetter.animatecar=function(div)
{
	var speed=0;
	speed=11000;
    //speed=Math.floor((Math.random()*1000)+4200);
   // speed=Math.floor((Math.random()*500)+4200);
    $("#"+div).css({'top':$('#carDivsInner').height()});
	console.log($('#carDivsInner').height());
    $("#"+div).animate(
    {
		'top':'-='+($(document).height()+($("#"+div).outerHeight()))
    },speed,function()
    {
     $(this).stop();
      id = $(this).prop('id');
      startingLetter.animatecar(id);
    });
}
// get Random Word//
startingLetter.getWord=function()
{
	var randomWord=0,word='',langWord='';
	langWord=startingLetter.wordData[startingLetter.totalQue].langWord;
	word=startingLetter.wordData[startingLetter.totalQue].word;
	wordName=word;
	questionId=startingLetter.wordData[startingLetter.totalQue].questionId;
	wordDiv.innerHTML=langWord;
	document.getElementById("wordDiv").setAttribute("data",word[0]);
	startingLetter.getUniqueLetters(word);
}
// get unique letters that set to div //
startingLetter.getUniqueLetters=function(word)
{
	var randomLetter='';
	startingLetter.letterArr.push(word[0]);
	for(var i=0;i<4;i++)
	{	
		randomLetter=Math.floor(Math.random() * (startingLetter.letters.length));
		while($.inArray(startingLetter.letters[randomLetter],startingLetter.letterArr)!=-1)
		{
			randomLetter=Math.floor(Math.random() *(startingLetter.letters.length));
		}
		startingLetter.letterArr.push(startingLetter.letters[randomLetter]);
	}
	shuffleArray(startingLetter.letterArr);
}
// play sound again //
startingLetter.playSoundAgain=function()
{
	clearInterval(startingLetter.noResponseTimer);
	clearTimeout(startingLetter.timeOut);
	document.getElementById('playsound').src=(Utils.Path+"sounds/"+startingLetter.wordData[startingLetter.totalQue].sound);
	document.getElementById('playsound').play();
	startingLetter.startTimer();
}
//check Answer //
startingLetter.checkAnswer=function(obj)
{
	var cubeData,wordData,soundStr='',crachedData='';
	startingLetter.skipFlag=false;
	startingLetter.attemptCnt++
	startingLetter.letterArr.length=0;
	clearInterval(startingLetter.noResponseTimer);
	$(obj).removeClass('rotateCls');
	cubeData=document.getElementById(obj.id).getAttribute("cubeData");
	
	wordData=document.getElementById("wordDiv").getAttribute("data");
	$("#skipDiv").css("pointer-events","none");
	$('.backgroundProp').stop();
	$('#carDivsInner').css('pointer-events','none');
		$('#soundDiv').css('pointer-events','none');
	if(startingLetter.nextQuestionTimeOut)
	{
		clearTimeout(startingLetter.nextQuestionTimeOut);
		startingLetter.nextQuestionTimeOut=null;
	}
	if(cubeData == wordData)
	{
		scoredMarks=10;
		$(obj).stop();
		document.getElementById('resultDiv').style.visibility='visible';
		startingLetter.correctCounter++;
		console.log(wordName,totalNos,"word");
		if(Utils.mobileDeviceFlag)
			Android.addLearntData(cubeData,totalNos,"word");  
		//soundStr="sounds/"+wordData+".mp3";
		soundStr="sounds/Instruction/Carpassinghorn.mp3";
		startingLetter.showScore();
		startingLetter.correctAnimateCar(obj);
	}
	else
	{
		scoredMarks=0;
		$('#'+obj.id).stop();
		crachedData=document.getElementById(obj.id).getAttribute("crachedData");
		document.getElementById(obj.id).style.backgroundImage="url("+Utils.Path+"images/"+crachedData+")";
		$(obj).css('pointer-events','none');
		startingLetter.attemptFlag=true;
		startingLetter.wrongCnt++;
		
			soundStr="sounds/instruction/carcrash.mp3"; 
			startingLetter.showScore();
	}
	startingLetter.nextQuestionTimeOut=setTimeout(function()
	{
		startingLetter.nextQuestion();
	},1500);
	startingLetter.wordData.splice(startingLetter.totalQue,1);
	document.getElementById('playsound').src=(Utils.Path+""+soundStr);
	document.getElementById('playsound').play();
}
//right Animation
startingLetter.correctAnimateCar=function(obj)
{
	$(obj).animate(
	{
		'top':'-='+($(document).height()+($(obj).outerHeight()))
	},1800,function()
	{
	  id = $(this).prop('id');
	});
}
// next Question //
startingLetter.nextQuestion=function()
{
	clearInterval(startingLetter.noResponseTimer);
	clearTimeout(startingLetter.nextQuestionTimeOut);
	$("#skipDiv").css("pointer-events","auto");
	$('.backgroundProp').stop();
	startingLetter.letterArr.length=0;
	carDivsInner.innerHTML='';
	wordDiv.innerHTML='';
	startingLetter.questionCount++;
	document.getElementById('resultDiv').style.visibility='hidden';
	$('#carDivsInner').css('pointer-events','auto');
	$('#soundDiv').css('pointer-events','auto');
	clearTimeout(startingLetter.nextQ);
	if(startingLetter.totalQue < startingLetter.wordData.length)
	{
		startingLetter.getWord();
		startingLetter.createDiv();
	}
	else if(startingLetter.totalQue==startingLetter.wordData.length && startingLetter.wordData.length !=0)
		startingLetter.showPopup();
	else
	{
		startingLetter.showLastPage();
	}
}
//skip Question
startingLetter.skippedQuestion=function()
{	
	startingLetter.skippedCnt++;
	startingLetter.totalQue++;	
	if(startingLetter.totalQue==startingLetter.wordData.length)
		startingLetter.showPopup();
	else	
		startingLetter.nextQuestion();
}
//show modal
startingLetter.showPopup=function()
{
	clearInterval(startingLetter.noResponseTimer);
	clearTimeout(startingLetter.timeOut);
	$('#askForSkipedQuestionDiv').show();
	$('#textInstuction').text(startingLetter.hardcodedData.responseMsg);
	$('#Yes').text(startingLetter.hardcodedData.yes);
	$('#No').text(startingLetter.hardcodedData.no);
	document.getElementById('soundDiv').style.display="block";
	document.getElementById('skipDiv').style.display="block";
	document.getElementById('wordDiv').style.visibility="visible";
	document.getElementById('playsound').pause();
	document.getElementById("gamepage").style.display="block";
}
startingLetter.showSkippedQuestions=function()
{
	$('#askForSkipedQuestionDiv').hide();
	document.getElementById("gamepage").style.display="block";
	document.getElementById('soundDiv').style.display="block";
	document.getElementById('skipDiv').style.display="block";
	document.getElementById('wordDiv').style.visibility="visible";
	startingLetter.skipFlag=true;
	startingLetter.skippedCnt=0
	startingLetter.totalQue=0;
	startingLetter.letterArr.length=0;
	$('.backgroundProp').stop();
	carDivsInner.innerHTML='';
	wordDiv.innerHTML='';
	startingLetter.getWord();
	startingLetter.createDiv();
}
// gets call on home button //
startingLetter.HomePage=function()
{
	clearInterval(startingLetter.noResponseTimer);
	$('.backgroundProp').stop();
	document.getElementById("playSoundBack").pause();
	if(startingLetter.attemptFlag)
	{
		scoredMarks=0;
		startingLetter.attemptFlag=false;
		startingLetter.showScore();
	}
	location.reload();
}
startingLetter.playInstruction=function()
{
	startingLetter.soundFlag=true;
	if(startingLetter.objPointerFlag)
		$(".pointerClass").css({"pointer-events":"none"});
	getDuration(Utils.Path+'sounds/'+startingLetter.wordData[startingLetter.totalQue].sound);
	//getDuration(Utils.Path+'sounds/'+startingLetter.hardcodedData.instruction);
}
function getDuration(src)
{
	var duration=0;
	if(startingLetter.soundFlag)
	{
		$('#playsound').on("loadedmetadata", function()
		{
			startingLetter.soundFlag=false;
			duration=$('#playsound').prop('duration');
			$('#playsound').unbind("loadedmetadata");
			startingLetter.playNextSound(duration);
		});
		$('#playsound').prop('src',src);
	}
}
startingLetter.playNextSound=function(duration)
{
	document.getElementById('playsound').play();
	if(startingLetter.soundTimer)
	{
		clearTimeout(startingLetter.soundTimer);
		startingLetter.soundTimer=null;
	}
	startingLetter.soundTimer=setTimeout(function()
	{
		document.getElementById('playsound').pause();
		document.getElementById('playsound').src=Utils.Path+'sounds/Instruction/'+startingLetter.hardcodedData.instruction;
		document.getElementById('playsound').play();
		/* clearInterval(startingLetter.noResponseTimer);
		clearTimeout(startingLetter.timeOut); */
		
		setTimeout(function(){
			if(startingLetter.objPointerFlag)
			{
				startingLetter.objPointerFlag=false;
				$(".pointerClass").css({"pointer-events":"auto"});
			}
		},duration*800);
		startingLetter.startTimer();
	},duration*1000);
}

startingLetter.startTimer=function()
{
	clearTimeout(startingLetter.soundTimer);
	if(startingLetter.noResponseTimer)
	{
		clearInterval(startingLetter.noResponseTimer);
		startingLetter.noResponseTimer=null;
		startingLetter.seconds=0;
	}	
	startingLetter.noResponseTimer=setInterval(function() 
	{
		startingLetter.seconds++;
		if(startingLetter.seconds>=7)
		{
			clearTimeout(startingLetter.soundTimer);
			startingLetter.soundTimer=null;
			  document.getElementById("playsound").src=Utils.Path+"sounds/instruction/"+startingLetter.hardcodedData.noResponce;
			document.getElementById("playsound").play();  
		//	$(".pointerClass").css("pointer-events","auto");
			clearInterval(startingLetter.noResponseTimer)
			if(startingLetter.timeOut)
			{
				clearTimeout(startingLetter.timeOut);
				startingLetter.timeOut=null;
			}
			startingLetter.timeOut=setTimeout(function()
			{
				startingLetter.seconds=0;
				startingLetter.startTimer();
			},2000);
		}
	},1000);
} 
//show score
startingLetter.showScore=function()
{
	startingLetter.attemptFlag=false;
	console.log(resId,questionId,scoredMarks,10,1,starstartingLetterme);
	if(Utils.mobileDeviceFlag)
		Android.addScore(resId,questionId,scoredMarks,10,1,starstartingLetterme);	
}
//show last page
startingLetter.showLastPage=function()
{
	clearTimeout(startingLetter.soundTimer);
	clearInterval(startingLetter.noResponseTimer);
	document.getElementById('soundDiv').style.display="none";
	document.getElementById('skipDiv').style.display="none";
	document.getElementById('askForSkipedQuestionDiv').style.display="none";
	document.getElementById('wordDiv').style.visibility="hidden";
	document.getElementById("endpage").style.display="block";
	document.getElementById("gamepage").style.display="none";
	document.getElementById('playsound').pause();
	document.getElementById('gameOver').innerHTML=startingLetter.hardcodedData.message2;
	$('#nextDiv').addClass('blink_me');
	if(Utils.mobileDeviceFlag) 
		Android.StudentCertification(startingLetter.correctCounter,totalQuestion,"6"); 
	startingLetter.giveStars();
}
startingLetter.createStars=function()
{
	var newImage,newDiv,i,numberOfStars=5;
	for(i=1;i<=numberOfStars;i++)
	{
		newDiv= document.createElement("div");
		newDiv.setAttribute("id","starDiv"+i); 
		newDiv.setAttribute("class","noPaddingcls stars col-xs-2 col-md-2 col-lg-2 col-sm-2"); 

		newImage= document.createElement("img");
		newImage.setAttribute("id","starImg"+i); 
		newImage.setAttribute("class","img-responsive noPaddingcls col-sm-12 col-lg-12 col-md-12 col-xs-12"); 
		newImage.setAttribute("src",Utils.Path+"images/star1.png");
		$(newDiv).append(newImage);
		$("#starDiv").append(newDiv);
	}
	$("#starDiv").css("visibility","hidden");
}
startingLetter.giveStars=function()
{
	
	var i,numberOfStars=startingLetter.correctCounter;
	for(i=1;i<=numberOfStars;i++)
		document.getElementById("starImg"+i).setAttribute("src",Utils.Path+"images/star2.png");
	if(numberOfStars!=0)
	{
		document.getElementById('playsound').src=Utils.Path+'sounds/instruction/Star'+numberOfStars+'.mp3';
		document.getElementById('playsound').play();
	}
	$("#starDiv").css("visibility","visible");
}
startingLetter.showNextGame=function()
{
	if(Utils.mobileDeviceFlag)
		Android.GotoNextGame();
}