var d = document;
// meerdere onloads handelen
function addOnload(newFunction) {
	var oldOnload = window.onload;
	if (typeof oldOnload == "function") {
		window.onload = function() {
			if (oldOnload) {oldOnload();}
			newFunction();
		}
	} else {window.onload = newFunction;} 
}

// x-browser events koppelen
function addEvent(obj, evType, fn, useCapture){
	if (obj.addEventListener){
		obj.addEventListener(evType, fn, useCapture);
		return true;
	} else if (obj.attachEvent){
		var r = obj.attachEvent("on"+evType, fn);
		return r;
	} else {
		// alert("Handler could not be attached");
	}
}

function array_search(key, haystack) {
	for(var i in haystack) {
		if(haystack[i] == key) return i; 
	}
	return false;
};

function addTargets() {
	var a = d.getElementsByTagName('a');
	for (var i = 0, aL = a.length; i < aL; i++) {
		if (a[i].rel && !a[i].target) {
			a[i].target = a[i].rel;
		}
	}
}
// addOnload(addTargets);

// xml-http-request-object
var xhr = {
	req : false, url : '', responseHandler : '', sendString : '', sendMethod : 'post', async : true, action : 'json',
	init : function() {
		if(window.XMLHttpRequest) {
	    	try {this.req = new XMLHttpRequest();} catch(e) {this.req = false;}
	    } else if(window.ActiveXObject) {try {this.req = new ActiveXObject("Msxml2.XMLHTTP");
	      	} catch(e) {try {this.req = new ActiveXObject("Microsoft.XMLHTTP");} catch(e) {this.req = false;}}
	    }
	},
	run : function () {
		if (this.req) {
			this.req.open(this.sendMethod, this.url, this.async);
			this.req.onreadystatechange = this.responseHandler;
			this.req.setRequestHeader('Content-Type', 'application/x-www-form-urlencoded');
			this.req.send(this.action + '=' + this.sendString);
		}
	}
};

function haalNieuwe (divIDs, nSec) {
	var myReq = xhr;
	myReq.responseHandler = handleResponse;
	myReq.url = 'http://' + location.hostname + '/_xhr/haalnieuwe.php';
	myReq.init();

	this.handle = null;
	this.startTimer = function () {
		this.handle = setInterval(function(obj) {
			return(function() {
				obj.doe();
			});
		}(this), (nSec * 1000));
	};
	
	this.doe = function () {
		var JSONobject = new Object();
		JSONobject.tsSinds = tsSinds;
		JSONobject.nu = new Date().getTime();
		myReq.sendString = JSON.stringify(JSONobject);
		myReq.action = 'haalNieuwe';
		myReq.run();
	};
	
	function handleResponse () {
		if(myReq.req.readyState == 4 && myReq.req.status == 200) {
			var JSONtext = myReq.req.responseText;
			var JSONobject = JSON.parse(JSONtext);
			if(JSONobject.ok) {
				for (var i in divIDs) {
					if (JSONobject[divIDs[i]] != false)
						d.getElementById(divIDs[i]).innerHTML = JSONobject[divIDs[i]] + d.getElementById(divIDs[i]).innerHTML;
				}
				tsSinds = JSONobject.tsNieuwste;
				var ids = JSONobject.arrIDs;
				if (ids.length > 0) {
					var m = d.title.match(/^\((\d+)\)(.*?)$/);
					document.title = m ? "(" + (parseInt(m[1])+ids.length) +")" + m[2] : "(" + ids.length + ") " + d.title;
				}
				for (var i in ids) {
					animatedcollapse.addDiv(ids[i]);
				}
				animatedcollapse.init();
				animatedcollapse.show(ids);
			} else {
				toonAjaxbericht('Geen nieuwe tweets.', 2);
			}
		}
	};
}

