// Add an eventListener to browsers that can do it somehow.
// Originally by the amazing Scott Andrew.
function addEvent(obj, evType, fn){
  if (obj.addEventListener){
    obj.addEventListener(evType, fn, true);
    return true;
  } else if (obj.attachEvent){
	var r = obj.attachEvent("on"+evType, fn);
    return r;
  } else {
	return false;
  }
}

addEvent(window,'load',tripcodeSet);
addEvent(window,'load',collapseOrExpand);
addEvent(window,'load',hiliter);
addEvent(window,'load',dateFill);

////////////////////////////////////////////////////////////////

var last_hilited = '';
var useFrame = getCookie("useFrame")=="t" ? true : false;

function dateFill() {
	adj = parseInt(getCookie("timezone"));
	ems = document.getElementsByTagName('em');
	num = ems.length;
	d = new Date();
	tz = d.getTimezoneOffset() * 60;
	for(i=0;i<num;i++) {
		if(ems[i].className=="date") {
			t = parseInt(ems[i].getAttribute("title"));
			adj ? d.setTime((t+adj-TZ)*1000) : d.setTime((t-TZ)*1000);
			yyyy = d.getFullYear();
			mm = d.getMonth() + 1;
			if(mm<10) { mm = "0" + mm };
			dd = d.getDate();
			if(dd<10) { dd = "0" + dd };
			hh = d.getHours();
			if(hh<10) { hh = "0" + hh };
			ii = d.getMinutes();
			if(ii<10) { ii = "0" + ii };
			ss = d.getSeconds();
			if(ss<10) { ss = "0" + ss };
			timeString = yyyy + "-" + mm + "-" + dd + " " + hh + ":" + ii + ":" + ss;
			if(!adj) {
				timeString += " GMT";
			}
			ems[i].firstChild.nodeValue = timeString;
			ems[i].style.display = 'inline';
		}
	}
}

function pop(me,label) {
	var d,h,i,s;
	if(useFrame) {
		if(document.getElementById("popon")) {
			document.getElementById("popon").firstChild.setAttribute("src",me);
		} else {

			d = document.createElement("DIV");
			d.setAttribute("id","popon");

			// Iframe
			i = document.createElement("IFRAME");
			i.src = me;

			// Title bar
			h = document.createElement("H1");
			h.appendChild(document.createTextNode(label));
			Evt.addEventListener(h,"mousedown",dragPress,false);
			
			// Close button
			s = document.createElement("SPAN");
			s.setAttribute("id","close");
			Evt.addEventListener(s,"mouseup",popoffEvent,false);
			s.appendChild(document.createTextNode("Close"));

			d.appendChild(h);
			d.appendChild(i);

			if(x=readCookie("left")) {
				d.style.left = x + "px";
			}
			if(x=readCookie("top")) {
				d.style.top = x + "px";
			}

			document.body.appendChild(d);
			h.appendChild(s);
		}
	} else {
		var myOptions = 'hotkeys,scrollbars=yes,width=500,height=500';
	    window.name=location.href;
		popUpWin = window.open(me,'_blank',myOptions);
	}
	return false;
}

function popoffEvent(event) {
	event = new Evt(event);
	if(d = event.source.parentNode.parentNode) {
		// Safari is weird
		if(d.nodeName == "H1") d = d.parentNode;

		popoff(d.id);
	}
	event.consume();
	Evt.removeEventListener(document,"mousemove",dragMove,false);
	Evt.removeEventListener(document,"mouseup",dragRelease,false);
}

function popoff(reload) {
	if(opener) {
		if(reload==true) {
			opener.location.reload();
			setTimeout("window.close()",3000);
		} else {
			window.close();
		}
	} else {
		if(div=window.parent.document.getElementById("popon")) {
			if(reload==true) {
				window.parent.location.reload();
			}
			createCookie("top",div.offsetTop>=0 ? div.offsetTop : 0 );
			createCookie("left",div.offsetLeft);
			window.parent.document.body.ondrag = null;
			window.parent.document.body.onselectstart = null;
			div.parentNode.removeChild(div);
		}
	}
}

function tripcodeSet()
{
	if(me = document.getElementById("tripcode")) {
		if(tripcode = getCookie("tripcode")) {
			me.value = tripcode.replace("+"," "); // Bad interplay between JS/PHP
		}
	}
	if(me = document.getElementById("verify")) {
		me.value = "";
	}
}

function getCookie(name)
{
	var cookie = document.cookie;
	var key = document.cookie.indexOf(name);
	if (key == -1 || !name) {
		return false;
	}
	var start = key+name.length+1;
	var end = document.cookie.indexOf(';',key);
	if (end == -1) {
		end=document.cookie.length;
	}
	return unescape(document.cookie.substring(start,end));
}

function checkPost()
{
	// Name is required
	if (!document.getElementById('name').value) {
		alert('A name is required');
		document.getElementById('name').focus();
		return false;
	}

	if(document.getElementById('title')) {

		// Category is required if thread starter
		me = document.forms["post"];
		count = 0;
		for(i=0;i<me.elements.length;i++) {
			if(me.elements[i].name.indexOf('categories') == 0 &&
				me.elements[i].checked) {
				count++;
			}
		}
		if(count<1) {
			alert('At least one category is required');
			return false;
		}
	}

	// If verification enabled, it is required
	if(me = document.getElementById("verify")) {
		if(!me.value) {
			alert("Please enter a verification as shown");
			me.focus();
			return false;
		}
	}

	// Really should enter a tripcode
	if(!document.getElementById("tripcode").value) {
		return confirm("Are you sure you want to submit without a tripcode? You won't be able to delete your comment without one.");
	}

    // Preverify
    if(me && http) {
        http.open("GET","post?verify="+escape(me.value),true);
        http.onreadystatechange = preverify;
        http.send(null);
    } else {
		postit();
    }
}

