﻿var speeds=new Object();
speeds["slow"]=12000;
speeds["medium"]=8000;
speeds["fast"]=4400;

var cur_en;
var cur_th;
var hint_count=3;
var ispeed=speeds["slow"];
var cur_wrong;
var i_word=0;
var i_char=0;
var xdest;
var ani_start_time;
var rem_time;
var paused=false;

/* calculates the percentage based on correct and total answers */
function calculateScorePerc(correctCounter, totalCounter) {
	scorePercentage = (correctCounter / totalCounter) * 100;
	// update the percentage display
	$("#score").html(Math.ceil(scorePercentage)+"%");
	if ($("#sel-adapt").attr('checked')) {
		var newspeed;
		if (scorePercentage>60)
			newspeed=$("#speed").val()=="slow"?"medium":"fast";
		else if (scorePercentage>40)
			newspeed="medium";
		else
			newspeed="slow";
		if (newspeed!=$("#speed").val())
			$("#speed").val(newspeed).trigger("change");
	}
}

function glyph(tchar,ie_ver,hint,type) {
	this.tchar=tchar;
	this.ie_ver=ie_ver;
	this.hint=hint;
	this.type=type;
}

var ab=[
new glyph("\\","\\",'W','ep'),
new glyph("(","(",'Z','ep'),
new glyph(")",")",'X','ep'),
new glyph("+","+",'!','ep'),
new glyph(",",",",'}','ep'),
new glyph("-","-",'3','ep'),
new glyph(".",".",'"','ep'),
new glyph("/","/",'2','ep'),
new glyph("?","?",'M','ep'),
new glyph("ก","ก",'d','cons'),
new glyph("ข","ข",'-','cons'),
new glyph("ฃ","ฃ",'\\','rare'),
new glyph("ค","ค",'8','cons'),
new glyph("ฅ","ฅ",'|','rare'),
new glyph("ฆ","ฆ",'S','cons'),
new glyph("ง","ง",'\'','cons'),
new glyph("จ","จ",'0','cons'),
new glyph("ฉ","ฉ",'C','cons'),
new glyph("ช","ช",'=','cons'),
new glyph("ซ","ซ",':','cons'),
new glyph("ฌ","ฌ",'G','cons'),
new glyph("ญ","ญ",'P','cons'),
new glyph("ฎ","ฎ",'E','cons'),
new glyph("ฏ","ฏ",'D','cons'),
new glyph("ฐ","ฐ",'{','cons'),
new glyph("ฑ","ฑ",'R','cons'),
new glyph("ฒ","ฒ",'<','cons'),
new glyph("ณ","ณ",'I','cons'),
new glyph("ด","ด",'f','cons'),
new glyph("ต","ต",'9','cons'),
new glyph("ถ","ถ",'5','cons'),
new glyph("ท","ท",'m','cons'),
new glyph("ธ","ธ",'T','cons'),
new glyph("น","น",'o','cons'),
new glyph("บ","บ",'[','cons'),
new glyph("ป","ป",'x','cons'),
new glyph("ผ","ผ",'z','cons'),
new glyph("ฝ","ฝ",'/','cons'),
new glyph("พ","พ",'r','cons'),
new glyph("ฟ","ฟ",'a','cons'),
new glyph("ภ","ภ",'4','cons'),
new glyph("ม","ม",',','cons'),
new glyph("ย","ย",'p','cons'),
new glyph("ร","ร",'i','cons'),
new glyph("ฤ","ฤ",'A','rare'),
new glyph("ล","ล",']','cons'),
new glyph("ฦ","ฦ",'?','rare'),
new glyph("ว","ว",';','cons'),
new glyph("ศ","ศ",'L','cons'),
new glyph("ษ","ษ",'K','cons'),
new glyph("ส","ส",'l','cons'),
new glyph("ห","ห",'s','cons'),
new glyph("ฬ","ฬ",'>','cons'),
new glyph("อ","อ",'v','cons'),
new glyph("ฮ","ฮ",'V','cons'),
new glyph("ฯ","ฯ",'O','tp'),
new glyph("ะ","ะ",'t','vowel'),
new glyph(String.fromCharCode(3633),"&#160;&#8205;&#3633;",'y','vowel'),	// อั
new glyph("า","า",'k','vowel'),
new glyph(String.fromCharCode(3635),"&#160;&#8205;&#3661;า",'e','vowel'),	// อำ
new glyph(String.fromCharCode(3636),"&#160;&#8205;&#3636;",'b','vowel'),	// อิ
new glyph(String.fromCharCode(3637),"&#160;&#8205;&#3637;",'u','vowel'),	// อี
new glyph(String.fromCharCode(3638),"&#160;&#8205;&#3638;",'7','vowel'),	// อึ
new glyph(String.fromCharCode(3639),"&#160;&#8205;&#3639;",'n','vowel'),	// อื
new glyph(String.fromCharCode(3640),"&#160;&#8205;&#3640;",'6','vowel'),	// อุ
new glyph(String.fromCharCode(3641),"&#160;&#8205;&#3641;",'^','vowel'),	// อู
new glyph(String.fromCharCode(3642),"&#160;&#8205;&#3642;",'B','rare'),	// อฺ
new glyph("฿","฿",'&','tp'),
new glyph("เ","เ",'g','vowel'),
new glyph("แ","แ",'c','vowel'),
new glyph("โ","โ",'F','vowel'),
new glyph("ใ","ใ",'.','vowel'),
new glyph("ไ","ไ",'w','vowel'),
new glyph("ๅ","ๅ",'1','rare'),
new glyph("ๆ","ๆ",'q','tp'),
new glyph(String.fromCharCode(3655),"&#160;&#8205;&#3655;",'H','vowel'),	// อ็
new glyph(String.fromCharCode(3656),"&#160;&#8205;&#3656;",'j','tone'),	// อ่
new glyph(String.fromCharCode(3657),"&#160;&#8205;&#3657;",'h','tone'),	// อ้
new glyph(String.fromCharCode(3658),"&#160;&#8205;&#3658;",'U','tone'),	// อ๊
new glyph(String.fromCharCode(3659),"&#160;&#8205;&#3659;",'J','tone'),	// อ๋
new glyph(String.fromCharCode(3660),"&#160;&#8205;&#3660;",'N','tp'),	// อ์
new glyph(String.fromCharCode(3661),"&#160;&#8205;&#3661;",'Y','rare'),	// อํ
new glyph("๐","๐",'Q','digit'),
new glyph("๑","๑",'@','digit'),
new glyph("๒","๒",'#','digit'),
new glyph("๓","๓",'$','digit'),
new glyph("๔","๔",'%','digit'),
new glyph("๕","๕",'*','digit'),
new glyph("๖","๖",'(','digit'),
new glyph("๗","๗",')','digit'),
new glyph("๘","๘",'_','digit'),
new glyph("๙","๙",'+','digit')];

