/*
 * MindInsight online testpaper Script
 * Version 1.10 (jan 24,2009)
 * Copyright (c) 2008-2009 prithvi
 * 
 */
var current=0;
var currInfo=0;
var currentSection = 0;
var qattempted = 0;
var progressRatio;
var questionPrefix = "question";
var halfProgressWidth = 0;
var informationPrefix = "information";
var noofsec = 0;
var sec1count = 0;
var sec2count = 0;
var sec3count = 0;
var sec4count = 0;
var sec5count = 0;
var totalTime = 0.0;
var countArray = new Array();
var nameArray = new Array();
var scoreArray = new Array();
var questionTimeArray = new Array();
var sectionTimeArray = new Array(0.0,0.0,0.0,0.0,0.0);
var oldCounterValue = 0;
var attemptedQuestion = "";
var totalQuestion = 0;
var numberOfInformations = 0;
var next = "";
var secCountArray  = new Array(0,0,0,0,0);
var secMapArray = new Array(0,0,0,0,0);
var qattemptedArray = new Array();
var flagStatusArray = new Array();
var mappingArray = new Array();
var verifiedQArray = new Array();
var unverifiedQArray = new Array();
var ansTblHtm = ""; 
var std = "<td>";
var etd = "</td>";
var str = "<tr>";
var etr = "<tr>";
var clockID  = null;
var saveID = null;
var clockRunning  = false;
var clockCounter = 6000;
var minutes = 0;
var seconds = 0;
var mouseover = "onmouseover=\"this.style.cursor='pointer';\" ";
var savePeriod = 360000;
var testStatus = 1;

var ansStr = "";
var psaveID = null;
var optionArr = new Array('0','A','B','C','D','E');
/********* For Demo Test **********/

function getScreenWidth(){
	 var myWidth = 0;
	 if( typeof( window.innerWidth ) == 'number' ) {
	    //Non-IE
	    myWidth = window.innerWidth;
	   } else if( document.documentElement && document.documentElement.clientWidth) {
	    //IE 6+ in 'standards compliant mode'
	    myWidth = document.documentElement.clientWidth;
	   } else if( document.body && document.body.clientWidth ) {
	    //IE 4 compatible
	    myWidth = document.body.clientWidth;
	   }
	   return myWidth;
	 }

function launchDemoTest()
{
	//alert("launchDemo");
	var W=getScreenWidth();
	var H=screen.availHeight;
	newwindow=window.open("/testcenter/pages/testcenter/demotesthome.jsp","t20practice",'toolbar=0,scrollbars=yes,location=0,statusbar=0,menubar=0,resizable=1,fullscreen=yes');
	if (window.focus) {newwindow.focus()}
	var msg = " Test in Progress <br> Please wait...";
	jQuery.blockUI({message:msg,css: { 
		border: '2px solid #fff',padding: '15px',backgroundColor: '#7a0000','-webkit-border-radius': '10px',
		'-moz-border-radius': '10px',opacity: '1.0',color: '#fff'},
	overlayCSS:{  
		backgroundColor:'#000',opacity:'0.8'}
	});
	return false;
}

/****************************************************************/

function startClock()
{
	saveID = setTimeout("periodicSave()",180000);
	if(testStatus==3)
	{
		psaveID=setInterval("save()",savePeriod);
	}
	var t = document.getElementById('time').value;

	var mytime = new Array();
	mytime = t.split('.');
	if(!mytime[1])
	{
		mytime[1] = "0";
	}
	clockCounter = parseInt(mytime[0]);
	clockCounter = clockCounter*60;
	clockCounter = clockCounter + parseInt(mytime[1]);
	oldCounterValue = clockCounter;

	stopClock();
	showTime();

}

