/*
 * FAQ-specific JavaScript functions
 */

// Global variables
var displayedAnswer = "";
var currentQuestion = "";
var currentScore = 0;

// Servlet-related contants
var	baseUrl = "servlet?";
var commandParameter = "cmd";
var displayQuestionsCommand = "displayQuestions";
var displayAnswerCommand = "displayAnswer";
var displayAnswerEvalCommand = "displayAnswerAndEval";
var evaluationCommand = "evaluation";
var categoryParameter = "category";
var questionParameter = "question";
var scoreParameter = "score";
var commentParameter = "comment";

// Error message to display if Ajax calls fails
var genericErrorMessage = "Det har oppstått en feil.";
var ajaxNotSupported = "Web-browseren støtter ikke Ajax";

/*
 * This code runs when the FAQ page is loaded
 */
function init() {

	// Get the choice element
	var element = $("choice");
	if (element !== null) {
		catId = element.value;
		if (catId.length > 0) {

			// Expand the chosen category
			linkElementId = catId + "link";
			element = $(linkElementId);
			element.className = "expanded";
			Effect.BlindDown(catId, sliderparams);
		}
	}

	// Show questions for the chosen main category
	var category = catId + "01";
	displayQuestions(category);

	// Show the "choose a question" prompt
	showElement("info_about_coloumn");
}

/*
 * Expands the top level faq category.
 */
function expandCategory(catNum) {

	// Retrieve the questions for the selected category
	var indexString = (100 + catNum).toString().substring(1);
	var category = getSelectedSubCategory("cat" + indexString);

	// Generate a list of questions or a popup
	var element = $(category);
	var fn = element.onclick.toString();
	var pos = fn.indexOf("popup");
	if (pos > 0) {
		popupAnswer(category);
	}
	else {
		displayQuestions(category);
	}

	// Expand and collapse the boxes
	var max = 10;
	for (var index = 1; index <= max; index++) {
		indexString = (100 + index).toString().substring(1);
		elementId = "cat" + indexString;
		linkElementId = elementId + "link";

		// Handle selected category
		if (index == catNum) {
			element = $(linkElementId);
			if (element !== null) {
				element.className = "expanded";
				Effect.BlindDown(elementId, sliderparams);
			}
		}

		// Handle unselected category
		else {
			element = $(linkElementId);
			if (element !== null) {
				element.className = "";
				Effect.BlindUp(elementId, sliderparams);
			}
		}
	}
}

/*
 * Finds out which category is currently selected
 */
function getSelectedCategory(catId) {

	// First find out which main category is selected
	var mainCat = getSelectedMainCategory();
	if (mainCat === null) {
		return null;
	}

	// Check first category
	var count = 1;
	var indexString = (100 + count).toString().substring(1);
	var elementId = mainCat + indexString;
	var element = $(elementId);
	if (element.checked) {
		return elementId;
	}

	// Look for other categories
	while (element !== null) {
		count++;
		indexString = (100 + count).toString().substring(1);
		elementId = mainCat + indexString;
		element = $(elementId);
		if (element !== null) {
			if (element.checked) {
				return elementId;
			}
		}
	}
	return null;
}

/*
 * Finds out which main category is currently selected
 */
function getSelectedMainCategory() {

	// Check first main category
	var count = 1;
	var indexString = (100 + count).toString().substring(1);
	var elementId = "cat" + indexString + "link";
	var element = $(elementId);
	if (element.className == "expanded") {
		return "cat" + indexString;
	}

	// Look for other main categories
	while (element !== null) {
		count++;
		indexString = (100 + count).toString().substring(1);
		elementId = "cat" + indexString + "link";
		element = $(elementId);
		if (element !== null) {
			if (element.className == "expanded") {
			return "cat" + indexString;
			}
		}
	}
	return null;
}

/*
 * Finds out which category is currently selected
 */
function getSelectedSubCategory(mainCat) {

	// First find out which main category is selected
	var count = 1;
	var indexString = (100 + count).toString().substring(1);
	var elementId = mainCat + indexString;
	var element = $(elementId);
	if (element.checked) {
		return elementId;
	}

	// Look for other categories
	while (element !== null) {
		count++;
		indexString = (100 + count).toString().substring(1);
		elementId = mainCat + indexString;
		element = $(elementId);
		if (element !== null) {
			if (element.checked) {
				return elementId;
			}
		}
	}
	return null;
}

