var isNS4 = (document.layers) ? true : false;
var isIE4 = (document.all && ! document.getElementById) ? true : false;
var isIE5 = (document.all && document.getElementById) ? true : false;
var isNS6 = (!document.all && document.getElementById) ? true : false;
var isIE5Mac = (navigator.userAgent.indexOf("Mac") != -1 && isIE5);
var debugMode = false;
var deb = new scriptDebugger();
var fades = new Array();
var fadeCounter = 0;
var newWindow;
var intraWindow;

function openIntranet(){
	intraWindow = window.open("https://carriereswitch-nl.ssl.eatserver.nl/", "intraWindow", "menubar=no, loaction=no, resizable=yes, status=yes, toolbar=no");
}

function openLink(url){
	newWindow = window.open(url);
}

function printDocument(url){
	var printQuery = url.indexOf("?") == -1 ? "?print=true" : "&print=true";
	this.printWindow = window.open(url + printQuery, "printWindow", "width=800,height=600,status=no,resizable=yes,scrollbars=yes");
}

function trim(str){
	if(typeof str == "string" && str != ""){
		return(str.match(/^\s*(\S*(\s+\S*)*)\s*$/)[1]);
	}
	return("");
}

function getDOMObject(str){
  if (document.all){
    return(document.all[str]);
  }else if (document.getElementById) {
    return(document.getElementById(str));
  }
}

function inArray(needle, haystack){
	for(var i in haystack){
		if(needle == haystack[i]){
			return(true);
		}
	}
	return(false);
}

function getStyle(el,styleProp)
{
	var x = getDOMObject(el);
	if (x.currentStyle)
		var y = x.currentStyle[styleProp];
	else if (window.getComputedStyle)
		var y = document.defaultView.getComputedStyle(x,null).getPropertyValue(styleProp);
	return y;
}

function setOpacity(id, x){

	if(getDOMObject(id).filters && getDOMObject(id).filters.alpha){
		getDOMObject(id).filters.alpha.opacity = x;
		return(true);
	}
	if(getDOMObject(id).style.opacity != null){
		getDOMObject(id).style.opacity = 0.01 * x;
		return(true);
	}

//	return(getDOMObject(id).setOpacity(x));
}

function getNewFadeId(){
	fadeCounter += 1;
	fades[fadeCounter] = true;
	return(fadeCounter);
}

function cancelFade(id){
	fades[id] = false;
}

function fadeOut(layer, x, step, fadeId){
	if(fades[fadeId]){
		if(!(x < 0) && setOpacity(layer, x)){
			x -= step;
			window.setTimeout("fadeOut(\"" + layer + "\", " + x + ", " + step + ", " + fadeId + ")", 40);
		}else{
			setOpacity(layer, 0);
			getDOMObject(layer).style.visibility = "hidden";
			setOpacity(layer, 100);
		}
	}
}

function getDOMX(id){
	var x = 0;
	if(getDOMObject(id)){
	// nn4up ---------------
		if (isNS4){
			if ( getDOMObject(id) != window )			x = getDOMObject(id).pageX;
		}
	// gk, iemac, iewin ---------------
		else{
			currentX = 0;
			if ( getDOMObject(id).offsetParent ){
				object = getDOMObject(id);
				while ( object.offsetParent ){
					currentX += object.offsetLeft;
					object = object.offsetParent;
				}
			}else if ( getDOMObject(id).x ){
				currentX += getDOMObject(id).x;
			}
			x = currentX;
			if (isIE5Mac){
				x += parseInt( "0" + document.body.currentStyle.marginLeft, 10  );
			}
		}
	}
	return x;
}

function getDOMY(id){
	var x = 0;
	if(getDOMObject(id)){
	// nn4up ---------------
		if (isNS4){
			if ( getDOMObject(id) != window )			x = getDOMObject(id).pageY;
		}
	// gk, iemac, iewin ---------------
		else{
			currentX = 0;
			if ( getDOMObject(id).offsetParent ){
				object = getDOMObject(id);
				var IECorrection = 0;
				while ( object.offsetParent ){
					currentX += object.offsetTop;
					object = object.offsetParent;
				}
			}else if ( getDOMObject(id).y ){
				currentX += getDOMObject(id).y;
			}
			x = currentX;
			if ( isIE5Mac){
				x += parseInt( "0" + document.body.currentStyle.marginLeft, 10  );
			}
		}
	}
	return x;
}

