/* Boxes */
function bc(){
	if (getCookie("sscope")=="true") document.search_form.p_scope.checked=true;
	var bx = new Array("box_search","box_stats","box_chat","box_spell","box_user","box_login","box_news","box_favourites","box_tips","box_newessays","box_ranking");
	for (i=0;i<bx.length;i++)if(bx[i])hs(bx[i]);
	initChatScript();
}
function hs(d){if((getCookie(d))&&(getCookie(d)=="c"))sh(d);}
function sh(d){
	if(document.getElementById(d)){
		if(document.getElementById(d).style.display=="none"){
			eraseCookie(d);
			document.getElementById(d).style.display="block";
		}
		else{
			setCookie(d,"c");
			document.getElementById(d).style.display="none";
		}
	}
}
function sh_nocookie(d){
	if(document.getElementById(d)){
		if(document.getElementById(d).style.display=="none"){
			document.getElementById(d).style.display="block";
		}
		else{
			document.getElementById(d).style.display="none";
		}
	}
}
function eraseCookie(name){setCookie(name,"");}
function setCookie(NameOfCookie, value){document.cookie = NameOfCookie + "=" + escape(value);}
function getCookie(NameOfCookie){
	if (document.cookie.length > 0) {
		begin = document.cookie.indexOf(NameOfCookie+"=");
		if (begin != -1) {
			begin += NameOfCookie.length+1;
			end = document.cookie.indexOf(";", begin);
			if (end == -1) end = document.cookie.length;
			return unescape(document.cookie.substring(begin, end));
		}
	}
	return null;
}

/* Boxes critic */
function cSearch(f){
	if (f.id == "search_form_center") {
		if(f.p_query_center.value=="") {
			alert("Search box is empty");
			return false;
		}
		else {
			setCookie("sscope", f.p_scope.checked);
		}
	}
	else {
		if(f.p_query.value=="") {
			alert("Search box is empty");
			return false;
		} else {
			setCookie("sscope", f.p_scope.checked);
		}
	}
	if(f.p_query.value=="") {
		alert("Search box is empty");
		return false;
	} else {
		setCookie("sscope", f.p_scope.checked);
	}
}
function cChat(f){
	if(document.forms['chatForm'].elements['p_comment'].value == ""){
		alert("Chat box is empty.");
	} else {
		sendComment();
	}
}
function cLogin(f){
	if(f.p_name.value=="" || f.p_password.value==""){
		alert("All login fields must be completed");
		return false;
	}
}
function deleteMessage(id, from) {
	if (confirm("Delete message?")) {
		window.location.href = "/messages/messages_delete.php?p_message_id="+id+"&p_delete_from="+from;
	}
}


/* AJAX Stuff */
var GetChaturl = "/chat/box_chat_action.php?action=get";
var SendChaturl = "/chat/box_chat_action.php?action=send";

// Chat box initialization
function initChatScript() {
	if (document.forms['chatForm']) {
		if(document.forms['chatForm'].elements['p_comment']){
			document.forms['chatForm'].elements['p_comment'].setAttribute('autocomplete','off'); //this non standard attribute prevents firefox' autofill function to clash with this script
		}
		receiveChatText(); //initiates the first data query
	}
}

//initiates the first data query
function receiveChatText() {
	if (httpReceiveChat.readyState == 4 || httpReceiveChat.readyState == 0) {
		moredata = "";
		if(document.sForm.sUserId.value > 0){
			moredata = "&logged=on";
		}
		httpReceiveChat.open("GET",GetChaturl+moredata,true);
		httpReceiveChat.onreadystatechange = handlehHttpReceiveChat;
		httpReceiveChat.send(null);
	}
}

//deals with the servers' reply to requesting new content
function handlehHttpReceiveChat() {
	content="";
	if (httpReceiveChat.readyState == 4) {
		results = httpReceiveChat.responseText.split('---'); //the fields are seperated by ---
		if (results.length > 3) {
			for(i=0; i<(results.length-1); i=i+3) { //goes through the result one message at a time
				if(results[i+1]=="CheatHouse Admin"){
					results[i+1]="<font color='#F8FEC9'>"+results[i+1]+"</font>";
					results[i+2]="<font color='#FFCC00'>"+results[i+2]+"</font>";
				}
				content += "&nbsp;<b>[<a href='user/user_view.php/p_user_id/"+results[i]+"' class='fa_8o'><b>"+results[i+1]+"</b></a>]</b><table align='center' width='96%' class='fa_8'><tr><td>"+results[i+2];
				if(i<results.length-4){
					content += "<hr class='dot'/>";
				}
				content += "</td></tr></table>";
			}
			document.getElementById("box_chat_entries").innerHTML = content;
		}
		setTimeout('receiveChatText();',4000); //executes the next data query in 4 seconds
	}
}