function stopClock()
{

	if(clockRunning)
	{
		clearTimeout(clockID);
	}
	clockRunning = false;
}
function showTime()
{

	if(clockCounter)
	{
		minutes = clockCounter/60;	
		seconds = clockCounter %60;
		if(seconds < 10)
			seconds = "0"+seconds;
		document.getElementById('theTime').value = ""+parseInt(minutes)+":"+seconds;
		clockID = setTimeout("showTime()",1000);
		clockRunning = true;
	}
	else
	{
		stopClock();
		timeOver();
	}
	clockCounter  = clockCounter -1;
}
function timeOver()
{

var msg="Your Time is up. Test is getting submitted automatically.";
displayMessageInPopUp(msg);
submit();
/*	jQuery.blockUI({message: jQuery('#quest_popup'),css: { 
		border: '2px solid #7a0000',
		opacity: '.9', 
		color: '#000' 
	},
	overlayCSS:{  
		backgroundColor:'#000',  
		opacity:'0.8'  
	}});*/
}
var verifyCallback =
{
		cache:false,
		success: function(o) {
	updateTestResult(o.responseText);	 
}
}
var testpaperCallback =
{
		cache:false,
		success: function(o) {
	document.getElementById("mid-qarea").innerHTML = o.responseText;
	init();
}
}
var testhomeCallback =
{
		cache:false,
		success: function(o) {
	document.getElementById('mid-before2').innerHTML = o.responseText;
	var sectionCount = document.getElementById('sectioncount').value;
	var sectionScore = document.getElementById('sectionscore').value;
	var sectionName = document.getElementById('sectionname').value;
	var numbOfSections = document.getElementById('numberOfSections').value;

	countArray = sectionCount.split(":");
	scoreArray = sectionScore.split(":");
	nameArray = sectionName.split(":");
	var startTable ="<table class=\"testDetail\">";
	var header = "<tr><th colspan=\"3\">Test Structure</th></tr>";
	header = header+"<tr><th width=\"30%\">Section</th><th width=\"40%\">No. Of Questions</th><th width=\"30%\">Marks</th></tr>";
	var endTable ="</table>";
	startTable = startTable+header;
	for(i =0; i<numbOfSections; i++)
	{
		startTable = startTable + "<tr>";
		startTable = startTable + "<td>"+nameArray[i]+"</td>";
		startTable = startTable + "<td>"+countArray[i]+"</td>";
		startTable = startTable + "<td>"+scoreArray[i]+"</td>";
		startTable = startTable + "</tr>";
	}
	startTable = startTable + endTable;
	document.getElementById('sectiontable').innerHTML = startTable;
}
}
function init()
{
	noofsec = document.getElementById('noofsec').value;
	secCountArray[0] = document.getElementById('sec1count').value;
	secCountArray[1] = document.getElementById('sec2count').value;
	secCountArray[2] = document.getElementById('sec3count').value;
	secCountArray[3] = document.getElementById('sec4count').value;
	secCountArray[4] = document.getElementById('sec5count').value;
	totalQuestion  = document.getElementById('numberOfQuestion').value;
	testStatus = document.getElementById('testStatus').value; //amrita.a
	//alert(testStatus);
	var tmp1 = document.getElementById('questionTiming').value;
	var tmp2 = document.getElementById('sectionTiming').value;
	var flagValues = document.getElementById('flagStatus').value;
	if(tmp1.length == 0 || tmp2.length == 0)
	{
		initTimingArrays();
	}else
	{
		questionTimeArray = tmp1.split(":");
		sectionTimeArray = tmp2.split(":");
		flagStatusArray = flagValues.split(":");
	}
	totalTime = document.getElementById('testTime').value;
	attemptedQuestion = document.getElementById('questionsAttempted').value;

	numberOfInformations = document.getElementById('numberOfInformations').value;
	if(totalQuestion<100)
	{
		progressRatio = 100/totalQuestion;
		document.getElementById('qprogress-parent').style.width = "100px";
	}else
	{
		document.getElementById('qprogress-parent').style.width = totalQuestion+"px";
	}

	halfProgressWidth = parseInt(totalQuestion/2)-5 +"px";
	initMappingArray();
	initQAttemptedArray();
	generateAnswerTable();
	loadButtons();
	generateSectionDivs();
	loadSavedSession();
	updateQProgress();

}
/*
 * Use this method to initialize any array for all questions
 * Currently Time and Flag status array is initialized.
 */
function initTimingArrays()
{
	for(var i=0;i< totalQuestion; i++)
	{
		questionTimeArray[i] = 0;
		flagStatusArray[i] = 0;
	}
}
function initQAttemptedArray()
{
	for(i=0;i<totalQuestion;i++)
	{
		qattemptedArray[i] = 0;
	}
}
function updateQProgress()
{
	var ele = document.getElementById('qprogress');
	ele.innerHTML = "<span style=\"color:white;margin-left:"+halfProgressWidth+"\">"+qattempted+"/"+totalQuestion+"</span>";
	ele.style.width = (progressRatio*qattempted)+"%";
}
function initMappingArray()
{
	var count = 0;
	for(i=0;i<numberOfInformations; i++)
	{
		var limit = document.getElementById('span_'+i).value;
		for(j=0; j<limit; j++)
		{
			mappingArray.splice(mappingArray.length,0,i)
			count= count +1;
		}
	}
}
function generateAnswerTable()
{
	var starttable = "<table style=\"color:white\" border=\"1\"><tr><td></td><td>Flag</td><td>A</td><td>B</td><td>C</td><td>D</td><td>E</td><td>Clear</td></tr>";
	var endtable   = "</table>";
	var count = 0;
	ansTblHtm = starttable;
	for(i=0; i<totalQuestion; i++)
	{		
		generateAnswerTableRow(i);

	}
	ansTblHtm = ansTblHtm + endtable;
	//alert(ansTblHtm);
	document.getElementById('anstable').innerHTML = ansTblHtm;
	ansTblHtm = "";
}

function loadSavedSession()
{
	if((attemptedQuestion =='')||(attemptedQuestion == null) )
	{

	}else
	{
		var len = attemptedQuestion.length;
		attemptedQuestion = attemptedQuestion.substring(0,len);
		var optionArray = new Array();
		optionArray = attemptedQuestion.split(":");
		var end = optionArray.length;
		for(var i=0;i<end; i++)
		{
			var qRadio = document.getElementsByName("question_"+i);
			var aRadio = document.getElementsByName("R"+i);
			var opt = optionArray.splice(0,1);
			if(opt == null || opt == "null")
			{
			}
			else
			{
				qattempted ++;
				qattemptedArray[i]=1;
				document.getElementById("C"+i).style.display = "";
				aRadio[opt-1].checked = true;
				qRadio[opt-1].checked = true;
			}	
			if(flagStatusArray[i] ==1)
			{
				//alert(id+"FlagStatus: "+flagStatusArray[id])
				addToReview(i);
			}

		}
	}
}

