/***********************************************
* Algemenen code voor de website, hierin staan de functies die worden gebruikt
	direct op de pagina of door een van de andere javafiles
***********************************************/

// convert all characters to lowercase to simplify testing
var agt=navigator.userAgent.toLowerCase();

// *** BROWSER VERSION ***
// Note: On IE5, these return 4, so use is_ie5up to detect IE5.
var is_major = parseInt(navigator.appVersion);
var is_minor = parseFloat(navigator.appVersion);

// Note: Opera and WebTV spoof Navigator.  We do strict client detection.
// If you want to allow spoofing, take out the tests for opera and webtv.
var is_nav  = ((agt.indexOf('mozilla')!=-1) && (agt.indexOf('spoofer')==-1)
				&& (agt.indexOf('compatible') == -1) && (agt.indexOf('opera')==-1)
				&& (agt.indexOf('webtv')==-1) && (agt.indexOf('hotjava')==-1));

var is_ie     = ((agt.indexOf("msie") != -1) && (agt.indexOf("opera") == -1));
var is_ie4up  = (is_ie && (is_major >= 4));

var is_ff		= (agt.indexOf("firefox/") != -1);
var is_ff1up	= (is_ff && (is_major >= 1));

var is_opera = (agt.indexOf("opera") != -1);
var is_opera2 = (agt.indexOf("opera 2") != -1 || agt.indexOf("opera/2") != -1);
var is_opera3 = (agt.indexOf("opera 3") != -1 || agt.indexOf("opera/3") != -1);
var is_opera4 = (agt.indexOf("opera 4") != -1 || agt.indexOf("opera/4") != -1);
var is_opera5 = (agt.indexOf("opera 5") != -1 || agt.indexOf("opera/5") != -1);
var is_opera6 = (agt.indexOf("opera 6") != -1 || agt.indexOf("opera/6") != -1);
var is_opera6less = (is_opera2 || is_opera3 || is_opera4 || is_opera5 || is_opera6);

var RootDir;
var winErrorWindow=null;
var ErrorHandeling;

function nKsetRoot(strDir) {
	RootDir = strDir;
}

function nKerror(strError) {
  if(winErrorWindow == null) {
   	OpenErrorWindow();
	}
	nKshowError(strError);
}

function OpenErrorWindow() {
	winErrorWindow = window.open('', 'Error Window', 'width=500,height=600,menubar=0,resizable=0,toolbar=0,titlebar=0');
}

function nKshowError(strMessage) {
 	winErrorWindow.document.write(strMessage);
}

function EndOfPage() {
	if(winErrorWindow !== null) {
		winErrorWindow.focus()
	}
}

function EmptyTbody(tBodyName) {
	var tbody = document.getElementById(tBodyName);
	if(tbody != null) {
		var bodyRows = tbody.rows;
		var nNbRows  = bodyRows.length;

		for (var nIndexRow=0 ; nIndexRow < nNbRows ; nIndexRow++) {
		   //bodyRows[0].removeNode(true); //-- 'removeNode' doesn't work with FireFox
		   tbody.removeChild(bodyRows[0]);
		}
	}
}

function emptyObj(Obj) {
//	window.alert('JA:' +Obj.innerHTML);
  if(Obj.hasChildNodes() && Obj.childNodes) {
    while(Obj.firstChild) {
      Obj.removeChild(Obj.firstChild);
    }
  }
}

function MakeBox(BoxObj, ID, Obj) {
	ContainerBox = document.getElementById(ID);
	if(ContainerBox) {
		ContainerBox.parentNode.removeChild(ContainerBox);
	}
	else {
		var ContainerBox = document.createElement('div');
		ContainerBox.id = ID;
		ContainerBox.onclick = function() {
			this.style.display = "none";
		}
		ContainerBox.style.position = 'absolute';
		ContainerBox.appendChild(BoxObj);
	 	var Parent = Obj.parentNode;
		var NextSibling = Obj.nextSibling;

		if(!NextSibling) {
			Parent.appendChild(ContainerBox);
		}
		else {
			Parent.insertBefore(ContainerBox, NextSibling);
		}
	}
}

