/// <reference path="jQuery.intellisense.js"/>
/// <reference path="xeko.js"/>
/// <reference path="messaging.js"/>

$(document).ready(function() {

	$("#startQuizzleButton").click(function(e) {
		e.preventDefault();
		if (xeko.pages.quizzles.validate()) xeko.pages.quizzles.startQuizzle();
	});

	$("#answerButton").click(function(e) {
		e.preventDefault();
		xeko.pages.quizzles.answerQuizzle();
	});

	$("#nextButton").click(function(e) {
		e.preventDefault();
		xeko.pages.quizzles.nextQuizzle();
	});

	// Fill in Agent data
	if (xeko.agentinfo.agentID.length > 0) {
		$(".agentId").text(xeko.agentinfo.agentID);
	}
	else {
		$(".agentId").text("Guest");
	}

	// Make sure user is logged in before navigating to the Create Quizzle page
	$(".quizzlesCreateQuizzle").click(function(e) {
		if (!xeko.forceLogin(xeko.messaging.alert.QUIZZLE_CREATE_LOGIN_REQUIRED)) {
			e.preventDefault();
		}
	});
});

xeko.pages.quizzles = {
	"currentQuestion": 0,
	"numberOfQuestions": 5,
	"selectedMissions": "",
	"selectedSubjects": "",
	"correctAnswers": 0,
	"totalPointsEarned": 0,
	"validate": function() {
		var isValid = true;

		// valid when user selects at least one Mission, Subjects are not required
		this.selectedMissions = "";
		$("input[name='mission']:checked").each(function() {
			xeko.pages.quizzles.selectedMissions += $(this).val() + ", ";
		});

		if (xeko.pages.quizzles.selectedMissions.length > 0) {
			xeko.validation.clearMessage("quizzleMissionsLabel");
			xeko.pages.quizzles.selectedMissions = xeko.pages.quizzles.selectedMissions.substr(0, xeko.pages.quizzles.selectedMissions.length - 2);
		}
		else {
			isValid = false;
			xeko.validation.showMessage("quizzleMissionsLabel", xeko.messaging.alert.CHALLENGE_MISSION_NOT_SELECTED);
		}

		// Get selected Subjects
		this.selectedSubjects = "";
		$("input[name='subject']:checked").each(function() {
			xeko.pages.quizzles.selectedSubjects += $("label[for='" + $(this).attr("id") + "']").text() + ", ";
		});
		if (xeko.pages.quizzles.selectedSubjects.length > 0) xeko.pages.quizzles.selectedSubjects = xeko.pages.quizzles.selectedSubjects.substr(0, xeko.pages.quizzles.selectedSubjects.length - 2);

		// Number of questions to return
		this.numberOfQuestions = $("input[name='questionCount']:checked").val();

		return isValid;
	},

	"startQuizzle": function() {
		$.ajax(
		{
			method: "get",
			url: "/widgets/widget.Quizzles.handler.php?type=getquizzles",
			data:
			{
				n : this.numberOfQuestions,
				tags : xeko.utilities.urlEncode(this.selectedMissions) + "," + xeko.utilities.urlEncode(this.selectedSubjects)
			},
			beforeSend: function() {
				// let user know lookup is in process
				xeko.lightbox.show("Searching Quizzles...", true, "quizzles");
			},

			success: function(xml) {
				xeko.pages.quizzles.hideError();

				// This gets the list of quizzles that match the selected missions and subjects
				if (xml != null && $("quizzle", xml).size() > 0) {
					xeko.pages.quizzles.parseXml(xml);
				}
				else {
					xeko.pages.quizzles.throwError("No Quizzles found for your selections.");
				}
			},
			error: function(xmlHttpRequest, status, err) {
				if (xmlHttpRequest.status > 0) xeko.pages.quizzles.throwError("Quizzle search error.");
			},
			complete: function() {
				xeko.lightbox.hide("quizzles");
			}
		});
	},

	"parseXml": function(xml) {
		var html = "";

		// Adjust number of questions if the questions found is less than what was requested
		var q = $("quizzle", xml).size();
		if (this.numberOfQuestions > q) {
			this.numberOfQuestions = q;
		}

		// Create HTML for each question
		var i = 1;
		$(xml).find("quizzle").each(function() {
			// Get card art, default to [?] image if none found 
			var cardHotspot = xeko.utilities.removeSpaces($("hotspot", this).text());
			var cardNumber = $("number", this).text();
			var imgPath = "/images/g/g_image.gif";
			if (cardHotspot != "" && cardNumber != "") {
				imgPath = "/images/cardart/" + cardHotspot + "/activities_medium/" + cardNumber + ".jpg";
			}

			// Question text
			html += '<div id="question' + i + '" class="hidden"><img src="' + imgPath + '" class="questionThumb"/><div class="questionContainer"><div class="p1"><b>By:</b> ';
			html += $("createdbyuserid", this).text();
			html += '</div>';
			html += '<div class="questionText">' + $("questiontext", this).text() + '</div>';
			html += '<div class="radioList padt">';


			// Answers
			var correctAnswer = "";
			var correctId = "";
			var answerIndex = 0;
			var allOfTheAbove = "";

			$("answer", this).each(function() {
				answerIndex++;
				var answerGuid = $(this).attr("id");
				var answerText = $("answertext", this).text();

				var answerHtml = '<div><input type="radio" name="q' + i + '" id="q' + i + 'a' + answerIndex + '" value="' + answerGuid + '"/><label for="q' + i + 'a' + answerIndex + '">' + answerText + '</label></div>';
				if (answerText.indexOf("of the above") == -1) {
					html += answerHtml;
				}
				else {
					allOfTheAbove = answerHtml;
				}

				if ($("iscorrectanswer", this).text() == "1") {
					correctAnswer = $("answertext", this).text();
					correctId = answerGuid;
				}
			});

			// Append "all of the above" or "none of the above" answer, if any
			html += allOfTheAbove;

			// Question points
			var points = $("pointvalue", this).text();

			// TODO: get default points
			if (points == "") points = 20;

			// Add hidden tags for right/wrong answers
			html += '</div><div class="p1 answer">';
			html += '<div id="wrongAnswer' + i + '" class="hidden padtb">Bat breath! The correct answer is ' + correctAnswer + '.</div>';
			html += '<div id="rightAnswer' + i + '" class="hidden padtb">Dolphin smart! You earned <span id="points' + i + '">' + points + '</span> Xeko Points.</div>';
			html += '</div></div><div class="clear"></div><input type="hidden" value="' + correctId + '" id="answer' + i + '" />';
			html += '<input type="hidden" value="' + $(this).attr("id") + '" id="quizzleId' + i + '" />';
			html += '</div>';

			// Increment counter
			i++;
		});

		// Add HTML to container
		$("#questionsContainer").html(html);

		// Show results
		if (this.numberOfQuestions > 0) {
			// Add click event to answer radio buttons
			$(".radioList input").click(function(e) {
				$("#answerButton").get(0).src = "/images/btn/btn_finalanswer.gif";
			});

			// Update total question text
			$(".totalQuestions").text(this.numberOfQuestions);

			// Show questions
			$("#startQuizzle").hide();
			$("#quizzleQuestions").show();

			// Show first question
			xeko.pages.quizzles.nextQuizzle();
		}
		else {
			xeko.pages.quizzles.throwError("Quizzle parse error.");
		}
	},

	"answerQuizzle": function() {
		var quizzleId = $("#quizzleId" + this.currentQuestion).val();
		var yourAnswer = $("input[name='q" + this.currentQuestion + "']:checked");
		if (yourAnswer != null && yourAnswer.length > 0) {
			var answerGuid = yourAnswer.val();

			$.ajax(
			{
				method: "get",
				url: "/widgets/widget.Quizzles.handler.php?type=answerquizzle",
				data:
				{
					"quizzleid": quizzleId,
					"answerid": answerGuid
				},
				beforeSend: function() {
					// let user know lookup is in process
					xeko.lightbox.show("Answering question...", true, "quizzles");
				},

				success: function(xml) {
					xeko.pages.quizzles.hideError();

					// This gets the list of quizzles that match the selected missions and subjects
					if (xml != null) {

						if ($("iscorrect", xml).text() == "1") {
							var responseGuid = $("agentquizzleresponse", xml).attr("id");
							xeko.pages.quizzles.getAgentReward(responseGuid);
						}

						// Show correct answer
						xeko.pages.quizzles.showCorrectAnswer(answerGuid);
					}
					else {
						xeko.pages.quizzles.throwError("Error posting answer.");
					}
				},
				error: function(xmlHttpRequest, status, err) {
					if (xmlHttpRequest.status > 0) xeko.pages.quizzles.throwError("Error posting answer.");
				},
				complete: function() {
					xeko.lightbox.hide("quizzles");
				}
			});
		}
	},

	// Get reward
	"getAgentReward": function(guid) {
		//alert(guid);
		$.ajax(
			{
				method: "get",
				url: "/widgets/widget.AgentInfo.handler.php?request=agentreward&triggerid=" + guid,
				beforeSend: function() {
					// let user know lookup is in process
					xeko.lightbox.show("Answering question...", true, "quizzles");
				},

				success: function(xml) {
					if (xml != null) {

						xeko.pages.quizzles.correctAnswers++;
						xeko.pages.quizzles.totalPointsEarned += Number($("#points" + xeko.pages.quizzles.currentQuestion).text());
						xeko.flashHeader.triggerPoints();
					}
					else {
						xeko.pages.quizzles.throwError("Error getting agent reward.");
					}
				},
				error: function(xmlHttpRequest, status, err) {
					if (xmlHttpRequest.status > 0) xeko.pages.quizzles.throwError("Error getting agent reward.");
				},
				complete: function() {
					xeko.lightbox.hide("quizzles");
				}
			});
	},

	"showCorrectAnswer": function(answerGuid) {
		var correctAnswer = $("#answer" + this.currentQuestion).val();
		//var yourAnswer = $("input[name='q" + this.currentQuestion + "']:checked");
		var correctId = $("input[value='" + correctAnswer + "']").attr("id");

		if (answerGuid.length > 0) {
			$("#answerTheQuestion").hide();

			if (correctAnswer != answerGuid) {
				// Wrong answer
				$("#wrongAnswer" + this.currentQuestion).show();

				// Set incorrect answer to gray
				var yourAnswerId = $("input[value='" + answerGuid + "']").attr("id");
				$("label[for='" + yourAnswerId + "']").addClass("grayOut");
			}
			else {
				// Right Answer
				$("#rightAnswer" + this.currentQuestion).show();
			}

			// Set correct answer highlight
			var answerLabel = $("label[for='" + correctId + "']");
			answerLabel.html(answerLabel.html() + " ***").addClass("highlightAnswer");

			// Show correct answer text
			$("#correctAnswer" + this.currentQuestion).html(answerLabel.html());

			$("#question" + this.currentQuestion + " input").attr("disabled", "disabled");

			$("#answerButton").hide();
			$("#nextButton").show();
		}
		else {
			$("#answerTheQuestion").show();
		}
	},

	"nextQuizzle": function() {
		if (this.currentQuestion < this.numberOfQuestions) {
			// Hide current question, show next
			$("#question" + this.currentQuestion).hide();
			this.currentQuestion++;
			$("#question" + this.currentQuestion).show();

			// Update title and buttons
			$("#currentQuestion").text(this.currentQuestion);
			$("#answerButton").show();
			$("#nextButton").hide();

			// Reset answer button
			$("#answerButton").get(0).src = "/images/btn/btn_finalanswer_gray.gif";
		}
		else {
			$("#correctAnswers").text(this.correctAnswers);
			$("#totalQuestions").text(this.numberOfQuestions);

			$("#quizzleQuestions").hide();
			$("#quizzleDone").show();

			// Add bonus points
			xeko.pages.quizzles.totalPointsEarned += Number($(".extraPoints").text());

			// Fill in total points
			$("#totalPointsEarned").text(this.totalPointsEarned);
		}
	},
	"throwError": function(msg) {
		$("#startQuizzleMessage").text(msg).show();
	},
	"hideError": function() {
		$("#startQuizzleMessage").hide();
	}
};
