var lessonList;
var LLshowing = 0, LLnum = 10;
var lessonContent = new Array();
var showingLesson = 0;

function initTutorial() {
	$$('.firstHide').each(Element.hide);
	loadLessonList();
	$('wrapper').removeClassName('hide');
}

function loadLessonList() {
	var pars = 'act=getList&for=user';
	var myAjax = new Ajax.Request('list.xml.php', {
		method: 'get',
		parameters: pars,
		asynchronous: false,
		onComplete: function(transport) {
			lessonList = transport.responseXML.getElementsByTagName('lesson');
			showLessonList(lessonList.length - LLnum);
			updateUserSummary(transport.responseXML.getElementsByTagName('lessonList')[0].getAttribute('pass'), transport.responseXML.getElementsByTagName('lessonList')[0].getAttribute('total'));
		}
	});
}

var boxList = new Array('welcome_text', 'lesson_content', 'help');
function showUp(target) {
	if (target != 'lesson_content') showingLesson = 0;
	showLessonList();
	for (var i = 0; i < boxList.length; i++) {
		if ($(boxList[i]) != null) {
			if (boxList[i] == target) $(boxList[i]).show();
			else $(boxList[i]).hide();
		}
	}
	scroll(0, 0);
}

function updateUserSummary(pass, total) {
	var htmlText = '';
	var percent = (total > 0) ? parseInt(pass / total * 10000) / 100 : 0;
	if (percent > 100) percent = 100;
	var barWidth = 200;
	htmlText += '<div class="header">Summary</div>';
	htmlText += '<hr style="width: '+(barWidth * percent / 100)+'px;" class="percentBar a"/><hr style="width: '+(barWidth * (100 - percent) / 100)+'px;" class="percentBar b"/>';
	htmlText += percent + '% Completed';
	$('userSummary').update(htmlText);
}

function showLessonList(start) {
	if (start == undefined) start = LLshowing;
	else LLshowing = start;

	if (start >= lessonList.length) start = lessonList.length - LLnum;
	if (start < 0) start = 0;

	var htmlText = '<ul>';
	htmlText += '<li class="header">Step by Step</li>';
	for (var i = start; i < lessonList.length && i < start + LLnum; i++) {
		htmlText += '<li';
		var classText = '';
		if (i == start + LLnum - 1 || i == lessonList.length - 1) classText += "bottom";
		if (lessonList[i].getAttribute('oid') == showingLesson) classText += " listOver";
		htmlText += ' class="' + classText + '"';
		htmlText += ' onclick="javascript:showLesson('+lessonList[i].getAttribute('oid')+')"';
		if (lessonList[i].getAttribute('oid') != showingLesson) htmlText += ' onmouseover="mOver(this, \'menu\');" onmouseout="mOut(this, \'menu\');"';
		htmlText += '>';
		if (lessonList[i].getAttribute('type') == 0) htmlText += '&ensp;- ';
		htmlText += lessonList[i].getElementsByTagName('topic')[0].firstChild.nodeValue;
		//if (lessonList[i].getAttribute('pass') == 1) htmlText += ' <img src="picture/pass.png" />';
		htmlText += '</li>';
	}
	htmlText += "</ul>";
	if (start > 0) htmlText += '<span class="prev" onclick="prevLessonList();" onmouseover="mOver(this, \'menu\');" onmouseout="mOut(this, \'menu\');">Prev</span>';
	if (start + LLnum < lessonList.length) htmlText += '<span class="next" onclick="nextLessonList();" onmouseover="mOver(this, \'menu\');" onmouseout="mOut(this, \'menu\');">Next</span>';
	$('lesson_list').update(htmlText);
}

function nextLessonList() {
	var nextStart = LLshowing + LLnum;
	if (nextStart > lessonList.length - LLnum) nextStart = lessonList.length - LLnum;
	showLessonList(nextStart);	
}

function prevLessonList() {
	var prevStart = LLshowing - LLnum;
	if (prevStart < 0) prevStart = 0;
	showLessonList(prevStart);
}

