// JavaScript Document
document.onkeydown = getKeyCode_FastAnswers;
var keyPressed_FastAnswers;
var fa_noresize = false;
var tallyArray = new Array(); //first time a question is clicked, this will store the question id so that the question click is only tallied once. Click again and it won't tally.
var lastSearchType = 'none';
var resultsLoaded = false;

function getKeyCode_FastAnswers(e) {
	var code;
	if (!e) var e = window.event;
	if (e.keyCode) code = e.keyCode;
	else if (e.which) code = e.which;
	keyPressed_FastAnswers = code;
}

function show_popup(mylink, windowname, width, height) {
	if (! window.focus)return true;
	var href;
	if (typeof(mylink) == 'string') {
		href=mylink;
	} else {
		href=mylink.href;
	}
	window.open(href, windowname, 'width=' + width + ',height=' + height + ',scrollbars=yes,menubar=no,toolbar=no,location=no,directories=no,status=no,resizeable=yes');
}

function setupAJAXRequest() {
	var xmlHttp;
	
	try {
		// Firefox, Opera 8.0+, Safari
		xmlHttp=new XMLHttpRequest();
	} catch (e) {
		// Internet Explorer
		try {
			xmlHttp=new ActiveXObject("Msxml2.XMLHTTP");
		} catch (e) {
			try {
				xmlHttp=new ActiveXObject("Microsoft.XMLHTTP");
			} catch (e) {
				alert("Your browser does not support AJAX!");
				return false;
			}
		}
	}
	
	return xmlHttp;
}

function AJAX_getAnswers(fastAnswerPath) {
	var xmlHttp;
	var params;
	var pageToOpen = fastAnswerPath + "/fastanswer_components/getAnswers.php";
	var question = document.fastanswerform.fastanswerquestionbox.value;
	document.fastanswerform.fastanswerquestionboxhidden.value = question; //backup the question since the text box will be erased momentarily
	
	if ((question != "Type your question here") && (question != "Type in another question") && (question.length > 0)) {
		document.getElementById('fastanswersloading').style.display = 'block';
		
		xmlHttp = setupAJAXRequest();
		
		xmlHttp.onreadystatechange=function() {
			if(xmlHttp.readyState==4) {
				var response = xmlHttp.responseText;
				document.getElementById('fastanswersloading').style.display = 'none';
				document.getElementById('youasked').innerHTML = "<b>You asked:</b> " + document.getElementById('fastanswerquestionbox').value;
				document.getElementById('fastanswerquestionbox').value = "Type in another question";
				document.getElementById('fastanswerquestionbox').blur();
				document.getElementById('fastanswer_result_answers').innerHTML = response;
				resultsLoaded = true;
			}
		}
		
		//alert("whoid=" + document.fastanswerform.fastanswerwho.value + "\nwhatid=" + document.fastanswerform.fastanswerwhat.value);
		
		params = "question=" + question.replace(/ /g, "%20");
		params += "&type=" + document.fastanswerform.fastanswertype.value;
		if (document.fastanswerform.fastanswertype.value == "advanced") {
			params += "&whoid=" + document.fastanswerform.fastanswerwho.value;
			params += "&whatid=" + document.fastanswerform.fastanswerwhat.value;
		} else {
			params += "&whoid=" + document.fastanswerform.adef_whoid.value;
			params += "&whatid=" + document.fastanswerform.adef_whatid.value;
		}
		
		xmlHttp.open("POST",pageToOpen,true);
		xmlHttp.setRequestHeader("Content-type", "application/x-www-form-urlencoded");
		xmlHttp.setRequestHeader("Content-length", params.length);
		xmlHttp.setRequestHeader("Connection", "close");
		xmlHttp.send(params);
	} else {
		alert("Please enter a valid question.");
	}
}

function AJAX_topQuestions() {
	var xmlHttp;
	var params = "";
	
	xmlHttp = setupAJAXRequest();
	
	xmlHttp.onreadystatechange=function() {
		if(xmlHttp.readyState==4) {
			var response = xmlHttp.responseText;
			document.getElementById('fastanswer_result_answers').innerHTML = response;
		}
	}
	
	
	params = "?whoid=" + document.fastanswerform.adef_whoid.value;
	params += "&whatid=" + document.fastanswerform.adef_whatid.value; 
	
	xmlHttp.open("GET",rootDir + "fastanswer_components/topquestions.php" + params,true);
	xmlHttp.send(null);
}

//////////////////////////////////////////////////////
//		VISUAL MODIFICATIONS ON THE SEARCH BOX		//
//////////////////////////////////////////////////////
function searchby(type) {
	if (fa_noresize == false) {
		if (BrowserDetect.browser == "Explorer") {
			setSearchbyTab(type);
			setSearchByContentIE(type);
			setSearchBySizeIE(type);
			setSearchByResults(type);
		} else {
			fa_noresize = true;
			setSearchbyTab(type);
			setSearchByContent(type);
			setSearchBySize(type);
			setSearchByResults(type);
		}
	}
}