function generateSectionDivs()
{
	var sectionhtml = "";
	var romanArray = new Array("I","II","III","IV","V");
	var qcount = 0;
	for(i=0;i<noofsec; i++)
	{
		sectionhtml = sectionhtml+"<div id=\"sec" +i+"\" onclick=\"goToSection("+i+")\" "+mouseover+" class=\"secbutton\"><font size=\"5\" class=\"sectext\">"+romanArray[i]+"</font></div>";
		qcount = parseInt(qcount) + parseInt(secCountArray[i]);
		secMapArray[i] = qcount;
	}
	document.getElementById('secbuttons').innerHTML = sectionhtml;
	document.getElementById('sec'+currentSection).setAttribute("class","secbutton-selected");
}

function generateAnswerTableRow(id)
{
	ansTblHtm = ansTblHtm +str;
	ansTblHtm = ansTblHtm + std;
	ansTblHtm = ansTblHtm + 
	"<a id=\"A"+id+"\" style=\"text-decoration:underline\" onclick=\"goToQuestion('"+(id)+"')\" onmouseover=\"this.style.cursor='pointer';\">"+(id+1)+"</a>";
	ansTblHtm = ansTblHtm + etd;

	ansTblHtm = ansTblHtm +std;
	ansTblHtm = ansTblHtm +
	"<a><img id=\"F"+id+"\" src=\"/images/testcenter/whiteflag.png\" border=\"none\" onmouseover=\"this.style.cursor='pointer';\" onclick=\"addToReview('"+id+"')\"/></a>";
	ansTblHtm = ansTblHtm + etd;

	ansTblHtm = ansTblHtm +std;
	ansTblHtm = ansTblHtm +
	"<input type=\"radio\" onclick=\"answerTableRadioClick('"+id+"')\" name=\"R"+id+"\" />";
	ansTblHtm = ansTblHtm + etd;

	ansTblHtm = ansTblHtm +std;
	ansTblHtm = ansTblHtm +
	"<input type=\"radio\" onclick=\"answerTableRadioClick('"+id+"')\" name=\"R"+id+"\" />";
	ansTblHtm = ansTblHtm + etd;

	ansTblHtm = ansTblHtm +std;
	ansTblHtm = ansTblHtm +
	"<input type=\"radio\" onclick=\"answerTableRadioClick('"+id+"')\" name=\"R"+id+"\" />";
	ansTblHtm = ansTblHtm + etd;

	ansTblHtm = ansTblHtm +std;
	ansTblHtm = ansTblHtm +
	"<input type=\"radio\" onclick=\"answerTableRadioClick('"+id+"')\" name=\"R"+id+"\" />";
	ansTblHtm = ansTblHtm + etd;

	ansTblHtm = ansTblHtm +std;
	ansTblHtm = ansTblHtm +
	"<input type=\"radio\" onclick=\"answerTableRadioClick('"+id+"')\" name=\"R"+id+"\" />";
	ansTblHtm = ansTblHtm + etd;

	ansTblHtm = ansTblHtm +std;
	ansTblHtm = ansTblHtm +
	"<a id=\"C"+id+"\" onmouseover=\"this.style.cursor='pointer';\" style=\"text-decoration:underline;display:none;\" onclick=\"clearAnswer('"+id+"')\"/>Clear</a> ";
	ansTblHtm = ansTblHtm + etd;
	ansTblHtm = ansTblHtm + etr;

}
function clearAnswer(id)
{
	if(qattemptedArray[id] == 1)
	{
		qattemptedArray[id] =0;
		qattempted--;
		updateQProgress();

		var aRadio = document.getElementsByName("R"+id); 
		for(i=0;i<aRadio.length;i++) 
		{
			aRadio[i].checked = false; 
		}
		var qRadio = document.getElementsByName("question_"+id); 
		for(j=0;j<qRadio.length;j++) 
		{
			qRadio[j].checked = false; 
		}
	}
}
function showAnswerSheet()
{

	document.getElementById('anscontainer').style.display = "";
	document.getElementById('hidebutton').style.display = "";
}
function hideAnswerSheet()
{
	document.getElementById('hidebutton').style.display = "none";
	document.getElementById('anscontainer').style.display = "none";

}
function loadButtons()
{
	//hidePrev();
}
function nextQuestion()
{
	if(current == totalQuestion-1)
		return;
	updateTimeData(current);
	hideCurrentQuestion();
	current = parseInt(current) +1;
	switchInformation();
	/*if(current == totalQuestion-1)
	{
		hideNext();
	}else
	{
		showNext();
	}
	if(current == 0)
	{
		hidePrev();
	}else
	{
		showPrev();
	}*/
	showCurrentQuestion();
	selectSection();
}
function prevQuestion()
{
	if(current == 0)
		return;
	updateTimeData(current);
	hideCurrentQuestion();
	current = parseInt(current) -1;
	switchInformation();
	/*if(current == totalQuestion-1)
	{
		hideNext();
	}else
	{
		showNext();
	}
	if(current == 0)
	{
		hidePrev();
	}else
	{
		showPrev();
	}*/
	showCurrentQuestion();
	selectSection();
}
function selectNextSection()
{
	if(secMapArray[currentSection] < current)
	{
		document.getElementById('sec'+currentSection).setAttribute("class","secbutton");
		currentSection = currentSection +1;
		document.getElementById('sec'+currentSection).setAttribute("class","secbutton-selected");
	}
}
function selectPrevSection()
{
	if(current < secMapArray[currentSection])
	{
		document.getElementById('sec'+currentSection).setAttribute("class","secbutton");
		currentSection = currentSection -1;
		document.getElementById('sec'+currentSection).setAttribute("class","secbutton-selected");
	}
}