function showLesson(oid) {
	
	if (oid == 0 || (oid > 0 && lessonList[oid - 1] == null)) {
		return;
	}
	
	if (oid < 0) oid = lessonList.length;

	showingLesson = oid;

	var id = lessonList[oid - 1].getAttribute('id');

	if (lessonContent[id] == null) {
		var pars = "act=getContent&id=" + id;
		var myAjax = new Ajax.Request('list.xml.php', {
			method: 'get',
			parameters: pars,
			asynchronous: false,
			onComplete: function (transport) {
				lessonContent[id] = transport.responseXML.getElementsByTagName('lesson')[0];
			}
		});

	}
	
	var data = lessonContent[id];
	if (data == null) {
		return;
	}

	var type = data.getAttribute('type');
	var quesType = data.getElementsByTagName('question')[0].getAttribute('questype');
	var ques_num = data.getElementsByTagName('question')[0].getAttribute('quesnum');

	var htmlText = '<p class="content">' + data.getElementsByTagName('topic')[0].firstChild.nodeValue;
	if (lessonList[oid - 1].getAttribute('pass') == 1) htmlText += ' <img src="picture/pass.png" />';
	htmlText += '</p>';
	
	htmlText += '<hr />';
	htmlText += '<div class="content"><span>'+data.getElementsByTagName('content')[0].firstChild.nodeValue+'</span></div>';
	if (type != -1) {
		if (quesType != 2) {
			htmlText += '<p class="question">คำถามผ่านด่าน</p>';
			htmlText += '<div class="question">'+data.getElementsByTagName('question')[0].firstChild.nodeValue+'</div>';
			htmlText += '<p class="answer">คำตอบ</p>';
			htmlText += '<input class="btnStartEditor" type="button" value="คลิกปุ่มนี้เพื่อทำการตอบคำถาม" onclick="javascript:$(\'answerBox\').removeClassName(\'hide\'); startEditor(); this.style.display = \'none\';"/>';
			htmlText += '<div id="answerBox" class="answer hide">';
		}
			htmlText += '<form id="answer_form" name="answer_form"  action="#" onsubmit="javascript:sendAns(); return false;">';
			htmlText += '<input type="hidden" name ="id" value="'+id+'" />';
		if (quesType != 2) {
			if (quesType == 0) {
				htmlText += '<table border="0" cellspacing="0" cellpadding="0">';
				var runner = 0;
				for (;runner < ques_num;) {
					htmlText += '<tr style="height: 30px;">';
					for (var i = 0; i < 5; i++, runner++) {
						htmlText += '<td style="width: 20px; text-align: right;">';
						if (runner < ques_num) htmlText += (runner+1)+'. ';
						htmlText += '</td>'; 
						htmlText += '<td style="width: 120px;">';
						if (runner < ques_num) {
							htmlText += '<select name="ans['+runner+']">';
							htmlText += '<option value="1">ถูก</option>';
							htmlText += '<option value="0">ผิด</option>';
							htmlText += '</select> ';
						}
						htmlText += '</td>';
					}
					htmlText += '</tr>';
				}
				htmlText += '</table><br />';
				htmlText += '<input type="submit" id="btnAnswer" value="ส่งคำตอบ" class="eng_button" /><br />';
			}
			// It's a testing, not a real one.
			else if (quesType == 1) {
				htmlText += '<textarea id="ans" name="ans" rols="3" cols="30"></textarea><br />';
				htmlText += '<input type="submit" id="btnAnswer" value="Compile & Run" class="eng_button" style="font-size: 8pt;"/>';
				htmlText += ' <input type="button" id="btnReset" onclick="resetEditorValue();" value="Reset" class="eng_button" style="font-size: 8pt;"/><br />';
				htmlText += '<fieldset id="output" class="hide"></fieldset>';
			}
		
		} else {
			htmlText += '<input class="btnStartEditor" type="submit" value="ไปยังหน้าถัดไป" />';
		}
	}
	htmlText += '<div id="answer_status" style="margin-left:10px; margin-top: 20px; color: #039;"></div></form></div>';
	

	htmlText += '<br /><br /><hr>';
	if (showingLesson > 1) htmlText += '<a href="javascript: prevLesson();"><< ไปหน้าก่อนหน้า</a> | ';
	//htmlText += '<a href="javascript: showLesson(0);">กลับไปยังหน้ารวมบทเรียน</a>';
	if (showingLesson < lessonList.length) htmlText += ' | <a href="javascript:nextLesson();"> ไปหน้าถัดไป >> </a>';
	$('lesson_content').update(htmlText);
	showUp('lesson_content');
	//dp.SyntaxHighlighter.ClipboardSwf = 'SyntaxHighlighter/Scripts/clipboard.swf';
	//dp.SyntaxHighlighter.HighlightAll('code');
}