/*
 * Asks the server for a list of questions.
 */
function displayQuestions(catId) {

	// Show the "choose a question" prompt
	showElement("info_about_coloumn");

	// Create a URL
	var url = baseUrl;
	url += commandParameter + "=" + displayQuestionsCommand;
	url += "&";
	url += categoryParameter + "=" + catId;

	// Get an XMLHttpRequest object
	var xhr = getXHR();

	// Create a callback function
	xhr.onreadystatechange = function() {
		if (xhr.readyState == 4) {
			if (xhr.status == 200) {
				$("questions").innerHTML = xhr.responseText;
			}
			else {
				$("questions").innerHTML = genericErrorMessage;
			}
		}
	};
	xhr.open("get", url, true);
	xhr.send(null);
}

/*
 * Displays an answer in a popup box
 */
function popupAnswer(questionId) {

	// Hide the "choose a question" prompt
	hideElement("info_about_coloumn");

	// Delete old answers
	if (displayedAnswer.length > 0) {
		if (displayedAnswer !== "popupdiv") {
			element = $(displayedAnswer);
			if (element !== null) {
				element.innerHTML = "";
				hideElement(displayedAnswer);
			}
		}
	}

	// Create a URL
	var url = baseUrl;
	url += commandParameter + "=" + displayAnswerCommand;
	url += "&";
	url += questionParameter + "=" + questionId;

	// Get an XMLHttpRequest object
	var xhr = getXHR();

	// Create a callback function
	xhr.onreadystatechange = function() {
		if (xhr.readyState == 4) {
			if (xhr.status == 200) {
				$("answer").innerHTML = xhr.responseText;
				popup();
				displayedAnswer = "popupdiv";
				currentQuestion = questionId;
			}
			else {
				$("questions").innerHTML = genericErrorMessage;
			}
		}
	};
	xhr.open("get", url, true);
	xhr.send(null);
}

/*
 * Displays a popup answer box across two columns
 */
function popup() {

	// Get the link element
	var anchorElementId = "twocoloumn";
	var anchorElement = $(anchorElementId);

	// Get the position of the anchor element
	var linkTop = getY(anchorElement);
	var linkLeft = getX(anchorElement);
	linkTop += 38;
	linkLeft += 1;

	// Get the popup and position it
	var element = $("popupdiv");
	element.style.left = linkLeft + "px";
	element.style.top = linkTop + "px";
	showElement("popupdiv");
	element.style.left = linkLeft + "px";
	element.style.top = linkTop + "px";
}

/*
 * Closes the popup answer and resets it for reuse
 */
function closePopup() {
	hideElement("popupdiv");
	
	// Reset the popup box
	resetPopupStars();
	hideElement("evaluation_comments");
	hideElement("evaluation_sent");
	showElement("send_button");
	currentScore = 0;
	$("comments").value = "";

	// Show the "choose a question" prompt
	showElement("info_about_coloumn");
}

/*
 * Resets all stars in the popup answer to unselected
 */
function resetPopupStars() {
	for (var index = 1; index <= 5; index++) {
		scoreId = "score" + index;
		$(scoreId).className = "star";
	}
}

/*
 * Displays evaluation box below stars for popup answer
 */
function popupScore(points) {

	// Show the comment area
	showElement("evaluation_comments");
	$("comments").focus();

	// Reset all stars to unselected
	resetPopupStars();

	// Select the chosen star
	var	selectedId = 'score' + points;
	$(selectedId).className = "star selected";
	currentScore = points;
}

/*
 * Sends the evaluation score and text from a popup
 */
function sendPopupEval() {

	// Hide the send button
	hideElement("send_button");

	// Reset the selected score
	var selectedScore = 0;


	// Escape the comment
	var comment = $("comments").value;
	var eComment = escape(comment);
	
	// Create an URL
	var url = baseUrl;
	url += commandParameter + "=" + evaluationCommand;
	url += "&";
	url += questionParameter + "=" + currentQuestion;
	url += "&";
	url += scoreParameter + "=" + currentScore;
	url += "&";
	url += commentParameter + "=" + eComment;

	// Get an XMLHttpRequest object
	var xhr = getXHR();

	// Create a callback function
	xhr.onreadystatechange = function() {
		if (xhr.readyState == 4) {
			if (xhr.status == 200) {
				showElement("evaluation_sent");
			}
			else {
				closePopup();
				$("questions").innerHTML = genericErrorMessage;
			}
		}
	};
	xhr.open("get", url, true);
	xhr.send(null);
}