function selectSection()
{
	document.getElementById('sec'+currentSection).setAttribute("class","secbutton");
	var low = 0;
	var high = secMapArray[0];
	for(var i =0; i< noofsec; i++)
	{
		if(current >= low )
		{
			if(current < high)
			{

				document.getElementById('sec'+i).setAttribute("class","secbutton-selected");
				currentSection = i;
				break;
			}
			else
			{
				low = high;
				high = secMapArray[i+1];
			}
		}else
		{

			low = high;
			high = secMapArray[i+1];

		}
	}
}


function goToSection(id)
{

	for(i=0;i<noofsec;i++)
	{
		if(i == id)
		{
		//	document.getElementById('sec'+id).setAttribute("class","secbutton-selected");
			document.getElementById('sec'+i).className="secbutton-selected";
		}else
		{
		//	document.getElementById('sec'+i).setAttribute("class","secbutton");
			document.getElementById('sec'+i).className="secbutton";
		}
	}
	var cnt = 0;
	/*for(i=0;i<id;i++)
	{
		cnt = cnt + parseInt(secCountArray[id]);
	}*/
	currentSection = id;
	if(id == 0)
	{
		goToQuestion(0);
	}else
	{
		goToQuestion(secMapArray[id-1]);
	}
}
function updateTimeData(id)
{
	var diff = (oldCounterValue - clockCounter)/60;
	oldCounterValue = clockCounter;
	diff = diff.toFixed(2);
	var sum = 0;
	var low = 0;
	var high = secMapArray[0];
	for(var i =0; i< noofsec; i++)
	{
		if(current >= low )
		{
			if(current < high)
			{
				sectionTimeArray[i] = parseFloat(sectionTimeArray[i]) + parseFloat(diff);
				sectionTimeArray[i] = sectionTimeArray[i].toFixed(2);
				break;
			}
			else
			{
				low = high;
				high = secMapArray[i+1];
			}
		}else
		{

			low = high;
			high = secMapArray[i+1];

		}
	}
	questionTimeArray[id] = parseFloat(questionTimeArray[id])+parseFloat(diff);
	questionTimeArray[id] = questionTimeArray[id].toFixed(2);
}
function answerTableRadioClick(id)
{
	if(qattemptedArray[id] == 0)
	{
		qattemptedArray[id] =1;
		qattempted++;
		updateQProgress();
	}

	goToQuestion(id);
	var aRadio = document.getElementsByName("R"+id); 
	var qRadio = document.getElementsByName("question_"+id); 
	for(i=0;i<aRadio.length;i++) 
	{
		if(aRadio[i].checked == true)
		{
			qRadio[i].checked = true;
		}
	}
	document.getElementById("C"+id).style.display = "";
}
function questionTableRadioClick(id)
{
	if(qattemptedArray[id] == 0)
	{
		qattemptedArray[id] =1;
		qattempted++;
		updateQProgress();
	}
	var aRadio = document.getElementsByName("R"+id); 
	var qRadio = document.getElementsByName("question_"+id); 
	for(i=0;i<qRadio.length;i++) 
	{
		if(qRadio[i].checked == true)
		{
			aRadio[i].checked = true;
		}
	}
	document.getElementById("C"+id).style.display = "";
}
/*
function addToReview(obj,id)
{
	flagStatusArray[id] = 1;
	var ele = document.getElementById("qflag_"+id);
	ele.setAttribute("src","/images/testcenter/redflag.png");
	ele.setAttribute("onclick","removeFromReview("+id+")");
	obj.setAttribute("src","/images/testcenter/redflag.png");
	obj.setAttribute("onclick","removeFromReview("+id+")");
}
function setReviewFlag(obj,id)
{
	flagStatusArray[id] = 1;
	var ele = document.getElementById("F"+id);
	ele.setAttribute("src","/images/testcenter/redflag.png");
	ele.setAttribute("onclick","removeFromReview("+id+")");
	obj.setAttribute("src","/images/testcenter/redflag.png");
	obj.setAttribute("onclick","removeFromReview("+id+")");
}*/
function addToReview(id)
{
	flagStatusArray[id] = 1;
	var ele = document.getElementById("F"+id);
	ele.setAttribute("src","/images/testcenter/redflag.png");
	ele.setAttribute("onclick","removeFromReview("+id+")");
	ele = document.getElementById("qflag_"+id);
	ele.setAttribute("src","/images/testcenter/redflag.png");
	ele.setAttribute("onclick","removeFromReview("+id+")");
}
function removeFromReview(id)
{
	flagStatusArray[id] = 0;
	var ele = document.getElementById("F"+id);
	ele.setAttribute("src","/images/testcenter/whiteflag.png");
	ele.setAttribute("onclick","addToReview("+id+")");
	ele = document.getElementById("qflag_"+id);
	ele.setAttribute("src","/images/testcenter/whiteflag.png");
	ele.setAttribute("onclick","addToReview("+id+")");
}