function getWindowHeight(){
	if(window.innerHeight){
		return(window.innerHeight);
	}else{
		if(document.documentElement.clientHeight){
			return(document.documentElement.clientHeight);
		}else{
			return(document.body.offsetHeight);
		}
	}
}

function getWindowWidth(){
	if(window.innerWidth){
		return(window.innerWidth);
	}else{
		if(document.documentElement.clientWidth){
			return(document.documentElement.clientWidth);
		}else{
			return(width = document.body.offsetWidth);
		}
	}
}

function scriptDebugger(){
  this.anchorIndex = 0;
  if(debugMode){
    this.debugWindow = window.open("", "debugWindow", "width=400,height=350,status=no,resizable=yes,scrollbars=yes");
	  this.debugWindow.document.write("<html><body>\n");
	}
	
	this.alert = function(str){
	  if(debugMode){
	    this.anchorIndex++;
		  this.debugWindow.document.write("<a name=\"" + this.anchorIndex + "\"></a>" + str + "<br>\n");
			this.debugWindow.scrollTo(0, 10000);
		}
	}
	
	this.evtAlert = function(str){
	  if(debugMode){
	    this.anchorIndex++;
	    this.debugWindow.document.write("<a name=\"" + this.anchorIndex + "\"></a><font color=\"#ff0000\">" + str + "</font><br>\n");
			this.debugWindow.scrollTo(0, 10000);
		}
	}
}


function StretchDiv(DomId, top, right, bottom, left){
	this.id = DomId;
	this.t = top;
	this.r = right;
	this.b = bottom;
	this.l = left;
  	this.stretchX = !(left < 0 || right < 0);
	this.stretchY = !(top < 0 || bottom < 0);
	this.showId = function(){
		alert(this.id);
	}
 
	this.setMargins = function(top, right, bottom, left){
		this.t = top;
		this.r = right;
		this.b = bottom;
		this.l = left;
		this.stretchX = !(left == "" || right == "");
		this.stretchY = !(top == "" || bottom == "");
		if(getDOMObject(this.id).style.left){
			getDOMObject(this.id).style.left = left.toString() + "px";
		}else{
			getDOMObject(this.id).style.right = right.toString() + "px";
		}
		if(getDOMObject(this.id).style.top){
			getDOMObject(this.id).style.top = top.toString() + "px";
		}else{
			getDOMObject(this.id).style.bottom = bottom.toString() + "px";
		}
		this.stretch();
	}

	this.stretch = function(){
		var width, height, additional;
		additional = 0;
		additional += ((navigator.appVersion.indexOf("MSIE") != -1) && (navigator.appVersion.indexOf("MSIE 8") == -1)) ? -4 : 0;
		if(this.stretchX){
			width = getWindowWidth() - (this.l + this.r) + additional;
			getDOMObject(this.id).style.width = width.toString() + "px";
		}
		if(this.stretchY){
			height = getWindowHeight() - (this.t + this.b) + additional;
			getDOMObject(this.id).style.height = height.toString() + "px";
		}
		return(true);
	}

	this.addToEventList = function(x){
		var oldHandler = window.onresize;
		function newHandler(){
			x.stretch();
		}
		if(oldHandler){
			window.onresize = function(){ oldHandler(); newHandler(); };
		}else{
			window.onresize = function(){ newHandler(); };
		}
	}
  
	this.addToEventList(this);
	this.stretch();
}

function alertItems(name){
	var items = menuHandler.getItemsByUrl(name);
	var s = "";

	if(items.length == 0){
		alert("lege array");
	}else{
		for(var i in items){
			s = items[i].getText() + "\n";
		}
		alert(s);
	}

}

