// JavaScript Document
var currentType;
var totalChoicesDisplayed = 2;
var userGrade;
var pickedOption;
//var storeImage;
var solArray = new Array();
var finalSelectedAnswer;
var emailSource;
var queid;
var xmlQId;

$(document).ready(function(){ 
	
	//for showing date//
	$("#currentDate").load("/server/checkAnswer.php?what=3&grade=grade1");
	///for mail///	
	var path=document.location.href;
	emailSource = path.indexOf("emailSource");	
	var grade = path.substring(path.indexOf("grade=") + 6,path.length);	
	document.getElementById('whichGrade').innerHTML="Grade 1";
	if(emailSource > 0)  //if through mail
	{
	
		userGrade = grade;
		
		pickedOption = path.substring(path.indexOf("pickedAns=") + 10,path.indexOf("qid=")-1);
		queid = path.substring(path.indexOf("qid=") + 4,path.indexOf("grade=")-1);
	
		loadQuestions(grade);
		
	}
	////////////////////////////////////
	else
	{
	
		//by default loading grade1//
		fillColor("G1bgcolor");  
		document.getElementById("checkAnsId").innerHTML = "";
		
		userGrade = 'grade1';
		loadQuestions('grade1');
		////////////////////////////////////
		//}
	}
	//$("#dummy").load("/server/qotdUtility.php?what=10&grade=grade2",showGraph);
	$("#loginid").load("/server/qotdUtility.php?what=5",checkSessionIsActive);
});

function printQuestions()
{
 document.location.href = "/server/printQOTD.php?what=1";	
}

function showGraph()
{
	
	
	var filename = "/media/flash/QOTD.swf";

	var correctres = document.getElementById("dummy").innerHTML ;
	var correctresNum  = parseFloat(correctres);
	if(correctresNum > 0)
	{
		document.getElementById("graphid").style.display = "block";
		document.getElementById("submitid").style.display = "block";
		InvokeQOTDGraph(filename, 170,170,"graphid",correctresNum,userGrade);  //40 is correct response, comes from php
	}
	else
	{
		document.getElementById("submitid").style.display = "none";
		document.getElementById("graphid").style.display = "none";
	}
}

function rootFolder()
{
	return "http://"+ window.location.hostname+"/";
}


function InvokeQOTDGraph(flashFileName, frameWidth, frameHeight, tagName,correctResPer,disGrade)
{	
	if(disGrade == 'grade1')
		show_grade ='Grade 1';
	else if(disGrade == 'grade2')
		show_grade ='Grade 2';
	else if(disGrade == 'grade3')
		show_grade ='Grade 3';
	else if(disGrade == 'grade4')
		show_grade ='Grade 4';
	else if(disGrade == 'grade5')
		show_grade ='Grade 5';
	else if(disGrade == 'grade6')
		show_grade ='Grade 6';
	else if(disGrade == 'grade7')
		show_grade ='Grade 7';
	else if(disGrade == 'grade8')
		show_grade ='Grade 8';
	
	var so = new SWFObject(flashFileName,"sotester", frameWidth, frameHeight, "8", "#f4d9ac");
	so.addParam("base", "/media/flash");

	so.addVariable("correctResponse", correctResPer);
	so.addVariable("grade", show_grade);
	so.useExpressInstall('/scripts/expressinstall.swf');
 	so.addParam("quality", "high");
	so.write(tagName);
}



function checkSessionIsActive()
{
	
	if(document.getElementById("loginid").innerHTML == 0)  ///session is active
	{
		document.getElementById("forgetpwdid").style.display = "none";

		document.getElementById("logindetailid").style.display = "none";
		document.getElementById("welcomedetailid").style.display = "block";
		
		$("#showuserid").load("/server/qotdUtility.php?what=2");
		
		showAllScores();
		document.getElementById("placeBtnId").className = "SignoutBtn";
	
	}
	else
	{

	    document.getElementById("forgetpwdid").style.display = "block";
		document.getElementById("logindetailid").style.display = "block";
		document.getElementById('unameid').value = "";
		document.getElementById('passwordid').value = "";
		document.getElementById("errMessage1").innerHTML = "";
		document.getElementById("welcomedetailid").style.display = "none";	

	}
}
function showAllScores()
{
	/*$("#showacscoreid").load("/server/qotdUtility.php?what=11");
	$("#showqscoreid").load("/server/qotdUtility.php?what=12");*/
	$("#percentageid").load("/server/qotdUtility.php?what=11");
	$("#totresid").load("/server/qotdUtility.php?what=13");
	$("#corresid").load("/server/qotdUtility.php?what=14");	
	$("#totscoreid").load("/server/qotdUtility.php?what=15");	
	
}
function loadBasedOnGrade()
{
	//alert(document.getElementById("dummy").innerHTML);
	if((document.getElementById("dummy").innerHTML) >= 1)
	{
		var grade = document.getElementById("dummy").innerHTML;
		
		if(grade == 1)
			userGrade = 'grade1';
		else if(grade == 2)
			userGrade = 'grade2';
		else if(grade == 3)
			userGrade = 'grade3';
		else if(grade == 4)
			userGrade = 'grade4';
		else if(grade == 5)
			userGrade = 'grade5';
		else if(grade == 6)
			userGrade = 'grade6';
		else if(grade == 7)
			userGrade = 'grade7';
		else if(grade == 8)
			userGrade = 'grade8';
		loadQuestions(userGrade);
	}
		
		
}

