var ajaxObject; 	// the XMLHttpRequest / IEthingy object
var submitURL; 	// the comment submit page

var separator = '<!-- response -->'; // the comments and object separator
var newCommentDivId = 'newStuff'; // new comments div elementId
var commentCount = 'noOfComments'; // no of comments elementId  
var commentForm = 'add_comment'; // comment form elemendId

function initAjax () {
	ajaxObject = null;
	if (window.XMLHttpRequest) { ajaxObject = new XMLHttpRequest(); }
	else if (window.ActiveXObject) { ajaxObject = new ActiveXObject("Microsoft.XMLHTTP"); }
	if (ajaxObject == null) { return false; }
	return true;
}

function getComment (formId) {
	var formObject = document.getElementById(formId);
	var	data = "";
	for (var i = formObject.elements.length - 1; i >= 0; i--){
		data += formObject.elements[i].name + "=" + encodeURI(formObject.elements[i].value) + "&";
	}
	data = data.substr(0, (data.length - 1));	// to remove the trailing &
	return data;
}

function submitComment () {
	var form = document.getElementById(commentForm);
	if (form._commentPreview.previewTimer) clearTimeout(form._commentPreview.previewTimer);
	
	initAjax();
	var query = getComment(commentForm);
	ajaxObject.onreadystatechange = commentResponse;
	ajaxObject.open('POST', submitURL, true);
	ajaxObject.setRequestHeader("Content-type", "application/x-www-form-urlencoded; charset=UTF-8");
	ajaxObject.setRequestHeader("Connection", "close");
	ajaxObject.send(query);
	buildLoader();
}

function commentResponse () {
	if (ajaxObject.readyState == 4 || ajaxObject.readyState == 'complete') {
		killLoader();
		var form = document.getElementById(commentForm);
		if (ajaxObject.status == 200) {
			try	{
				var response = ajaxObject.responseText;
				var newComments = response.slice(0, response.lastIndexOf(separator));
				var result = eval( "(" + response.slice(response.lastIndexOf(separator) + separator.length) + ")" );
				if (result.isError == false) {
					document.getElementById(newCommentDivId).innerHTML += newComments;
					document.getElementById(commentCount).innerHTML = result.noOfComments;
					form.noOfComments.value = result.noOfComments;
					
					clearCommentForm();
					form._commentPreview.hidePreview();
					setCommentCookies();
					smokeNewComments();
				} else {
					showError(result.errorMessage);
				}
				writeCaptcha(result.captcha);
			} catch (error) {
				showError('Some stupid error occured :(');
			}
		} else {
			showError('Some stupid error :(');
		}
		form._commentPreview.getPreview();
	}
}

function Preview (textarea, previewURL) {
	var o = this;
	o.textarea = document.getElementById(textarea);
	if (!o.textarea) return null;
	o.box = document.getElementById('commentPreview');
	
	this.getMessage = function () {
		if (!o.message || (o.message && o.message != o.textarea.value)) {
			o.message = o.textarea.value;
			if (o.previewTimer) clearTimeout(o.previewTimer);
			o.previewTimer = setTimeout(function () { o.getPreview(); }, 1500);
		}
	}
	
	this.getPreview = function () {
		if (o.message && o.message != '') {
			if (!initAjax() || !previewURL) return false;
			
			var query = 'message=' + encodeURI(o.message);
			ajaxObject.onreadystatechange = o.showPreview;
			ajaxObject.open('POST', previewURL, true);
			ajaxObject.setRequestHeader("Content-type", "application/x-www-form-urlencoded; charset=UTF-8");
			ajaxObject.send(query);
		}
		
		if (o.message == '') o.hidePreview();
	}
	
	this.showPreview = function () {
		if (ajaxObject.readyState == 4 || ajaxObject.readyState == 'complete') {
			if (ajaxObject.status == 200) {
				try	{
					var response = ajaxObject.responseText;
					var preview = response.slice(0, response.lastIndexOf(separator));
					var result = eval( "(" + response.slice(response.lastIndexOf(separator) + separator.length) + ")" );
					if (result.isError == false) {						
						var stagingBox = document.createElement('div');
						var label = document.createElement('p');
						var previewBox = document.createElement('div');
						
						stagingBox.style.position = 'absolute';
						stagingBox.style.width = '320px';
						stagingBox.style.visibility = 'hidden';
						label.className = 'label';
						previewBox.id = 'previewBox';
						
						label.appendChild(document.createTextNode('preview'));
						previewBox.innerHTML += preview;
						stagingBox.appendChild(label);
						stagingBox.appendChild(previewBox);
						o.box.parentNode.insertBefore(stagingBox, o.box);
						
						cleanElement(o.box); // in sitemap.js
						roll(o.box, stagingBox.offsetHeight); // in sitemap.js
						while (stagingBox.firstChild) o.box.appendChild(stagingBox.firstChild);
						stagingBox.parentNode.removeChild(stagingBox);
					} else {
						showError(result.errorMessage);
					}
				} catch (error) {
					showError('Some stupid error occured.');
				}
			} else {
				showError('Some stupid error');
			}
		}
	}

	this.hidePreview = function () {
		roll(o.box, 0);
		cleanElement(o.box);
		o.message = o.textarea.value;
	}
}