function hidePrev(){document.getElementById("prev").style.display = "none";}
function showPrev(){document.getElementById("prev").style.display = "";}
function hideNext(){document.getElementById("next").style.display = "none";}
function showNext(){document.getElementById("next").style.display = "";}
function hideSubmit(){document.getElementById("submit").style.display = "none";}
function showSubmit(){document.getElementById("submit").style.display = "";}
function hideCurrentQuestion(){document.getElementById('question'+current).style.display = "none";}
function showCurrentQuestion(){ document.getElementById('question'+current).style.display = ""; }
function showInformation(id){
	document.getElementById('information_'+id).style.display = "";
	currInfo = id;
}
function hideInformation(id){
	document.getElementById('information_'+id).style.display = "none";
}

function switchInformation()
{
	if(currInfo == mappingArray[current])
	{

	}else{
		hideInformation(currInfo);
		showInformation(mappingArray[current]);
	}
}
function goToQuestion(id)
{
	updateTimeData(current);
	hideCurrentQuestion();
	current = id;
	
	switchInformation();
	showCurrentQuestion();
	selectSection();
}
/*

function switchView()
{
	document.getElementById('main-before').style.display = "none";
	document.getElementById('main-after').style.display = "";
	startClock();
}

*/
function switchView()
{
	//alert("switchView");
	var form = document.getElementById('questionpaper');
	YAHOO.util.Connect.setForm(form);
	//alert("switchView");
	var transaction = YAHOO.util.Connect.asyncRequest("GET", "/testcenter/mi_starttest.action", startTestCallback, null);	
}

var startTestCallback =
{
		cache:false,
		success: function(o) {
	var status = o.responseText;
//	alert(status);
	if(status.indexOf('success')!=-1)
	{
		document.getElementById('main-before').style.display = "none";
		document.getElementById('main-after').style.display = "";
		startClock();
	}
	else if(status.indexOf('login')!=-1)
	{
		document.getElementById('main-before').style.display = "none";
		document.getElementById('statusMsg').innerHTML = "You login session has expired. Please login and take the test.";
		document.getElementById('status').style.display="";
	}
	else
	{
		document.getElementById('main-before').style.display = "none";
		document.getElementById('statusMsg').innerHTML = "We are unable to process your request currently. Please try again.";
		document.getElementById('status').style.display="";
	}
}
}
/**************************************************
 * Post result submission processing starts here  *
 */
var posx = 0;
var posy = 0;
var currentReview = 0;
var wrongArray = new Array();
var userSectionScoreArray = new Array();
var correctArray = new Array();
var leftArray = new Array();
var numberOfIncorrect = 0;
var scoreNameArray = new Array("Your Score","Average Score","CuttoffScore","Highest Score");
var userTotalScore;
var userSectionScore;
var sectionWiseLeftArr = new Array();
var sectionWiseCorrectArr = new Array();
var sectionWiseIncorrectArr = new Array();

function popupAlert(id)
{
	var msg = "";
	if(id == 'save')
	{
		msg = "On saving it you won't be able to continue this session.<br> Are you sure you want to save?";
	}else if(id =='submit')
	{
		msg = "Once submitted you won't be able to take test again.<br> Are you sure you want to submit?";
	}else
	{
		msg = "Once submitted you won't be able to take test again.<br> Are you sure you want to submit?";
	}
	document.getElementById('confirmMsg').innerHTML = msg;
	jQuery.blockUI({message:jQuery('#processingMsg'),css: { 
		border: 'none',
		opacity: '.9',
		color: '#fff'
	},
	overlayCSS:{  
		backgroundColor:'#000',  
		opacity:'0.8'  
	}});
}
var submitCallback =
{
	cache:false,
	success: function(o) {
	document.getElementById('result-div').innerHTML = o.responseText;
	document.getElementById('main-after').style.display = "none";
	initPostSubmit();
	initResult();
	generateCharts();
	restore();
	showFlashCharts();
	//submitResponseProcessing();
}
}
var submitAitsCallback =
{
	cache:false,
	success: function(o) {
	document.getElementById('result-div').innerHTML = o.responseText;
	document.getElementById('main-after').style.display = "none";
	genAnsSheet();
	restore();
}
}
function submit()
{
	clearTimeout(saveID);
	if(testStatus == 3)
	{
		clearInterval(psaveID);
	}
	showProcessingPopUp("submit");
	settingTimeDetails();
	var form = document.getElementById('questionpaper');
	var time = document.getElementById('theTime').value;
	time = time.replace(/:/,".");
	form.time.value = time;
	YAHOO.util.Connect.setForm(form);
	//alert(testStatus);
	if (testStatus == 1)
	{ 
		var transaction = YAHOO.util.Connect.asyncRequest("GET", "/testcenter/mi_submittest.action", submitCallback, null);
	}
	else if (testStatus == 3)
	{ 
		var transaction = YAHOO.util.Connect.asyncRequest("GET", "/testcenter/mi_submitaitstest.action", submitAitsCallback, null);
	}
	
}