$(document).ready(function(){ 
	$("#placeBtnId").click(function(){
									
		if(document.getElementById("placeBtnId").className == "SigninBtn")
		{
			var usr=document.getElementById('unameid').value;
			var pwd=document.getElementById('passwordid').value;
			if(usr == "" || pwd == "")
			{
				document.getElementById("errMessage1").style.display = "block";
				document.getElementById("errMessage1").innerHTML = "Username or Password cannot be blank";
			}
			else
			{
				$('div.blockLogin1').block({  
				message: '<h7><img src="/media/images/pleasewait.gif"/>Loading</h7>',
				css: { border: '1px solid #a00', weight:'100%'} });	
				
				$("#loginid").load("/server/qotdUtility.php?what=1&user=" + usr +"&pass=" + pwd ,checkLogin);
			}
		}
		else
		{
				document.getElementById("logindetailid").style.display = "block";
				document.getElementById('unameid').value = "";
				document.getElementById('passwordid').value = "";
				document.getElementById("errMessage1").innerHTML = "";
				document.getElementById("placeBtnId").className = "SigninBtn";
				document.getElementById("forgetpwdid").style.display = "block";
				
				document.getElementById("welcomedetailid").style.display = "none";
			    $("#loginid").load("/server/qotdUtility.php?what=4&user=" + usr);
		
		}
	});

});

function checkLogin()
{
	$('div.blockLogin1').unblock();
	var usr=document.getElementById('unameid').value;
	if(document.getElementById("loginid").innerHTML == 0)  ///user can login
	{
		document.getElementById("errMessage1").style.display = "none";
		document.getElementById("logindetailid").style.display = "none";
		document.getElementById("welcomedetailid").style.display = "block";
		document.getElementById("forgetpwdid").style.display = "none";
		
		//pickedOption = findPickedAnswer();			
		$("#dummy").load("/server/checkAnswer.php?what=2&grade=" + userGrade + "&pickedOption=" + pickedOption + "&signupBtn=1");	

		$("#showuserid").load("/server/qotdUtility.php?what=2");
		//$("#showscoreid").load("/server/qotdUtility.php?what=3");
		showAllScores();

		document.getElementById("placeBtnId").className = "SignoutBtn";	
		$("#dummy").load("/server/checkAnswer.php?what=4&grade=" + userGrade,loadBasedOnGrade);

	}
	else   ///incorrect username/password
	{
		document.getElementById("errMessage1").style.display = "block";
		document.getElementById("errMessage1").innerHTML = "Incorrect username/password";
	}
}
function findPickedAnswer()
{	
		var selectedOption="";
		if(currentType == 0) /// if radio 
		{
			for (var ii=1; ii<=totalChoicesDisplayed; ii++)	//5 is total number of options available
			 {	
					var radioid = "radioid"+ii;
					if(document.getElementById(radioid).checked == true)
					{
						selectedOption=ii;
						return selectedOption;
					}
			 }
			 return 0;
		}
		
}	