function haalEenTweet(twID, divID) {
	var myReq = xhr;
	myReq.responseHandler = handleResponse;
	myReq.divID = divID;
	myReq.url = 'http://' + location.hostname + '/_xhr/haalEenTweet.php';
	myReq.init();

	var JSONobject = new Object();
	JSONobject.id = twID;
	myReq.sendString = JSON.stringify(JSONobject);
	myReq.action = 'haalTweet';
	myReq.run();
	
	function handleResponse () {
		if(myReq.req.readyState == 4 && myReq.req.status == 200) {
			var JSONtext = myReq.req.responseText;
			var JSONobject = JSON.parse(JSONtext);
			d.getElementById(myReq.divID).innerHTML = JSONobject.tweet;
		}
	};
	return false;
}

// boxje voor (ajax)feedback
var berichtbox, to;
function toonAjaxbericht(bericht, duur) {
	berichtbox = d.getElementById('ajaxbericht');
	if (!berichtbox) {
		var nwEl = d.createElement('div');
		nwEl.id = 'ajaxbericht';
		berichtbox = d.body.appendChild(nwEl);
	}
	clearTimeout(to);
	berichtbox.innerHTML = bericht;
	var y = d.documentElement ? d.documentElement.scrollTop : d.body.scrollTop;
	berichtbox.style.top = y + 'px';
	berichtbox.style.display = 'block';
	if (duur > 0) {
		to = setTimeout('berichtbox.style.display="none"', duur*1000);
	}
}

// tabbladfunctionaliteit
var Tabjes = function(arrIDs, defTabID, tabmenuID) {
	var arrIDs = arrIDs, defTabID = defTabID, tabmenuID = tabmenuID;
	this.arrTabs = new Array();
	this.arrLinks = new Array();
	for (var i = 0, id; (id = arrIDs[i]); i++ ) {
		this.arrTabs.push(id);
	}
	// object krijgt id's van divs als argumenten, in array. defTabID is van de defaulttab
	var defTabLink, dataDivID, selfObj = this;
	var init = function() {
		var lis = d.getElementById(tabmenuID).getElementsByTagName('li');
		for (var i = 0, id; (id = arrIDs[i]); i++ ) {
			addEvent(lis[i].getElementsByTagName('a')[0], 'click', function(e) {
				e = e || window.event;
				if (e && e.preventDefault) e.preventDefault();
				else e.returnValue = false;
				selfObj.toonTab(e.target || e.srcElement);
			});
			if (id == defTabID) {
				defTabLink = lis[i].getElementsByTagName('a')[0];
				dataDivID = id;
			}
		}
		selfObj.toonTab(defTabLink, dataDivID);
		selfObj.setLinks(tabmenuID);
	};
	addOnload(init);
}
Tabjes.prototype.setLinks = function(lijstID) {
	this.arrLinks = d.getElementById(lijstID).getElementsByTagName('a');
};
Tabjes.prototype.toonTab = function (pLink, dataDivID) {
	if (typeof(dataDivID) == 'undefined') {
		var e = window.event || function(cx) {
			if(typeof Event!="undefined" && cx){
				for(var ii=0; ii<cx.arguments.length; ii++)
					if(cx.arguments[ii] instanceof Event)
						return cx.arguments[ii];
				return arguments.callee(cx.caller);
			}
			return null;
		}(arguments.callee.caller);
		var targ = e.target ? e.target : e.srcElement;
		if (targ.nodeType == 3) // defeat Safari bug
			targ = targ.parentNode;
		var dataDivID = this.arrTabs[array_search(targ, this.arrLinks)];
	}
	for (var i = 0, L = this.arrTabs.length; i < L; i++) { 
		d.getElementById(this.arrTabs[i]).style.display = 'none';
	}
	d.getElementById(dataDivID).style.display = 'block';
	for (var i = 0, L = this.arrLinks.length; i < L; i++) {
		this.arrLinks[i].className = 'taboff';
	}
	pLink.className = 'tabon';
};

