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.Attempt=0;
	Measurement.timer;
	Measurement.attemptFlag=false;
	Measurement.flag=true;
	Measurement.checkUniqueQuestion=[];
}
Measurement.setImages=function()
{
	document.body.style.backgroundImage="url("+Utils.path+Measurement.coverImage+")";
	document.getElementById("homeid").style.visibility="hidden";
	document.getElementById("nextbtnid").style.display="none";
	$("#playbtnid").prop("src","images/Play.png");
	$("#homeid").prop("src","images/Home.png");
	$("#logoid").prop("src","images/logo.png");
	$("#nextbtnid").prop("src","images/Next.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";
	document.getElementById("homeid").style.visibility="visible";
	$("#customerOrderImg").prop("src","images/customer1standig.png");
	$("#serverImg").prop("src","images/assistantlookingup.png");
	document.getElementById("acknowledgementDiv").innerHTML="";
   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.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!=Measurement.QuetionArray.length-1){
			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];
		}
		else if(Measurement.QuetionArray[Measurement.QuetionCounter].unit=="मिलीलीटर"){
			var ran=Math.floor(Math.random()*Measurement.miliOptionsArray.length);
			var noOfOrder=Measurement.miliOptionsArray[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/how_much_F.mp3");
				}     
				Measurement.AnswerFlag=false;
			}
			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");
				document.getElementById("Instruction").style.visibility="visible";
				$("#selectOption").addClass("animated fadeInUp");
			}
		}
		else{
			Measurement.AnswerFlag=true;
			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.getData=function(object)
{
	totalMarks=10;
	var selectdWord=document.getElementById(object.id).innerHTML.split(" ");
	selectdWord=selectdWord[0];
	Measurement.Attempt++;
	if(selectdWord==Measurement.Answer)
	{
		Measurement.attemptFlag=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");
		clearTimeout(Measurement.timer);
		setTimeout(function()
		{
			$("#serverImg").prop("src","images/assistantlookingup.png");
		if(Measurement.Attempt==1)
			scoredMarks=10;
		else
			scoredMarks=5;
		Measurement.scoreFunction();
		Measurement.nextLevel();
		},5500);
	}
	else
	{
		$("#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()
		{
			$("#serverImg").prop("src","images/assistantlookingup.png");
			$("#nextbtnid").css("pointer-Events","auto");
			$("#selectOption").css("pointer-Events","auto");
			if(Measurement.Attempt==2)
			{
				$("#nextbtnid").css("pointer-Events","none");
				$("#selectOption").css("pointer-Events","none");
				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()
{
	if(Measurement.Attempt==0)
	{
		scoredMarks=-1;
		Measurement.scoreFunction();
	}
	else if(Measurement.attemptFlag==false)
	{
		scoredMarks=0;
		Measurement.scoreFunction();	
	}
	document.getElementById("playSound").pause();
	$("#selectOption").removeClass("animated fadeInUp");
	document.getElementById('selectOption').innerHTML="";
	document.getElementById("Instruction").style.visibility="hidden";
    document.getElementById('Order').innerHTML="";
	document.getElementById('noOfOrder').innerHTML="";
	Measurement.QuetionCounter++;
	Measurement.counter=1;
	Measurement.customerOrderArray=[];
	Measurement.orderCounter=0;
	Measurement.quecounter=0;
	Measurement.AnswerFlag=true;
	Measurement.Attempt=0;
	Measurement.attemptFlag=false;
	clearInterval(Measurement.Timer);
	clearTimeout(Measurement.instructionTimer);
	$("#salesman").css("visibility","hidden");
	$("#customer").css("visibility","hidden");
	if(Measurement.QuetionCounter==Measurement.noOfQuestions)
	{
		Measurement.gameOver();
	}
	else
	{
		Measurement.CreateMeasurement();
	}
}
//go to the cover page
Measurement.callHome=function()
{
	scoredMarks=0;
	Measurement.scoreFunction();
	location.reload(true);
}
//display game over page
Measurement.gameOver=function()
{
	document.getElementById("playSound").pause();
	clearInterval(Measurement.Timer);
	clearTimeout(Measurement.instructionTimer);
	document.getElementById("coverpage").style.display="none";
    document.getElementById("gamepage").style.display="none";
	document.getElementById("endpage").style.display="block";
	document.getElementById("acknowledgementDiv").style.display="none";
	document.getElementById("resetbtnid").src=Utils.path+"images/resetbutton.png";
	document.getElementById("creditbtnid").src=Utils.path+"images/credits.png";
	document.getElementById('acknowledgementDiv').style.backgroundImage="url('images/orderboard.png')";
	document.getElementById("gameover").innerHTML=Measurement.hardcodedData.gameover;
	for(i=0;i<Object.keys(Measurement.AcknowledgementPageData).length;i++)
	{
		div=document.createElement('div');
		div.className="font nopadding col-xs-12 col-sm-12 col-md-12 col-lg-12";
		div.innerHTML=Object.keys(Measurement.AcknowledgementPageData)[i]+" : "+Object.values(Measurement.AcknowledgementPageData)[i];
		acknowledgementDiv.appendChild(div);
	}
	div=document.createElement('div');
	div.className="font col-xs-12 col-sm-12 col-md-12 col-lg-12";
	div.innerHTML=Measurement.hardcodedData['createdOn'];
	acknowledgementDiv.appendChild(div);
}
//credit 
Measurement.showCredits=function()
{
	document.getElementById("acknowledgementDiv").style.display="block";
}