function loadQuestions(grade)
{
	totalChoicesDisplayed = 2;
	document.getElementById("showExplanationId").style.display = "none";	
	document.getElementById("explanationtextid").innerHTML = "";
	document.getElementById("submitid").style.display = "block";
	
	if(grade == 'grade1')
	{
		document.getElementById('whichGrade').innerHTML="Grade 1";
		fillColor("G1bgcolor"); 
	}
	else if(grade == 'grade2')
	{
		document.getElementById('whichGrade').innerHTML="Grade 2";
		fillColor("G2bgcolor");  
	}
	else if(grade == 'grade3')
	{
		document.getElementById('whichGrade').innerHTML="Grade 3";
		fillColor("G3bgcolor");   
	}
	else if(grade == 'grade4')
	{
		document.getElementById('whichGrade').innerHTML="Grade 4";
		fillColor("G4bgcolor");  
	}
	else if(grade == 'grade5')
	{
		document.getElementById('whichGrade').innerHTML="Grade 5";
		fillColor("G5bgcolor");	 
	}
	else if(grade == 'grade6')
	{
		document.getElementById('whichGrade').innerHTML="Grade 6";
		fillColor("G6bgcolor");   
	}
	else if(grade == 'grade7')
	{
		document.getElementById('whichGrade').innerHTML="Grade 7";
		fillColor("G7bgcolor");  
	}
	else if(grade == 'grade8')
	{
		document.getElementById('whichGrade').innerHTML="Grade 8";
		fillColor("G8bgcolor");	 
	}
	$('div.blockLogin').block({  
	message: '<h7><img src="/media/images/pleasewait.gif"/>Loading</h7>',
	css: { border: '1px solid #a00', weight:'100%'} });	
				
	//$("#dummy").load("/server/qotdUtility.php?what=10&grade=" + grade,showGraph);
	document.getElementById("checkAnsId").innerHTML = "";
	userGrade = grade;
	
	$.post("/server/loadQuestions.php",{
		action: "buildXML",
		gradeIs: grade },
		function(xml)  { 
			 displayOneNode(xml);
		}); 
	

	return false;   
	
	
}

function fillColor(colorName)
{
	document.getElementById("bgcolorid").className =  colorName;
}


function displayOneNode(xml)
{	
	$('div.blockLogin').unblock();			
	
	var stringText = "";
	var stringText1 = "";
	var selectedOption=new Array();
	$("#qotd_id").empty();	
	
	$("message",xml).each(function(id) {
		message = $("message",xml).get(id);
		
	solArray[1] = $("sol1",message).text();
	solArray[2] = $("sol2",message).text();
	solArray[3] = $("sol3",message).text();
	solArray[4] = $("sol4",message).text();
	
	var imagePath=$('imagePath',message).text();	///for question image//
	var imageName=$('imageName',message).text();
	
	var explanation=$('expl',message).text();	///for explanation image//
	var expImage=$('expImage',message).text();
	
	currentType = $("type",message).text();
	if(currentType == 0) /// if radio 
	{
		for (ii=1; ii<5; ii++)	
		{
			selectedOption[ii] = ($("selected",message).text() == ii) ? checkRadioButton(ii,"check",$("sol" + ii,message).text(),imagePath):checkRadioButton(ii,"uncheck",$("sol" + ii,message).text(),imagePath);					
		}
	}
	
	 stringText = '<table width="100%" border="0" cellpadding="5" cellspacing="0" ><tr align="left"><td colspan="2" class= "qtext">' + $("question",message).text() + 
	'</td></tr><tr align="left"><td width="50%"><table width="100%" border="0" cellspacing="0" cellpadding="0">'+
	 selectedOption[1] +'<tr><td colspan="2">&nbsp;</td></tr>' + selectedOption[2] +'<tr><td colspan="2">&nbsp;</td></tr>'; 
				
	if ($("sol3",message).text() != "")
	{
	   stringText = stringText + selectedOption[3] +'<tr><td colspan="2">&nbsp;</td></tr>';
	   totalChoicesDisplayed++;
	}
	   
	if ($("sol4",message).text() != "")
	{
	   stringText = stringText + selectedOption[4] + '<tr><td colspan="2">&nbsp;</td></tr>';			
	   totalChoicesDisplayed++;
	}	
	
	stringText =  stringText +  '</table></td><td valign="top"><table width="100%" border="0" cellspacing="0" cellpadding="0" align="right" ><tr><td id="displayimageid1">';
	
	
	if(imageName != "") //question image
	{
		//check for swf//
		var images = imageName.split('.');
		if (images.length == 2) //yes it is an image
		{
		
		/*if (images[1] == "swf")						 
			 stringText =  stringText + '</td></tr>';
		else*/
			 stringText =  stringText + '<img src="' + imagePath + imageName + '" class="img1">' +'</td></tr>';			
		}
	}
	else
		 stringText =  stringText + '</td></tr>';
	
	//for explanation image//
	var explanationImgPath=imagePath;
	var showExpImage="";
	
	if(expImage != "")
	{
		 //check for swf//
		var images1 = expImage.split('.');
		if (images1.length == 2) //yes it is an image
		{
			showExpImage='<img src="' + explanationImgPath + expImage + '" class="img1">';
			if (images1[1] == "swf")
				 var disExpImage ='<table><tr><td id="expimageid1" align="right">' +'</td></tr></table>';
			else
				var disExpImage = '<table><tr><td>' + showExpImage + '</td></tr></table>';
				
		}
	}
	else
		disExpImage = "";
		
		
	
	stringText =  stringText + '</table></td></tr>' 
	stringText =  stringText + '</table>';
	
	if(explanation != "")
		document.getElementById("explanationtextid").innerHTML = 'Explanation: ' + explanation;
		
	document.getElementById("displayexpimageid").innerHTML  = disExpImage;
	
	$("#qotd_id").append(stringText);
		
	//////////////////////////////////////////
	if(expImage != "")
	{
		if (images1[1] == "swf")///for explanation swf
			invokeSWF(imagePath,expImage, 'expimageid1',250,250)
	}
	
	
	
	if(emailSource > 0)  //if through mail
	{
		emailSource = 0;
		if(queid == $("qid",message).text()) //link is  valid
		{
		document.getElementById("showExplanationId").style.display = "block";
		document.getElementById("submitid").style.display = "block";

		$("#findAns").load("/server/checkAnswer.php?what=1&grade=" + userGrade + "&pickedOption=" + pickedOption,checkAnsIsCorrect);
		
		}
		else //link is not valid
		{
			document.getElementById("showExplanationId").style.display = "none";
		
			
			 stringText = '<table width="100%" border="0" cellpadding="5" cellspacing="0" ><tr align="left"><td class="qtext">' + 'Sorry. This question has already expired. <a href="#" class="qtext" onClick = "loadQuestions(userGrade);return false;"  target="_self">Click here</a> for Today\'s Question</a>' + '</td></tr>';
			 
			  stringText += '<tr><td height="200px"></td></tr>';
			  
			  stringText +=  '</table>';
			 
			 $("#qotd_id").empty();	
			 $("#qotd_id").append(stringText);
			 
			 document.getElementById("submitid").style.display = "none";
		}
		
	}
	else if($("type",message).text() == 2) //means question is not available for particular grade
	{
		 stringText = '<table width="100%" border="0" cellpadding="5" cellspacing="0" ><tr align="left"><td class= "qtext" align="center" valign="middle">' + 'Question is not available today for this grade' + '</td></tr>';
		 
		  stringText += '<tr><td height="200px"></td></tr>';
		  
		  stringText +=  '</table>';
		 
		 $("#qotd_id").empty();	
		 $("#qotd_id").append(stringText);
		 
		
	}
	
	
	
	xmlQId = $("qid",message).text();
	$("#dummy").load("/server/qotdUtility.php?what=10&qid=" + xmlQId,showGraph);

	});
}