function setSearchbyTab(type) {
	switch(type) {
		case "smart":
			document.getElementById("fa_searchnav_category").className = "";
			document.getElementById("fa_searchnav_advanced").className = "";
			document.fastanswerform.fastanswertype.value = "smart";
			break;
		case "category":
			document.getElementById("fa_searchnav_smart").className = "";
			document.getElementById("fa_searchnav_advanced").className = "";
			document.fastanswerform.fastanswertype.value = "category";
			break;
		case "advanced":
			document.getElementById("fa_searchnav_smart").className = "";
			document.getElementById("fa_searchnav_category").className = "";
			document.fastanswerform.fastanswertype.value = "advanced";
			break;
	}
	document.getElementById("fa_searchnav_" + type).className = "selected_fa_search";
}

function setSearchBySizeIE(type) {
	var endWidth;
	
	if (type == 'smart') endWidth = 28;
	if ((type == 'category') || (type == 'advanced')) {
		endWidth = 74;
	}
	
	document.fastanswerform.style.width = endWidth + "em";
}

function setSearchBySize(type) {
	var i;
	var duration = 200;
	var steps = 20;
	var stepSize;
	var endWidth;
	var startWidth = document.fastanswerform.style.width;
	startWidth = startWidth.substring(0, startWidth.length - 1);
	startWidth = parseFloat(startWidth);
	
	if (type == 'smart') endWidth = 28;
	if ((type == 'category') || (type == 'advanced')) {
		endWidth = 74;
	}
	
	stepSize = (endWidth - startWidth)/steps;
	
	for (i = 0; i < steps; i++) {
		window.setTimeout("setSearchBySizeTo(" + (startWidth + (i*stepSize)) + ");", i*duration/steps);
	}
	window.setTimeout("setSearchBySizeTo(" + endWidth + ");", duration);
	window.setTimeout("fa_noresize = false", duration);
}

function setSearchBySizeTo(emValue) {
	document.fastanswerform.style.width = emValue + "em";
}

function setSearchByContentIE(type) {
	if (type == 'smart') {
		if (document.getElementById("fa_searchcontent_smart").style.display == 'none') {
			document.getElementById("fa_searchcontent_smart").style.display = 'block';
		}
		document.getElementById("fastanswerquestionbox").style.marginTop = "0px";
		if (document.getElementById("fa_searchcontent_category").style.display != 'none') {
			document.getElementById('fa_searchcontent_category').style.display = 'none';
		}
	}
	if ((type == 'category') || (type == 'advanced')) {
		AJAX_updateCount();
		if ((type == 'category') && (document.getElementById("fa_searchcontent_smart").style.display != 'none')) {
			document.getElementById("fa_searchcontent_smart").style.display = 'none';
		} else if ((type == 'advanced') && (document.getElementById("fa_searchcontent_smart").style.display == 'none')) {
			document.getElementById("fa_searchcontent_smart").style.display = 'block';
		}
		document.getElementById("fastanswerquestionbox").style.marginTop = "1em";
		if (document.getElementById("fa_searchcontent_category").style.display == 'none') {
			document.getElementById("fa_searchcontent_category").style.display = 'block';
		}
	}
}

function setSearchByContent(type) {
	if (type == 'smart') {
		document.getElementById("fastanswerquestionbox").style.marginTop = "0px";
		if (document.getElementById("fa_searchcontent_smart").style.display == 'none') {
			Effect.BlindDown("fa_searchcontent_smart", {duration: .2});
		}
		if (document.getElementById("fa_searchcontent_category").style.display != 'none') {
			window.setTimeout("document.getElementById('fa_searchcontent_category').style.display = 'none';",50);
			Effect.BlindUp("fa_searchcontent_category", {duration: .2});
		}
	}
	if ((type == 'category') || (type == 'advanced')) {
		AJAX_updateCount();
		document.getElementById("fastanswerquestionbox").style.marginTop = "1em";
		if ((type == 'category') && (document.getElementById("fa_searchcontent_smart").style.display != 'none')) {
			Effect.BlindUp("fa_searchcontent_smart", {duration: .2});
		} else if ((type == 'advanced') && (document.getElementById("fa_searchcontent_smart").style.display == 'none')) {
			Effect.BlindDown("fa_searchcontent_smart", {duration: .2});
		}
		if (document.getElementById("fa_searchcontent_category").style.display == 'none') {
			Effect.BlindDown("fa_searchcontent_category", {duration: .2});
			window.setTimeout("document.getElementById('fa_searchcontent_category').style.display = 'block';",210);
		}
	}
}

