var Measurement={}; // namespace name
var Utils={};
Utils.path='';
Utils.mobileDeviceFlag = false;
var questionId = 0, startTime = 0, scoredMarks = 0, totalMarks =10, resId = 0,  label = "", level=1;
$(document).ready(function()
{
    if ((navigator.userAgent.match(/Android|BlackBerry|iPhone|iPad|iPod|Opera Mini|IEMobile/i)) && !(window.location.href.includes('http')))
		Utils.mobileDeviceFlag=true;
	$(".se-pre-con").fadeOut("slow");
	setTimeout(function()
	{
		Measurement.setImages();
	},100);
},200);
Measurement.globalVariables=function()
{
	Measurement.noOfQuestions=5;
	Measurement.onOfOptions=4;
	Measurement.QuetionArray=[];
	Measurement.optionsArray=[];
	Measurement.QuetionCounter=0;
	Measurement.Answer;
	Measurement.counter=1;
	Measurement.customerOrderArray=[];
	Measurement.orderCounter=0;
	Measurement.quecounter=0;
	Measurement.Timer;
	Measurement.previousAnswer;
	Measurement.gramOptionsArray=[100,200,250,500];
	Measurement.miliOptionsArray=[10,50,100,150,200];
	Measurement.checkOptionArray=["ग्रॅम","किलोग्रॅम"];
	Measurement.previousSound;
	Measurement.audiosToPlay=[];
	Measurement.AnswerFlag;
	Measurement.CustomerAnswer;
	Measurement.timer;
	Measurement.attemptFlag=false;
	Measurement.scoreFlag=false;
	Measurement.correctCounter=0;
	Measurement.seconds = 0;
	Measurement.noResponseTimer = 0;
	Measurement.checkUniqueQuestion=[];
}
Measurement.setImages=function()
{
	document.body.style.backgroundImage="url("+Utils.path+Measurement.coverImage+")";
	document.getElementById("nextbtnid").style.display="none";
	$("#playbtnid").prop("src","images/Play.png");
	$("#logoid").prop("src","images/logo.png");
	$("#nextbtnid").prop("src","images/skip.png");
    document.getElementById('orderPage').style.backgroundImage="url('images/orderboard.png')";
    document.getElementById('selectOption').style.backgroundImage="url('images/handBoard.png')";
	document.getElementById('orderTextDiv').innerHTML="ORDER";
	document.getElementById('Instruction').innerHTML=Measurement.Instruction;
	//document.getElementById("Instruction").style.visibility="hidden";
}
//create options
Measurement.selectMatrix=function()
{
	Measurement.globalVariables();
	document.body.style.backgroundImage ="url('images/BG.png')";
	document.getElementById("coverpage").style.display="none";
	document.getElementById("endpage").style.display="none";
	document.getElementById("gamepage").style.display="block";
	document.getElementById("nextbtnid").style.display="block";
	$("#customerOrderImg").prop("src","images/customer1standig.png");
	$("#serverImg").prop("src","images/assistantlookingup.png");
   Measurement.populate();
}
//populate questions from json
Measurement.populate=function()
{
	var array=[];
	for(var j=0;j<Measurement.noOfQuestions-1;j++)
	{	
		var randomNumber=Math.floor(Math.random()*Measurement.Data.length);
		while(array.includes(Measurement.Data[randomNumber]))
		{
			randomNumber=Math.floor(Math.random()*Measurement.Data.length);
		}
		array.push(Measurement.Data[randomNumber]);
		Measurement.QuetionArray.push(Measurement.Data[randomNumber]);
	}
	var ranNo=Math.floor(Math.random()*Measurement.Data.length);
	Measurement.QuetionArray.push(Measurement.Data[ranNo]);
	console.log(Measurement.QuetionArray);
	shuffleArray(Measurement.QuetionArray);
	Measurement.CreateMeasurement(); 
}
//suffle the array
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;
}
Measurement.CreateMeasurement=function()
{ 
	$("#selectOption").css("pointer-Events","auto");
	$("#nextbtnid").css("pointer-Events","auto");
	d = new Date();  //date object
	startTime = d.getDate() + "-" + (d.getMonth() + 1) + "-" + d.getFullYear() + " " + d.getHours() + ":" + d.getMinutes() + ":" + d.getSeconds();  //to get the current date
	var j,unit,cnt=0;
	Measurement.scoreFlag=false;
	Measurement.optionsArray=[];
	Measurement.Answer=Measurement.QuetionArray[Measurement.QuetionCounter].unit; 
	Measurement.optionsArray.push(Measurement.Answer);
	for(var j=0;j<Measurement.onOfOptions-1;)
	{
		var randomNumber=Math.floor(Math.random()*Measurement.Data.length);
		if(!Measurement.optionsArray.includes(Measurement.Data[randomNumber].unit)){
			Measurement.optionsArray.push(Measurement.Data[randomNumber].unit);
			j++;
			}
	 cnt++;
	} 
	shuffleArray(Measurement.optionsArray);
    for(j=0;j<Measurement.onOfOptions;j++)
	{
		var questonDiv= document.createElement("span");
		questonDiv.setAttribute("id","quediv"+(j+1));
		questonDiv.setAttribute("class"," nopadding units");
        document.getElementById('selectOption').appendChild(questonDiv);
       if(j!=4){
			unit=Measurement.optionsArray[j];
			questonDiv.innerHTML=unit+" ,"; 
			questonDiv.setAttribute("onclick","Measurement.getData(this)");
		}
	}
	unit=Measurement.optionsArray[j-1];
	document.getElementById("quediv"+(j)).innerHTML=unit; 
	document.getElementById("quediv"+(j)).setAttribute("onclick","Measurement.getData(this)");
	var ranNo=Math.floor(Math.random()*Measurement.QuetionArray[Measurement.QuetionCounter].List.length);
	while(Measurement.checkUniqueQuestion.includes(Measurement.QuetionArray[Measurement.QuetionCounter].List[ranNo].name))
	{
		 ranNo=Math.floor(Math.random()*Measurement.QuetionArray[Measurement.QuetionCounter].List.length);
	}
	Measurement.checkUniqueQuestion.push(Measurement.QuetionArray[Measurement.QuetionCounter].List[ranNo].name);
	Measurement.customerOrderArray.push(Measurement.QuetionArray[Measurement.QuetionCounter].List[ranNo].name);
	console.log(Measurement.checkUniqueQuestion);
	var max=Number(Measurement.QuetionArray[Measurement.QuetionCounter].List[ranNo].Max)+1;//
	var min=Number(Measurement.QuetionArray[Measurement.QuetionCounter].List[ranNo].Min);//
	var noOfOrder=Math.floor(Math.random() * (max - min) ) + min;
	if(Measurement.QuetionArray[Measurement.QuetionCounter].unit=="ग्रॅम"){
		var ran=Math.floor(Math.random()*Measurement.gramOptionsArray.length);
		var noOfOrder=Measurement.gramOptionsArray[ran];
		}
	label=Measurement.QuetionArray[Measurement.QuetionCounter].List[ranNo].name;//
	Measurement.customerOrderArray.push(Measurement.QuetionArray[Measurement.QuetionCounter].List[ranNo].Audio); //
	Measurement.customerOrderArray.push(Measurement.QuetionArray[Measurement.QuetionCounter].List[ranNo].gender); 
	Measurement.customerOrderArray.push(noOfOrder);
	Measurement.playInstructions();
}
Measurement.playInstructions=function()
{
	$("#salesman").css("visibility","visible");
	$("#customer").css("visibility","hidden");
	$("#selectOption").css("visibility","hidden");
	if(Measurement.counter%2!=0)
	{
		document.getElementById('salesman').innerHTML=Measurement.shopkeeperInstruction[Measurement.quecounter].Instruction;
		getDuration(Utils.path+"sounds/"+Measurement.shopkeeperInstruction[Measurement.quecounter].sound);
		document.getElementById("playSound").play();
	}
	Measurement.communication();
}
function getDuration(src) {
    var duration = 0;
    $('#playSound').on("loadedmetadata", function () {
        duration = $('#playSound').prop('duration');
		$('#playSound').unbind("loadedmetadata");
		Measurement.playNextSound(duration);
    });
	$('#playSound').prop('src', src);
}
Measurement.playNextSound = function (duration)                             //function for instruction
{
    document.getElementById('playSound').play();
    if (Measurement.instructionTimer) {
        clearTimeout(Measurement.instructionTimer);
        Measurement.instructionTimer = null;
    }
    Measurement.instructionTimer = setTimeout(function () {
	if(Measurement.AnswerFlag==false)
		{
			$("#playSound").prop("src",Utils.path+'sounds/'+Measurement.CustomerAnswer);
			document.getElementById("playSound").play();
		}
    }, duration * 1000);
}
Measurement.communication = function ()                             //function for instruction
{
	if (Measurement.Timer) {
        clearInterval(Measurement.Timer);
        Measurement.Timer = null;
    }
	Measurement.Timer=setInterval(function () {
		Measurement.counter++;
		if(Measurement.counter%2 != 0)
		{
			Measurement.quecounter++;
			if(Measurement.quecounter<3)
			{
			$("#salesman").css("visibility","visible");
			$("#customer").css("visibility","hidden");
			if(Measurement.quecounter==1){
				if(Measurement.customerOrderArray[2]=="M"){
					document.getElementById('salesman').innerHTML=Measurement.shopkeeperInstruction[Measurement.quecounter].Instruction+" "+Measurement.previousAnswer+" "+"?";       
					getDuration(Utils.path+"sounds/"+Measurement.shopkeeperInstruction[Measurement.quecounter].sound);
					}
					else{
					document.getElementById('salesman').innerHTML="किती"+" "+Measurement.previousAnswer+" "+"?";  
					getDuration(Utils.path+"sounds/Instruction2.mp3");
					}
					Measurement.AnswerFlag=false;
				//getDuration(Utils.path+"sounds/"+Measurement.shopkeeperInstruction[Measurement.quecounter].sound);
			}
			else{
				$("#playSound").prop("src",Utils.path+'sounds/'+Measurement.CustomerAnswer);
				document.getElementById("playSound").play();
				document.getElementById('salesman').innerHTML=Measurement.previousAnswer+"   "+Measurement.shopkeeperInstruction[Measurement.quecounter].Instruction+""+"?"; 
				setTimeout(function(){
				getDuration(Utils.path+"sounds/"+Measurement.shopkeeperInstruction[Measurement.quecounter].sound);
				},1300);
			}
			document.getElementById("playSound").play();
			}
			if(Measurement.quecounter==2){
				$("#selectOption").css("visibility","visible");
				$("#selectOption").addClass("animated fadeInUp");
				document.getElementById("Instruction").style.visibility="visible";
				Measurement.startTimer();
			}
		}
		else{
			Measurement.AnswerFlag=true;
			console.log(Measurement.customerOrderArray);
			if(Measurement.orderCounter<=2)
			{
				$("#salesman").css("visibility","hidden");
				$("#customer").css("visibility","visible");
				if(Measurement.orderCounter==2)
				Measurement.previousAnswer=document.getElementById('customer').innerHTML=Measurement.customerOrderArray[Measurement.orderCounter+1];
				else
				Measurement.previousAnswer=document.getElementById('customer').innerHTML=Measurement.customerOrderArray[Measurement.orderCounter];
				document.getElementById("playSound").play();
				if(Measurement.orderCounter==0){
					document.getElementById('Order').innerHTML=Measurement.customerOrderArray[Measurement.orderCounter];
					Measurement.orderCounter++;
					Measurement.CustomerAnswer=Measurement.customerOrderArray[Measurement.orderCounter];
					getDuration(Utils.path+"sounds/"+ Measurement.customerOrderArray[Measurement.orderCounter]);
				}
				else{
					Measurement.orderCounter++;
					document.getElementById('noOfOrder').innerHTML=Measurement.customerOrderArray[Measurement.orderCounter];
					Measurement.CustomerAnswer=Measurement.customerOrderArray[Measurement.orderCounter]+".mp3";
					getDuration(Utils.path+"sounds/"+Measurement.customerOrderArray[Measurement.orderCounter]+".mp3");
				}
				Measurement.orderCounter++;
			}
		}
		
	},3500);
}
Measurement.startTimer = function () {
	if (Measurement.noResponseTimer) {
		clearInterval(Measurement.noResponseTimer);
		Measurement.noResponseTimer = null;
		Measurement.seconds = 0;
	}
	Measurement.noResponseTimer = setInterval(function () {
		Measurement.seconds++;
		if (Measurement.seconds >= 5) {
			document.getElementById("playSound").src = Utils.path + "sounds/please_ans_the_ques.mp3";
			document.getElementById("playSound").play();
			clearInterval(Measurement.noResponseTimer);
			Measurement.timeOut = setTimeout(function () {
				Measurement.seconds = 0;
				Measurement.startTimer();
			}, 2000);
		}
	}, 1000);
}