function CreateBox(BoxName) {
  var divblock=document.createElement("div");
  divblock.setAttribute("id", BoxName);
  document.body.appendChild(divblock)
}

function CloseBox(BoxName) {
	var Parent=document.getElementById(BoxName).parentNode;
  var Box=document.getElementById(BoxName);
	Parent.removeChild(Box);
}

function ShowHideElement(ElementID, Image) {
	var Element = document.getElementById(ElementID);
	if(Element.style.display == "none") {
		Element.style.display = "block";
		Image.src = RootDir+"Img/up.png";
	}
	else {
		Element.style.display = "none";
		Image.src = RootDir+"Img/down.png";
	}
}

function nkReroute(Link, Value) {
	window.location = Link+Value;
}

function FillSelectXML(FieldName, XMLFile, ValueField, DisplayField) {
	if(!ValueField) {
   	var ValueField = 'link';
	}

	if(!DisplayField) {
   	var DisplayField = 'name';
	}

  getXmlHttpObject();

	var url=RootDir+XMLFile;
	var xmlDoc = loadXMLDoc(url);
	var x = xmlDoc.getElementsByTagName('menuitem');
  var List = document.getElementById(FieldName);
	List.innerHTML = "";

  for(i=0;i<x.length;i++) {
    var Name=x[i].getAttribute(DisplayField);
    var ID=x[i].getAttribute(ValueField);
    var Element = document.createElement('option');
  	Element.value = ID;
    Element.innerHTML = Name;
    List.appendChild(Element);
//		List.innerHTML += '<option value="'+i+'">'+Name+'</option>';
/*
    for(j=0;x[i].childNodes[j];j++) {
      var SubName= x[i].childNodes[j].getAttribute('name');
      if(j < 1) {
         window.alert(SubName);
      }
    }

*/
  }
}

function moveItemUp(elementName) {
  var element = document.getElementById(elementName);
  for(i = 0; i < element.options.length; i++) {
    if(element.options[i].selected == true) {
      if(i != 0) {
        var temp = new Option(element.options[i-1].text,element.options[i-1].value);
        var temp2 = new Option(element.options[i].text,element.options[i].value);
        element.options[i-1] = temp2;
        element.options[i-1].selected = true;
        element.options[i] = temp;
      }
    }
  }
}

function moveItemDown(elementName) {
  var element = document.getElementById(elementName);
  for(i = (element.options.length - 1); i >= 0; i--) {
    if(element.options[i].selected == true) {
      if(i != (element.options.length - 1)) {
        var temp = new Option(element.options[i+1].text,element.options[i+1].value);
        var temp2 = new Option(element.options[i].text,element.options[i].value);
        element.options[i+1] = temp2;
        element.options[i+1].selected = true;
        element.options[i] = temp;
      }
    }
  }
}

function RemovePage(elementName, removerLink) {
  var Confirmed = window.confirm('Weet u zeker dat u de geselecteerde pagina\'s wilt verwijderen');
	if(!Confirmed) {
	 return;
	}
  var element = document.getElementById(elementName);
	var PostData = '';
  for(var i=0;i<element.options.length; i++) {
		if(element.options[i].selected) {
	    PostData += 'pagesToRemove[]='+element.options[i].value+'&';
			removeObject(element.options[i]);
			i--;
		}
  }
	xmlHttp.open('POST', RootDir+'XML/menu.xml.php', true);
  xmlHttp.setRequestHeader("Content-type", "application/x-www-form-urlencoded");
  xmlHttp.setRequestHeader("Content-length", PostData.length);
  xmlHttp.setRequestHeader("Connection", "close");
  xmlHttp.send(PostData);

}

function selectAllOptions(name) {
  var selObj = document.getElementById(name)
  for (var i=0; i<selObj.options.length; i++) {
    selObj.options[i].selected = 'selected';
  }
}

function FillObj(ObjID, Value, XML) {
	var Object = document.getElementById(ObjID);
	if(!XML) {
	  Object.innerHTML = Value;
	}
	else {
	  getXmlHttpObject();

		var url=RootDir+XMLFile;
		var xmlDoc = loadXMLDoc(url);
	}
}