if(navigator.appVersion.indexOf("MSIE") == -1){
	Element.prototype.fadeStart = -1;
	Element.prototype.fadeEnd = 0;
	Element.prototype.fadeStep = 5;
	Element.prototype.isFading = false;
	
	Element.prototype.setOpacity = function(opacity){
		if(this.filters && this.filters.alpha){
			this.filters.alpha.opacity = opacity;
			return(true);
		}
		if(this.style.opacity != null){
			this.style.opacity = 0.01 * opacity;
			return(true);
		}
		return(false);	
	}
	
	Element.prototype.getOpacity = function(){
		if(this.filters && this.filters.alpha){
			return(this.filters.alpha.opacity);
			}
		if(this.style.opacity){
			return(this.style.opacity * 100);
		}
		return(100);
	}
	
	Element.prototype.fade = function(start, end, step){
		this.fadeStart = start;
		this.fadeEnd = end;
		this.fadeStep = step;
		if(!this.isFading){
			this.isFading = true;
			this._fader(this);
		}
	}

	Element.prototype.fadeTo = function(opacity, step){
		this.fadeEnd = opacity;
		this.fadeStep = step;
		this.fadeStart = this.getOpacity();
		deb.alert("fadeTo: fading: " + this.isFading + " start: " + this.fadeStart + " end: " + this.fadeEnd);
		if(!this.isFading){
			this.isFading = true;
			this._fader();
		}
		return(true);
	}

	Element.prototype._fader = function(){
		var me = this;
		if(this.fadeStart == this.fadeEnd){
			this.isFading = false;
		}else{
			if(this.fadeStart > this.fadeEnd){
				this.fadeStart -= this.fadeStep;
				if(this.fadeStart < this.fadeEnd){
					this.fadeStart = this.fadeEnd;
				}
			}else{
				this.fadeStart += this.fadeStep;
				if(this.fadeStart > this.fadeEnd){
					this.fadeStart = this.fadeEnd;
				}
			}
			this.setOpacity(this.fadeStart);
			window.setTimeout(function (){ me._fader() }, 40);
		}
	}
}

if(String){

	String.prototype.pixelsToNumerical = function() {
		if(!this.match(/^[0-9]+px$/)){
			return(null);
		}
		var numericalString = this.substr(0, this.length - 2);
		return(Number(numericalString));
	}
	
}
	
function collapseSelection(){
	try{
		if(window.getSelection().collapseToStart){
			window.getSelection().collapseToStart();
		}
		if(window.getSelection().empty){
			window.getSelection().emty();
		}
	}catch(e){window.status = ("Probeer eens een echte browser, zoals Firefox!");}
}

function getLabelForElement(id){
	var labels = document.getElementsByTagName("label");
	if(labels.length != 0){
		for(var i in labels){
			if(labels[i].htmlFor == id){
				return(labels[i]);
			}
		}
	}else{
		return(null);
	}
	return("onbekend");
}

function FormValidator(formName, callWhenValidated){
	this.formName = formName;
	this.items = new Array();
	this.callWhenValidated = callWhenValidated;
	
	
	this.addItem = function(id, obligatory, regExp, maxLength){
		var label = getLabelForElement(id);
		if(label != null){
			var name = label.innerHTML;
		}
		this.items.push({"element" : document.getElementById(id), "id" : id, "label" : label, "name" : name, "obligatory" : obligatory, "regExp" : regExp, "maxLength" : maxLength});
	}
	
	this.validate = function(){
		var item;
		var showAlert = false;
		var alertString = "";
		for(var i in this.items){
			var item = this.items[i];
			item.label.className = "captionNormal";
			if(item.obligatory && item.element.value.length == 0){
				alertString += "Geen waarde ingevuld voor " + item.name + "\n";
				item.label.className = "captionHighlight";
				showAlert = true;
			}else if(item.element.value.length > item.maxLength){
				alertString += "Te lange tekst gebruikt bij " + item.name + "\n";
				item.label.className = "captionHighlight";
				item.element.value = item.element.value.substring(0, item.maxLength);
				showAlert = true;
			}else if(!(item.element.value.match(item.regExp) || item.element.value.length == 0)){
				alertString += "Ongeldige waarde ingevuld bij " + item.name + "\n";
				item.label.className = "captionHighlight";
				showAlert = true;
			}
		}
		if(showAlert){
			alert(alertString);
			return(false);
		}
		if(this.callWhenValidated != null){
			return(this.callWhenValidated(this.formName));
		}
		return(true);
	}
	
	if(document.getElementById(this.formName).onsubmit == null || document.getElementById(this.formName).onsubmit == ""){
		document.getElementById(this.formName).setAttribute("onsubmit", "return(" + this.formName + "Validator.validate());");
	}
}

