String.prototype.addClass = function(theClass)
{
  if (this != "")
  {
    if (!this.classExists(theClass))
      return this + " " + theClass;
  }
  else
    return theClass;
  return this;
}

String.prototype.classExists = function(theClass)
{
  var regString = "(^| )" + theClass + "\W*";
  var regExpression = new RegExp(regString);
  if (regExpression.test(this))
    return true;
  return false;
}

String.prototype.removeClass = function(theClass)
{
  var regString = "(^| )" + theClass + "\W*";
  var regExpression = new RegExp(regString);
  return this.replace(regExpression, "");
}

function isIE()
{
	var ieVer = (navigator.appName == 'Microsoft Internet Explorer')?
		parseFloat((new RegExp("MSIE ([0-9]{1,}[.0-9]{0,})")).exec(navigator.userAgent)[1]):-1;
	return (ieVer != -1);
}

function isIE6()
{
	var ieVer = (navigator.appName == 'Microsoft Internet Explorer')?
		parseFloat((new RegExp("MSIE ([0-9]{1,}[.0-9]{0,})")).exec(navigator.userAgent)[1]):-1;
	return (ieVer == 6);
}

function setCookie(nm, val, days) 
{
	var expires = "";
	if (days)
	{
		var dt = new Date();
		dt.setTime(dt.getTime() + (days * 24 * 60 * 60 * 1000));
		expires = "; expires=" + dt.toGMTString();
	}
	document.cookie = nm + "=" + escape(val) + expires + "; path=/";
}

function getCookie(nm) 
{
	var kw = nm + "=";
	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(kw) == 0)
			return unescape(c.substring(kw.length, c.length));
	}
	return null;
}

function eraseCookie(nm) 
{
	document.cookie = nm + "=" + "; expires=Thu, 01-Jan-1970 00:00:00 GMT"; 
}

function ajax(theurl, thepostdata, theonsuccess, theonfail)
{
	var themethod = "GET";
	if (thepostdata)
		themethod = "POST";
	
	var req = 0;
	if (window.XMLHttpRequest)
		req = new XMLHttpRequest();
	else
		req = new ActiveXObject("Microsoft.XMLHTTP");
	
	if (!req)
		debug("Ajax request could not be created.");
		
	req.onreadystatechange = function() {
		if (req.readyState == 4 && req.responseText && req.responseText.length > 0)
		{
			if (req.responseText.search(/error/i) == 0)
			{
				if (theonfail)
					theonfail(req.responseText);
				else
					alert("An error occured while processing request '" + theurl + "'. Please try again or notify this error message to the webmaster.\n" + req.responseText);
			}
			else
			{
				if (theonsuccess)
					theonsuccess(req.responseText);
				else
					eval(req.responseText);
			}
		}
	}

	var ts = (new Date()).getTime();
	if (theurl.indexOf("?") == -1)
		theurl += "?ts=" + ts;
	else
		theurl += "&ts=" + ts;
	
	req.open(themethod, theurl, true);
	req.setRequestHeader("Connection", "close");
	if (thepostdata)
	{
		req.setRequestHeader("Content-type", "application/x-www-form-urlencoded");
		req.setRequestHeader("Content-length", thepostdata.length);
		req.send(thepostdata);
	}
	else
		req.send(null);
}

function getElementPosition(obj) 
{
	var curleft = curtop = 0;
	if (obj.offsetParent) 
	{
		curleft = obj.offsetLeft;
		curtop = obj.offsetTop;
		while (obj = obj.offsetParent) 
		{
			curleft += obj.offsetLeft;
			curtop += obj.offsetTop;
		}
	}
	return [curleft, curtop];
}

function getElementDimension(obj) 
{
	return [ obj.offsetWidth | obj.style.pixelWidth, obj.offsetHeight | obj.style.pixelHeight ];
}

function getElementsByFilter(_id, _class, _tag, _root)
{
	if (!_root)
		_root = document;
	var el = _root.firstChild;
	var out = new Array();
	while (el)
	{
		var found = true;
		if (_id && (!el.id || el.id.toUpperCase() != _id.toUpperCase()))
			found = false;
		if (_class && (!el.className || el.className.toUpperCase() != _class.toUpperCase()))
			found = false;
		if (_tag && (!el.tagName || el.tagName.toUpperCase() != _tag.toUpperCase()))
			found = false;
		if (found)	
			out.push(el);
		if (el.firstChild)
			out = out.concat(getElementsByFilter(_id, _class, _tag, el));
		el = el.nextSibling;
	}
	return out;
}

function ud(enc)
{
	var dec = "";
	var ln = enc.length;
	var i = 0;
	var ch, high, low;
	while (i < ln)
	{
		ch = enc.charAt(i);
		if (ch == '+')
		{
			dec += " ";
			++i;
		}
		else if (ch == '%')
		{
			if (i < ln - 2)
			{
				high = enc.charCodeAt(i + 1);
				low = enc.charCodeAt(i + 2);
				if (high >= 48 && high <= 57)
					high -= 48;
				else if (high >= 65 && high <= 90)
					high -= 55;
				else if (high >= 97 && high <= 122)
					high -= 87;
				if (low >= 48 && low <= 57)
					low -= 48;
				else if (low >= 65 && low <= 90)
					low -= 55;
				else if (low >= 97 && low <= 122)
					low -= 87;
				dec += String.fromCharCode((high << 4) + low);
				i += 3;
			}
			else
			{
				dec += "%";
				++i;
			}
		}
		else
		{
			dec += ch;
			++i;
		}
	}
	return dec;
}