function GetValue(ObjID) {
	var HTMLObject = document.getElementById(ObjID);
	return HTMLObject.value;
}

var StartNumber = 0;

function ShowTable(ObjID, XMLFile, Fields, Elem, FieldHeaders, Max) {

	var HTMLObject = document.getElementById(ObjID);
  HTMLObject.innerHTML = "";
	var tbl     = document.createElement("table");
	tbl.border = "0";
	tbl.className = "XMLTable";
	var tblBody = document.createElement("tbody");
	var tblContent = document.createElement("tbody");
	var NumOfRows = Fields.length

	if(!Max) {
		Max = 20;
	}

	var row = document.createElement("tr");
	var cell = document.createElement("th");
	cell.onclick = function() {
    FillTable(XMLFile, Elem, Fields, tblContent, Max, -Max);
  };
	cell.id = "XMLPrev";
	var cellText = document.createTextNode('');
	cell.appendChild(cellText);
	row.appendChild(cell);

	for (var i = 0;i<NumOfRows; i++) {
		var cell = document.createElement("th");
		if(i < FieldHeaders.length) {
			var cellText = document.createTextNode(FieldHeaders[i]);
		}
		else {
			var cellText = document.createTextNode(' ');
		}
		cell.appendChild(cellText);
		row.appendChild(cell);
	}
	var cell = document.createElement("th");
//	cell.attachEvent('onclick', "FillTable('"+XMLFile+"', '"+Elem+"', Fields, 'TableXMLContent', "+Max+", "+Max+")");
	cell.onclick = function() {
    FillTable(XMLFile, Elem, Fields, tblContent, Max, Max);
  };
//  object.onchange =
	cell.id = "XMLNext";
	var cellText = document.createTextNode(' ');
	cell.appendChild(cellText);
	row.appendChild(cell);
	tblBody.appendChild(row);

	tblBody.appendChild(row);
	tbl.appendChild(tblBody);

	tblContent.id = "TableXMLContent";
	var row = document.createElement("tr");
	var cell = document.createElement("td");
	cell.colspan=Fields.length;
	cell.appendChild(cellText);
	row.appendChild(cell);
	tblContent.appendChild(row);
	tbl.appendChild(tblContent);

  HTMLObject.appendChild(tbl);

	if(!Max) {
		Max = 20;
	}

	FillTable(XMLFile, Elem, Fields, tblContent, Max, 0);
}

function FillTable(Source, Elem, Fields, ContainerObj, Max, Start) {
  getXmlHttpObject();
  emptyObj(ContainerObj);
	var url=RootDir+Source;
	var xmlDoc = loadXMLDoc(url);
	var x = xmlDoc.getElementsByTagName(Elem);

	StartNumber = StartNumber + Start;
	if(StartNumber > x.length) {
		StartNumber = Math.floor(x.length/Max)*Max;
	}

	if(StartNumber < 0) {
		StartNumber = 0
	}

	MaxNow = StartNumber + Max;
	if(x.length < MaxNow) {
		MaxNow = x.length;
	}
  for(i=StartNumber;i<MaxNow;i++) {
		var row = document.createElement("tr");
		var cell = document.createElement("td");
		var cellText = document.createTextNode(' ');
		cell.appendChild(cellText);
		row.appendChild(cell);
    for(j=0;j<Fields.length;j++) {
	    var CellContent = x[i].getAttribute(Fields[j]);
			var Cell = document.createElement("td");
			var cellText = document.createTextNode(CellContent);
			Cell.appendChild(cellText);
			row.appendChild(Cell);
    }
		var cell = document.createElement("td");
		var cellText = document.createTextNode(' ');
		cell.appendChild(cellText);
		row.appendChild(cell);
		ContainerObj.appendChild(row);
	}
	return;
}

