/* JavaScript Document  
/  @author Nityanand Ojha
*/

const vertMargin = 20;
var rubricfntSize = "17px"
var quesfntSize = "17px"
var optionFntSize = "17px";
var fontFace = "Rubric";
var fontFace1 = "Ans, sans-serif";

var colorObj = {initial:"", select:"#99ffff"};
var rArr = ["Amazing","Brilliant","Excellent","Good","GoodJob","Superb","Welldone","Wonderful"];
var wArr = ["Oops"];
var _main;
var _rubricTxt;
var _quesTxt;
var srialNo;
var option;
var correctMC = [];
var audio;
var animDiv;
var count=1;
var interval;
var submitBtn;
var answerBtn;
var blankTxtField;
var selMC;
var Qno = 0;
var inCorrect = 0;
var rubAudio;

const introDelay = 1000;
var introVid;
//////// G for grammer, V for vocabulary..........
var introType = "";
var p_3;


function startIntro(_data)
{
	p_3 = _data;

	window.addEventListener("blur", e=>{
		//console.log("BLURRRRRR................");
		window.parent.postMessage({ "fun": "saveData", "arg": {p_3}, "saveLMS": true}, '*');
	})
	introVid = document.createElement("video");
	titleText = document.createElement("div");
	document.body.appendChild(introVid);
	introVid.style.position = "absolute";
	introVid.style.top = "0px";
	
	introVid.addEventListener("ended", onEnd);
	
	//titleText.style.width = "1280px";
	titleText.style.position = "absolute";
	titleText.style.fontFamily = "Title";
	titleText.style.opacity = 0;
	titleText.style.textAlign = "center";
	titleText.style.fontSize = "50px";
	document.body.appendChild(titleText);
	
	
	switch (introType.toLowerCase())
	{
		case "g":
			titleText.innerHTML = data.title;
			titleText.style.top="400px";
			titleText.style.left="750px";
			titleText.style.color = "#fff";
			introVid.src = "Assets/intro/Title_Grammar.mp4"
			introVid.play();
			setTimeout(showTitle, 3000);
			break;
		case "v":
			titleText.innerHTML = data.title;
			titleText.style.top="400px";
			titleText.style.left="420px";
			titleText.style.color = "#fff";
			introVid.src = "Assets/intro/Title_Vocab.mp4"	
			introVid.play();
			setTimeout(showTitle, 5000);
			break;
		default:
			introVid.removeEventListener("ended", onEnd);
			$(titleText).animate({opacity:0},1);
			$(introVid).animate({opacity:0},1, odd_one_out);
			//vidCont.style.backgroundImage = "url('Assets/images/bg.png')";		
			
		break;
	}
	/*submitBtn = document.getElementById("submit");
	submitBtn.style.visibility = "hidden";
	answerBtn = document.getElementById("answer");
	answerBtn.style.visibility = "hidden";*/
}

function showTitle()
{
	$(titleText).animate({opacity:1},1000);
	
}


function onEnd()
{
	vidCont.style.backgroundImage = "url('Assets/images/bg.png')";
	introVid.removeEventListener("ended", onEnd);
	$(titleText).animate({opacity:0},introDelay);
	$(introVid).animate({opacity:0}, introDelay, odd_one_out);
	
}

window.addEventListener('load', function(e) {
	function bindEvent(element, eventName, eventHandler) {
		if (element.addEventListener) {
			element.addEventListener(eventName, eventHandler, false);
		} else if (element.attachEvent) {
			element.attachEvent('on' + eventName, eventHandler);
		}
	}
	bindEvent(window, 'message', function(e) {
		//console.log("ON PAGE: ", e);
		try {
			//console.log("Ebook calling: ", e.data.fun, "ARG: ", e.data.arg);
			window[e.data.fun](e.data.arg);
		}catch(err) {
			console.log("Ebook calling error: ", err);
		}
	})
	//startIntro();
})