function invokeSWF(imagePath,expImage, divId,imageWidth,imageHeight)
{
	var playImage = imagePath + expImage;
	var so = new SWFObject(playImage,"sotester", imageWidth, imageHeight, "8", "#F0F7FD");
	so.addParam("base", "/media/images");

	so.useExpressInstall('/scripts/expressinstall.swf');
	so.addParam("quality", "high");

	so.write(divId);	
}

function checkRadioButton(number,status,message, imagePath)
{	
		var dispMessage = message;
		
		var isSentAcross = CheckIfImageSentAcross(message);
		if (isSentAcross == true)
		{
			dispMessage='<img src="' + imagePath + message + '" class="img2">';	
		}	

		if(status == "check")
		{
			 var optionChecked = '<tr><td width="10%" align="left"><input type="radio" name="radio" id="radioid' + number + '" value="' + number + '" checked="checked"> </td><td align="left" class="optionText">'+ dispMessage + '</td></tr>';
	  	}
		else
		{
		var optionChecked = '<tr><td width="10%" align="left"><input type="radio" name="radio" id="radioid' + number + '" value="' + number + '">' + '</td><td align="left" class="optionText">'+ dispMessage + '</td></tr>';
		}
		return optionChecked;
}

function CheckIfImageSentAcross(message)
{
	var images = message.split('.');
	
	if (images.length == 2) //yes it is an image
	{
		if ((images[1] == "jpg") || (images[1] == "JPG") || (images[1] == "JPEG") || (images[1] =="jpeg") || 
			(images[1] == "gif") || (images[1] == "GIF"))
			{
				return true;
			}
	}
	return false;	
}