function th2en(ch) {
	for (var i=0;i<ab.length;i++)
		if (ch==ab[i].tchar)
			return ab[i].hint;
	return 0;
}

/* function to randomize and choose which array key gets picked */
function next_item() {
	cur_wrong=0;
	i_char=0;
	var show;
	if ($("#sel-word").attr('checked')) {
		if (i_word>=words.length)
			i_word=0;
		show=cur_th=words[i_word++];
		cur_en="";
		for (var i=0;i<cur_th.length;i++)
			cur_en+=th2en(cur_th[i]);
	}
	else {
		var g;
		do {
			g=ab[Math.floor(Math.random()*ab.length)];
		} while (!$("#sel-"+g.type).attr('checked'));
		show=g.ie_ver;
		cur_th=g.tchar;
		cur_en=g.hint;
	}
	$("#consonant").html(show);
}

var grch="<img class='hint-icon' src='/img/green_check_2524.png' />";
function green_checks(n) {
	var checks=grch;
	for (var j=1;j<n;j++)
		checks+=grch;
	return checks;
}

/* compare the user-submitted answer with the current value */
function compareAnswer(ans) {
	// only want to check for the answer if the keyup event reveals an actual letter or character, rather than an empty event like the SHIFT key
	if (ans.length>0) {
		if (ans==cur_en[i_char]||ans==cur_th[i_char]) { // if the user gets a correct answer
			if (++i_char<cur_th.length) {
				$("#hint").html(green_checks(i_char));
				cur_wrong=0;
			}
			else {
				pauseAnimation();
				incrementCorrectCount();
				incrementTotalCount();
				calculateScorePerc(correctCounter,totalCounter);
				var x=$("#consonant").css("margin-left");
				var y=$("#consonant").css("margin-top");
				$("#explosion").css("margin-left",x).css("margin-top",y).css("display","block")
			.animate({ opacity: 0 },1000,function() { $(this).css("display","none").css("opacity",1.0); });
				if (i_char>1)
					$("#hint").html(green_checks(i_char)).animate({ opacity: 0.0 },function() {
						$(this).html("").css("opacity",1.0);
					});
				else
					$("#hint").html("");
				disableStartBtn();
				startAnimation();
			}
		} else { // if a user gets an incorrect answer; but ONLY want to do this when the keyup is NOT the shift key
			if (++cur_wrong>=$("#hint-count").val())
				$("#hint").html("Hint: "+cur_en[i_char]);
			else
				$("#hint").html("<img class='hint-icon' src='/img/red_x_2524.png' />");
			incrementTotalCount();
			calculateScorePerc(correctCounter, totalCounter);
		}
	}
}