function submitDemo()
{
	showProcessingPopUp("submit");
	settingTimeDetails();
	clearTimeout(saveID);
	var form = document.getElementById('questionpaper');
	var time = document.getElementById('theTime').value;
	time = time.replace(/:/,".");
	form.time.value = time;
	YAHOO.util.Connect.setForm(form);
	//alert("Calling submit demo");
	var transaction = YAHOO.util.Connect.asyncRequest("GET", "/testcenter/mi_submitdemo.action", submitCallback, null);
}


var periodicSaveCallback =
{
		cache:false,
		success: function(o) {
//	alert("Saved:");	
}
}

function settingTimeDetails()
{
	var sectiming = sectionTimeArray[0];
	for(var i =1;i< noofsec; i++ )
	{
		sectiming =  sectiming+":"+sectionTimeArray[i];
	}
	document.getElementById('questionTiming').value = questionTimeArray.join().replace(/,/g,":");
	//alert(document.getElementById('flagStatus').value);
	document.getElementById('flagStatus').value = flagStatusArray.join().replace(/,/g,":");
	document.getElementById('sectionTiming').value = sectiming;
}

function periodicSave()
{
	var form = document.getElementById('questionpaper');
	var time = document.getElementById('theTime').value;
	settingTimeDetails();
	time = time.replace(/:/,".");
	form.time.value = time;
	YAHOO.util.Connect.setForm(form);
	var transaction = YAHOO.util.Connect.asyncRequest("GET", "/testcenter/mi_savetest.action", periodicSaveCallback, null);
}

var saveCallback =
{
		cache:false,
		success: function(o) {
	document.getElementById('result-div').innerHTML = o.responseText;
	document.getElementById('main-after').style.display = "none";
	restore();
}
}

var saveAitsCallback =
{
		cache:false,
		success: function(o) {
		document.getElementById('saveImg').src="http://www.static.mindinsight.com/R2/testcenter/images/save.png";
}
}

function save()
{
	if (testStatus == 3)
	{ 
		//alert("You cannot save the test. Click submit to submit the test.");
		//alert("saving your test");
		document.getElementById('saveImg').src="http://www.static.mindinsight.com/R2/testcenter/images/saving.png";
		var form = document.getElementById('questionpaper');
		YAHOO.util.Connect.setForm(form);
		var transaction = YAHOO.util.Connect.asyncRequest("GET", "/testcenter/mi_saveAitsResult.action", saveAitsCallback, null);		
	}
	else
	{
		clearTimeout(saveID);
		showProcessingPopUp("save");
		settingTimeDetails();
		var form = document.getElementById('questionpaper');
		var time = document.getElementById('theTime').value;
		time = time.replace(/:/,".");
		form.time.value = time;
		YAHOO.util.Connect.setForm(form);
		var transaction = YAHOO.util.Connect.asyncRequest("GET", "/testcenter/mi_savetest.action", saveCallback, null);		
	}
}
function submitResponseProcessing()
{
	document.getElementById('main-after').style.display = "none";
	initPostSubmit();
}

function initResult()
{
	generateResultTabe();
}

function initPostSubmit()
{
	userSectionScore = document.getElementById('r_sectionScore').value;
	userTotalScore = document.getElementById('r_totalScore').value;
	userSectionScoreArray = userSectionScore.split(":");
	correctArray = document.getElementById('r_correctQuestions').value.split(":");
	wrongArray =  document.getElementById('r_wrongQuestions').value.split(":");
	leftArray = document.getElementById('r_leftQuestions').value.split(":");
	sectionWiseLeftArr = document.getElementById('r_sectionWiseLeft').value.split(":");
	sectionWiseCorrectArr = document.getElementById('r_sectionWiseCorrect').value.split(":");
	sectionWiseIncorrectArr = document.getElementById('r_sectionWiseIncorrect').value.split(":");
	displayMessageInPopUp("Result saved successfully. Generating analysis Report<br>Please wait...")

}
function showProcessingPopUp(id)
{
	var msg;
	if(id == "save")
	{
		msg = " Saving your Test Data <br> Please wait...";
	}else if(id == "submit")
	{
		msg = " Submitting your TestPaper <br> Please wait...";
	}
	displayMessageInPopUp(msg);
}
function displayMessageInPopUp(msg)
{
	jQuery.blockUI({message:msg,css: { 
		border: '2px solid #fff',
		padding: '15px',
		backgroundColor: '#7a0000',
		'-webkit-border-radius': '10px',
		'-moz-border-radius': '10px',
		opacity: '1.0',
		color: '#fff'
	},
	overlayCSS:{  
		backgroundColor:'#000',  
		opacity:'0.8'  
	}
	});
}

