if(window.addEventListener) {
window.addEventListener("load", loadActions, true);
}
else if(window.attachEvent) {
window.attachEvent("onload", loadActions);
}

function loadActions() {
	if(document.getElementById("mform")) {
		try {
		encodeURIComponent("test");
		}
		catch(e) {
		return;
		}

		document.getElementById('mform').onsubmit = function(){return false;}

		document.getElementById('previewb').onclick = handleAction;
		document.getElementById('addb').onclick = handleAction; 
		document.getElementById('mcancel').onclick = cancelHttpRequest;
	}
}

data = new Array();
function handleAction() {
document.body.style.cursor = 'wait';
data['action'] = this.value;
pd = processData(data['action']);
	if(!pd) {return;}
http = initiateXMLHttp();
	if(!http) {
	document.getElementById('mform').onsubmit = function() {return true;};
	window.onsubmit = function(){return true;}
		if(data['action'] == "Post") document.getElementById('addb').click();
		else if(data['action'] == "Preview") document.getElementById('previewb').click();
	return;
	}

messagestr = "action=" + "edit" + "&n=" + "Pulp.CommentBox" + "&preview=" + "1" + "&text=" + data['message0'] + "&ajax=1"; 
handler = "/pulpwiki/pmwiki.php";
sendRequest(http,handler,messagestr);
}

function processData(action) {
data['name0'] = document.getElementById('mnamex').value;
data['message0'] = document.getElementById('mmessagex').value;

if(!data['message0']) {showErrorMessage("You must enter the following field: Message");return false;}
if(!data['name0']) {data['name0'] = '?';}
if(data['name0'].length > 40) {showErrorMessage("Your name must be less than 40 characters long");return false;}
if(data['message0'].length > 50000) {showErrorMessage("Your message must be less than 50000 characters long");return false;}	

if(action == "Preview") {
data['id0'] = "preview";
data['date0'] = getCBDate();
}
else if(action == "Post") {
data['name0'] = encodeURIComponent(data['name0']);
	if(document.getElementById('messages').childNodes[0].id == "merror") {
	data['lastid'] = 0;
	}			
	else if(lastid = document.getElementById('messages').childNodes[1]) {
	lastid = lastid.id;
	idlen = lastid.length;
	data['lastid'] = lastid.substring(1,idlen);
		if(isNaN(parseInt(data['lastid']))) {showErrorMessage("An error has occurred!");return false;}
	}
	else {
	showErrorMessage("An error has occurred!");return false;
	}
}

data['message0'] = encodeURIComponent(data['message0']);
return true;
}

function getCBDate() {
dobj = new Date();
yr = dobj.getFullYear();
yr = yr.toString();
yr = yr.substr(2,2);
marray = new Array("Jan", "Feb", "Mar", "Apr", "May", "Jun", "Jul", "Aug", "Sep", "Oct", "Nov", "Dec");
m = dobj.getMonth();
m = marray[m];
d = dobj.getDate();
hr = dobj.getHours();
mn = dobj.getMinutes();
mn = mn.toString();
if(mn.length == 1) mn = "0" + mn;
mdate = d + " " + m + " " + yr + " " + hr + ":" + mn;
return mdate;
}

function initiateXMLHttp() {
if(window.XMLHttpRequest) {
    	try {
	http = new XMLHttpRequest();
        } 
	catch(e) {
	http = false;
        }
} 
else if(window.ActiveXObject) {
       	try {
        http = new ActiveXObject("Msxml2.XMLHTTP");
      	} 
	catch(e) {
        try {
        http = new ActiveXObject("Microsoft.XMLHTTP");
        } 
	catch(e) {
        http = false;
        }
	}
}
if(http) return http;
else return false;
}

function sendRequest(http,handler,mstr) {
document.domain == "localhost" ? domain = document.domain + "/pulpwiki.net" : domain = document.domain;
http.open("POST", "http://" + domain + handler,true);
http.setRequestHeader("Content-Type","application/x-www-form-urlencoded; charset=UTF-8");
http.send(mstr);
http.onreadystatechange = handleHttpResponse;
statusind = document.getElementById('statusindicator');
cancel = document.getElementById('mcancel');
cancel.innerHTML = "CANCEL";
statusind.innerHTML = "Busy...";
statusind.style.visibility = "visible";
cancel.style.visibility = "visible";
}