function resetEditorValue() {
	var data = lessonContent[lessonList[showingLesson - 1].getAttribute('id')];
	editAreaLoader.setValue("ans", data.getElementsByTagName('precode')[0].firstChild.nodeValue);
	startCursor = data.getElementsByTagName('precode')[0].getAttribute('startcursor');
	editAreaLoader.setSelectionRange("ans", startCursor, startCursor);
}

function startEditor() {
	if ($('ans') == null) return;
	var data = lessonContent[lessonList[showingLesson - 1].getAttribute('id')];
	editAreaLoader.init({
		id: "ans",
		syntax: "cpp",
		language: "th",
		start_highlight: true,
		allow_resize: "no",
		allow_toggle: false,
		toolbar: "save, load, |, search, go_to_line, |, undo, redo, |, select_font",
		font_family: "Courier New"
	});
	
	editAreaLoader.setValue("ans", data.getElementsByTagName('precode')[0].firstChild.nodeValue);
	startCursor = data.getElementsByTagName('precode')[0].getAttribute('startcursor');
	editAreaLoader.setSelectionRange("ans", startCursor, startCursor);
}

function prevLesson() {
		showLesson(showingLesson - 1);
}

function nextLesson() {
		showLesson(showingLesson + 1);
}

function sendAns() {
	if ($('answer_form').ans != null) $('answer_form').ans.value = editAreaLoader.getValue("ans");

	var pars = $('answer_form').serialize();
	if ($('btnAnswer') != undefined && false) {
		$('btnAnswer').disabled = true;
		$('btnAnswer').addClassName('eng_disabled');
		$('btnAnswer').removeClassName('eng_button');
	}
	$('answer_status').update('<img src="../pictures/loading_16x16.gif" alt="Loading.." /> กำลังตรวจสอบข้อมูล');
	if ($('output') != undefined) $('output').update('').addClassName('hide');

	var myAjax = new Ajax.Request('answer.xml.php', {
		method: 'post',
		parameters: pars,
		onComplete: function(transport) {
			var result = parseInt(transport.responseXML.getElementsByTagName('answer')[0].getAttribute('result'), 10);
			if (result == 1) {
				loadLessonList();
				$('answer_status').update('ถูกต้องครับ คลิก <a href="javascript:nextLesson();">ที่นี่</a> เพื่อไปหน้าถัดไป');
			} else if (result == 2) {
				$('answer_status').update('โปรดเข้าสู่ระบบ เพื่อเข้าสู่หน้าถัดไป');
			} else if (result == 0) {
				$('answer_status').update('คำตอบไม่ถูกต้อง ลองใหม่อีกครั้ง');
				if ($('btnAnswer') != undefined) {
					$('btnAnswer').disabled = false;
					$('btnAnswer').addClassName('eng_button');
					$('btnAnswer').removeClassName('eng_disabled');
				}
			} else if (result == 3) {
				$('answer_status').update('');
				loadLessonList();
				nextLesson();
			} else if (result == 4) {
				var data = transport.responseXML.getElementsByTagName('answer')[0];
				$('output').update('<legend>ผลลัพธ์</legend>' + data.getElementsByTagName('output')[0].firstChild.nodeValue.nl2br()).removeClassName('hide');
				loadLessonList();
				$('answer_status').update('ถูกต้องครับ คลิก <a href="javascript:nextLesson();">ที่นี่</a> เพื่อไปหน้าถัดไป');
			} else if (result == 5) {
				var data = transport.responseXML.getElementsByTagName('answer')[0];
				if (data.getElementsByTagName('cmpStat')[0].firstChild.nodeValue == 'OK') {
					$('output').update('<legend>ผลลัพธ์</legend>' + data.getElementsByTagName('output')[0].firstChild.nodeValue.nl2br()).removeClassName('hide');
				} else {
					$('output').update('<legend>Error message</legend>' + data.getElementsByTagName('cmpStat')[0].firstChild.nodeValue).removeClassName('hide');
				}
				$('answer_status').update('');
			}
		}
	});
}


function showManual() {
	alert('Under Construction!');
}
function showInstall() {
	alert('Under Construction!');
}