/* Non-ajax comment specific js */

function smokeNewComments () {
	var thingy = document.getElementById('newStuff');
	// initializing the reply button
	var links = thingy.getElementsByTagName('a');
	for (var i = links.length - 1; i >= 0; i--) {
		if (links[i].className.indexOf('commentreply') != -1) {
			links[i].onclick = move;
		}
	}
	// fading in the new comments
	var divs = thingy.getElementsByTagName('div');
	for (var i = divs.length - 1; i >= 0; i--) {
		if (divs[i].id.indexOf('comment') != -1 && divs[i]._appeared != true) {
			divs[i]._appeared = true;
			appear(divs[i], 40);
		}
	}
}

/*
move
	used to shift the comment form
	code by referencing quirksmode.org and w3schools.com
*/
function move() {
	var idToMove = "addcomment";
	var destination = this;
	while (destination.nodeName != 'DIV' || destination.className.indexOf('comment') >= 0) { 
		destination = destination.parentNode; 
	}
	var thingy = document.getElementById(idToMove);
	// var destination = document.getElementById(moveToId);
	
	var x = destination.lastChild;
	while (x.nodeType != 1) {	// making sure the lastChild is an element and not text
		x = x.previousSibling;
	}
	//setOpacity (idToMove, 0);
	destination.insertBefore(thingy, x);
	document.getElementById('message').focus();
	//appear (thingy, 20);
	return false;
}

function initCommentForm (ajaxURL, previewURL) {
	submitURL = ajaxURL;

	var elementId = commentForm;
	thingy = document.getElementById(elementId);
	
	thingy.onsubmit = validateCommentForm;
	if (initAjax() == true) { thingy.setAttribute("action", "javascript:submitComment()"); }
	
	loadCommentCookies();
	
	initEvent('message', 'focus', activate);
	initEvent('name', 'focus', activate);
	initEvent('email', 'focus', activate);
	initEvent('homepage', 'focus', activate);
	initEvent('captcha', 'focus', activate);
	
	initEvent('message', 'blur', deactivate);
	initEvent('name', 'blur', deactivate);
	initEvent('email', 'blur', deactivate);
	initEvent('homepage', 'blur', deactivate);
	initEvent('captcha', 'blur', deactivate);
	
	thingy._commentPreview = new Preview('message', previewURL);
	initEvent('message', 'keyup', thingy._commentPreview.getMessage);
}

// Comment submission
function buildLoader () {
	disableForm(commentForm);
	document.getElementById('submit').style.display	=	'none';		//Hide the 'Submit' button
	initLoadMessage('status', "Submitting  your  comment...");		//Initialise the message in the status message div
	initLoad('status');												//Load the status message
	document.getElementById('status').style.display	=	'inline';	//Display the loading message	
}
function killLoader () {
	document.getElementById('status').style.display	=	'none';		//Hide the loading message
	killLoad();														//Kill the loader
	killLoadMessage('status');										//Remover the message from the status div
	document.getElementById('submit').style.display	=	'inline';	//Display the 'Submit' button
	enableForm(commentForm);
}