function handleHttpResponse() {
if(http.readyState == 4) {
try {
statuscheck = http.status;
}
catch(e) {
showErrorMessage('Error: Unable to connect!');
return;	
}

if(statuscheck == 200) {
window.status = '';
if(http.responseXML) response = http.responseXML.documentElement;	
else {showErrorMessage('An error has occurred!');return;}

if(response.getElementsByTagName('status').length > 0) {
mstatusn = response.getElementsByTagName('status');
mstatus = getNodeValue(mstatusn[0]);
	if(mstatus != "ok") {
	!mstatus ? error = "An error has occurred!" : error = mstatus;
	showErrorMessage(error);
	return;
	}
	else {
	mwiki = response.getElementsByTagName('mwiki');
		if(!mwiki){showErrorMessage('An error has occurred!');return;}
		for(q=0;q<mwiki.length;q++) {
		midn = mwiki[q].getElementsByTagName('id');
		data['id'+q] = getNodeValue(midn[0]);
		mdaten = mwiki[q].getElementsByTagName('date');
		data['date'+q] = getNodeValue(mdaten[0]);
		mnamen = mwiki[q].getElementsByTagName('name');
		data['name'+q] = getNodeValue(mnamen[0]);
		mmessagen = mwiki[q].getElementsByTagName('message');
		data['message'+q] = getNodeValue(mmessagen[0]);
		mn = makeMessage(q);
		addMessage(mn,data['action']);
		}
	}
endTasks();
}
else if(response.getElementsByTagName('mblock').length > 0) {
mblockn = response.getElementsByTagName('mblock');
mmessage = getNodeValue(mblockn[0]);
mmessage = mmessage.replace(/\<div id=\'wikitext\'\>/,'');
mmessage = mmessage.replace(/\<\/div\>\s*$/,'');

	if(!mmessage) {showErrorMessage("An error has occurred!"); return;}
	if(data['action'] == "Post") {
	mmessage = encodeURIComponent(mmessage);
	messagestr = "lastid=" + data['lastid'] + "&name=" + data['name0'] + "&message=" + mmessage; 
	handler = "/pulpwiki/messagesajax.php";
	http = initiateXMLHttp();
	sendRequest(http,handler,messagestr);
	}
	else if(data['action'] == "Preview") {
	data['message0'] = mmessage;
	mn = makeMessage(0);
		if(!mn) {showErrorMessage("An error has occurred!"); return;}
	addMessage(mn,data['action']);
	endTasks();
	}
}
}
else {
showErrorMessage('An error has occurred!');
return;
}
}
}

function getNodeValue(mnode) {
nodeslength = mnode.childNodes.length;
	for(i=0;i<nodeslength;i++) {
		if(mnode.childNodes[i].nodeType == "4") {
		nodevalue = mnode.childNodes[i].nodeValue;
		return nodevalue;
		}
	}
	for(i=0;i<nodeslength;i++) {
		if(mnode.childNodes[i].nodeType == "3") {
		nodevalue = mnode.childNodes[i].nodeValue;
		return nodevalue;
		}
	}	
return false;
}

function makeMessage(n) {
div1 = document.createElement('div');
div1.id = 'c' + data['id'+n];
div1.className = "mmessage";
div1.innerHTML = data['message'+n];
div2 = document.createElement('div');
div2.className = "mfloat";
div3 = document.createElement('div');
div3.className = "mfloat2";
span1 = document.createElement('span');
span1.className = "name";
span1.innerHTML = data['name'+n] + "&nbsp;";
span2 = document.createElement('span');
span2.className = "date";
span2.innerHTML = data['date'+n];;
div3.appendChild(span1);
div3.appendChild(span2);
div2.appendChild(div3);
div1.insertBefore(div2,div1.firstChild);
return div1;
}

function addMessage(mmessage,type) {
	if(type=="Preview") {
		if(document.getElementById('cpreview')) {
		mpw = document.getElementById('cpreview');
		mpwparent = mpw.parentNode;
		oldpreview = mpwparent.removeChild(mpw);
		}
		else {
		mpwparent = document.getElementById('mpwp');
		}
	mpwparent.appendChild(mmessage);
	mpwparent.style.display = "block";
	}
	if(type=="Post") {
	mgs = document.getElementById('messages');
	mgs.insertBefore(mmessage,mgs.firstChild);
	newhr = document.createElement('hr');
	newhr.className = "mhr";
	mgs.insertBefore(newhr,mgs.firstChild);
	document.getElementById('mpwp').style.display = "none";
	document.getElementById('mmessagex').value = "";
	if(document.getElementById('merror')) document.getElementById('merror').style.display = "none";
	}
return true;
}

function endTasks() {
document.getElementById('mcancel').style.visibility = "hidden";
document.getElementById('statusindicator').style.visibility = "hidden";
document.body.style.cursor = 'default';
}

function cancelHttpRequest() {
http.abort();
endTasks();
showErrorMessage('Action cancelled!');
return;
}

cancelmessage = false;
function showErrorMessage(errormessage) {
document.getElementById('mcancel').innerHTML = "";
em = document.getElementById('statusindicator');
em.innerHTML = errormessage;
em.style.visibility = "visible";
document.body.style.cursor = 'default';
	if(cancelmessage) {
	window.clearTimeout(cancelmessage);
	}
cancelmessage = window.setTimeout('cancelMessage()',10000);
}

function cancelMessage() {
document.getElementById('statusindicator').style.visibility = "hidden";
document.getElementById('statusindicator').innerHTML = "&nbsp;";
cancelmessage = false;
}