function odd_one_out(){
	document.body.removeChild(titleText);
	titleText = null;
	document.body.removeChild(introVid);
	introVid = null;
	
	srialNo = document.createElement("div");
	_main = document.getElementById("main")
	audio = document.createElement("audio");
	_main.appendChild(audio);
	sourceMP3 = document.createElement("source");
	audio.appendChild(sourceMP3)
	sourceOGG = document.createElement("source");
	audio.appendChild(sourceOGG)	
	_main = document.getElementById("main");
	
	_rubricTxt = document.createElement("div");
	document.body.appendChild(_rubricTxt);
	_rubricTxt.style.position = "absolute";
	_rubricTxt.innerHTML = data.rubric;
	_rubricTxt.style.fontSize = rubricfntSize;
	_rubricTxt.style.fontFamily = fontFace;
	_rubricTxt.style.color = "#3d8eb9";
	//_rubricTxt.style.background = "#fff";
	_rubricTxt.style.left = 0+"px";
	_rubricTxt.style.top = 0+"px";
	
	_rubricTxt.style.width = Math.min(_rubricTxt.offsetWidth, 500)+"px";
	
	rubAudio = document.createElement("img");
	rubAudio.src = "Assets/images/audio.png";
	_rubricTxt.appendChild(rubAudio);
	rubAudio.style.width = "30px";
	rubAudio.style.height = "30px";
	rubAudio.style.marginRight = "10px";
	rubAudio.style.cssFloat = "left";
	rubAudio.style.cursor = "pointer";
	rubAudio.addEventListener("click", onrubAudioClicked);
	
	_rubricTxt.insertBefore(rubAudio, _rubricTxt.childNodes[0]);
	
	addQuestion(0);
}

function onShowDialog(){
	new openDialogPopup({
		parent: _main,
		displayText: "<p><b>Answers</b><br>1 - birthday &emsp; 2 - home<br> 3 - balloons &emsp; 4 - cake <br>5 - friends</p>",
		left: 20,
		top: 325,
		width: 300,
		height: 160,
		lineHeight:35,
		backgroundColor:"#fff",
		});
}

function onrubAudioClicked(){
	rubAudio.src = "Assets/images/audio_ho.png";

	sourceMP3.src = "Assets/mp3/rubric.mp3";
	sourceOGG.src = "Assets/mp3/rubric.ogg";
	audio.load();
	audio.play();
	audio.addEventListener("ended", soundComplete);
}

function soundComplete(){
	audio.removeEventListener("ended", soundComplete);
	rubAudio.src = "Assets/images/audio.png";
}

function addingNextPre(){
	nextpreNav = document.createElement("div");
	nextpreNav.className = "nextpreNav";
	nextpreNav.setAttribute("id", "nextpreNav");
	nextpreNav.style.top = 516+"px";
	nextpreNav.style.left = 165+"px";
	_main.appendChild(nextpreNav);
	
	nextBtn = document.createElement("div");
	nextBtn.setAttribute("id", "nextBtn");
	
	preBtn = document.createElement("div");
	preBtn.setAttribute("id", "preBtn");
	disableObj(preBtn);
	nextpreNav.appendChild(nextBtn);
	nextpreNav.appendChild(preBtn);
	
	nextpreNav.addEventListener("click", onNavigationClick);
}

function onNavigationClick(e){
	
	if(e.target.id == "preBtn")
	{
		submitBtn.style.pointerEvents = "none";
		submitBtn.style.opacity = 0.5;
		inCorrect = 0;
		removePrevious();
		addQuestion(--Qno);	
		
		if(!Qno)
		{
			disableObj(e.target);
			return;
		}
		enableObj(getElement("nextBtn"));
		
	}else if(e.target.id == "nextBtn")
	{
		submitBtn.style.pointerEvents = "none";
		submitBtn.style.opacity = 0.5;
		inCorrect = 0;
		Qno++
		removePrevious();
		addQuestion(Qno);
		
		if(Qno==data.optionArr.length-1)
		{
			//console.log(Qno," dddddddddddddddddddd ",data.optionArr.length-1);
			disableObj(e.target);
			return;
		}
		enableObj(getElement("preBtn"));
	}	
	
}

function disableObj(obj)
{
	obj.style.pointerEvents = "none";
	obj.style.opacity = 0.5;
}

function enableObj(obj)
{
	obj.style.pointerEvents = "auto";
	obj.style.opacity = 1;
}

function getElement(str){
	return (document.getElementById(str));
}