//stores a new comment on the server
function sendComment() {
	currentChatText = document.forms['chatForm'].elements['p_comment'].value;
	if(currentChatText == ""){
		alert("Chat box is empty.");
		return false;
	}
	if (currentChatText != '' & (httpSendChat.readyState == 4 || httpSendChat.readyState == 0)) {
		param = 'comment='+currentChatText+'&user='+document.sForm.sUserId.value;
		httpSendChat.open("POST",SendChaturl,true);
		httpSendChat.setRequestHeader('Content-Type','application/x-www-form-urlencoded');
		httpSendChat.onreadystatechange = handlehHttpSendChat;
		httpSendChat.send(param);
		document.forms['chatForm'].elements['p_comment'].value = '';
	} else {
		setTimeout('sendComment();',1000);
	}
}

//deals with the servers' reply to sending a comment
function handlehHttpSendChat() {
	if (httpSendChat.readyState == 4) {
		receiveChatText(); //refreshes the chat after a new comment has been added (this makes it more responsive)
	}
}


function addChatHistoryEntry() {
	alert(document.getElementById("outputList"));
}


/* XMLHttpRequest */
//initiates the XMLHttpRequest object
//as found here: http://www.webpasties.com/xmlHttpRequest
function getHTTPObject() {
	var xmlhttp;
	/*@cc_on
	@if (@_jscript_version >= 5)
	try {
	xmlhttp = new ActiveXObject("Msxml2.XMLHTTP");
	} catch (e) {
	try {
	xmlhttp = new ActiveXObject("Microsoft.XMLHTTP");
	} catch (E) {
	xmlhttp = false;
	}
	}
	@else
	xmlhttp = false;
	@end @*/
	if (!xmlhttp && typeof XMLHttpRequest != 'undefined') {
		try {
			xmlhttp = new XMLHttpRequest();
		} catch (e) {
			xmlhttp = false;
		}
	}
	return xmlhttp;
}

// initiates the two objects for sending and receiving data
var httpReceiveChat = getHTTPObject();
var httpSendChat = getHTTPObject();
var httpRateObject = getHTTPObject();


/* Rate System */
var MAX_RATE = 5;
function starOn(idNum) {
	$("star"+idNum).src = "/_files/general/images/v4/fullStar.gif"
}

function starOff(idNum) {
	$("star"+idNum).src = "/_files/general/images/v4/emptyStar.gif"
}

function newRate(rate) {
	var j = 1;
	while( j <= MAX_RATE ) {
		starOff(j);
		j++;
	}

	switch ( rate ) {
		case 1:
		$("rating_description").innerHTML = "Poor";
		break;
		case 2:
		$("rating_description").innerHTML = "Nothing Special";
		break;
		case 3:
		$("rating_description").innerHTML = "Worth Reading";
		break;
		case 4:
		$("rating_description").innerHTML = "Good";
		break;
		case 5:
		$("rating_description").innerHTML = "Very Good";
		break;
		default:
		$("rating_description").innerHTML = "Rate this essay";
		break;

	}

	if ( rate == 0 ) {
		return;
	}

	for( var i = 1 ; i <= rate; i++) {
		starOn(i);
	}

	return;

}

function setRate (rate) {
	var rateUrl = "/essay/ajax_essay_rating.php";
	var j = 1;
	while( j <= MAX_RATE ) {
		$("star" + j ).onmouseover = null;
		$("star" + j ).onmouseout = null;
		$("star" + j ).onclick = null;
		j++;
	}

	newRate( rate );

	/*Ajax*/
	httpRateObject.open("GET",rateUrl + "?rate=" + rate + "&id=" + $("p_essay_id").value,true);
	httpRateObject.onreadystatechange = function () {
		if(httpRateObject.readyState == 4 && httpRateObject.status == 200)
		{
			responseTextSplit = httpRateObject.responseText.split("|");
			if(responseTextSplit.length > 1) 	{
				$("rating_td").innerHTML = '<img src="/_files/general/images/v4/new/' + responseTextSplit[1]  +  '"/> Rated!'
			}
			else {
				$("rating_td").innerHTML += "Already Rated!"
			}
			$("rating_description").innerHTML = responseTextSplit[0];
		}
	};
	httpRateObject.send(null);

	return;
}

