// 8 May //
var startingLetter={};
var Utils={};
Utils.Path='';
Utils.mobileDeviceFlag=false;
var questionId=0,startTime=0,scoredMarks=0,totalMarks=10,resId=0,totalNos=0,wordName='';
startingLetter.wordData=[];
startingLetter.questionCount=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('nextDiv').style.display="none";
	//	document.getElementById('home').style.visibility="hidden";
		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.attemptCnt=0;
	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('nextDiv').style.display="none";
	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('home').style.visibility="visible";
	document.getElementById('wordDiv').style.visibility="visible";
	document.getElementById('nextDiv').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);
	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('next').src=Utils.Path+"images/Next.png";
	document.getElementById('playAgain').src=Utils.Path+"images/replay.png";
	document.getElementById('credit').src=Utils.Path+"images/credits.png";
	document.getElementById('soundImg').src=Utils.Path+"images/sound.png";
	document.getElementById('carDivs').style.backgroundImage=Utils.Path+'url(images/road2.png)';
	document.getElementById('gameOverNAck').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);
	}
	startingLetter.playInstruction();
	var d=new Date();
	startTime=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()*25000)+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[0].langWord;
	word=startingLetter.wordData[0].word;
	wordName=word;
	questionId=startingLetter.wordData[0].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()
{
	document.getElementById('playsound').src=(Utils.Path+"sounds/"+startingLetter.wordData[0].sound);
	document.getElementById('playsound').play();
} 
//check Answer //
startingLetter.checkAnswer=function(obj)
{
	var cubeData,wordData,soundStr='',crachedData='';
	startingLetter.skipFlag=false;
	$(obj).removeClass('rotateCls');
	cubeData=document.getElementById(obj.id).getAttribute("cubeData");
	wordData=document.getElementById("wordDiv").getAttribute("data");
	if(startingLetter.wrongCnt==0)
		scoredMarks=10;
	else if(startingLetter.wrongCnt==1)
		scoredMarks=5;
	else
		scoredMarks=0;
	if(startingLetter.nextQuestionTimeOut)
	{
		clearTimeout(startingLetter.nextQuestionTimeOut);
		startingLetter.nextQuestionTimeOut=null;
	}
	if(cubeData == wordData)
	{
		$(obj).stop();
		document.getElementById('resultDiv').style.visibility='visible';
		
		console.log(wordName,totalNos,"word");
		 if(Utils.mobileDeviceFlag)
			Android.addLearntData(cubeData,totalNos,"word");  
		$('#carDivsInner').css('pointer-events','none');
		$('#soundDiv').css('pointer-events','none');
		//soundStr="sounds/"+wordData+".mp3";
		soundStr="sounds/Instruction/Carpassinghorn.mp3";
		
		startingLetter.showScore();
		startingLetter.nextQuestionTimeOut=setTimeout(function()
		{
			startingLetter.nextQuestion();
		},3000);
		startingLetter.correctAnimateCar(obj);
	}
	else
	{
		$('#'+obj.id).stop();
		$(obj).css('pointer-events','none');
		crachedData=document.getElementById(obj.id).getAttribute("crachedData");
		document.getElementById(obj.id).style.backgroundImage="url("+Utils.Path+"images/"+crachedData+")";
		startingLetter.attemptFlag=true;
		startingLetter.wrongCnt++;
		if(startingLetter.wrongCnt == 1 || startingLetter.wrongCnt == 2)
			soundStr="sounds/instruction/carcrash.mp3"; 
		else
			soundStr="sounds/instruction/carcrash.mp3"; 
		startingLetter.attemptCnt++;
	}
	document.getElementById('playsound').src=(Utils.Path+""+soundStr);
	document.getElementById('playsound').play();
}
startingLetter.correctAnimateCar=function(obj)
{
	$(obj).animate(
	{
		'top':'-='+($(document).height()+($(obj).outerHeight()))
	},1800,function()
	{
	  id = $(this).prop('id');
	});
}
// next Question //
startingLetter.nextQuestion=function()
{
	clearTimeout(startingLetter.nextQuestionTimeOut);
	$('.backgroundProp').stop();
	carDivsInner.innerHTML='';
	wordDiv.innerHTML='';
	startingLetter.questionCount++;
	document.getElementById('resultDiv').style.visibility='hidden';
	$('#carDivsInner').css('pointer-events','auto');
	$('#soundDiv').css('pointer-events','auto');
	if(startingLetter.attemptFlag)
	{
		scoredMarks=0;
		startingLetter.attemptFlag=false;
		startingLetter.showScore();
	}
	if(startingLetter.skipFlag)
	{
		scoredMarks=-1;
		startingLetter.showScore();
	}
	if(startingLetter.questionCount < 5)
	{
		startingLetter.wordData.splice(0,1);
		startingLetter.initVariables();
		startingLetter.getWord();
		startingLetter.createDiv();
	}
	else
		startingLetter.showLastPage();
}
// gets call on home button //
startingLetter.HomePage=function()
{
	$('.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[0].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();
		setTimeout(function(){
			if(startingLetter.objPointerFlag)
			{
				startingLetter.objPointerFlag=false;
				$(".pointerClass").css({"pointer-events":"auto"});
			}
		},duration*800);
	},duration*1000);
}