/*
validateCommentForm
	validates the add_comment form on submitting data
	error notification based on quirksmode.org/dom/error.html
*/
function validateCommentForm () {
	var form = document.getElementById(commentForm);
	
	if (trim(form.message.value) == '') {
		var emessage = 'You\'ve got to write your opinion if you want to comment!';
		showError(emessage, form.message);
		form.message.focus();
		return false;
	}
	
	if (trim(form.captcha.value) == '') {
		var emessage = 'The answer please. Its a necessary evil to prevent spam.';
		showError(emessage, form.captcha);
		form.captcha.focus();
		return false;
	}
	
	return true;
}

function showError (message, associateDiv) {
	var form = document.getElementById(commentForm);
	var p = document.createElement('p');
	var error = document.createElement('div');
	if (!associateDiv) { associateDiv = form.captcha; }
	
	p.appendChild(document.createTextNode(message));
	error.appendChild(p);
	error.className = 'error';
	
	if (associateDiv._hasError) {
		form.removeChild(associateDiv._hasError);
	}
	form.appendChild(error);
	
	associateDiv._hasError = error;
	associateDiv.onchange = removeError;
}
function removeError () {
	if (this._hasError) { 
		this._hasError.parentNode.removeChild(this._hasError);
		this._hasError = null;
	}
}

function trim (str) {
	return str.replace(/^\s+|\s$/g,'');
}

/* For onfocus and onblur (deactivate) of input elements */
function activate () {
	this.style.backgroundColor = "#400";
	this.style.color = "#797979";
}
function deactivate (elementId) {
	var thingy;
	if (elementId && typeof(elementId) != 'object') { thingy = document.getElementById(elementId); }
	else { thingy = this; }
	thingy.style.backgroundColor = "#190000";
	thingy.style.color = "#444";
}

function disableForm (formId) {
	var form = document.getElementById(formId);
	for (var i = form.elements.length - 1; i >= 0; i--){
		form.elements[i].disabled = true;
	}
}
function enableForm (formId) {
	var form = document.getElementById(formId);
	for (var i = form.elements.length - 1; i >= 0; i--){
		form.elements[i].disabled = false;
	}
}

function clearCommentForm () {
	var form = document.getElementById(commentForm);
	form.message.value = '';
	form.captcha.value = '';
}
function setCommentCookies () {
	var form = document.getElementById(commentForm);
	createCookie('name', form.name.value, 365);
	createCookie('email', form.email.value, 365);
	createCookie('homepage', form.homepage.value, 365);
}
function loadCommentCookies () {
	var form = document.getElementById(commentForm);
	var temp;
	temp = readCookie('name');
	form.name.value = (temp == null) ? '' : temp;
	temp = readCookie('email');
	form.email.value = (temp == null) ? '' : temp;
	temp = readCookie('homepage');
	form.homepage.value = (temp == null) ? '' : temp;
	deactivate('name');
	deactivate('email');
	deactivate('homepage');
}

function writeCaptcha (question) {
	var label = document.getElementById('captcha_label');
	captcha = question.replace(/[a-zA-Z]/g, 
		function(c){return String.fromCharCode((c<="Z"?90:122)>=(c=c.charCodeAt(0)+13)?c:c-26);});
		
	label.innerHTML = captcha;
	// label._captcha = captcha;
	
	var input = document.getElementById('captcha');
	if (input.value != '') { input.value = ''; }
}

/*
	Cookies script
	Taken from www.quirksmode.org
*/
function createCookie (name, value, days) {
	if (days) {
		var date = new Date();
		date.setTime(date.getTime()+(days*24*60*60*1000));
		var expires = "; expires="+date.toGMTString();
	}
	else { var expires = ""; }
	document.cookie = name+"="+value+expires+"; path=/";
}
function readCookie (name) {
	var nameEQ = name + "=";
	var ca = document.cookie.split(';');
	for(var i=0;i < ca.length;i++) {
		var c = ca[i];
		while (c.charAt(0)==' ') c = c.substring(1,c.length);
		if (c.indexOf(nameEQ) == 0) return c.substring(nameEQ.length,c.length);
	}
	return null;
}