$(document).ready(function(){					   
	$("#submitid").click(function(){ 
				
		$('div.blockLogin').block({  
		message: '<h7><img src="/media/images/pleasewait.gif"/>Please wait...</h7>',
		css: { border: '1px solid #a00' , width:'60%'} });	
				
		pickedOption = findPickedAnswer();			
		$("#findAns").load("/server/checkAnswer.php?what=1&grade=" + userGrade + "&pickedOption=" + pickedOption,checkAnsIsCorrect);
		$("#dummy").load("/server/qotdUtility.php?what=10&qid=" + xmlQId,showGraph);


	});
});

function checkAnsIsCorrect()
{
	$('div.blockLogin').unblock();
	//showing true false image//
	document.getElementById("showExplanationId").style.display = "block";
	
	if(document.getElementById("findAns").innerHTML == 0)
	{
		document.getElementById("showCorrectWrongId").innerHTML = "<img src='/media/qotd/images/CorrectMark.gif'>";
	}
	else
	{
		document.getElementById("showCorrectWrongId").innerHTML = "<img src='/media/qotd/images/WrongMark.gif'>";
	}
	//////////////////////////
	
	///what answer is picked////
	var urSelectedAns = new Array();
	if(currentType == 0) 
	{
		var temp = "sol" + pickedOption;
		selectedAns	= $(temp,message).text();
	}
	else
	{
		pickedOption += ","; 
		urSelectedAns = pickedOption.split(',');
		var selectedAns = "";
		for(ii=0;ii<urSelectedAns.length;ii++)
		{
		var tempRealAns = "sol" + urSelectedAns[ii];
		if(urSelectedAns[ii+1])
			 selectedAns = selectedAns +  $(tempRealAns,message).text() + " , ";
		else	
			 selectedAns = selectedAns +  $(tempRealAns,message).text();
		}
	}
	
	var isSentAcross = false;
	//alert("sol array=" + solArray);
	for (var ii=1;ii<5;ii++)
	{
		var tempVar = solArray[ii];
		isSentAcross = CheckIfImageSentAcross(tempVar);
		if (isSentAcross == true)
			break;
	}
	
	if(isSentAcross == true)
		finalSelectedAnswer = pickedOption;
	else
		finalSelectedAnswer = selectedAns ;
		
	document.getElementById("finalresponseid").innerHTML = "Your response: "  + finalSelectedAnswer;
	
	//alert(finalSelectedAnswer);
	///////////////////////////////////
		
		
	//////////for showing correct ans//
	var correctAns =  new Array();
	finalCorrectAns = "";
	correctAns = ($("solution",message).text()).split(",");	
	for(kk=0;kk<correctAns.length;kk++)
	{
		var tempCorrectAns = "sol" + correctAns[kk];
		if(correctAns[kk+1])
			finalCorrectAns = finalCorrectAns + $(tempCorrectAns,message).text() + " , ";
		else
			finalCorrectAns = finalCorrectAns + $(tempCorrectAns,message).text();
	}
			
	for (var ii=0;ii<correctAns.length;ii++)
	{
		var trimmedVar = trim(correctAns[ii]);
		correctAns[ii]=trimmedVar;
	}
	correctAns.sort();
	var displayCorrectAns = "";
	if (isSentAcross == true)	
		displayCorrectAns = correctAns; 		
	else
		displayCorrectAns=finalCorrectAns; 
			
	document.getElementById("correctresponseid").innerHTML = "Correct response: " + displayCorrectAns;
	//alert(document.getElementById("correctresponseid").innerHTML );
	//////////////////////////////////
		
	////interaction with database
	$("#checkAnsId").load("/server/checkAnswer.php?what=2&grade=" + userGrade + "&pickedOption=" + pickedOption + "&signupBtn=0");	
	//$("#showscoreid").load("/server/qotdUtility.php?what=3");
	showAllScores();
	
}

function trim(s)
{
	return s.replace(/^\s*|\s(?=\s)|\s*$/g, "");
}


	
	
		/*stringText1 ='<table width="100%" border="1">' + 
		'<tr><td id="showCorrectWrongId"></td></tr>'+
		'<tr><td id = "finalresponseid" class= "qtext"></td></tr>'+
		'<tr><td id="correctresponseid" class= "qtext"></td></tr>';
	
		if(explanation != "")
			stringText1 =  stringText1 + '<tr><td class= "qtext" >Explanation : ' + explanation + '</td></tr>' ;
					
		stringText1 =  stringText1 + disExpImage;
	
		stringText1 =  stringText1 + '</table>';*/
		
		///////////for explanation//////////////////
		