function addQuestion(indx){
	var ypos=_rubricTxt.offsetHeight+vertMargin;
	if(data.optionLine){
		var optionLine = document.createElement("ques");
		document.body.appendChild(optionLine);
		optionLine.style.position = "absolute";
		optionLine.innerHTML = data.optionLine;
		optionLine.style.fontSize = quesfntSize;
		optionLine.style.fontFamily = fontFace1;
		optionLine.classList.add("optionLine");
		optionLine.style.left = 50+"px";
		optionLine.style.top = ypos+"px";		
		ypos += optionLine.offsetHeight+vertMargin;
	}
	
	var quesImg = new Image(400,290);
	var str = "Assets/images/Image_1.jpg";
	quesImg.src = str;
	_main.appendChild(quesImg);
	quesImg.style.position = "absolute";
	quesImg.style.left = "20px";
	quesImg.style.top = ypos+"px";
	ypos += quesImg.offsetHeight+vertMargin;
	
	for(var j=0; j<data.optionArr.length; j++){
		
		_quesTxt = document.createElement("ques")
		document.body.appendChild(_quesTxt);
		_quesTxt.style.position = "absolute";
		_quesTxt.innerHTML = data.quesArr[j].ques;
		_quesTxt.style.top = ypos+"px"
		_quesTxt.style.left = 0+"px";
		_quesTxt.style.fontSize = quesfntSize;
		_quesTxt.style.fontFamily = fontFace1;
		
		blankTxtField = document.getElementById("txtF");
		blankTxtField.id = "txtField"+j;
		blankTxtField.style.fontSize = quesfntSize;
		blankTxtField.style.fontFamily = fontFace1;
		blankTxtField.style.textAlign = "center";
		blankTxtField.style.width = blankSize[j]+"px";
		blankTxtField.addEventListener("change", onChangeTxt);		
		ypos += _quesTxt.offsetHeight+15;

		console.log("ADDED now checking with: ", p_3);
		if(p_3[j] && p_3[j].selected){
			blankTxtField.value = p_3[j].selected;
			if(p_3[j].isRight){
				setColor(blankTxtField, "#29ce29");
			}else{
				setColor(blankTxtField, "#ff0000");
			}
		}
		
		for(var i=0; i<data.optionArr[j].length; i++){	
			if(data.optionArr[j][i]){	
				//console.log(data.optionArr[j],"111111111114444");	
				option = document.createElement("div");
				option.style.position = "absolute"
				option.className = "optionDesign";
				option.innerHTML = data.optionArr[j][i];
				option.style.textAlign = "left";
				option.style.fontFamily = fontFace1;
				_main.appendChild(option);
				option.id = "op"+j+"_"+i;
				option.style.fontSize = optionFntSize;
				
				if(option.innerHTML == data.optionArr[j][data.Aarr[j]]){
					correctMC[j] = document.getElementById("op"+j+"_"+i);
					//console.log(option.innerHTML);
				}
				option.style.top = ypos+ "px";
				option.style.left = parseInt(_quesTxt.style.left)+vertMargin+"px";
				ypos +=  spacingBetweenOption + option.offsetHeight;
				var h = Math.max(option.offsetWidth, 100);
				ypos += vertMargin;
			}
			
		}
	}
	
}

function hArrangingOptions(indx){
	for(var i=0; i<data.optionArr[indx].length; i++){
		var cc = document.getElementById("op"+i)
		
		if(i==0){
			cc.style.left = _quesTxt.style.left;
		}else{
			var prevOp = document.getElementById("op"+(i-1))
			cc.style.left = parseInt(prevOp.style.left,10)+(prevOp.offsetWidth+spacingBetweenOption)+"px";
		}
		cc.style.top = parseInt(_quesTxt.style.top)+optionBelow+"px";
	}
}

function vArrangingOptions(indx){
	for(var i=0; i<data.optionArr[indx].length; i++){
		var cc = document.getElementById("op"+i)
		
		if(i==0){
			cc.style.top = parseInt(_quesTxt.style.top,10)+(_quesTxt.offsetHeight+optionBelow)+"px";
		}else{
			var prevOp = document.getElementById("op"+(i-1))
			cc.style.top = parseInt(prevOp.style.top,10)+(prevOp.offsetHeight+spacingBetweenOption)+"px";
		}
		
		cc.style.left = _quesTxt.style.left;
	}
}