function setSearchByResults(type) {
	//alert(lastSearchType + "--" + type + "-- Results Loaded: " + resultsLoaded);
	if ((lastSearchType != type) && (resultsLoaded == true)) {
		AJAX_topQuestions();
		document.getElementById('youasked').innerHTML = "";
		lastSearchType = type;
		resultsLoaded = false;
	}
}

function askQuestionBoxFocus() {
	document.getElementById("fastanswerquestionbox").focus();
	document.getElementById("fastanswerquestionbox").style.backgroundColor = "#8495a9";
	window.setTimeout('document.getElementById("fastanswerquestionbox").style.backgroundColor = "#FFFFFF";', 200);
}

//////////////////////////////////////////////////
//		VISUAL MODIFICATION TO THE ANSWERS		//
//////////////////////////////////////////////////

function toggleAnswerVisibility(id, componentsPath) {
	if (document.getElementById('qaAnswer_' + id).style.display == 'none') {
		AJAX_TallyQuestion(id, componentsPath);
		if ((BrowserDetect.browser == "Explorer") && (BrowserDetect.version >= 7)) {
			document.getElementById('qaAnswer_' + id).style.display = 'block';
		} else {
			Effect.BlindDown('qaAnswer_' + id, {duration: .15});
		}
		document.getElementById('fastanswerresult_' + id).style.marginTop = "1.5em";
		//document.getElementById('qaQuestion_' + id).style.display = 'none';
	} else {
		if ((BrowserDetect.browser == "Explorer") && (BrowserDetect.version >= 7)) {
			document.getElementById('qaAnswer_' + id).style.display = 'none';
		} else {
			Effect.BlindUp('qaAnswer_' + id, {duration: .15});
		}
		document.getElementById('fastanswerresult_' + id).style.marginTop = "0px";
		//document.getElementById('qaQuestion_' + id).style.display = 'block';
	}
}

function answeropt(type, id) {
	//change colors on first answer nav box if this is it
	if (document.getElementById("firstAnswerNavBox" + id) != null) document.getElementById("firstAnswerNavBox" + id).className = "fa_answernav";
	
	if (type == 'rate') {
		document.getElementById("fa_answer_rate_" + id).style.display = 'block';
		document.getElementById("fa_answernav_rate_" + id).className = "selected_fa_search";
		
		document.getElementById("fa_answer_contact_" + id).style.display = 'none';
		document.getElementById("fa_answernav_contact_" + id).className = "";
	} else {
		document.getElementById("fa_answer_rate_" + id).style.display = 'none';
		document.getElementById("fa_answernav_rate_" + id).className = "";
		
		document.getElementById("fa_answer_contact_" + id).style.display = 'block';
		document.getElementById("fa_answernav_contact_" + id).className = "selected_fa_search";
	}
}


function checkEmail(value) {
	//this function was taken and modified from http://javascriptkit.com
	var filter=/^([\w-]+(?:\.[\w-]+)*)@((?:[\w-]+\.)*\w[\w-]{0,66})\.([a-z]{2,6}(?:\.[a-z]{2})?)$/i
	var results;
	if (filter.test(value))
		results=true
	else{
		results=false;
	}
	return results;
}

function AJAX_TallyQuestion(questionId, componentsPath) {
	var alreadyUsed = false;
	for (i = 0; i < tallyArray.length; i++) {
		if (questionId == tallyArray[i]) {
			alreadyUsed = true;
			i = tallyArray.length;
		}
	}
	if (alreadyUsed == false) {
		tallyArray.push(questionId);
		var xmlHttp;
		var params;
		var pageToOpen = componentsPath + "faq_tally.php";
		
		xmlHttp = setupAJAXRequest();
		
		xmlHttp.onreadystatechange=function() {
			if(xmlHttp.readyState==4) {
				var response = xmlHttp.responseText;
			}
		}
		
		params = "qid=" + questionId;
		
		xmlHttp.open("POST",pageToOpen,true);
		xmlHttp.setRequestHeader("Content-type", "application/x-www-form-urlencoded");
		xmlHttp.setRequestHeader("Content-length", params.length);
		xmlHttp.setRequestHeader("Connection", "close");
		xmlHttp.send(params);
	}
}