Measurement.getData=function(object)
{
	totalMarks=10;
	clearInterval(Measurement.noResponseTimer);
	var selectdWord=document.getElementById(object.id).innerHTML.split(" ");
	selectdWord=selectdWord[0];
	if(selectdWord==Measurement.Answer)
	{
		Measurement.attemptFlag=true;
		Measurement.scoreFlag=true;
		$("#playSound").prop("src",Utils.path+'sounds/'+Measurement.previousAnswer+".mp3");
		document.getElementById("playSound").play();
		setTimeout(function(){
		getDuration(Utils.path+"sounds/"+Measurement.QuetionArray[Measurement.QuetionCounter].unitAudio);
		},1000);
		setTimeout(function(){
			$("#serverImg").prop("src","images/assistanthappy.png");
			getDuration(Utils.path+"sounds/Right_answer.mp3");
			},2000);
			setTimeout(function(){
				$("#serverImg").prop("src","images/assistanthappy.png");
				getDuration(Utils.path+"sounds/clapping.mp3");
				},3500);
		$("#salesman").css("visibility","hidden");
		$("#customer").css("visibility","visible");
		document.getElementById('customer').innerHTML=Measurement.customerOrderArray[Measurement.orderCounter-1]+"  "+selectdWord;
		document.getElementById('noOfOrder').innerHTML=Measurement.customerOrderArray[Measurement.orderCounter-1]+" "+selectdWord;
		$("#nextbtnid").css("pointer-Events","none");
		$("#selectOption").css("pointer-Events","none");
		Measurement.correctCounter++;
		clearTimeout(Measurement.timer);
		setTimeout(function()
		{
			Measurement.QuetionArray.splice(Measurement.QuetionCounter, 1);
			$("#serverImg").prop("src","images/assistantlookingup.png");
			scoredMarks=10;
		Measurement.scoreFunction();
		Measurement.nextLevel();
		},5500);
	}
	else
	{
		Measurement.scoreFlag=true;
		$("#serverImg").prop("src","images/assistantunsad.png");
		document.getElementById('playSound').src=Utils.path+"sounds/wrong_ans.mp3";
		document.getElementById("playSound").play();
		$("#nextbtnid").css("pointer-Events","none");
		$("#selectOption").css("pointer-Events","none");
		Measurement.timer=setTimeout(function()
		{
			Measurement.QuetionArray.splice(Measurement.QuetionCounter, 1);
			$("#serverImg").prop("src","images/assistantlookingup.png");
			scoredMarks=0;
			Measurement.scoreFunction();
			Measurement.nextLevel();
		},3500);
	}
}
//score Function
Measurement.scoreFunction = function () {
	console.log(resId, questionId, scoredMarks, totalMarks, level, startTime, label);
	if (Utils.mobileDeviceFlag) {
		Android.addScore(resId, questionId, scoredMarks, totalMarks, level, startTime, label);
	}
}
//display next level
Measurement.nextLevel=function()
{
	document.getElementById("playSound").pause();
	$("#selectOption").removeClass("animated fadeInUp");
	document.getElementById("Instruction").style.visibility="hidden";
    document.getElementById('selectOption').innerHTML="";
    document.getElementById('Order').innerHTML="";
	document.getElementById('noOfOrder').innerHTML="";
	if(Measurement.scoreFlag==false)
		Measurement.QuetionCounter++;
	Measurement.counter=1;
	Measurement.customerOrderArray=[];
	Measurement.orderCounter=0;
	Measurement.quecounter=0;
	Measurement.AnswerFlag=true;
	clearInterval(Measurement.Timer);
	clearTimeout(Measurement.instructionTimer);
	$("#salesman").css("visibility","hidden");
	$("#customer").css("visibility","hidden");
	if(Measurement.QuetionArray.length==0)
		{
			Measurement.gameOver();
		}
	else if( Measurement.QuetionCounter==Measurement.QuetionArray.length)
		{
			document.getElementById("playSound").pause();
			clearInterval(Measurement.noResponseTimer);
			document.getElementById("responseBoxDiv").style.display="block";
			document.getElementById("confiramtionText").innerHTML=Measurement.hardcodedData.responseMsg;
			document.getElementById("Yes").innerHTML=Measurement.hardcodedData.yes;
			document.getElementById("No").innerHTML=Measurement.hardcodedData.no;
		}
		else 
		{
			Measurement.CreateMeasurement();
		}
}
//display skip questions
Measurement.showSkippedQuestions=function()
{
document.getElementById("responseBoxDiv").style.display="none";
Measurement.QuetionCounter=0;
Measurement.CreateMeasurement();	
}
//display game over page
Measurement.gameOver=function()
{
	document.getElementById("playSound").pause();
	clearInterval(Measurement.noResponseTimer);
	document.getElementById("responseBoxDiv").style.display="none";
	document.getElementById("coverpage").style.display="none";
    document.getElementById("gamepage").style.display="none";
	document.getElementById("endpage").style.display="block";
	document.getElementById("next").src=Utils.path+"images/Next.png";
	document.getElementById('next').classList.add('blink_me');
	document.getElementById("gameover").innerHTML=Measurement.hardcodedData.gameover;
	Measurement.createStars();
	Measurement.giveStars();
}
//function which creates star divs
Measurement.createStars=function()
{
	var newImage,newDiv,i,numberOfStars=5;
	for(i=1;i<=5;i++)
	{
		newDiv= document.createElement("div");
		newDiv.setAttribute("id","starDiv"+i); 
		newDiv.setAttribute("class","nopadding  col-xs-2 col-md-2 col-lg-2 col-sm-2"); 
		$("#starsDiv").append(newDiv);
		
		newImage= document.createElement("img");
		newImage.setAttribute("id","starImg"+i); 
		newImage.setAttribute("class","img-responsive nopadding col-sm-12 col-lg-12 col-md-12 col-xs-12"); 
		newImage.setAttribute("src",Utils.path+"images/star1.png");
		$(newDiv).append(newImage);
	}
}
 Measurement.giveStars=function()
{
	Measurement.queCnt=5;
 var fractionVar,i,numberOfStars=0,temp;
var total_No_of_Questions=5; 
ans=total_No_of_Questions/5;
temp=Measurement.correctCounter/ans;
numberOfStars=Math.floor(temp);
temp=Math.round(temp); 
for(i=1;i<=Math.floor(numberOfStars);i++)
	document.getElementById("starImg"+i).setAttribute("src",Utils.path+"images/star2.png");
	if(numberOfStars!=0)
	{
	document.getElementById("playSound").src=Utils.path+"sounds/"+"star"+numberOfStars+".mp3";
	document.getElementById("playSound").play();
	}
	console.log(Measurement.correctCounter,Measurement.queCnt);
	if(Utils.mobileDeviceFlag)
		Android.StudentCertification(Measurement.correctCounter,Measurement.queCnt,"5"); 
}
Measurement.goNext=function()
{
if(Utils.mobileDeviceFlag)
	Android.GotoNextGame();
}