function OpenWindowPopup(Url, Name, Top, Left, Width, Height, Refresh) {
	if(!Width) {
   	Width = 600;
	}
	if(!Height) {
		Height = 200;
	}

	if (Width == -2) {
		if (window.screen) {
			Width = screen.availWidth;
		}
	}
	if (Height == -2) {
		if (window.screen) {
			Height = screen.availHeight;
		}
	}

		var Feats = "toolbar=no,location=no,directories=no,status=no,menubar=no,scrollbars=no,resizable=yes,modal=yes";	// modal=yes does work sometimes :-)
		if(!Top) {
			if (window.screen) {
				var hght = Height;
				if (hght <= 0) {
					hght = screen.availHeight;
				}
				Feats = Feats+",top="+(screen.availHeight-hght)/2+"px";
			}
		}
		else {
			Feats = Feats+",top="+Top+"px";
		}
		if (!Left) {
			if (window.screen) {
				var wdt = Width;
				if (wdt <= 0) {
					wdt = screen.availWidth;
				}
				Feats = Feats+",left="+(screen.availWidth-wdt)/2+"px";
			}
		}
		else {
			Feats = Feats+",left="+Left+"px";
		}

		if (Width >= 0) {
			Feats = Feats+",width="+Width+"px";
		}
		else if (Width == -2) {
			Feats = Feats+",width=100%";
		}
		if (Height >= 0) {
			Feats = Feats+",height="+Height+"px";
		}
		else if (lHeight == -2) {
			Feats = Feats+",height=100%";
		}
 		var myWindow = window.open(Url,Name,Feats);
		if (!myWindow) {
			alert('Popup killer?');
			return;
		}
		if (!myWindow.opener) {
			myWindow.opener = self;
		}
}

function OpenModalDialog(Url, Name, Top, Left, Width, Height, Reload) {
	Height = Height || 500;
	if (Width == -2) {
		if (window.screen) {
			Width = screen.availWidth;
		}
	}
	if (Height == -2) {
		if (window.screen) {
			Height = screen.availHeight;
		}
	}
	if(CanDoModal()) {
		var Feats = "status:yes;help:no;center:yes;resizable:yes;";
		if (Top >= 0) {
			Feats = Feats+"dialogTop:"+Top+"px;";
		}
		else if (Top == -2) {
			Feats = Feats+"dialogTop:center;";
		}
		if (Left >= 0) {
			Feats = Feats+"dialogLeft:"+Left+"px;";
		}
		else if (Left == -2) {
			Feats = Feats+"dialogLeft:center;";
		}
		if (Width >= 0) {
			Feats = Feats+"dialogWidth:"+Width+"px;";
		}
		else if (Width == -2) {
			Feats = Feats+"dialogWidth:100%;";
		}
		if (Height >= 0) {
			Feats = Feats+"dialogHeight:"+Height+"px;";
		}
		else if (Height == -2) {
			Feats = Feats+"dialogHeight:100%;";
		}
		myWindow = showModalDialog(Url,self,Feats);
    if(Reload == true) {
      history.go(0)
    }
	}
	else {
		OpenWindowPopup(Url, Name, Top, Left, Width, Height);
	}
}

function DisableField(ObjID, OwnObj) {
  var RelativeField = document.getElementById(ObjID);
  if(OwnObj.value == "") {
    RelativeField.value = "";
    RelativeField.disabled = false;
  }
  else {
    RelativeField.disabled = true;
  }
}

function CanDoModal() {
	if (is_opera6less) {
		return false;
	}
	if (typeof(showModalDialog) == "undefined") {
		return false;
	}
	return true;
}

function closeThis(elementID) {
	var elementToClose = document.getElementById(elementID)
	if(elementToClose) {
		removeObject(elementToClose);
	}
//  QuitEvent(evt);
}

function QuitEvent(evt) {
	evt = evt || window.event;
	try {
		evt.stopPropagation();			// Firefox
	}
	catch(e) {
		evt.cancelBubble = true;		// Internet Explorer
	}
}

function loadXMLDoc(dname) {
	var xmlDoc;

	// code for IE
	if (window.ActiveXObject) {
		xmlDoc=new ActiveXObject("Microsoft.XMLDOM");
		xmlDoc.async="false";
	} // code for Mozilla, Firefox, Opera, etc.
	else if (document.implementation && document.implementation.createDocument) {
		xmlDoc=document.implementation.createDocument("","",null);
		xmlDoc.async=false;
	}
	else {
		alert('Your browser cannot handle this script');
	}
	xmlDoc.load(dname);

	return xmlDoc;
}