function testComponent (c) {
	var result = "Component properties:\n";
	result += "ID: " + c.id;
	result += "\nName: " + c.name;
	result += "\nValue: " + c.value;
	result += "\nClass: " + c.style.className;
	alert(result);
	return;
}

function changeSrc ( objId , new_src ) {
	$(objId.toString()).src = new_src;
}

function changeClass ( objId , new_class ) {
	$(objId).style.className = new_class;
}

function formSubmit ( formId ) {
	$(formId).submit();
}

function advSearchSwitch () {
	if($('adv_search').innerHTML == 'more options') {
		$('search_form').action = 'search/advanced_search.php';
		$('adv_search').innerHTML = 'less options';
	}
	else {
		$('search_form').action = 'search/search.php';
		$('adv_search').innerHTML = 'more options';
	}
	return false;
}

function append_form(news_entry_id) {
	var div_id = "news_comments_" + news_entry_id;
	$(div_id).innerHTML += 	"<div style='FONT:bold 13px Arial;COLOR:#94C2C0;' align='center' id='form_"+news_entry_id+"'>" +
	"<p style='margin-left:10px;'><b><i>Comment this news entry.</i></b></p>" +
	"<form action='comment/ajax_comment.php' type='post' >" +
	"<div class='comment_left'>" +
	"<strong>Title</strong><br/>" +
	"<strong>Comment</strong><br/>" +
	"</div>" +
	"<div class='comment_right'>" +
	"<input type='text' name='title' id='title_"+news_entry_id+"' style='width:350px;border:1px solid black;'/><br/>" +
	"<textarea id='comment_"+news_entry_id+"' name='comment' style='width:350px;height:135px;border:1px solid black;'></textarea><br/>" +
	"<input type='hidden' value='"+news_entry_id+"' name='entryid'/>" +
	"<input type='button' value='Submit!' onclick=\"add_comment('"+news_entry_id+"');\" style='width:85px;margin-top:5px;'/>" +
	"</div>" +
	"<div id='clear'><br/></div>" +
	"</form>" +
	"</div>";
}

function open_news_comments(news_entry_id) {

	function loadingImage ( xmlHttpRequest, responseHeader ) {
		var div_id = "news_comments_" + news_entry_id;
		/*$("news_comments_" + news_entry_id).toggle();
		$("news_comments_" + news_entry_id).innerHTML = "";
		$("news_comments_" + news_entry_id).innerHTML = "<img src='loading2.gif' border='0' style='float:left'/><br/>Loading";*/
		var loadingimg = new Image();
		loadingimg.src = 'loading2.gif';
		loadingimg.border = 0;
		loadingimg.style.marginLeft = 25;
		//alert(2);
		//$("news_comments_" + news_entry_id).innerHTML += "<img src='loading2.gif' border='0' style='margin: 25px;'/><br/>Loading";
		$(div_id).appendChild(loadingimg);
		$(div_id).toggle()

	}

	function updateComments ( xmlHttpRequest , responseHeader ) {
		var commentsHTML = "";
		$("news_comments_" + news_entry_id).innerHTML = "";
		commentResponseText = xmlHttpRequest.responseText.evalJSON();
		if (commentResponseText["comments"]) {
			comments = commentResponseText["comments"];
			comments.each(
			function(comm) {
				commentsHTML += "<div id='comment_"+comm["id"]+"'>";
				commentsHTML += "<font color='white'><b>"+comm['title']+"</b></font>, "+comm['date']+"<br/>\n";
				commentsHTML += "<IMG align='top' SRC='/_files/general/images/v5css/new/comment.gif' WIDTH='21' HEIGHT='20' BORDER='0'/> Author: <a href='user/user_view.php/p_user_id/"+comm['author_id']+"'><b>"+comm['author_name']+"</b></a><br/>" + comm["content"] + "<br/>";
				if(commentResponseText["admin"]) {
					commentsHTML += "<div align='right'>";
					commentsHTML += "<a class='omo' href=\"javascript:remove_comment('"+comm['id']+"')\">";
					commentsHTML += "<img width='9' vspace='0' hspace='0' height='10' border='0' src='_files/general/images/left_column/erase.gif' alt='(Erase Comment)'/>remove</a></div>";
				}
				commentsHTML += "<hr>";
				commentsHTML += "</div>";
			}
			);
			$("news_comments_" + news_entry_id).innerHTML += commentsHTML;
		}
		if(commentResponseText["logged_in"]) {
			append_form(news_entry_id);
		}

	}

	if($("news_comments_" + news_entry_id).innerHTML == "") {
		var url = "comment/ajax_comment.php";
		var param = "entryid=" + news_entry_id;
		//var divn = 0;
		var myajax = new Ajax.Request(url, {
			method: 'get',
			parameters: param,
			onCreate: loadingImage,
			onComplete: updateComments
		}
		);

	}

	else { $("news_comments_" + news_entry_id).toggle(); }
}