function AJAX_SubmitRating(questionId, studentQuestion, componentsPath) {
	var opts = document.getElementById('fa_answer_rate_' + questionId).getElementsByTagName("input");
	var rating;
	var comment = document.getElementById('ratingcomments_' + questionId).value;
	var i;
	
	for (i = 0; i < opts.length; i++) {
		if ((opts[i].name == ('rating_' + questionId)) && (opts[i].checked == true)) rating = opts[i].value;
	}
	if (comment == 'Please let us know why you rated the way you did.') comment = "";
	
	if (typeof(rating) == "undefined") {
		alert("Please select either \"Very helpful\", \"Somewhat helpful\", \"Just OK\", or \"Not helpful\" to submit your rating.");
	} else {
		var xmlHttp;
		var params;
		var pageToOpen = componentsPath + "answers_response.php";
		
		xmlHttp = setupAJAXRequest();
		
		xmlHttp.onreadystatechange=function() {
			if(xmlHttp.readyState==4) {
				var response = xmlHttp.responseText;
				document.getElementById('fa_answer_rate_' + questionId).style.height = "12em";
				document.getElementById('fa_answer_rate_' + questionId).innerHTML = response;
			}
		}
		
		params = "id=" + questionId;
		params += "&type=rate";
		params += "&question=" + studentQuestion.replace(/ /g,"%20");
		params += "&rating=" + rating;
		params += "&comment=" + comment.replace(/ /g,"%20");
		
		xmlHttp.open("POST",pageToOpen,true);
		xmlHttp.setRequestHeader("Content-type", "application/x-www-form-urlencoded");
		xmlHttp.setRequestHeader("Content-length", params.length);
		xmlHttp.setRequestHeader("Connection", "close");
		xmlHttp.send(params);
	}
}

function AJAX_SendEmail(questionId, componentsPath) {
	var formObjArray = new Array();
	var inputs = document.getElementById("fa_answer_contact_" + questionId).getElementsByTagName("input");
	var email = inputs[0].value;
	var question = inputs[1].value;
	var emailTo;
	var contents = document.getElementById("fa_answer_contact_" + questionId).getElementsByTagName("textarea")[0].value;
	
	for (i = 0; i < inputs.length; i++) { formObjArray.push(inputs[i]); }
	formObjArray.push(document.getElementById("fa_answer_contact_" + questionId).getElementsByTagName("textarea")[0]);
	
	//check to see if there is a hidden value for the emailto or if it is a select statement
	if (inputs.length > 3) {
		emailTo = inputs[2].value; //hidden emailto value
	} else {
		var temp = document.getElementById("fa_answer_contact_" + questionId).getElementsByTagName("select")[0];
		emailTo = temp.options[temp.selectedIndex].value;
		formObjArray.push(temp);
	}
	
	if ((email.length > 0) && (question.length > 0) && (contents.length > 0)) {
		if (checkEmail(email) == true) {
			for (i = 0; i < formObjArray.length; i++) { formObjArray[i].disabled = true; }
			
			var xmlHttp;
			var params;
			var pageToOpen = componentsPath + "/answers_response.php";
			
			xmlHttp = setupAJAXRequest();
			
			xmlHttp.onreadystatechange=function() {
				if(xmlHttp.readyState==4) {
					var response = xmlHttp.responseText;
					//alert(response);
					document.getElementById('fa_answer_contact_' + questionId).style.height = "12em";
					document.getElementById('fa_answer_contact_' + questionId).innerHTML = response;
				}
			}
			
			params = "id=" + questionId;
			params += "&type=email";
			params += "&email=" + email;
			params += "&question=" + question.replace(/ /g,"%20");
			params += "&emailto=" + emailTo;
			params += "&contents=" + contents.replace(/ /g,"%20");
			
			xmlHttp.open("POST",pageToOpen,true);
			xmlHttp.setRequestHeader("Content-type", "application/x-www-form-urlencoded");
			xmlHttp.setRequestHeader("Content-length", params.length);
			xmlHttp.setRequestHeader("Connection", "close");
			xmlHttp.send(params);
		} else {
			alert("Please input a valid email address.");
		}
	} else {
		alert("Please fill in all of the above infromation to send an email.");	
	}
}

//////////////////////////////////////////////
//			TOP QUESTIONS CONTROL			//
//////////////////////////////////////////////

function AJAX_remainingTopQs(value) {
	var xmlHttp;
	var params;
	
	xmlHttp = setupAJAXRequest();
	
	xmlHttp.onreadystatechange=function() {
		if(xmlHttp.readyState==4) {
			var response = xmlHttp.responseText;
			//alert(response);
			document.getElementById('fa_answer_contact_' + questionId).style.height = "12em";
			document.getElementById('fa_answer_contact_' + questionId).innerHTML = response;
		}
	}
	
	params = "ids=" + value;
	
	xmlHttp.open("POST",pageToOpen,true);
	xmlHttp.setRequestHeader("Content-type", "application/x-www-form-urlencoded");
	xmlHttp.setRequestHeader("Content-length", params.length);
	xmlHttp.setRequestHeader("Connection", "close");
	xmlHttp.send(params);
}