function addNumbering(indx){
	srialNo.style.position = "absolute";
	srialNo.innerHTML = (indx+1);
	srialNo.style.width = 30+"px";
	srialNo.style.borderRadius = "50%";
	srialNo.style.fontSize = quesfntSize;
	srialNo.style.fontFamily = fontFace1;
	srialNo.style.border = "3px solid #F29B34";
	
	_main.appendChild(srialNo);
	srialNo.style.top = _quesTxt.offsetTop+"px";
	srialNo.style.left = (_quesTxt.offsetLeft-60)+"px";
	srialNo.style.textAlign = "center";
	
	srialNo.style.backgroundColor = "#fff";
	srialNo.style.padding = "8px";
}

function onChangeTxt(e){
	selMC = e.target;
	var cMCid = e.target.id.substr(8,1);
	checkAnswer(cMCid);
	//console.log(cMCid," =+=+=+=+=+=+=");
}

/* function onOPClick(e){
	selMC = e.target;
	var cMCid = e.target.id.substr(2,1);
	//console.log(cMCid)
	
	for(var i=0; i<data.optionArr[cMCid].length; i++){
		var getChild = document.getElementById("op"+cMCid+"_"+i)
		setColor(getChild, colorObj.initial);
	}
	
	setColor(selMC, colorObj.select);
	
	selMC.ans = selMC.innerHTML;
	
	var dspStr = selMC.innerHTML.split(".")[1];
	getElement("blankTxtField"+cMCid).value = dspStr;
	
	checkAnswer(cMCid);
} */

function checkAnswer(cMCid){
	//console.log("CHECK: ", cMCid);
	//console.log("OP: ", getElement("txtField"+cMCid));
	//console.log("SEL ", selMC);
	try{
	if(!p_3[cMCid]){
		p_3[cMCid] = {"selected": null, "isRight": false};
	}
	if(selMC.value == data.Aarr[cMCid]){
		p_3[cMCid].selected = selMC.value;
		p_3[cMCid].isRight = true;
		//setColor(selMC, "#29ce29");
		getElement("txtField"+cMCid).style.backgroundColor = "#29ce29";
		//setTimeout(drawNextQuestion, 3000);
		playFeedback("right");
	}else{
		p_3[cMCid].selected = selMC.value;
		p_3[cMCid].isRight = false;
		inCorrect++;
		//setColor(selMC, "#ff0000");
		getElement("txtField"+cMCid).style.backgroundColor = "#ff0000";
		//setTimeout(drawIncorrectQuestion, 4000);
		playFeedback("wrong");
	}
	}catch(err){
		console.log(err);
	}		
	console.log("DATA: ", p_3);
}

/*function onSubmitClick(e){
	if(selMC.ans == data.optionArr[Qno][data.Aarr[Qno]]){
		setColor(selMC, "#29ce29");
		blankTxtField.style.color = "#29ce29";
		setTimeout(drawNextQuestion, 3000);
		playFeedback("right");
		//feedbackVid.playCorrectFeedback(postSubmit);
	}else{
		inCorrect++;
		setColor(selMC, "#ff0000");
		blankTxtField.style.color = "#ff0000";
		setTimeout(drawIncorrectQuestion, 4000);
		playFeedback("wrong");
		//feedbackVid.playWrongFeedback(postSubmit);
	}
	
	disableOptions();
	disableBTN()
}*/

function postSubmit(){
	
}

function drawNextQuestion(){
	enableObj(getElement("preBtn"));
	
	if(Qno < data.optionArr.length-1){
		Qno++;
		removePrevious();
		addQuestion(Qno)
	}else{
		disableOptions();
		disableBTN();
		makeAnimationSpace();
		//console.log("activity finished 11111111111111");
	}
	
	selMC = null;
	inCorrect = 0;
	disableBTN();
	answerBtn.style.pointerEvents = "auto";
	answerBtn.style.opacity = 1;
	/*if(Qno<data.optionArr.length-1)
	{
		enableObj(nextBtn);
	}
	
	if(Qno)
	{
		enableObj(preBtn);
	}*/
}