function add_comment(news_entry_id) {
	var form_id = "form_" + news_entry_id;
	var div_id = "news_comments_" + news_entry_id;
	var title_value = $("title_" + news_entry_id).value;
	var comment_value = $("comment_" + news_entry_id).value;
	$(form_id).remove();
	var parame = $H({ entryid: news_entry_id, title: title_value, comment: comment_value });
	var url = "comment/ajax_comment.php";

	function loadingImage ( xmlHttpRequest, responseHeader ) {
		var loadingimg = new Image();
		loadingimg.src = 'loading2.gif';
		loadingimg.style.classname = 'loadingimg'
		var img_div = document.createElement('div');
		img_div.id = 'loadingimg';
		img_div.appendChild(loadingimg);
		img_div.innerHTML += "Loading";
		$(div_id).appendChild(img_div);

	}

	function insertComment ( xmlHttpRequest , responseHeader ) {
		var addCommentResponseText = xmlHttpRequest.responseText.evalJSON();
		$('loadingimg').remove();
		if (addCommentResponseText['error'] == 'true') {
			alert(addCommentResponseText['message']);
			append_form(news_entry_id);
		} else {
			$("news_comments_" + news_entry_id).innerHTML += addCommentResponseText['response']+"<br/><hr>\n";
			append_form(news_entry_id);
		}
	}

	var myajax = new Ajax.Request(url, {
		method: 'post',
		parameters: parame,
		onCreate: loadingImage,
		onComplete: insertComment
	}
	);
}
function remove_comment(comment_id) {
	if(confirm("Do you really want to remove this comment?")) {
		var url = "comment/ajax_comment.php";
		var paramet = $H({ "delete_comment": true, "comment_id": comment_id });
		var myajax = new Ajax.Request(url, {
			method: 'post',
			parameters: paramet,
			onCreate: loadingImage,
			onComplete: delComment
		}
		);
	}

	function loadingImage ( xmlHttpRequest, responseHeader ) {
		var loadingimg = new Image();
		loadingimg.src = 'loading2.gif';
		loadingimg.style.classname = 'loadingimg'
		var img_div = document.createElement('div');
		img_div.id = 'loadingimg';
		img_div.appendChild(loadingimg);
		img_div.innerHTML += "Loading<br/><hr>";
		$("comment_"+comment_id).innerHTML = "";
		$("comment_"+comment_id).appendChild(img_div);

	}

	function delComment ( xmlHttpRequest , responseHeader ) {
		var delCommentResponseText = xmlHttpRequest.responseText.evalJSON();
		$('loadingimg').remove();
		if (delCommentResponseText['error'] == 'true') {
			alert(delCommentResponseText['message']);
		} else {
			$("comment_"+comment_id).remove();
			alert(delCommentResponseText['response']);
		}
	}
}

function alternateDiv(hideDiv,showDiv)
{
	if(hideDiv == 'doesnt_have_acc')
	{
		$('reg').value = 'true';
	}
	else 
	{
		$('reg').value = 'false';
	}
	$(hideDiv).removeClassName("display_block");
	$(hideDiv).hide();
	$(showDiv).removeClassName("display_none");
	$(showDiv).show();
	return false;
}

function validateFileType(input_id)
{
	fileName = $(input_id).value;
	if(fileName.endsWith(".docx"))
	{
		alert("We're not accepting MS OFFICE 2007 files yet.\nPlease save this file in .doc format and try again.");
		$(input_id).value = "";
	}
	else if(!(fileName.endsWith(".doc") || fileName.endsWith(".txt") || fileName.endsWith(".odt")))
	{
		alert("Invalid File.\nUse .doc , .txt or .odt formats only.");
		$(input_id).value = "";
	}
}

function validateFileName(input_id, fileName)
{
	sentFile = $(input_id).value;
	if (!sentFile.endsWith(fileName))
	{
		alert("This file must be named "+fileName);
		$(input_id).value = "";
	}
}

function sendMailBeforePost(form_id)
{
	var url = "editing_service/ajax_mailer.php";
	var myajax = new Ajax.Request(url, {
		method: 'post',
		onComplete: submit_form
	});
	
	function submit_form(xmlHttpRequest , responseHeader)
	{
		if(xmlHttpRequest.responseText == "true")
		{
			$(form_id).submit();
		}
		else{
			alert(xmlHttpRequest.responseText)
		}
	}
	
}
