var xmlhttp;
function createXMLHttp(){ xmlhttp = (window.ActiveXObject) ? new ActiveXObject("Microsoft.XMLHTTP") : new XMLHttpRequest(); }
function $(id){ return document.getElementById(id); }
function $showhide(id){ $(id).style.display = ($(id).style.display == 'none') ? '' : 'none'; }
function $show(id){ $(id).style.display = '';}
function $hide(id){ $(id).style.display = 'none';}
function replaceAll( str, from, to ) {
    var idx = str.indexOf( from );
    while ( idx > -1 ) {
        str = str.replace( from, to );
        idx = str.indexOf( from );
    }
    return str;
}

/* xmlhttp post to specified URL with querystring then run handler when ready. */
function ajaxPagePost(url, qs, handle){
	createXMLHttp();
	xmlhttp.open("POST", url, true);
	xmlhttp.onreadystatechange = handle;
	xmlhttp.setRequestHeader("Content-Type","application/x-www-form-urlencoded;");
	xmlhttp.send(qs);
}

function addComment(id){
	var f = $('frm' + id);
 	var div = $('replybox' + id);
	var holder = $('allcomments' + id);
	var postData = 'n=' + f.txtname.value + '&m=' +  f.txtmsg.value + '&id=' + id;
 	postData = replaceAll(postData, " ", "|");
	postData = replaceAll(postData, "\r", "$_");
	postData = replaceAll(postData, "\n", "$_");
	//alert(postData);
	if(validate()) {
		ajaxPagePost('addcomment.php', postData, commentHandle);	
	}
	function commentHandle(){
		div.className = 'reply loading';
		f.btnreply.disabled = 'disabled';
		if (xmlhttp.readyState == 4){
			if (xmlhttp.status == 200){
				var com = document.createElement('p');
				com.innerHTML = xmlhttp.responseText;
				holder.insertBefore(com, holder.getElementsByTagName('p')[0]);
				div.className = 'reply'; f.btnreply.disabled = '';  f.txtmsg.value = '';
			}
		}
	}
	function validate()	{
		var errorMsg = '';
		f.txtname.className = 'textbox';
		f.txtmsg.className = 'textbox';
		if(f.txtname.value == ''){ errorMsg = 'error'; f.txtname.className = 'textbox errbox'};
		if(f.txtmsg.value == ''){ errorMsg = 'error'; f.txtmsg.className = 'textbox errbox'};
		if(errorMsg != ''){
			var msg = 'You have to fill in all fields to leave a comment, come on its only 2';
			alert(msg);
			return false;
		}
		else return true; 
	}
}

function confirmDel(){
	var msg = "Are you sure you want to delete this comment? You wont be able to get it back.";
	if (confirm(msg)){
		return true;
	} else {
		return false;
	}
}