function reviewWrongQuestions()
{
	jQuery.blockUI({message: jQuery('#questionresultdiv'),css: { 
		border: 'none', 
		top:'20px',
		left:'100px',
		width: '700px',
		height:'500px',
		opacity: '1', 
		color: '#000' 
	},
	overlayCSS:{  
		backgroundColor:'#000',  
		opacity:'0.8'  
	}
	});
	numberOfIncorrect = wrongArray.length;
	document.getElementById("resultquestion_"+wrongArray[currentReview]).style.display = "";
	current = currentReview;
	currentReview++;
	document.getElementById('reviewloc').innerHTML = "&nbsp;"+currentReview+" of "+totalQuestion+"&nbsp;&nbsp;";
}

function nextReviewQuestion()
{
	if(currentReview > totalQuestion-1)
	{
	}else
	{
		document.getElementById("resultquestion_"+current).style.display = "none";
		document.getElementById("resultquestion_"+currentReview).style.display = "";
		current = currentReview;
		currentReview++;
		document.getElementById('reviewloc').innerHTML = "&nbsp;"+currentReview+" of "+totalQuestion+"&nbsp;&nbsp;";
	}

}
function prevReviewQuestion()
{
	if(current <1)
	{
	}else
	{
		document.getElementById("resultquestion_"+current).style.display = "none";
		current--;
		document.getElementById("resultquestion_"+current).style.display = "";
		currentReview--;	
		document.getElementById('reviewloc').innerHTML = "&nbsp;"+(currentReview)+" of "+totalQuestion+"&nbsp;&nbsp;";
	}
}
function goToReviewQuestion(id)
{
	currentReview = id;
	nextReviewQuestion();
}
function showInfoForReview(id)
{
	var collapse = "<span class=\"expand\" onclick=\"hideInfoForReview("+id+")\" onmouseover=\"this.style.cursor='pointer';\">[-]</span>";
	document.getElementById('reviewinfo_'+id).innerHTML = collapse+document.getElementById('information_'+mappingArray[id]).innerHTML+"<br><br>";
}
function hideInfoForReview(id)
{
	document.getElementById('reviewinfo_'+id).innerHTML = "<span class=\"expand\" onclick=\"showInfoForReview("+id+")\" onmouseover=\"this.style.cursor='pointer';\">[+]</span>";
}
function addToWrong(id)
{

	wrongArray.splice(wrongArray.length,0,id);
}
function addToCorrect(id)
{
	correctArray.splice(correctArray.length,0,id);
}
function restore()
{
	jQuery.unblockUI();
}

function closeReview()
{
	document.getElementById("resultquestion_"+current).style.display = "none";
	hideInfoForReview(current);
	restore();
	showFlashCharts();
}

function showReviewQuestionPopup(id)
{
	//hideFlashCharts();
	jQuery.blockUI({message: jQuery('#questionresultdiv'),css: { 
		border: 'none', 
		top:'20px',
		left:'100px',
		width: '700px',
		height:'500px',
		opacity: '1', 
		color: '#000' 
	},
	overlayCSS:{  
		backgroundColor:'#000',  
		opacity:'0.8'  
	}
	});
	numberOfIncorrect = wrongArray.length;
	goToReviewQuestion(id);
}

function hideFlashCharts()
{
	document.getElementById('additional-charts').style.display = "none";
}
function showFlashCharts()
{
	document.getElementById('additional-charts').style.display = "";
}

function generateResultTabe()
{
	var startTable="<table border=1>";
	var endTabel = "</table>";
	var i =0;
	var qtablehtml = "";
	var colcount = 0;
	for(i=0; i<correctArray.length-1; i++)
	{
		qtablehtml = qtablehtml +"<div class=\"box\">"+"<a onmouseover=\"this.style.cursor='pointer';\" style=\"text-decoration:underline;\" onclick=\"showReviewQuestionPopup("+correctArray[i]+")\">"+(parseInt(correctArray[i])+1)+"</a>,</div>";
	}
	//alert("qcorrect="+qtablehtml);
	document.getElementById('qcorrect').innerHTML = qtablehtml;
	colcount = 0;
	i=0;
	qtablehtml = "";
	for(i=0; i<wrongArray.length-1; i++)
	{
		qtablehtml = qtablehtml +"<div class=\"box\"><a onmouseover=\"this.style.cursor='pointer';\" style=\"text-decoration:underline;\" onclick=\"showReviewQuestionPopup("+wrongArray[i]+")\">"+(parseInt(wrongArray[i])+1)+"</a>,</div>";
	}
	//alert("icorrect="+qtablehtml);
	document.getElementById('icorrect').innerHTML = qtablehtml;
	colcount = 0;
	i=0;
	qtablehtml = "";
	for(i=0; i<leftArray.length-1; i++)
	{
		qtablehtml = qtablehtml +"<div class=\"box\"><a onmouseover=\"this.style.cursor='pointer';\" style=\"text-decoration:underline;\" onclick=\"showReviewQuestionPopup("+leftArray[i]+")\">"+(parseInt(leftArray[i])+1)+"</a>,</div>";
	}
	document.getElementById('leftblank').innerHTML = qtablehtml;

}
function selectAll()
{
	var aRadio;
	var qRadio;
	for(i=0; i<totalQuestion; i++)
	{
		aRadio = document.getElementsByName("R"+i); 
		aRadio[3].checked = true;
		qRadio = document.getElementsByName("question_"+i); 
		qRadio[3].checked = true;
	}
}
function closeWindow()
{
	window.close();
	if (window.opener && !window.opener.closed) {
		window.opener.location.reload();
	}
	jQuery.unblockUI();
}
function wantToLeave()
{
	/*var ret = confirm("------------------------------------------------<br> Are you sure you want to exit<br>-----------------------");
	alert(ret)
	if(ret ==true)
	{*/
	//window.close();
	if (window.opener && !window.opener.closed) {
		window.opener.location.reload();
	}
}