function disableStartBtn() {
	$("#startBtn").attr('disabled', true);
}

function disableStopBtn() {
	$("#pauseBtn").attr('disabled', true);
}

function enableResetBtn() {
	$("#resetBtn").attr('disabled', false);
}

function enableStartBtn() {
	$("#startBtn").attr('disabled', false);
}

function enableStopBtn() {
	$("#pauseBtn").attr('disabled', false);
}

/* if the consonant <div> gets all the way to the end... */
function gotToEnd() {
	// In the case where the letter got to the end, the user never input an answer and should be penalized, but not if they already submitted a wrong answer.
	if (cur_wrong==0) {
		incrementTotalCount();
		calculateScorePerc(correctCounter, totalCounter);
		$("#hint").html("Answer: "+cur_en[i_char]);
	}
	startBtnToContinue();
	disableStopBtn();
	enableStartBtn();
	paused=false;
}

function incrementCorrectCount() {
	correctCounter = correctCounter + 1;
	$("#correctCount").html(correctCounter);
}

function incrementTotalCount() {
	totalCounter = totalCounter + 1;
	$("#totalCount").html(totalCounter);
}

/* start the consonant <div> from the beginning */
function resetConsonantDivPosition() {
	var x=Math.random()*400;
	$("#consonant").css("margin-top","-40px").css("margin-left",x+"px");
	next_item();
	xdest=Math.random()*400;
}

function resetCounters() {
	correctCounter = 0;
	totalCounter = 0;
	$("#score").html("0%");
	$("#correctCount").html(correctCounter);
	$("#totalCount").html(totalCounter);
}

/* start function */
function startAnimation() {
	resetConsonantDivPosition();
	rem_time=speeds[$("#speed").val()];
	resumeAnimation();
}
function resumeAnimation() {
	ani_start_time=(new Date()).getTime();
	$("#consonant").addClass('active')
	.animate({ marginTop: "377px", marginLeft: xdest+"px" },rem_time,"linear", function() { gotToEnd(); });
	$(document).bind('keypress.invaders',function(e) {
		$(document).focus();
		var code=keyevent2char(e);
		if (code==27)
			stop();
		else {
			var ans=String.fromCharCode(code);
			// only want this compare operation to work when the animation is running
			if ($("#consonant").hasClass('active')) {
				compareAnswer(ans);
			}
		}
		return false;
	});
}

/* change text value of the start button to "continue" */
function startBtnToContinue() {
	$("#startBtn").val("Continue");
}

/* change text value of the start button to "start" */
function startBtnToStart() {
	$("#startBtn").val("Start");
}

/* pause function */
function pauseAnimation() {
	$("#consonant").stop();
	$(document).unbind('keypress.invaders');
	// blur the input box if the quiz has been paused
	enableStartBtn();
}

/* "I give up!" function to give the answer - must stop the div and display an alert with the keystroke */

function keyevent2char(e) {
	if (e.altKey || e.ctrlKey)
		return 0;
	return e.charCode||e.keyCode||e.which;
}

/* document.ready */
function init_805664() {
	correctCounter = 0;
	totalCounter=0;

	$("#resetBtn").click(function() {
		pauseAnimation();
		startBtnToStart();
		enableStartBtn();
		disableStopBtn();
		$("#resetBtn").attr('disabled',true);
		resetCounters();
		resetConsonantDivPosition();
	});
	
	/* enable the start button */
	$("#startBtn").click(function() {
		$("#hint").html("");
		$("#counter").css("display","inline");
		$("#scoreHeader").css("display","inline");
		$("#score").css("display","inline");
		$("#correctCount").html(correctCounter);
		$("#totalCount").html(totalCounter);
		if (paused) {
			resumeAnimation();
			paused=false;
		}
		else
			startAnimation();
		disableStartBtn();
		enableStopBtn();
		enableResetBtn();
		$("#startBtn").blur();
	});

	$("#pauseBtn").click(function() {
		rem_time-=(new Date()).getTime()-ani_start_time;
		paused=true;
		pauseAnimation();
		startBtnToContinue();
		enableStartBtn();
		disableStopBtn();
		enableResetBtn();
	});

	$("#sel-word").click(function() {
		$(".charmode").attr('disabled',$(this).attr('checked'));
		next_item();
	});

	//at least one in the charmode group must always be selected
	//attempting to turn them all off sets 'word' mode
	$(".charmode").click(function() {
		$("#sel-word").attr('checked',false);
		if (!$(".charmode").is(':checked')) {
			$("#sel-cons").attr('checked',true);
			$("#sel-word").attr('checked',true);
			$(".charmode").attr('disabled',true);
		}
		next_item();
	});
}

