//2010-09-09 16:27:48
//function initialisations on page load
var pluginPath='../../wp-content/plugins/tkdtheory_v2/';
function loadPage()
{
	//setOverallTime(121);
	loadRanks();
	//countQ("reset")
	//setScore('reset')
	$('questionResult').update('').setStyle({ background: '#fff' });
	//setCountDown(31);
	last24();
}
//get question from next available index
function getQuestion()
{
if(window.questions.length==0)
{
	Questiontime='stop';
	OverallTime='stop';
	if($F("compOnly")==true)message='<div class="error">There are no questions available for your choosen parameters. Try selecting non-compulsary questions.</div>';
	else message='<div class="error">There are no questions available for your choosen parameters.</div>';
	$('quiz').update(message);
	$('average').update('');
	showOptions();
}
else if(OverallTime>0 || typeof OverallTime=='undefined' || OverallTime=='stop')
{
var remain=window.questions.length-asked;
var url = pluginPath+"getquestion.php?query="+window.questions[countQ("add")-1]+"&showLevel="+show+"&remain="+remain;
new Ajax.Request(url, 
			 {
				method: 'get',
				onComplete: function(transport) 
				{
					if(OverallTime>0 || typeof OverallTime=='undefined' || OverallTime=='stop')$('quiz').update(transport.responseText);
					if(Questiontime <30)Questiontime=31;
					pause='no';
				}
			}
		);
}
}

//load the available ranks into the quiz level selector
function loadRanks()
{
	new Ajax.Updater('range', pluginPath+'getRanks.php', { method: 'get' });	
	loadId("pageload");
}

//gets random list of id's for all questions withing current range
function loadId(position)
{
	var testType=$$('input:checked[type="radio"][name="testOption"]').pluck('id');
	if(testType=='')testType='noTest';
	if(position == "pageload")
	{
		minRank = 10;
		maxRank = 10;
		comp = "no";
		show = "yes";
		test='no';
	}
	else
	{
	 minRank = parseInt($("min").getValue());
	 maxRank = parseInt($("max").getValue());
	 comp = $("compOnly").getValue();
	 show = $('showLevel').getValue();
	}
	if(minRank > maxRank)
	{
		minRank = maxRank;
		maxRank = $("min").getValue();
	}
	
	var getListURL = pluginPath+'qList.php?min='+minRank+'&max='+maxRank+'&comp='+comp+'&seed='+Math.random()+'&testType='+testType;
	new Ajax.Request(getListURL, 
			 {
				method: 'get',
				onComplete: function(transport) 
				{
					window.questions=eval('(' + transport.responseText + ')');
					getQuestion();
					if(Questiontime == "stop" && window.questions.length!=0)
					{
						Questiontime = 31;
						setCountDown(Questiontime);	
					}
					if(OverallTime == "stop" && window.questions.length!=0)
					{
						OverallTime = 121;
						setOverallTime(OverallTime);
					}
				}
			}
		);
}

function stoptest()
{
	OverallTime="stop";
	Questiontime="stop";
}
//resets variable to start new quiz
function newQuiz()
{
	timeLeft=0;
	$('quiz').update('');
	new Ajax.Updater('quiz_results', pluginPath+'getQuizID.php', { method: 'get' });
	disableAll();
	stoptest();
	$('quiz_results').update("");
	$('rankButton').value ="Go";
	loadId("newQ");
	$('questionResult').update('').setStyle({ background: '#fff' });
	countQ("reset");
	setScore("reset");
	if(OverallTime == "stop" & $F('twoMin')!=null)setOverallTime(121);
	else if($F('twoMin')!=null)OverallTime = 121;
	if((Questiontime == "stop" && $F('twoMin')!=null) || (Questiontime == "stop" && $F('fullTest')!=null))setCountDown(31);
	else if($F('twoMin')!=null || $F('fullTest')!=null)Questiontime = 31;
	if($F('fullTest')!=null)$('pauseButton').removeClassName('hide');
	else $('pauseButton').addClassName('hide');
	asked=0;
	totalrank=0;
	$('average').update('<div><label>Average Question Level: </label><img src="'+pluginPath+'images/ten.png" /><form><input type="hidden" name="averagelvl" value="10" /></form></div>');
	$('complete').update("");
	$('range').toggle();
	$('showOptions').toggle();
}