function ue(plaintext)
{
	var SAFECHARS = "0123456789ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz-_.!~*'()";	// RFC2396 Mark characters
	var HEX = "0123456789ABCDEF";
	
	var encoded = "";
	for (var i = 0; i < plaintext.length; i++ ) 
	{
		var ch = plaintext.charAt(i);
		if (ch == " ") 
		{
			encoded += "+";	// x-www-ued, rather than %20
		}
		else if (SAFECHARS.indexOf(ch) != -1) 
		{
			encoded += ch;
		}
		else 
		{
			var charCode = ch.charCodeAt(0);
			if (charCode > 255) 
			{
				encoded += "+";
			} 
			else 
			{
				encoded += "%";
				encoded += HEX.charAt((charCode >> 4) & 0xF);
				encoded += HEX.charAt(charCode & 0xF);
			}
		}
	}
	
	return encoded;
}

function in_array(needle, haystack, strict)
{
	if (strict)
	{
		for (key in haystack)
			if (haystack[key] === needle)
				return true;
	}
	else
	{
		for (key in haystack)
			if (haystack[key] == needle)
				return true;
	}
	return false;
}

function insertAfter(referenceNode, newNode)
{
	if (referenceNode.nextSibling) 
	{
		referenceNode.parentNode.insertBefore( newNode, referenceNode.nextSibling );
	}
	else 
	{
		referenceNode.parentNode.appendChild( newNode);
	}
}

function changeStyleSheet(ss)
{
	var sheet = document.getElementById("ss_style");
	var ts = (new Date()).getTime();
	sheet.setAttribute("href", "css/style.css.php?theme=" + ss + "&ts=" + ts);
	
	var sheet_ie6 = document.getElementById("ss_style_ie6");
	if (sheet_ie6)
		sheet_ie6.setAttribute("href", "css/style_ie6.css.php?theme=" + ss + "&ts=" + ts);
		
	// TODO: Re-niftyfy or something like that...
}

function getPageDimensions()
{
	var viewportwidth;
	var viewportheight;
	
	if (typeof window.innerWidth != 'undefined')
	{
		viewportwidth = window.innerWidth,
		viewportheight = window.innerHeight
	}
	else if (typeof document.documentElement != 'undefined' 
		    && typeof document.documentElement.clientWidth !=	'undefined' 
		    && document.documentElement.clientWidth != 0)
	{
		viewportwidth = document.documentElement.clientWidth,
		viewportheight = document.documentElement.clientHeight
	}
	else
	{
		viewportwidth = document.getElementsByTagName('body')[0].clientWidth,
		viewportheight = document.getElementsByTagName('body')[0].clientHeight
	}
	
	return [viewportwidth, viewportheight];
}

function getPageOffset()
{
	if (self.pageXOffset)
		return [self.pageXOffset, self.pageYOffset];
	else if (document.documentElement && document.documentElement.scrollTop)
		return [document.documentElement.scrollLeft, document.documentElement.scrollTop];
	else if (document.body)
		return [document.body.scrollLeft, document.body.scrollTop];
}

function notifyThatThereAreNewReactions()
{
	var div = document.createElement("div");
	div.id = "reactions_notification_div";
	//div.style.opacity = "0.90";
	//div.style.filter = "alpha(opacity=90)";
	var As = document.getElementsByTagName("A");
	var s = "Nw. reacties: ";
	var n = 1;
	for (var i = 0; i < As.length; ++i)
	{
		var A = As[i];
		if (A.name.indexOf("newmsg_") != -1)
		{
			s += "<u class=\"clickMouseCursor\" onclick=\"scrollToAnchor('" + A.name + "');\"><b>" + n + "</b></u> ";
			++n;
		}
	} 
	div.innerHTML = s;
	if (isIE())
	{
		div.style.position = "absolute";
		div.style.setExpression("left", "document.body.scrollLeft + document.clientWidth / 2 - 160 + \"px\"");
		div.style.setExpression("top", "document.body.scrollTop + document.clientHeight / 2 - 30 + \"px\"");
	}
	document.body.appendChild(div);
}

function scrollToAnchor(aname)
{
	var As = document.getElementsByTagName("A");
	for (var i = 0; i < As.length; ++i)
	{
		var A = As[i];
		if (A.name == aname)
		{
			var pos = getElementPosition(A);
			var gotoY = pos[1] - 80;
			window.scroll(0, gotoY);
			if (isIE())
			{
				var div = document.getElementById("reactions_notification_div");
				if (div)
					div.style.top = gotoY + 10 + "px";
			}
			break;
		}
	}
}

function enableShowWhenParentHovered()
{
	var els = getElementsByClassName("showWhenParentHovered");
		
	for (var i = 0; i < els.length; ++i)
	{
		var el = els[i];
		var hovel = el.parentNode;
		var hovel_ifnotfound = hovel;
		while (hovel && !hovel.className.classExists("hoverParent"))
			hovel = hovel.parentNode;
		if (!hovel)
			hovel = hovel_ifnotfound;
		hovel.elementToShow = el;
		hovel.onmouseover = function() {
			this.elementToShow.className = this.elementToShow.className.addClass("active");
		}
		hovel.onmouseout = function() {
			this.elementToShow.className = this.elementToShow.className.removeClass("active");
		}
	}
}

function inheritLinks()
{
	var els = getElementsByClassName("inheritLink");
	for (var i = 0; i < els.length; ++i)
	{
		var el = els[i];
		var as = el.getElementsByTagName("a");
		if (as.length > 0)
		{
			var a = as[0];
			el.inheritedAnchor = a;
			el.onclick = function() {
				location.href = this.inheritedAnchor.href;
				return false;
			}
		}
	}
}