function preverify()
{
    if(http.readyState == 4) {
        if(http.responseText=="true") {
			postit();
        } else {
            alert("Verification mismatch");
        }
    }
}

function postit()
{
	document.getElementById("postButton").value="Posting...";
	document.getElementById("postButton").disabled="disabled";
	document.forms["post"].submit();
}

function collapse(id)
{
	document.getElementById(id).style.display = 'none';
	document.getElementById("collapser_" + id).style.display = 'none';
	document.getElementById("expander_" + id).style.display = 'inline';
	document.getElementById("filler_" + id).style.display = 'block';
}
function expand(id)
{
	document.getElementById(id).style.display = 'block';
	document.getElementById("collapser_" + id).style.display = 'inline';
	document.getElementById("expander_" + id).style.display = 'none';
	document.getElementById("filler_" + id).style.display = 'none';
}
function all(what)
{
	var date = new Date();
	date.setTime(date.getTime()+(24*60*60*1000));
	cookiestring = "; expires=" + date.toGMTString() + "; path=/";
	deletestring = "; expires=Thu, 01-Jan-70 00:00:01 GMT; path=/";
	if(what == "expand") {
		document.cookie = "expand=1" + deletestring;
	} else {
		document.cookie = "expand=0" + cookiestring;
	}


	cblocks = document.getElementsByTagName("blockquote");
	for(var i = 0; i<cblocks.length;i++) {
		thisid = cblocks[i].id;
		if(thisid.indexOf("cblock") == 0 && document.getElementById("collapser_" + thisid)) {
			if(what == "collapse") {
				collapse(thisid);
			} else if (what == "expand") {
				expand(thisid);
			}
		}
	}
}
function collapseOrExpand()
{
	var expand = true;
	if(what = getCookie("expand")) {
		if(what == "0") {
			expand = false;
		}
	}
	if(expand) {
		all('expand');
	} else {
		all('collapse');
	}
}

function fileCheck() {
	filename = document.forms["post"]["file_upload"].value;
	thread   = document.getElementById("thread");
	another  = document.getElementById("anotherbutton");
	iszip	 = filename.length-filename.indexOf("zip") == 3;

	// If it was a zip: get rid of the another button, if it is around
	// and add the "go in 1 thread" checkbox
	if(iszip) {
		if(another) {
			another.parentNode.parentNode.removeChild(another.parentNode);
		}
		if(thread) {
			thread.style.display = 'inline';
		}
	} else if(thread) {
		thread.style.display = 'none';
	}
	
	// If a file was specified and multiple uploads is enabled, add
	// "Another file" button
	if(!iszip && filename && numUploads<maxUploads && !another) {
		button = document.createElement("INPUT");
		button.setAttribute("type","button");
		button.setAttribute("id","anotherbutton")
		button.setAttribute("onclick","doAnother()");
		button.setAttribute("value","Another File");
		p = document.createElement("P");                                                             p.appendChild(button);
		me = document.getElementById("posting").parentNode;
		me.insertBefore(p,document.getElementById("anotherslot"));
	} else if (!filename && another) {
		another.parentNode.parentNode.removeChild(another.parentNode);
	}
		
}
function hilite(which) {
	if(last_hilited) {
		if(me = document.getElementById(last_hilited)) {
			me.style.background='';
		}
	}
	if(me = document.getElementById("i" + which)) {
		me.style.background = '#ffd';
		last_hilited = "i" + which;
		location.href = "#i" + which;
	} else {
		location.href = ROOT + "/" + which;
	}
}
function hiliter() {
	var parts = location.href.split("#");
	if(me = document.getElementById(parts[1])) {
		me.style.background = '#ffd';
		last_hilited = parts[1];
	}
}

function doAnother() {
    if(numUploads<maxUploads && (table=document.getElementById("posting"))) {
        me=table.parentNode;

        table = document.createElement("TABLE");
        tbody = document.createElement("TBODY");
        tr = document.createElement("TR");
        th = document.createElement("TH");
        td = document.createElement("TD");
        text = document.createTextNode("File:");

        th.appendChild(text);
        tr.appendChild(th);

        input = document.createElement("INPUT");
        input.setAttribute("type","file");
        input.setAttribute("name","file[]");
        td.appendChild(input);
        tr.appendChild(td);
        tbody.appendChild(tr);

        tr = document.createElement("TR");
        th = document.createElement("TH");
        td = document.createElement("TD");
        text = document.createTextNode("Comment:");
        th.appendChild(text);
        tr.appendChild(th);

        input = document.createElement("INPUT");
        input.setAttribute("type","text");
        input.setAttribute("name","comment[]")
        input.setAttribute("size","40")
        td.appendChild(input);
        tr.appendChild(td);
        tbody.appendChild(tr);

        table.appendChild(tbody);
        me.insertBefore(table,document.getElementById("anotherbutton").parentNode);

        numUploads++;
        if(numUploads>=maxUploads) {
            me.removeChild(document.getElementById("anotherbutton").parentNode);
        }
    }
}

/**
 ** xmlhttprequest setup
 ** from 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;
}

if(document.location.href.indexOf('/post')!=-1) {
	var http = getHTTPObject();
}