// JSON stuff, minified
if(!this.JSON){JSON={};}
(function(){function f(n){return n<10?'0'+n:n;}
if(typeof Date.prototype.toJSON!=='function'){Date.prototype.toJSON=function(key){return this.getUTCFullYear()+'-'+
f(this.getUTCMonth()+1)+'-'+
f(this.getUTCDate())+'T'+
f(this.getUTCHours())+':'+
f(this.getUTCMinutes())+':'+
f(this.getUTCSeconds())+'Z';};String.prototype.toJSON=Number.prototype.toJSON=Boolean.prototype.toJSON=function(key){return this.valueOf();};}
var cx=/[\u0000\u00ad\u0600-\u0604\u070f\u17b4\u17b5\u200c-\u200f\u2028-\u202f\u2060-\u206f\ufeff\ufff0-\uffff]/g,escapable=/[\\\"\x00-\x1f\x7f-\x9f\u00ad\u0600-\u0604\u070f\u17b4\u17b5\u200c-\u200f\u2028-\u202f\u2060-\u206f\ufeff\ufff0-\uffff]/g,gap,indent,meta={'\b':'\\b','\t':'\\t','\n':'\\n','\f':'\\f','\r':'\\r','"':'\\"','\\':'\\\\'},rep;function quote(string){escapable.lastIndex=0;return escapable.test(string)?'"'+string.replace(escapable,function(a){var c=meta[a];return typeof c==='string'?c:'\\u'+('0000'+a.charCodeAt(0).toString(16)).slice(-4);})+'"':'"'+string+'"';}
function str(key,holder){var i,k,v,length,mind=gap,partial,value=holder[key];if(value&&typeof value==='object'&&typeof value.toJSON==='function'){value=value.toJSON(key);}
if(typeof rep==='function'){value=rep.call(holder,key,value);}
switch(typeof value){case'string':return quote(value);case'number':return isFinite(value)?String(value):'null';case'boolean':case'null':return String(value);case'object':if(!value){return'null';}
gap+=indent;partial=[];if(Object.prototype.toString.apply(value)==='[object Array]'){length=value.length;for(i=0;i<length;i+=1){partial[i]=str(i,value)||'null';}
v=partial.length===0?'[]':gap?'[\n'+gap+
partial.join(',\n'+gap)+'\n'+
mind+']':'['+partial.join(',')+']';gap=mind;return v;}
if(rep&&typeof rep==='object'){length=rep.length;for(i=0;i<length;i+=1){k=rep[i];if(typeof k==='string'){v=str(k,value);if(v){partial.push(quote(k)+(gap?': ':':')+v);}}}}else{for(k in value){if(Object.hasOwnProperty.call(value,k)){v=str(k,value);if(v){partial.push(quote(k)+(gap?': ':':')+v);}}}}
v=partial.length===0?'{}':gap?'{\n'+gap+partial.join(',\n'+gap)+'\n'+
mind+'}':'{'+partial.join(',')+'}';gap=mind;return v;}}
if(typeof JSON.stringify!=='function'){JSON.stringify=function(value,replacer,space){var i;gap='';indent='';if(typeof space==='number'){for(i=0;i<space;i+=1){indent+=' ';}}else if(typeof space==='string'){indent=space;}
rep=replacer;if(replacer&&typeof replacer!=='function'&&(typeof replacer!=='object'||typeof replacer.length!=='number')){throw new Error('JSON.stringify');}
return str('',{'':value});};}
if(typeof JSON.parse!=='function'){JSON.parse=function(text,reviver){var j;function walk(holder,key){var k,v,value=holder[key];if(value&&typeof value==='object'){for(k in value){if(Object.hasOwnProperty.call(value,k)){v=walk(value,k);if(v!==undefined){value[k]=v;}else{delete value[k];}}}}
return reviver.call(holder,key,value);}
cx.lastIndex=0;if(cx.test(text)){text=text.replace(cx,function(a){return'\\u'+
('0000'+a.charCodeAt(0).toString(16)).slice(-4);});}
if(/^[\],:{}\s]*$/.test(text.replace(/\\(?:["\\\/bfnrt]|u[0-9a-fA-F]{4})/g,'@').replace(/"[^"\\\n\r]*"|true|false|null|-?\d+(?:\.\d*)?(?:[eE][+\-]?\d+)?/g,']').replace(/(?:^|:|,)(?:\s*\[)+/g,''))){j=eval('('+text+')');return typeof reviver==='function'?walk({'':j},''):j;}
throw new SyntaxError('JSON.parse');};}})();