//show score
startingLetter.showScore=function()
{
	startingLetter.attemptFlag=false;
	console.log(resId,questionId,scoredMarks,10,1,startTime);
	if(Utils.mobileDeviceFlag)
		Android.addScore(resId,questionId,scoredMarks,10,1,startTime);	
}
//show last page
startingLetter.showLastPage=function()
{
	clearTimeout(startingLetter.soundTimer);
	document.getElementById('soundDiv').style.display="none";
	document.getElementById('nextDiv').style.display="none";
	document.getElementById('wordDiv').style.visibility="hidden";
	document.getElementById("endpage").style.display="block";
	document.getElementById("acknowledgementDiv").style.display="block";
	document.getElementById("gamepage").style.display="none";
	document.getElementById('playsound').pause();
	document.getElementById('gameOver').innerHTML=startingLetter.hardcodedData.message2;
	for(i=0;i<Object.keys(startingLetter.AcknowledgementPageData).length;i++)
	{
		div=document.createElement('div');
		div.className="fontClass firstLetter col-xs-12 col-sm-12 col-md-12 col-lg-12";
		div.innerHTML=Object.keys(startingLetter.AcknowledgementPageData)[i]+" : "+Object.values(startingLetter.AcknowledgementPageData)[i];
		acknowledgementDiv.appendChild(div);
	}
	 div=document.createElement('div');
	div.className="fontClass firstLetter col-xs-12 col-sm-12 col-md-12 col-lg-12";
	div.innerHTML=startingLetter.hardcodedData['createdOn'];
	acknowledgementDiv.appendChild(div);
	document.getElementById("acknowledgementDiv").style.display="none"; 
}
//show credit
startingLetter.showCredits=function()
{
	document.getElementById("acknowledgementDiv").style.display="block";
}
//gets call on play again button
startingLetter.playAgain=function()
{
	startingLetter.wordData=[];
	startingLetter.questionCount=0;
	$('.backgroundProp').stop();
	document.getElementById('soundDiv').style.display="block";
	document.getElementById('nextDiv').style.display="block";
	document.getElementById('wordDiv').style.visibility="visible";
	document.getElementById("endpage").style.display="none";
	document.getElementById("acknowledgementDiv").style.display="none";
	acknowledgementDiv.innerHTML='';
	document.getElementById("gamepage").style.display="block";
	startingLetter.initVariables();
	getUniqueValArr(startingLetter.Data,startingLetter.wordData,10);
	startingLetter.getWord();
	startingLetter.createDiv();
}