/*
 * Displays an answer in the third column.
 */
function displayAnswer(questionId) {

	// Hide the "choose a question" prompt
	hideElement("info_about_coloumn");

	// Delete old answers
	if (displayedAnswer.length > 0) {
		if (displayedAnswer !== "popupdiv") {
			element = $(displayedAnswer);
			if (element !== null) {
				element.innerHTML = "";
				hideElement(displayedAnswer);
			}
		}
	}

	// Change background color of selected question 
	var oldQuestion = $(currentQuestion);
	if (oldQuestion !== null) {
		oldQuestion.style.backgroundColor = "#fff";
	}

	// Change background color of selected question 
	$(questionId).style.backgroundColor = "#E6EAC7";
		
	// Create a URL
	var url = baseUrl;
	url += commandParameter + "=" + displayAnswerEvalCommand;
	url += "&";
	url += questionParameter + "=" + questionId;

	// Get an XMLHttpRequest object
	var xhr = getXHR();

	// Create a callback function
	xhr.onreadystatechange = function() {
		if (xhr.readyState == 4) {
			if (xhr.status == 200) {
				answerId = questionId + "-answer";
				$(answerId).innerHTML = xhr.responseText;
				showElement(answerId);
				displayedAnswer = answerId;
				currentQuestion = questionId;
			}
			else {
				$("questions").innerHTML = genericErrorMessage;
			}
		}
	};
	xhr.open("get", url, true);
	xhr.send(null);
}

/*
 * Resets all stars in third column to unselected
 */
function resetStars() {
	for (var index = 1; index <= 5; index++) {
		scoreId = currentQuestion + "score" + index;
		$(scoreId).className = "star";
	}
}


/*
 * Displays evaluation box below stars for answer in third column
 */
function score(points) {

	// Show the comment area
	showElement(currentQuestion + "_evaluation_comments");
	$(currentQuestion + "_comments").focus();

	// Reset all stars to unselected
	resetStars();

	// Select the chosen star
	var	selectedId = currentQuestion + 'score' + points;
	$(selectedId).className = "star selected";
	currentScore = points;
}


/*
 * Sends the evaluation score and text from the third column
 */
function sendEval() {

	// Hide the send button
	hideElement(currentQuestion + "_send_button");

	// Reset the selected score
	var selectedScore = 0;

	// Escape the comment
	var comment = $(currentQuestion + "_comments").value;
	var eComment = escape(comment);
	
	// Create an URL
	var url = baseUrl;
	url += commandParameter + "=" + evaluationCommand;
	url += "&";
	url += questionParameter + "=" + currentQuestion;
	url += "&";
	url += scoreParameter + "=" + currentScore;
	url += "&";
	url += commentParameter + "=" + eComment;

	// Get an XMLHttpRequest object
	var xhr = getXHR();

	// Create a callback function
	xhr.onreadystatechange = function() {
		if (xhr.readyState == 4) {
			if (xhr.status == 200) {
				showElement(currentQuestion + "_evaluation_sent");
			}
			else {
				$("questions").innerHTML = genericErrorMessage;
			}
		}
	};
	xhr.open("get", url, true);
	xhr.send(null);
}

/*
 * Get the X coordinate of an element
 */
function getX(element) {
	var result = 0;
	while(element !== null ) {
		result += element.offsetLeft;
		element = element.offsetParent;
	}
	return result;
}

/*
 * Get the Y coordinate of an element
 */
function getY(element) {
	var result = 0;
	while(element !== null ) {
		result += element.offsetTop;
		element = element.offsetParent;
	}
	return result;
}

/*
 * Get an XMLHttpRequest object
 */
function getXHR() {

	// Firefox, Opera, Safari, IE7
	try {
		return new XMLHttpRequest();
	}
	catch (e) {}

	// Internet Explorer 6
	try {
		return new ActiveXObject("Msxml2.XMLHTTP");
	}
	catch (e) {}
	try {
		return new ActiveXObject("Microsoft.XMLHTTP");
	}
	catch (e) {}
	alert(ajaxNotSupported);
}