function showOptions()
{
$('range').toggle();
$('showOptions').toggle();
}
//keeps track of number of questions asked
function countQ(option)
{
	if(typeof countQ.counter == 'undefined' )countQ.counter = 0;
	if(option=="add")++countQ.counter;
	if(option=="reset")countQ.counter = 0;
	return countQ.counter;
}
//keeps track of number of correct answers
function setScore(option) 
{
	if(typeof setScore.counter == 'undefined' )setScore.counter = 0;
	if(option=="correct")++setScore.counter;
	if(option=="reset")setScore.counter = 0;
	return setScore.counter;
}
var timeLeft=0;
var pause='no';
//checks provided answer
function checkAnswer(qid)
{
	//gets checked value. will not proceed if no value has been selected
	//var value = null;
	pause='yes';
	if(Questiontime=='31')answerTime=30;
	else if(Questiontime != "stop")answerTime=Questiontime;
	else answerTime=0;
	var value = $RF('q', 'answer');
	disableAll();
	if(value !=null)
	{
		//alert(score);
		var testType=$$('input:checked[type="radio"][name="testOption"]').pluck('id');
		if(testType=='')testType='noTest';
		var checkerURL = pluginPath+'checkQuestion.php?qid='+qid+'&answer='+value+'&test_id='+$F('test_id')+'&min='+$F("min")+'&max='+$F("max")+'&comp='+$F("compOnly")+'&testType='+testType;
		//$("s").update(questions);	
		new Ajax.Request(checkerURL, 
		{
			method: 'get',
			onComplete: function(transport) 
			{
				var notice = $('questionResult');
				if(value == "timeout")
				{
					notice.update("You did not answer the question in time. The Correct Answer Was '" + transport.responseText+"'<br /> You have answered " + setScore("wrong") + " questions out of " + (countQ("get")) + " correctly.").setStyle({ background: '#fdd' });
				}
		//message resulting from correct answer
				else if (transport.responseText== "correct")
				{
					timeLeft+=answerTime;
					notice.update("'"+value + "' Is Correct.<br /> You have answered " + setScore("correct") + " questions out of " + (countQ("get")) + " correctly.").setStyle({ background: '#dfd' });
				}
		//message resulting from wrong answer
				else
				{
				  notice.update("'"+value+"' Is Incorrect. The Correct Answer Was '" + transport.responseText+"'<br /> You have answered " + setScore("wrong") + " questions out of " + (countQ("get")) + " correctly.").setStyle({ background: '#fdd' });
				}
				var percent = (setScore("get")/countQ("get"))*100;
				$('questionResult').insert({bottom:"  " + percent.toFixed(2)+"%"});
				if(countQ("get") == window.questions.length) 
				{
					Questiontime = "stop";
					OverallTime = "stop";
					$('remain').update('').setStyle({ background: '#fff' });
					$('quiz').update('').setStyle({ background: '#fff' });
					$('overall').update('').setStyle({ background: '#fff' });
					$('rankButton').update('Restart Quiz');
					if($F('twoMin')=='on')istest='twoMin';
					else if($F('fullTest')=='on')istest='full';
					else istest='off';
					var average=(totalrank/asked).toFixed(0);
					var url = pluginPath+"getresult.php?score="+setScore("get")+"&total="+countQ("get")+"&istest="+istest+"&average="+average+"&test_id="+$F('test_id')+"&timeLeft="+timeLeft;
					new Ajax.Request(url, 
					{
						method: 'get',
						onComplete: function(transport) 
						{
							$('complete').insert(transport.responseText);
						}
					});
				}
				else getQuestion();
			}
		});
	}
}
var asked=0;
var totalrank=0;
function getavg(avg)
{
	var prev=(totalrank/asked).toFixed(0);
	asked++;
	totalrank=totalrank+avg;
	var average=(totalrank/asked).toFixed(0);
	if(prev!=average)
	{
	new Ajax.Updater('average', pluginPath+'getavg.php?level='+average, { method: 'get' });	
	}

}
//countdown timer for each question
var Questiontime;
function setCountDown (time)
{	
	if($F('twoMin')!=null || $F('fullTest')!=null)
	{
		if(Questiontime != "stop")
		{
			if(OverallTime <=0) Questiontime = "stop";
			else 
			{
				Questiontime = time;
				if(pause!='yes')Questiontime--;
			  
				$("remain").update("<strong>Time remaining to answer Question: "+Questiontime+" seconds</strong>");
				setTimeout ( "setCountDown(Questiontime)", 1000 );
				if(Questiontime <= 0) 
				{
					$$("input[type=radio][name='answer'][value='timeout']")[0].writeAttribute("checked", "checked");
					checkAnswer($('qid').getValue());
				}
			}
		}
	}
}
//countdown timer for entire quiz
var OverallTime;
function setOverallTime (time)
{
	if($F('twoMin')!=null)
	{
		if(OverallTime != "stop")
		{
			OverallTime = time;
			if(pause!='yes')OverallTime--;
			$("overall").update("<strong>Quiz ends in "+OverallTime+" seconds</strong>");
			setTimeout ( "setOverallTime(OverallTime)", 1000 );
			if(OverallTime <= 0)  
			{
				disableAll();
				OverallTime="stop";
				Questiontime ="stop";
				if($F('twoMin')=='on')istest='twoMin';
				else if($F('fullTest')=='on')istest='full';
				else istest='off';
				var average=(totalrank/asked).toFixed(0);
				var url = pluginPath+"getresult.php?score="+setScore("get")+"&total="+(countQ("get")-1)+"&istest="+istest+"&average="+average+"&test_id="+$F('test_id')+"&timeLeft="+timeLeft;
				new Ajax.Updater('quiz', url, { method: 'get' });
				$('rankButton').update('Restart Quiz');
				$('questionResult').update('').setStyle({ background: '#fff' });
				$('remain').update('').setStyle({ background: '#fff' });
				$('overall').update('').setStyle({ background: '#fff' });
			}
		}
	}
	else 
	{
	$('remain').update('').setStyle({ background: '#fff' });
	$('overall').update('').setStyle({ background: '#fff' });
	}
}
function updatehs(update,score,average,number_correct,outof,testType,position)
{
	$('long').disable();
	var error='';
	if($F('name').split(' ').join('')=='')error+='<div>Please enter a Name to save your Score</div>';
	if($F('club').split(' ').join('')=='')error+='<div>Please enter a Club to save your Score</div>';
	if(error!='')
	{
		$('errorMsg').insert(error);
		$('errorMsg').removeClassName('hide');
	}
	else
	{
		$('errorMsg').addClassName('hide');
	var url = pluginPath+"updatehs.php?score="+score+"&name="+$('name').value+"&email="+$('email').value+"&average="+$F('averagelvl')+"&toupdate="+update+"&club="+$F('club')+"&number_correct="+number_correct+"&outof="+outof+"&testType="+testType+"&position="+position;
	new Ajax.Updater('highscore', url, { method: 'get' });
	}
}
function getHS(testType,position)
{
	var subdir='';
	if(position==0) subdir="../";
	if($('hstable')!=null)$('hstable').update('<img id="loadingGif" src="blog/'+subdir+pluginPath+'images/iconLoading.gif" />');
	if(testType=='select')
	{
		testType=$F('testType');
		filterBy='&filter='+$F('filterBy');
		if($('clubName')!=null)
		{
			if($F('clubName')!='')filterBy+='&clubName='+$F('clubName');
		}
		if($('regionName')!=null)
		{
			if($F('regionName')!='')filterBy+='&regionName='+$F('regionName');
		}
		if($('limitRank')!=null)
		{
			if($F('limitRank')!='')filterBy+='&limitRank='+$F('limitRank');
		}
	}
	else
	{
		filterBy='';
	}
	var url = pluginPath+"updatehs.php?testType="+testType+"&position="+position+filterBy;
	new Ajax.Updater('highscore', url, { method: 'get' });
	
}