function drawIncorrectQuestion(){
	enableOptions();
	answerBtn.style.pointerEvents = "auto";
	answerBtn.style.opacity = 1;
	/*if(Qno<data.optionArr.length-1)
	{
		enableObj(nextBtn);
	}
	
	if(Qno)
	{
		enableObj(preBtn);
	}*/
	
	for(var i=0; i<data.optionArr[Qno].length; i++){
		setColor(selMC, colorObj.initial);
	}
	blankTxtField.style.color = "#000000";
	blankTxtField.value = "";
	
	if(inCorrect >= attempt){
		selMC = null;
		playFeedback("correct");
		setColor(correctMC, "#29ce29");
		
		blankTxtField.value = correctMC.innerHTML;
		blankTxtField.style.color = "#29ce29";
		disableOptions();
		
		if(Qno < data.optionArr.length-1){
			setTimeout(drawNextQuestion, 3000);
		}else{
			setTimeout(makeAnimationSpace, 2500);
			//console.log("activity finished 2222222222222");
		}
		inCorrect = 0;
		
		//disableObj(nextBtn);
		//disableObj(preBtn);
		answerBtn.style.pointerEvents = "none";
		answerBtn.style.opacity = 0.5;
	}
}

function onSolutionClick(){
	for(var i=0; i<data.optionArr[Qno].length; i++){
		setColor(document.getElementById("op"+i), colorObj.initial);
	}
	setColor(correctMC, "#29ce29");
	blankTxtField.value = correctMC.innerHTML;
	blankTxtField.style.color = "#29ce29";
	
	disableOptions();
	disableBTN();
	if(Qno < data.optionArr.length-1){
		setTimeout(drawNextQuestion, 3000);
	}else{
		setTimeout(makeAnimationSpace, 3500);
	}
	playFeedback("correct");
}

function removePrevious(){
	for(var i=0; i<data.optionArr[Qno].length; i++){
		var getPrevOption = document.getElementById("op"+i);
		_main.removeChild(getPrevOption);
	}	
}

function playFeedback(val){
	var ranNum;
	switch(val){
		case "right":
			ranNum = parseInt(Math.random()*(rArr.length));
			//console.log(ranNum)
			audio.src = "Assets/mp3/"+rArr[ranNum]+".ogg";
		break;
		case "wrong":
			ranNum = parseInt(Math.random()*(wArr.length));
			audio.src = "Assets/mp3/"+wArr[ranNum]+".ogg";
		break
		case "correct":
			audio.src = "Assets/mp3/ThisIsTheCorrectAns.ogg";
		break
	}
	
	audio.play();
}

function makeAnimationSpace(){
	animDiv = document.createElement("video");
	document.body.appendChild(animDiv);
	animDiv.style.position = "absolute";
	animDiv.style.left = 0+"px";
	animDiv.style.top = 0+"px";
	animDiv.style.zIndex = 200;
	animDiv.src = "Assets/videos/activityComplete.mp4";
	animDiv.play();
	
	//interval = setInterval(playAnimation, 60);
}

function playAnimation(){
	if(count < 72){
		count++;
		animDiv.src ="Assets/activityComplete/actComp_"+count+".png";
	}else{
		clearInterval(interval);
	}
}

function disableBTN(){
	//disableObj(nextBtn);
	//disableObj(preBtn);
	
	submitBtn.style.pointerEvents = "none";
	submitBtn.style.opacity = 0.5;
	answerBtn.style.pointerEvents = "none";
	answerBtn.style.opacity = 0.5;
}

function enableBTN(){
	submitBtn.style.pointerEvents = "auto";
	submitBtn.style.opacity = 1;
	answerBtn.style.pointerEvents = "auto";
	answerBtn.style.opacity = 1;
	/*if(Qno<data.optionArr.length-1)
	{
		enableObj(nextBtn);
	}
	
	if(Qno)
	{
		enableObj(preBtn);
	}*/
}

function disableOptions(){
	for(var k=0; k<data.optionArr[Qno].length; k++){
		var getOp = document.getElementById("op"+k)
		getOp.style.pointerEvents = "none";
	}
}

function enableOptions(){
	for(var k=0; k<data.optionArr[Qno].length; k++){
		var getOp = document.getElementById("op"+k)
		getOp.style.pointerEvents = "auto";
	}
}

function setColor(mc, co){
	mc.style.backgroundColor = co;
}
window.addEventListener('blur', onBlur);
          function onBlur(e){
              pauseAudio();
         }

function pauseAudio()
{
	rubAudio.src = "Assets/images/audio.png";
	audio.pause();
	rubAudio.isAudioPlaying = false;
	rubAudio.pTime = audio.currentTime;
}