/* 
 * To change this template, choose Tools | Templates
 * and open the template in the editor.
 */

$(function() {
	$("#questionDisplay").dialog({
		resizable: true,
		height: 768,
		width: 1024,
		title: "Diagnoser Question",
		modal: true,
		autoOpen: false,
		buttons : {
			OK : function() {$(this).dialog("close")}
		}
	})

	$("#refreshingDialog").dialog({
		resizable: false,
		height: 150,
		width: 300,
		title: "Loading Assignment List",
		modal: true,
		autoOpen: false,
		buttons: {}
	})


	// bind events for display
	$("th.reportSectionQuestionColumn a.questionLink").live("click", function(ev) {
		// ajax the content
		$.ajax({
			url: $(this).attr("href"),
			success: function(data) {
				// insert into dialog
				$("#questionDisplay").html(data)
				// display dialog
				$("#questionDisplay").dialog("open");
			}
		})	
		ev.preventDefault();
		ev.stopPropagation();
		ev.stopImmediatePropagation();
		return false;
	})
	// bind events for list display
	// 
	

	$("#setRunningDialog").dialog({
		resizable: false,
		height: 680,
		width: 1024,
		title: "Diagnoser Question Set",
		modal: true,
		autoOpen: false
	})

	$(window).resize(function() {
		$("#setRunningDialog").dialog("option", "position", "center");
	})

	var historySelected = function(ev, data) {
		if(data.args.length > 2) {
			var selectedNode = data.args[0];
			var index;
			if(!$(selectedNode).is("li")) {
				selectedNode = $(selectedNode).parent("li")
			}
			index = $(selectedNode).attr("id").substring("his-".length)
			var oldIndex = $("#historyTree").find(".selectedHistoryNode").attr("id").substring("his-".length);
			if(oldIndex == undefined) {
				oldIndex = index;
			}
			$("#historyTree *").removeClass("selectedHistoryNode")
			$(selectedNode).addClass("selectedHistoryNode");
			// load up a different page
			var baseURL= $("#setRunnerForm").attr("action");
			var pageType;
			if($.trim($(selectedNode).text()) == "TEXT"){
				pageType="TEXT";
			} else {
				pageType="QUESTION";
			}
			var highestHistory = $("li[id^='his']").last().attr("id")
			var url = baseURL;
			url = url+"?questionSetRecordId="+$("#questionSetRecordId").val();
			url = url+"&startingHistoryIndex="+$("#startingHistoryIndex").val();
			// needed to make sure the current page is answerable and not treated just
			// as a view history if it's the current page
			if($(selectedNode).attr("id") != highestHistory) {
				url = url+"&historyIndex="+index+"&pageType="+pageType;
			}
			if(index != oldIndex) {
				$.ajax({
					url: url,
					success: function(data){
						renderJSONResponse(data)
						// do stuff like change button to back and disable inputs
						if($(selectedNode).attr("id") != highestHistory) {
							$(":radio,:text,textarea").attr('disabled', true);
							$("#next-question-button").val("Back");
						} else {
							$("#next-question-button").val("Next");
						}
						ev.preventDefault();
						ev.stopPropagation();
						ev.stopImmediatePropagation();
						return false;
					}
				})
			}
			console.log("History Index to load: "+index)
			ev.preventDefault();
			ev.stopPropagation();
			ev.stopImmediatePropagation();
			return false;
		}
	}
	
	$(".reviewSet").die("click")
	$(".reviewSet").live("click", function(ev) {
		var setName = $(ev.target).siblings(".setName").val();
		// get the frame
		$.ajax({
			url: $(this).attr("href"),
			success: function(data) {
				// insert into dialog
				$("#setRunningDialog").html(data)
				$("#setTitle").text(setName)
				$("#next-question-button").click(function(ev) {
					$("#setRunningDialog").dialog("close");

					$("#question-number").html("&nbsp;")
					$("#historyTree").html("&nbsp;")
					$("#setRunningDialog").html("")
				})
				$("#next-question-button").val("Close")
				$("#previous-questions h3").hide();
				$("#question-number").html("&nbsp;")
				$("#historyTree").html("&nbsp;")
				$("#setRunningDialog").dialog("open");
			}
		})
		ev.preventDefault();
		ev.stopPropagation();
		ev.stopImmediatePropagation();
		return false;
	})

	$(".takeSet").die("click")
	// bind events for running from assignment page
	$(".takeSet").live("click", function(ev) {
		var setName = $(ev.target).siblings(".setName").val();
		// hack to get around ajax resetting the scope for it's success callback
		diagnoser.takeSet($(this).attr("href"), setName);
		ev.preventDefault();
		ev.stopPropagation();
		ev.stopImmediatePropagation();
		return false;
	})

	diagnoser.nextButtonFunc = function(ev) {
		// validate numerics and free response
		if($("#free-text-response-area").length == 1) {
			var minAnswerLength = 4;
			if($("#free-text-response-area textarea").val().length > minAnswerLength)	{
				cyclePages();
			} else {
				// display problem dialog
				$("#error-reason").text("Your answer must be more than "+minAnswerLength+" characters long.")
				$("#validation-error-dialog").dialog("open")
				$("#next-question-button").one("click", diagnoser.nextButtonFunc);
			}
		} else if($("#numerical-response").length == 1) {
			var response = parseFloat($("#numerical-response").val())
			if(!isNaN(response)) {
				cyclePages();
			} else {
				//display problem dialog
				$("#error-reason").text("Your answer must be a number.")
				$("#validation-error-dialog").dialog("open")
				$("#next-question-button").one("click", diagnoser.nextButtonFunc);
			}
		} else {
			cyclePages();
		}	
	}
	diagnoser.takeSet = function(startingHREF, setName) {
		// ajax the content
		$.ajax({
			url: startingHREF,
			success: function(data) {
				// insert into dialog
				$("#setRunningDialog").html(data)
				$("#setTitle").text(setName)
				// request filler for the contentArea
				// extract the questionsetrecord id from the set runner frame
				var startElement = $("#startSetURL")
				if(startElement.size() == 0) {
					window.location="/"
				} else {
					var startURL = $(startElement).val();
					$("#historyTree").bind("select_node.jstree", historySelected)
					$("#historyTree").empty();
					$("#historyTree").append("<ul/>");	
					$("#historyTree").jstree({
						core : { animation : 0},
						ui : {select_limit: 1},
						themes : {icons : false},
						plugins : ["themes", "html_data", "ui"]
					});
					
					$("#validation-error-dialog").dialog({
						resizable: false,
						height: 200,
						width: 400,
						title: "Answer invalid",
						modal: true,
						autoOpen: false,
						buttons : {
							OK : function() {$(this).dialog("close")}
						}
					})

					$("#numerical-response").die("keypress")
					$("#numerical-response").live("keypress", function(ev) {
						if(ev.which == 13) {
							ev.preventDefault();
						}
					})

					$.getJSON(startURL,function(data2) {
							console.log(data2.content)
							renderJSONResponse(data2)
							
							$("#setRunningDialog").unbind("dialogbeforeclose")
							if($("#studentContent").size() != 0) {
								$("#setRunningDialog").bind("dialogbeforeclose", function(event, ui) {
									// refresh student home	
									window.location.reload(true)
									$("#refreshingDialog").siblings("div.ui-dialog-titlebar").children("a").hide()
									$("#refreshingDialog").dialog("open")
								})
							}
 							// display dialog
							$("#setRunningDialog").dialog("open");
						})
				}
			}
		})	
		
	}

	
	// display JSON response
	var renderJSONResponse = function(jsonData) {
		// update tree
		if(jsonData.history != undefined && jsonData.history.length != 0) {
			$("#previous-questions h3").show();
			$("#question-number").text("Ques. "+jsonData.history[jsonData.index].displayId)
			$("#questionId").val(jsonData.history[jsonData.index].questionId)
			var starterIndex = $("#historyTree li").size();
			var newHistory = jsonData.history.slice(starterIndex)
			$.each(newHistory, function(index, his) {
				var currentIndex = starterIndex + index;
				if(his.textPageId == undefined) {
					//$("#historyTree>ul").append("<li id='his-"+currentIndex+"'><a href='#'>"+his.displayId+"</a></li>")
					$("#historyTree").jstree("create_node", $("#historyTree"), "last",
						{
							data: his.displayId,
							attr: {
								id : "his-"+currentIndex
							}
						})
				} else {
					//if($("#historyTree>ul>li:last-child>ul").length == 0) {
					//	$("#historyTree>ul>li:last-child").append("<ul/>")
					//}
					//$("#historyTree>ul>li:last-child ul").append("<li id='his-"+currentIndex+"'><a href='#'>TEXT</a></li>")
					var nodeObj = {
							data: "TEXT",
							attr: {
								id : "his-"+currentIndex
							}
						}	
					var otherChildren = $("#historyTree>ul>li:last-child li")
					if($(otherChildren).size() != 0) {
						$("#historyTree").jstree("create_node", $("#historyTree>ul>li:last-child>ul>li:last-child"), "after", nodeObj)
					} else {
						$("#historyTree").jstree("create_node", $("#historyTree>ul>li:last-child"), "inside", nodeObj)
					}
				}
			})	
			$("#historyTree").jstree("close_all")
			var currentNode = $("#his-"+jsonData.index)
			$("#historyTree").jstree("select_node", currentNode, true)
			if($(currentNode).find("li").size() != 0) {
				$("#historyTree").jstree("open_node", $(currentNode));
			} else if($(currentNode).parents("li").size() != 0) {
				$("#historyTree").jstree("open_node", $(currentNode).parents("li"));
			}
			$("#historyTree *").removeClass("selectedHistoryNode");
			$(currentNode).addClass("selectedHistoryNode");
			//$("#historyTree").jstree("refresh")
		} else if(jsonData.history == undefined) {
			$("#previous-questions h3").hide();
			$("#question-number").html("&nbsp;")
			$("#historyTree").html("&nbsp;")
		} else {
			// history is empty array
			console.log("empty history array")
			if($("#historyTree li").size() != 0){
				console.log("Summary Page")
				$("#previous-questions h3").hide();
				$("#question-number").html("&nbsp;")
				$("#historyTree").html("&nbsp;")
			}
		}

		if(jsonData.index != jsonData.history.length-1) {
			$("#startingHistoryIndex").val(jsonData.index)
		} else {
			$("#startingHistoryIndex").val("-1")
		}

		$(".content-block").html(jsonData.content);
		$("#next-question-button").unbind("click")
		$("#next-question-button").one("click", diagnoser.nextButtonFunc);
	}

	var TEXTPAGE = 0;
	var QUESTION = 1;
	var RATING = 2;
	var REPORT = 3;

	var determinePageType = function() {
		if($("#textpage-content").length != 0) {
			return TEXTPAGE;
		} else if($("#question-content").length != 0) {
			return QUESTION;
		} else if($("#ratingURL").length != 0) {
			return RATING;
		} else {
			return REPORT;
		}
	}

	var cyclePages = function() {
		// get form data
		var params = $("#setRunnerForm").serialize();
		// get url
		var baseURL;
		var pageType = determinePageType();
		switch (pageType) {
			case TEXTPAGE:
			case QUESTION: 
				baseURL= $("#setRunnerForm").attr("action");
				break;
			case RATING:
				baseURL = $("#ratingURL").val();
				break;
			case REPORT:
				$("#setRunningDialog").dialog("close");
				$("#setRunningDIalog").html("");
				return;
				break;
			default : 
				alert("page type unrecognized in set runner javascript")
		}
		// construct full URL
		var url = baseURL+"?"+params;
		// ajax content
		$.ajax({
			url: url,
			success: function(data) {
				// render the ajax content
				if($.type(data) == "string") {
					// just add in place (rating or report page)
					$(".content-block").html(data);
					// and clear history and question number
					$("#previous-questions h3").hide();
					$("#question-number").html("&nbsp;")
					$("#historyTree").html("&nbsp;")
					
					$("#next-question-button").unbind("click")
					$("#next-question-button").one("click", diagnoser.nextButtonFunc);
				} else {
					$("#next-question-button").val("Next");
					renderJSONResponse(data);
				}
			}
		})
	}

})