function closePopBox() {
	var popBox = document.getElementById('popBox')
	if(popBox) {
	  removeObject(popBox);
	}
}

function cancelEvent(oEvent) {
	oEvent = oEvent || window.event;
	try {
		oEvent.stopPropagation();			// Firefox
		oEvent.preventDefault();			// Firefox
	}
	catch(e) {
		oEvent.cancelBubble = true;		// Internet Explorer
	   oEvent.returnValue = false;
	}
}

function removeObject(objToRemove) {
	var Parent = objToRemove.parentNode;
	Parent.removeChild(objToRemove);
}

function addEventHandler(oTarget, sEventType, fnHandler) {
    if (oTarget.addEventListener) {
        oTarget.addEventListener(sEventType, fnHandler, false);
    } else if (oTarget.attachEvent) {
        oTarget.attachEvent("on" + sEventType, fnHandler);
    } else {
        oTarget["on" + sEventType] = fnHandler;
    }
}

function setError(field) {
	if(!document.getElementById(field.id+'Error')) {
		var errorPic = document.createElement('img');
		errorPic.src = RootDir+'Images/Default/error.png';
		errorPic.id = field.id+'Error';
		field.parentNode.appendChild(errorPic);
		if(field.errorMessage) {
			var tableRow = document.createElement('tr');
			var tableCell = document.createElement('td');
			tableCell.colspan = 2;
			var message = document.createTextNode(field.errorMessage);
			tableCell.appendChild(message);
			tableRow.appendChild(tableCell);
//			window.alert(field.parentNode.parentNode.nextSibling.innerHTML);
//			field.parentNode.parentNode.insertBefore(tableRow, field.parentNode.parentNode.nextSibling);
		}
	}
}

function unsetError(field) {
	var errorPic = null;
	if(errorPic=document.getElementById(field.id+'Error')) {
		removeObject(errorPic);
	}
}

function getFieldValue(field) {
	unsetError(field);
	if(field.value == '' && field.obligatorily) {
		setError(field);
		return false;
	}
	else if(field.controlFunction) {
		strExec = field.controlFunction+'(\''+field.value+'\');';
  	if(eval(strExec) !== true) {
      setError(field);
			return false;
		}
	}

	return true;
}

function checkSecCode(insertedSecCode) {
	var secCode =	getCookie('securityCode');
	if(secCode.toLowerCase() == insertedSecCode.toLowerCase()) {
	 	return true;
	}
	return false;
}

function searchLink(oEvent) {
	oEvent = oEvent || window.event;
	var clickedObj = oEvent.srcElement;
	if(oEvent.target) {
		var clickedObj = oEvent.target;
	}
	searchBox('Link zoeken', searchContent(), clickedObj, 400);
}

function showLink(id, fieldID) {
	var field = document.getElementById(fieldID);
	field.value = RootDir+'?Page'+id;
	return;
}

function handleKey(oEvent) {
    window.alert('fdfds'+oEvent.keyCode);
}

function print_r(theObj){
  if(theObj.constructor == Array ||
     theObj.constructor == Object){
    document.write("<ul>")
    for(var p in theObj){
      if(theObj[p].constructor == Array||
         theObj[p].constructor == Object){
document.write("<li>["+p+"] => "+typeof(theObj)+"</li>");
        document.write("<ul>")
        print_r(theObj[p]);
        document.write("</ul>")
      } else {
document.write("<li>["+p+"] => "+theObj[p]+"</li>");
      }
    }
    document.write("</ul>")
  }
}

function htmlentities( s ){
    // http://kevin.vanzonneveld.net
    // +   original by: Kevin van Zonneveld (http://kevin.vanzonneveld.net)
    // *     example 1: htmlentities('Kevin & van Zonneveld');
    // *     returns 1: 'Kevin &amp; van Zonneveld'
   window.alert(s);
    var div = document.createElement('div');
    var text = document.createTextNode(s);
    div.appendChild(text);
    return div.innerHTML;
}

function is_string(inputVar){
     return (typeof(inputVar) == 'string');
}