function showHelp()
{
	document.getElementById('help_popup').style.display = "";
}
function hideHelp()
{
	document.getElementById('help_popup').style.display = "none";	
}
/*
 * Google charts
 * 
 */
var googlechart = "http://chart.apis.google.com/chart?";
var pieChartType = googlechart+"cht=p3";
var barChartType = googlechart+"cht=bvg";
var barChartDS = "&chds=0,5";
var barChartAdditional = "&chxr=0,0,4,1|1,0,5,1&chxt=x,y";
var barChartTitle = "&chtt=Time+Taken";
var barLegendPos = "&chdlp=r";
var barChartColor = "&chco=FBB917,FE6C2C,B35817,6E3117";
var barChartSize = "&chs=250x200";
var barChartLegend = "&chdl=Min|Your|Avg|Max";
var pieLegendPos = "&chdlp=t";
var pieChartSize = "&chs=250x150";
var pieChartLegend = "&chdl=Correct|Incorrect|LeftBlank";
var pieChartColor = "&chco=347C17,E42217,FBB917";
var pieChartTitle = "&chtt=User+Percentage";
var pieChartColor = "&chco=347C17,E42217,FBB917";
var smallChartSize = "&chs=150x150";
var corrIncorrPieLabel = "&chl=";
var totalQuestion = 0;
var barUrl = barChartType+barChartLegend+barChartSize+barLegendPos+barChartColor;
var pieUrl = pieChartType+pieChartLegend+pieChartSize+pieLegendPos+pieChartColor;
function generateCharts()
{
	displayMessageInPopUp("Generating graphs for the anaylysis.<br>Please wait for few seconds...");
	for(var i=0;i<totalQuestion; i++)
	{
		var pchdata = document.getElementById('qpie_'+i).value;
		var bchdata = document.getElementById('qbar_'+i).value;
		var pchdatal = pchdata.replace(/,/g,"|");
		var tmppieUrl  = pieUrl + "&chd=t:"+pchdata+"&chl="+pchdatal;
		var tmpbarUrl = barUrl +"&chd=t:"+bchdata+barChartDS+barChartAdditional;
		document.getElementById('piecontainer_'+i).innerHTML = "<img src=\""+tmppieUrl+"\" />";
		document.getElementById('barcontainer_'+i).innerHTML = "<img src=\""+tmpbarUrl+"\" />";

	}

	//alert("BAR URL: "+barUrl+" PIE URL: "+pieUrl);
}
function setRating(a)
{
  var rat = document.getElementById('rating');
  rat.value=a;
  var starElem = document.getElementById("starRating").getElementsByTagName("img");
  for( i=0; i<starElem.length; i++)
  {
   if(i<a)
   {
    starElem[i].setAttribute("src","/images/common/star-red.png");
   }else
   {
    starElem[i].setAttribute("src","/images/common/star-gray.png");
   }
	}
}

function submitFeedback()
{
	var form = document.getElementById('fb');
	YAHOO.util.Connect.setForm(form);
	var transaction = YAHOO.util.Connect.asyncRequest("GET", "/testcenter/aitsfeedback.action", submitfbCallback, null);
}

var submitfbCallback =
{
	cache:false,
	success: function(o) {
	window.close();
	if (window.opener && !window.opener.closed) {
		window.opener.location.reload();
	}
	
}
}
function submitAns()
{
	restore();
	jQuery.blockUI({message:jQuery('#feedback'),css: { 
		border: 'none',
		opacity: '.9',
		color: '#fff'
	},
	overlayCSS:{  
		backgroundColor:'#000',  
		opacity:'0.8'  
	}});
}

function genAnsSheet()
{
	for(var i=0; i<totalQuestion; i++)
	{		
		genAnsTableRow(i);
	}
	var ansText = document.getElementById('ansText');
	ansText.innerHTML = ansStr;
	
}
function genAnsTableRow(id)
{
	var qRadio = document.getElementsByName("question_"+id);
	var selOption = "0";
	
	for(var j=0;j<5;j++)
	{
		if ( qRadio[j].checked == true )
		{
			selOption = optionArr[qRadio[j].value];
		}
	}
	ansStr += (id+1)+"-"+selOption+" ";
}