function MultipleSelector(id){
	this.id = id;
	this.poolId = id + "Pool";
	this.pool = getDOMObject(this.poolId);
	this.selectionId = id + "Selection";
	this.selection = getDOMObject(this.selectionId);
	this.buttonId = id + "MoveButton";
	this.button = getDOMObject(this.buttonId);
	this.direction = "right";
	var buttonExtension = document.getElementById(this.buttonId).src.match(/\.([a-z]{3})$/)[1];
	this.leftArrow = new Image();
	this.leftArrow.src = "/images/l-arr." + buttonExtension;
	this.rightArrow = new Image();
	this.rightArrow.src = "/images/r-arr." + buttonExtension;

	
	this.click = function(e){
		var sourceChildren, i, j, option;
		var moveOptions = new Array();
		var selectedOptions = new Array();
		if(this.direction == "right"){
			sourceChildren = this.pool.childNodes;
			destination = this.selection;
		}else{
			sourceChildren = this.selection.childNodes;
			destination = this.pool;
		}
		for(i in sourceChildren){
			option = sourceChildren[i];
			if(option && option.nodeType && option.nodeType == 1 && option.selected){
				moveOptions.push(option);
//				destination.appendChild(option);
				option.selected = false;
			}
		
		}
		for(i in moveOptions){
			destination.appendChild(moveOptions[i]);
		}
		this.sort(destination);
		for(i in this.selection.childNodes){
			child = this.selection.childNodes[i];
			if(child && child.nodeType && child.nodeType == 1 && child.nodeName.toLowerCase() == "option" && child.parentNode.id == this.selectionId){
				option = "'" + escape(child.value) + "'";
				if(!inArray(option, selectedOptions)){
					selectedOptions.push(option);
				}
			}
		}
		document.getElementById(this.id).value = selectedOptions.join(",");
		e.stopPropagation();
	}
	
	this.sort = function(node){
		var sortArray = new Array();
		var row = new Array();
		var child;
		var sortData = new Array();
		while(child = node.firstChild){
			if(child && child.nodeType == 1 && child.nodeName.toLowerCase() == "option"){
				row["value"] = child.innerHTML;
				row["node"] = child;
				sortArray.push(this.optionArray(child));
			}
			node.removeChild(child);
		}
		sortArray.sort(this.sortByValue);
		for(var i in sortArray){
			node.appendChild(sortArray[i]["node"]);
		}
	}
	
	this.optionArray = function(node){
		var row = new Array();
		row["node"] = node;
		if(node.firstChild && node.firstChild.nodeType == 3){
			row["value"] = node.firstChild.nodeValue;
		}else{
			return(null);
		}
		return(row);
	}
	
	this.sortByValue = function(a, b){
		a = a["value"].toLowerCase();
		b = b["value"].toLowerCase();
		return((a < b) ? -1 : (a > b) ? 1 : 0);
	}
	
	this.leftFocus = function(e){
		this.direction = "right";
		this.button.src = this.rightArrow.src;
	}
	
	this.rightFocus = function(e){
		this.direction = "left";
		this.button.src = this.leftArrow.src;
	}
	
	connect(this.button, "onclick", this, this.click);
	connect(this.pool, "onfocus", this, this.leftFocus);
	connect(this.selection, "onfocus", this, this.rightFocus);
}

function DataView(url, targetId, additionalFunctionCall){
	this.url = url;
	this.targetId = targetId;
	this.query = "";
	this.req = null;
	this.additionalFunctionCall = additionalFunctionCall;
	
	this.show = function(id){
		this.req = getXMLHttpRequest();
		this.req.open("GET", this.url + "?id=" + id, true);
		this.req.setRequestHeader("Cookie", document.cookie);
		this.deferred = sendXMLHttpRequest(this.req);
		this.deferred.addCallback(bind(this.populateTarget, this));
		this.deferred.addErrback(bind(this.loadError, this));
	}
	
	this.populateTarget = function(data){
		data = evalJSONRequest(data);
		if(data.error){
			alert(data.errorMessage); // TODO eigen popupsysteem gebruiken
		}
		document.getElementById(this.targetId).innerHTML = data.html;
		try{
			this.additionalFunctionCall(data);
		}catch(e){
			deb.alert("Dataview: Functie kon niet aangeroepen worden.\n" + e);
		}
	}
	
	this.loadError = function(error){
		alert("ERROR: " + error); // TODO eigen popupsysteem gebruiken
		document.getElementById(this.targetId).innerHTML = "ERROR:<br/>" + error;
	}
}

//document.onclick = blurClicked;

function blurClicked(e){
	if(e.target.blur){
		e.target.blur();
	}
}

function updateAds(){
	var iFrames = document.getElementsByTagName("iframe");
//	iFrames[0].contentWindow.location.reload(true);
	window.frames[0].reload(true);
	return(true);
}

function init(){
	docInit();
	
//	createLoggingPane();
//	alert(window.getComputedStyle(getDOMObject("menu"), null).width);
}