function $RF(el, radioGroup) {
if($(el).type && $(el).type.toLowerCase() == 'radio') {
var radioGroup = $(el).name;
var el = $(el).form;
} else if ($(el).tagName.toLowerCase() != 'form') {
return false;
}

var checked = $(el).getInputs('radio', radioGroup).find(
function(re) {return re.checked;}
);
return (checked) ? $F(checked) : null;
}

function disableAll()
{
	answers= $$("input[type=radio][name='answer']");
	answers.each(function(item) {
  item.disable();
});
}
function showQuestionResult()
{
var url=pluginPath+'question_result.php?quiz_id='+$F('test_id');
window.open(url,'Quiz Results')
//new Ajax.Updater('quiz_results', url, { method: 'get' });
}
function last24()
{
	var url=pluginPath+'question_result.php';
	new Ajax.Updater('last24', url, { method: 'get' });
}
function pauseQuiz()
{
	var setheight=$('content').getStyle('height');	
	var setwidth=$('content').getStyle('width');
	$('pause').setStyle({height: setheight,
						width: setwidth});
	$('tree').addClassName('center');
	$('pauseButton').addClassName('hide');
	$('pause').removeClassName('hide');	
	pause='yes';			
}
function resumeQuiz()
{
$('pause').addClassName('hide');
$('pauseButton').removeClassName('hide');
pause='no';
}
