var xmlHttp = false;
var selectGroup = null;

if (document.images)
{
  pic1= new Image(); 
  pic1.src="../images/menubg.png"; 
  pic2 = new Image();
  pic2.src="../images/lia.gif";
  pic3 = new Image();
  pic3.src="../images/liahover.gif";
}

function GetXmlHttpObject()
{
	var xmlHttp=null;
	try{
		// Firefox, Opera 8.0+, Safari
		xmlHttp=new XMLHttpRequest();
	}
	catch(e){
		// Internet Explorer
		try{
			xmlHttp=new ActiveXObject("Msxml2.XMLHTTP");
		}catch (e){
			xmlHttp=new ActiveXObject("Microsoft.XMLHTTP");
		}
	}
	return xmlHttp;
}

/********************/
/* BEGIN PROTOTYPES */
/********************/
String.prototype.unescHtml = function(){
	var i,e={'&lt;':'<','&gt;':'>','&amp;':'&','&quot;':'"'},t=this; for(i in e) t=t.replace(new RegExp(i,'g'),e[i]);
	return t;
}
String.prototype.escHtml = function(){
	var i,e={'&':'&amp;','<':'&lt;','>':'&gt;','"':'&quot;'},t=this; for(i in e) t=t.replace(new RegExp(i,'g'),e[i]);
	return t;
}
String.prototype.trim = function(){
	return this.replace(/^\s+|\s+$/g,'');
}
String.prototype.splitrim = function(t){
	return this.trim().split(new RegExp('\\s*'+t+'\\s*'));
}
String.prototype.urlEncode = function(){
	return encodeURIComponent(this);
}
String.prototype.isEmail = function (){
	var rx = new RegExp("\\w+([-+.\’]\\w+)*@\\w+([-.]\\w+)*\\.\\w+([-.]\\w+)*");
	var matches = rx.exec(this);
	return (matches != null && this == matches[0]);
}
String.prototype.isURL = function (){
	var rx = new RegExp("http(s)?://([\\w-]+\\.)+[\\w-]+(/[\\w-\\+ ./?%:&=#\\[\\]]*)?");
	var matches = rx.exec(this);
	return (matches != null && this == matches[0]);
}
String.prototype.HTMLDecode = function(){
	var t="";
	if(this != ""){
		t=this.unescHtml();
		for(unesc=1;unesc<=255;unesc++){
			toreplace = "&#" + unesc + ";";
			if(t.indexOf(toreplace) != -1){
				re = new RegExp(toreplace, 'gi');
				t = t.replace(re, String.fromCharCode(unesc));
			}
		}
	}
	return t;
}
String.prototype.HTMLDecode2 = function(){
	var div = document.createElement('div');
	var text = document.createTextNode(this);
	div.appendChild(text);
	return div.innerHTML;
}
String.prototype.abbreviate = function(numchars){
	var helpstr = Left(this, numchars);
	if(this.length > numchars)
		helpstr+="...";
	return helpstr;
}
function Left(str, n){
	if (n <= 0)
	    return "";
	else if (n > String(str).length)
	    return str;
	else
	    return String(str).substring(0,n);
}
function Right(str, n){
    if (n <= 0)
       return "";
    else if (n > String(str).length)
       return str;
    else {
       var iLen = String(str).length;
       return String(str).substring(iLen, iLen - n);
    }

}
Array.prototype.move_element = function(index, delta) {
	var index2, temp_item;
	if (index < 0 || index >= this.length) {return false;}
	index2 = index + delta;
	if (index2 < 0 || index2 >= this.length || index2 == index) {return false;}
	// Move the elements in the array
	temp_item = this[index2];
	this[index2] = this[index];
	this[index] = temp_item;
	return true;
}
Array.prototype.removeItem = function (item) {
	for(var i=0;i<this.length;i++)
	{
		if(this[i]==item)
			return this.splice(i,1);
	}
	return false; // operation failed: not found
}
Array.prototype.peek = function(){
	if (this.length > 0){
		return this[this.length - 1];
	}else {
		return null;
	}
}
Array.prototype.contains = function(val){
	for(var i=0;i<this.length;i++)
	{
		if(this[i] == val)
			return true;
	}
	return false;
}
function HasClassName(objElement, strClass)
{
	if ( objElement.className )
	{
		var arrList = objElement.className.split(' ');
		var strClassUpper = strClass.toUpperCase();
		for ( var i = 0; i < arrList.length; i++ )
		{
			if ( arrList[i].toUpperCase() == strClassUpper )
			{
				return true;
			}
		}
	}
	return false;
}
function AddClassName(objElement, strClass, blnMayAlreadyExist)
{
	if ( objElement.className )
	{
		var arrList = objElement.className.split(' ');
		if ( blnMayAlreadyExist )
		{
			var strClassUpper = strClass.toUpperCase();
			for ( var i = 0; i < arrList.length; i++ )
			{
				if ( arrList[i].toUpperCase() == strClassUpper )
				{
					arrList.splice(i, 1);
					i--;
				}
			}
		}
		arrList[arrList.length] = strClass;
		objElement.className = arrList.join(' ');
	}else{
		objElement.className = strClass;
	}
}
function RemoveClassName(objElement, strClass)
{
	if ( objElement.className )
	{
		var arrList = objElement.className.split(' ');
		var strClassUpper = strClass.toUpperCase();
		for ( var i = 0; i < arrList.length; i++ )
		{
			if ( arrList[i].toUpperCase() == strClassUpper )
			{
				arrList.splice(i, 1);
				i--;
			}
		}
		objElement.className = arrList.join(' ');
	}
}

/* END PROTOTYPES */

function filter(arr, val)
{
	var regex = new RegExp(val, "i");
	var arrReturn = new Array();
	for(var i=0;i<arr.length;i++){
		if(regex.test(arr[i])){
			arrReturn[arrReturn.length] = arr[i];
		}
	}
	return arrReturn;
}

function clone_obj(obj) { 
	var c = obj instanceof Array ? [] : {}; 
	for (var i in obj) { 
		var prop = obj[i]; 
		if (typeof prop == 'object') { 
			if (prop instanceof Array) { 
				c[i] = [];
				for (var j = 0; j < prop.length; j++) { 
					if (typeof prop[j] != 'object') { 
						c[i].push(prop[j]); 
					} else { 
						c[i].push(clone_obj(prop[j])); 
					} 
				} 
			} else { 
				c[i] = clone_obj(prop); 
			} 
		} else { 
			c[i] = prop; 
		} 
	}
	return c; 
}

function Prepare_String(StringPrep){
		StringPrep = StringPrep.replace(/\+/g," ")
		StringPrep = StringPrep.replace(/%21/g,"!")
		StringPrep = StringPrep.replace(/%22/g,"")
		StringPrep = StringPrep.replace(/%23/g,"#")
		StringPrep = StringPrep.replace(/%24/g,"$")
		StringPrep = StringPrep.replace(/%25/g,"%")
		StringPrep = StringPrep.replace(/%26/g,"&")
		StringPrep = StringPrep.replace(/%27/g,"'")
		StringPrep = StringPrep.replace(/%28/g,"(")
		StringPrep = StringPrep.replace(/%29/g,")")
		StringPrep = StringPrep.replace(/%2A/g,"*")
		StringPrep = StringPrep.replace(/%2B/g,"+")
		StringPrep = StringPrep.replace(/%2C/g,",")
		StringPrep = StringPrep.replace(/%2D/g,"-")
		StringPrep = StringPrep.replace(/%2E/g,".")
		StringPrep = StringPrep.replace(/%2F/g,"/")
		StringPrep = StringPrep.replace(/%3A/g,":")
		StringPrep = StringPrep.replace(/%3B/g,";")
		StringPrep = StringPrep.replace(/%3C/g,"<")
		StringPrep = StringPrep.replace(/%3D/g,"=")
		StringPrep = StringPrep.replace(/%3E/g,">")
		StringPrep = StringPrep.replace(/%3F/g,"?")
		StringPrep = StringPrep.replace(/%40/g,"@")
		StringPrep = StringPrep.replace(/%5B/g,"[")
		StringPrep = StringPrep.replace(/%5C/g,"")
		StringPrep = StringPrep.replace(/%5D/g,"]")
		StringPrep = StringPrep.replace(/%5E/g,"^")
		StringPrep = StringPrep.replace(/%5F/g,"_")
		StringPrep = StringPrep.replace(/%60/g,"`")
		StringPrep = StringPrep.replace(/%7B/g,"{")
		StringPrep = StringPrep.replace(/%7C/g,"|")
		StringPrep = StringPrep.replace(/%7D/g,"}")
		StringPrep = StringPrep.replace(/%7E/g,"~")
		StringPrep = StringPrep.replace(/%A0/g," ")
		StringPrep = StringPrep.replace(/%A3/g,"£")
		StringPrep = StringPrep.replace(/%A7/g,"§")
		StringPrep = StringPrep.replace(/%A8/g,"¨")
		StringPrep = StringPrep.replace(/%B4/g,"´")
		StringPrep = StringPrep.replace(/%B5/g,"µ")
		StringPrep = StringPrep.replace(/%C0/g,"À")
		StringPrep = StringPrep.replace(/%C1/g,"Á")
		StringPrep = StringPrep.replace(/%C2/g,"Â")
		StringPrep = StringPrep.replace(/%C3/g,"Ã")
		StringPrep = StringPrep.replace(/%C4/g,"Ä")
		StringPrep = StringPrep.replace(/%C5/g,"Å")
		StringPrep = StringPrep.replace(/%C6/g,"Æ")
		StringPrep = StringPrep.replace(/%C7/g,"Ç")
		StringPrep = StringPrep.replace(/%C8/g,"È")
		StringPrep = StringPrep.replace(/%C9/g,"É")
		StringPrep = StringPrep.replace(/%CA/g,"Ê")
		StringPrep = StringPrep.replace(/%CB/g,"Ë")
		StringPrep = StringPrep.replace(/%CC/g,"Ì")
		StringPrep = StringPrep.replace(/%CD/g,"Í")
		StringPrep = StringPrep.replace(/%CE/g,"Î")
		StringPrep = StringPrep.replace(/%CF/g,"Ï")
		StringPrep = StringPrep.replace(/%D1/g,"Ñ")
		StringPrep = StringPrep.replace(/%D2/g,"Ò")
		StringPrep = StringPrep.replace(/%D3/g,"Ó")
		StringPrep = StringPrep.replace(/%D4/g,"Ô")
		StringPrep = StringPrep.replace(/%D5/g,"Õ")
		StringPrep = StringPrep.replace(/%D6/g,"Ö")
		StringPrep = StringPrep.replace(/%D9/g,"Ù")
		StringPrep = StringPrep.replace(/%DA/g,"Ú")
		StringPrep= StringPrep.replace(/%DB/g,"Û")
		StringPrep= StringPrep.replace(/%DC/g,"Ü")
		StringPrep= StringPrep.replace(/%DD/g,"Ý")
		StringPrep= StringPrep.replace(/%DF/g,"ß")
		StringPrep= StringPrep.replace(/%E0/g,"à")
		StringPrep= StringPrep.replace(/%E1/g,"á")
		StringPrep= StringPrep.replace(/%E2/g,"â")
		StringPrep= StringPrep.replace(/%E3/g,"ã")
		StringPrep= StringPrep.replace(/%E4/g,"ä")
		StringPrep= StringPrep.replace(/%E5/g,"å")
		StringPrep= StringPrep.replace(/%E6/g,"æ")
		StringPrep= StringPrep.replace(/%E7/g,"ç")
		StringPrep= StringPrep.replace(/%E8/g,"è")
		StringPrep= StringPrep.replace(/%E9/g,"é")
		StringPrep= StringPrep.replace(/%EA/g,"ê")
		StringPrep= StringPrep.replace(/%EB/g,"ë")
		StringPrep= StringPrep.replace(/%F0/g,"ð")
		StringPrep= StringPrep.replace(/%F1/g,"ñ")
		StringPrep= StringPrep.replace(/%F2/g,"ô")
		StringPrep= StringPrep.replace(/%F3/g,"ó")
		StringPrep= StringPrep.replace(/%F4/g,"ô")
		StringPrep= StringPrep.replace(/%F5/g,"õ")
		StringPrep= StringPrep.replace(/%F6/g,"ö")
		StringPrep= StringPrep.replace(/%F9/g,"ù")
		StringPrep= StringPrep.replace(/%FA/g,"ú")
		StringPrep= StringPrep.replace(/%FB/g,"û")
		StringPrep= StringPrep.replace(/%FC/g,"ü")
		StringPrep= StringPrep.replace(/%FD/g,"ý")
		StringPrep= StringPrep.replace(/%FF/g,"ÿ")
		return StringPrep;
	}
var refreshObject = new Object();

function getEl(stringEl){return (document.getElementById(stringEl)) ? document.getElementById(stringEl) : false;}

function showGroups(selected, refresh, hidden, btnEdit, btnDelete)
{
	refreshObject.id = refresh;
	refreshObject.hiddenField = hidden;
	refreshObject.btnEdit = btnEdit;
	refreshObject.btnDelete = btnDelete;
	
	xmlHttp=GetXmlHttpObject();
	selectGroup = selected;
	if(xmlHttp==null){
		alert ("Your browser does not support AJAX!");
		return;
	}
	var url="getgroups.asp?sid=" + Math.random() + "&selected="+selected;
	
	xmlHttp.onreadystatechange=	GroupStateChanged;
	xmlHttp.open("GET",url,true);
	xmlHttp.send(null);
	
}
function GroupStateChanged() 
{
	if (xmlHttp.readyState==4){
		document.getElementById(refreshObject.id).options.length=0;
		strGroups = xmlHttp.responseText.substring(0,xmlHttp.responseText.length-1);
		arrGroups = strGroups.split(",");
		for (y=0; y<arrGroups.length; y++) 
		{
			document.getElementById(refreshObject.id).options[y] = new Option(arrGroups[y].split("###")[1], arrGroups[y].split("###")[0]);
			if(arrGroups[y].split("###")[2] == 1){
				document.getElementById(refreshObject.id).options[y].selected = arrGroups[y].split("###")[2];
			}
		}
		window.showHideButtons(selectGroup, refreshObject.hiddenField, refreshObject.btnEdit, refreshObject.btnDelete);
		window.hidePopWin(false);
	}
}

function showBusinessCards(refresh)
{	
	refreshObject.id = refresh;
	xmlHttp=GetXmlHttpObject();
	if(xmlHttp==null){
		alert ("Your browser does not support AJAX!");
		return;
	}
	var url="getbusinesscards.asp?sid=" + Math.random();
	xmlHttp.onreadystatechange=	BusinessCardStateChanged;
	xmlHttp.open("GET",url,true);
	xmlHttp.send(null);
}

function BusinessCardStateChanged() 
{
	if (xmlHttp.readyState==4){
		strBusinessCards = xmlHttp.responseText.substring(0,xmlHttp.responseText.length);
		top.document.getElementById(refreshObject.id).innerHTML = strBusinessCards;
		window.hidePopWin(false);
	}
}

function showPicturesWithValue(refresh,picid,prtid,proid,type,value)
{	
	refreshObject.id = refresh;
	xmlHttp=GetXmlHttpObject();
	if(xmlHttp==null){
		alert ("Your browser does not support AJAX!");
		return;
	}
	var url="getpropertypictures.asp?sid=" + Math.random() + '&imm_prp_id=' + picid + '&imm_prt_id=' + prtid + '&imm_pro_id=' + proid + '&type=' + type + '&value='+value;
	xmlHttp.onreadystatechange=	PropertyPicturesStateChanged;
	xmlHttp.open("GET",url,true);
	xmlHttp.send(null);
	
}
function showPicturesVariable(url, parId, picId, refreshBlock, pictureModule, picturesTable, picturesPrefix, picturesVersionsTable, 
		picturesVersionsPrefix, picturesParent, picturesCategory, picturesCategoryTable, showCategories, type)
{
	refreshObject.id = refreshBlock;
	xmlHttp=GetXmlHttpObject();
	if(xmlHttp==null){
		alert ("Your browser does not support AJAX!");
		return;
	}
	var url='getPicturesComponent.asp?sid=' + Math.random() + '&parId=' + parId + '&refreshBlock=' + refreshBlock ;
	url +=	'&pictureModule=' + pictureModule + '&picId=' + picId + '&picturesTable=' + picturesTable;
	url += 	'&picturesPrefix=' + picturesPrefix + '&picturesVersionsTable=' + picturesVersionsTable;
	url += 	'&picturesVersionsPrefix=' + picturesVersionsPrefix + '&picturesParent=' + picturesParent + '&picturesCategory=' + picturesCategory; 
	url += 	'&picturesCategoryTable=' + picturesCategoryTable + '&showCategories=' + showCategories + '&type=' + type;
	xmlHttp.onreadystatechange=	PropertyPicturesStateChanged;
	xmlHttp.open("GET",url,true);
	xmlHttp.send(null);
}
function showPictures(refresh,picid,prtid,proid,type)
{	
	refreshObject.id = refresh;
	xmlHttp=GetXmlHttpObject();
	if(xmlHttp==null){
		alert ("Your browser does not support AJAX!");
		return;
	}
	var url="getpropertypictures.asp?sid=" + Math.random() + '&imm_prp_id=' + picid + '&imm_prt_id=' + prtid + '&imm_pro_id=' + proid + '&type=' + type;
	xmlHttp.onreadystatechange=	PropertyPicturesStateChanged;
	xmlHttp.open("GET",url,true);
	xmlHttp.send(null);
	
}
function PropertyPicturesStateChanged() 
{
	if (xmlHttp.readyState==4){
		strPropertyPictures = xmlHttp.responseText.substring(0,xmlHttp.responseText.length);
		document.getElementById(refreshObject.id).innerHTML = strPropertyPictures;
	}
}

function showDocuments(refresh,picid,prtid,proid,type)
{	
	refreshObject.id = refresh;
	xmlHttp=GetXmlHttpObject();
	if(xmlHttp==null){
		alert ("Your browser does not support AJAX!");
		return;
	}
	var url="getpropertydocuments.asp?sid=" + Math.random() + '&imm_brd_id=' + picid + '&imm_prt_id=' + prtid + '&imm_pro_id=' + proid + '&type=' + type;
	xmlHttp.onreadystatechange=	PropertyDocumentsStateChanged;
	xmlHttp.open("GET",url,true);
	xmlHttp.send(null);
}
function PropertyDocumentsStateChanged() 
{
	if (xmlHttp.readyState==4){
		strPropertyDocuments = xmlHttp.responseText.substring(0,xmlHttp.responseText.length);
		document.getElementById(refreshObject.id).innerHTML = strPropertyDocuments;
	}
}

function showDocumentsWithValue(refresh,picid,prtid,proid,type,value)
{	
	refreshObject.id = refresh;
	xmlHttp=GetXmlHttpObject();
	if(xmlHttp==null){
		alert ("Your browser does not support AJAX!");
		return;
	}
	var url="getpropertydocuments.asp?sid=" + Math.random() + '&imm_brd_id=' + picid + '&imm_prt_id=' + prtid + '&imm_pro_id=' + proid + '&type=' + type + '&value='+value;
	xmlHttp.onreadystatechange=	PropertyDocumentsStateChanged;
	xmlHttp.open("GET",url,true);
	xmlHttp.send(null);
	
}

function showPropertyActions(refresh, prtid, usrid, comid)	//DEPRECATED
{
	refreshObject.id = refresh;
	xmlHttp=GetXmlHttpObject();
	if(xmlHttp==null){
		alert ("Your browser does not support AJAX!");
		return;
	}
	var url="getpropertyactions.asp?sid=" + Math.random() + '&imm_act_prt_id=' + prtid + '&imm_act_usr_id=' + usrid + '&imm_act_com_id=' + comid;
	xmlHttp.onreadystatechange=	PropertyActionsStateChanged;
	xmlHttp.open("GET",url,true);
	xmlHttp.send(null);
}

function showUSRCOMPropertyActions(refresh, prtid, usrcomid)
{
	refreshObject.id = refresh;
	xmlHttp=GetXmlHttpObject();
	if(xmlHttp==null){
		alert ("Your browser does not support AJAX!");
		return;
	}
	var url="getpropertyactions.asp?sid=" + Math.random() + '&imm_act_prt_id=' + prtid + '&imm_act_usrcom_id=' + usrcomid;
	xmlHttp.onreadystatechange=	PropertyActionsStateChanged;
	xmlHttp.open("GET",url,true);
	xmlHttp.send(null);
}


function PropertyActionsStateChanged() 
{
	if (xmlHttp.readyState==4){
		strPropertyActions = xmlHttp.responseText.substring(0,xmlHttp.responseText.length);
		document.getElementById(refreshObject.id).innerHTML = strPropertyActions;
		window.hidePopWin(false, 1);
	}
}

function showCompanies(selected, refresh, hidden, btnEdit, btnDelete)
{
	refreshObject.id = refresh;
	refreshObject.hiddenField = hidden;
	refreshObject.btnEdit = btnEdit;
	refreshObject.btnDelete = btnDelete;
	
	xmlHttp=GetXmlHttpObject();
	selectCompany = selected;
	if(xmlHttp==null){
		alert ("Your browser does not support AJAX!");
		return;
	}
	var url="getcompanies.asp?sid=" + Math.random() + "&selected="+selected;
	xmlHttp.onreadystatechange=	CompanyStateChanged;
	xmlHttp.open("GET",url,true);
	xmlHttp.send(null);
}

function CompanyStateChanged() 
{
	if (xmlHttp.readyState==4){
		document.getElementById(refreshObject.id).options.length=0;
		strCompanies = xmlHttp.responseText.substring(0,xmlHttp.responseText.length-1);
		arrCompanies = strCompanies.split(",");
		for (y=0; y<arrCompanies.length; y++) 
		{
			document.getElementById(refreshObject.id).options[y] = new Option(arrCompanies[y].split("###")[1], arrCompanies[y].split("###")[0]);
			if(arrCompanies[y].split("###")[2] == 1){
				document.getElementById(refreshObject.id).options[y].selected = arrCompanies[y].split("###")[2];
			}
		}
		window.showHideButtons(selectCompany, refreshObject.hiddenField, refreshObject.btnEdit, refreshObject.btnDelete);
		window.hidePopWin(false);
	}
}

function sortTable(order, ordered, dir, pagename){
	setdirection = '';
	if(order == ordered){
		if(dir == ''){
			setdirection = 'desc';
		}else{
			setdirection = '';
		}
	}
	window.location.href = pagename + '&order=' + order + '&direction=' + setdirection;
}
function checkOrder(order,direction){
	if(order != ''){
		var obj = document.getElementById(order)
		if(obj){
			//alert(obj.innerHTML);
			if(direction != ''){
				obj.innerHTML=obj.innerHTML.replace("spacer.gif","sortup.png");
			}else{
				obj.innerHTML=obj.innerHTML.replace("spacer.gif","sortdown.png");
			}
		}
	}
}

function showHideButtons(id,hiddenfield, btnEdit, btnDel){
//alert(id + " / " + hiddenfield + " / " + btnEdit + " / " + btnDel);
	if(id == ""){
		if(document.getElementById(btnEdit)){
			document.getElementById(btnEdit).style.visibility='hidden';
		}
		if(document.getElementById(btnDel)){
			document.getElementById(btnDel).style.visibility='hidden';
		}
	}else{
		if(document.getElementById(btnEdit)){
			document.getElementById(btnEdit).style.visibility='visible';
		}
		if(document.getElementById(btnDel)){
			document.getElementById(btnDel).style.visibility='visible';
		}
		if(document.getElementById(hiddenfield)){
			document.getElementById(hiddenfield).value=id;
		}
	}
}

function selSwap(from, to)
{
	from = document.getElementById(from);
	to = document.getElementById(to);
	for( var i = 0; i < from.options.length; ++i )
	{
		if(from.options[i].selected )
		{
			if(from.options[i].value != ""){
				from.options[i].selected = false;
				to.options[to.options.length] = new Option(from.options[i].text,from.options[i].value);
				if(document.getElementById(to.name.replace("sel","txt"))){
					document.getElementById(to.name.replace("sel","txt")).value += from.options[i].value + ',';
				}
				if(document.getElementById(from.name.replace("sel","txt"))){
					document.getElementById(from.name.replace("sel","txt")).value = document.getElementById(from.name.replace("sel","txt")).value.replace(',' + from.options[i].value + ',',',');
				}
				from.options[i] = null;
			}
		}
	}
	sortList(to.id);
	sortList(from.id);
}
function sortList(listid) 
{ 
	var lb = document.getElementById(listid); 
	arrTexts = new Array(); 
	arrSelTexts = new Array(); 
	arrValues = new Array(); 
	arrOldTexts = new Array();
	for(i=0; i<lb.length; i++) 
	{ 
		arrTexts[i] = lb.options[i].text.toLowerCase(); 
		arrSelTexts[i] = lb.options[i].text;
		arrValues[i] = lb.options[i].value; 

		arrOldTexts[i] = lb.options[i].text.toLowerCase(); 
	} 
	arrTexts.sort(); 
	for(i=0; i<lb.length; i++) 
	{ 
		lb.options[i].text = arrTexts[i].substring(0,1).toUpperCase() + arrTexts[i].substring(1); 
		for(j=0; j<lb.length; j++) 
		{ 
			if (arrTexts[i] == arrOldTexts[j]) 
			{ 
				lb.options[i].value = arrValues[j]; 
				j = lb.length; 
			} 
		} 
	} 
}

function setPopupAndPageTitle(pagetitle){
	document.title = 'FacilApps - ' + pagetitle;
	pagetitle=pagetitle.replace(/ /g,'&nbsp;');
	if(document.getElementById("pagetitle")){
		document.getElementById("pagetitle").innerHTML = document.getElementById("pagetitle").innerHTML + "&nbsp;-&nbsp;<span style='font-size:12;'>" + pagetitle + "</span>";
	}
}

function yellowFade(el){
	el.style.background = 'rgb(255,255,0)';
	if(el.type == 'text'){
		el.style.border = 'solid';
		el.style.borderWidth = '1px 1px 1px 1px';
		el.style.borderColor = '#a5acb2';
		el.style.height = '18';
	}
	if(el.type == 'textarea'){
		el.style.border = 'solid';
		el.style.borderWidth = '1px 1px 1px 1px';
		el.style.borderColor = '#a5acb2';
	}
	if(el.type == 'select-one'){
		var b = 155;
		(function g(){
			el.style.background = 'rgb(255,255,'+ (b+=6) +')';
			if (b < 255){
				test = setTimeout(g, 10);
			}
		})();
	}else{
		var b = 155;
		(function f(){
			el.style.background = 'rgb(255,255,'+ (b+=4) +')';
			if (b < 255){
				test = setTimeout(f, 60);
			}
		})();
	}
	
}

function addremChecked(chkvalue,checked, textfield){
	if(checked){
		if(document.getElementById(textfield)){
			if(document.getElementById(textfield).value.indexOf(',' + chkvalue + ',') == -1){
				document.getElementById(textfield).value = document.getElementById(textfield).value + chkvalue + ',';
			}
		}
	}else{
		if(document.getElementById(textfield)){
			document.getElementById(textfield).value = document.getElementById(textfield).value.replace(',' + chkvalue + ',',',');
		}
	}
}

function checkOnePropertyCheckbox(checked,uncheck,uncheckid){
	if(checked){
		document.getElementById(uncheck).checked = false;
		addremChecked(uncheckid + '#' + document.getElementById(uncheck).value,document.getElementById(uncheck).checked,'txtMEDChecked');
	}
}

// FORM VALIDATION
function checkRequired(arrRequired){
	isRequired = true;
	for(z=0;z<arrRequired.length;z++){
		setDefaultStyle(arrRequired[z]);
		if(document.getElementById(arrRequired[z]).value == '' || document.getElementById(arrRequired[z]).value == ',' ){
			scroll(0,0);
			document.getElementById(arrRequired[z]).style.background='#FFC3B2';
			isRequired = false;
		}
	}
	return isRequired;
}
function checkDates(arrDates){
	isDate = true;
	for(z=0;z<arrDates.length;z++){
		if(document.getElementById(arrDates[z])){
			setDefaultStyle(arrDates[z]);
			if(document.getElementById(arrDates[z]).value != ''){
				if(!IsDate(document.getElementById(arrDates[z]).value)){
					scroll(0,0);
					document.getElementById(arrDates[z]).style.background='#FFC3B2';
					isDate = false;
				}
			}
		}
	}
	return isDate;
}
function checkIntegers(arrIntegers){
	isInteger = true;
	for(z=0;z<arrIntegers.length;z++){
		if(document.getElementById(arrIntegers[z])){
			setDefaultStyle(arrIntegers[z]);
			if(document.getElementById(arrIntegers[z]).value != ''){
				if(!IsInteger(document.getElementById(arrIntegers[z]).value)){
					scroll(0,0);
					document.getElementById(arrIntegers[z]).style.background='#FFC3B2';
					isInteger = false;
				}
			}
		}
	}
	return isInteger;
}
function checkObligedFields(arrObliged){
	isNotObliged = true;
	for(z=0;z<arrObliged.length;z++){
		if(document.getElementById(arrObliged[z])){
			setDefaultStyle(arrObliged[z]);
			if(document.getElementById(arrObliged[z]).options[document.getElementById(arrObliged[z]).selectedIndex].text.indexOf("gemeente") != -1 || document.getElementById(arrObliged[z]).value == '' || document.getElementById(arrObliged[z]).value == ',' ){
				scroll(0,0);
				document.getElementById(arrObliged[z]).style.background='#FFC3B2';
				isNotObliged = false;
			}
		}
	}
	return isNotObliged;
}
function setDefaultStyle(el){
	document.getElementById(el).style.background='#FFFFFF';
	document.getElementById(el).style.border = 'solid';
	document.getElementById(el).style.borderWidth = '1px 1px 1px 1px';
	document.getElementById(el).style.borderColor = '#a5acb2';
	document.getElementById(el).style.height = '18';
}
function checkFloats(arrFloats){
	isFloat = true;
	for(z=0;z<arrFloats.length;z++){
		if(document.getElementById(arrFloats[z])){
			document.getElementById(arrFloats[z]).style.background='#FFFFFF';
			document.getElementById(arrFloats[z]).style.border = 'solid';
			document.getElementById(arrFloats[z]).style.borderWidth = '1px 1px 1px 1px';
			document.getElementById(arrFloats[z]).style.borderColor = '#a5acb2';
			document.getElementById(arrFloats[z]).style.height = '18';
			if(document.getElementById(arrFloats[z]).value != ''){
				document.getElementById(arrFloats[z]).value = document.getElementById(arrFloats[z]).value.replace(/\./g, ",");
				if(!IsFloat(document.getElementById(arrFloats[z]).value)){
					scroll(0,0);
					document.getElementById(arrFloats[z]).style.background='#FFC3B2';
					isFloat = false;
				}
			}
		}
	}
	return isFloat;
}
function checkEmail(str) {
	var at="@";
	var dot=".";
	var lat=str.indexOf(at);
	var lstr=str.length;
	var ldot=str.indexOf(dot);
	if (str.indexOf(at)==-1){
	   return false;
	}
	if (str.indexOf(at)==-1 || str.indexOf(at)==0 || str.indexOf(at)==lstr){
	   return false;
	}
	if (str.indexOf(dot)==-1 || str.indexOf(dot)==0 || str.indexOf(dot)==lstr){
		return false;
	}
	if (str.indexOf(at,(lat+1))!=-1){
		return false;
	}
	if (str.substring(lat-1,lat)==dot || str.substring(lat+1,lat+2)==dot){
		return false;
	}
	if (str.indexOf(dot,(lat+2))==-1){
		return false;
	}
	if (str.indexOf(",")!=-1){
		return false;
	}
	return true;
}
function IsFloat(strString){
	var strValidChars = "0123456789.,-";
	var strChar;
	var blnResult = true;
	if (strString.length == 0) return false;
	for (i = 0; i < strString.length && blnResult == true; i++){
		strChar = strString.charAt(i);
		if (strValidChars.indexOf(strChar) == -1)
		{
			blnResult = false;
		}
	}
	return blnResult;
}
function IsInteger(strString){
	var strValidChars = "0123456789";
	var strChar;
	var blnResult = true;
	if (strString.length == 0) return false;
	for (i = 0; i < strString.length && blnResult == true; i++){
		strChar = strString.charAt(i);
		if (strValidChars.indexOf(strChar) == -1 && !(strChar == "-" && i == 0))
		{
			blnResult = false;
		}
	}
	return blnResult;
}
function IsDate(strString){
	var strValidChars = "0123456789-/";
	var strChar;
	var blnResult = true;
	if (strString.length == 0) return false;
	for (i = 0; i < strString.length && blnResult == true; i++){
		strChar = strString.charAt(i);
		if (strValidChars.indexOf(strChar) == -1)
		{
			blnResult = false;
		}
	}
	return blnResult;
}
function IsCorrectDate(strString){
	if(strString.length == 0)
		return true;
	if(!IsDate(strString))
		return false;
	arr_date = strString.replace(/-/g, "/").split("/");
	if(arr_date.length < 3)	
		return false;
	// month
	if(arr_date[1].charAt(0) == "0")
		arr_date[1] = arr_date[1].charAt(1);
	if(parseInt(arr_date[1]) > 12 || parseInt(arr_date[1]) < 1) // month
		return false;
	arrMonthDays = [31,29,31,30,31,30,31,31,30,31,30,31];
	var index = parseInt(arr_date[1]) -1;
	if(arrMonthDays[index] < parseInt(arr_date[0])) // days in month
		return false;
	return true;
}
function isCorrectTime(strString){
	if(strString.length == 0)
		return true;
	if(strString.length < 4) // (x:xx) = 4 characters
		return false;
	if(strString.indexOf(":") <= 0)
		return false;
	arr_time = strString.split(":");
	if(parseInt(arr_time[0]) < 0 || parseInt(arr_time[0]) > 23)
		return false;
	if(parseInt(arr_time[1]) < 0 || parseInt(arr_time[1]) > 59)
		return false;
	return true;
}
function fixDateString(strString){
	if(!IsCorrectDate(strString))
		return strString;
	strString = strString.replace(/-/g, '/');
	if(strString.split("/")[1].length == 1)
		strString = strString.split("/")[0]+"/0"+strString.split("/")[1]+"/"+strString.split("/")[2];
	return strString;
}
function fixTimeString(strString){
	if(!IsInteger(strString))
		return strString;
	return Left(strString, (strString.length)-2) + ':' + Right(strString, 2);
}
function getDate()
{
	var currentTime = new Date();
	var month = currentTime.getMonth() + 1;
	var day = currentTime.getDate();
	var year = currentTime.getFullYear();
	if(month.toString().length == 1)
		month = "0"+month;
	if(day.toString().length == 1)
		day = "0"+day;
	return month + "/" + day + "/" + year;
}
function getDateDayMonthYear()
{
	var currentTime = new Date();
	var month = currentTime.getMonth() + 1;
	var day = currentTime.getDate();
	var year = currentTime.getFullYear();
	if(month.toString().length == 1)
		month = "0"+month;
	if(day.toString().length == 1)
		day = "0"+day;
	return day + "/" + month + "/" + year;
}

function getTime()
{
	var currentTime = new Date();
	var hours = currentTime.getHours();
	var minutes = currentTime.getMinutes();
	if (minutes < 10)
		minutes = "0" + minutes;
	return hours + ":" + minutes;
}
function getTimeSeconds(oDate)
{
	var hours = oDate.getHours();
	var minutes = oDate.getMinutes();
	var seconds = oDate.getSeconds();
	if(minutes < 10)
		minutes = "0" + minutes;
	if (seconds < 10)
		seconds = "0" + seconds;
	return hours+":"+minutes+":"+seconds;
}
function dateDifference(strDate1,strDate2, type){
	// returns date difference with a maximum in days
	var datDate1 = Date.parse(strDate1);
	var datDate2 = Date.parse(strDate2);
	var datDiff = (datDate2-datDate1);
	if(type=="s")
		return datDiff/1000;
	if(type=="m")
		return datDiff/(1000*60);
	if(type=="h")
		return datDiff/(1000*60*60);
	return datDiff/(1000*60*60*24);
}
// END FORM VALIDATION

// JAVASCRIPT DOM FUNCTIONS
function getNumberOf(txtNumberof){
	if(document.getElementById(txtNumberof).value == ''){
		document.getElementById(txtNumberof).value = 0;
		document.getElementById(txtNumberof + "_display").value = 1;
	}
	return parseInt(document.getElementById(txtNumberof).value);
}
function addToCounter(counter,txtNumberof){
	counter += 1;
	document.getElementById(txtNumberof).value = parseInt(document.getElementById(txtNumberof).value) + 1;
	document.getElementById(txtNumberof + "_display").value = parseInt(document.getElementById(txtNumberof).value) + 1;
	return counter;
}
function createTableCell(row, location, width, height, colspan, align, className, valign){
	var cell = row.insertCell(location);
	if(width != undefined)cell.width = width;
	if(height != undefined)cell.height = height;
	if(align != undefined)cell.align = align;
	if(colspan != undefined)cell.colSpan = colspan;
	if(className != undefined)cell.className = className;
	if(valign != undefined)cell.vAlign = valign;
	return cell;
}	
function TableInitialise(table, headerrows)
{
	while(getTableRowCount(table,0) > headerrows)
	{
		i=getTableRowCount(table,0);
		i--;
		getTable(table,0).deleteRow(i);
	}
}
function getTableRowCount(TableId)
{
	return getTable(TableId,0).rows.length;
}
function createSpan(text,className){
	var textNode = document.createTextNode(text.replace('&nbsp;','\u00a0'));
	var span = document.createElement('span');
	span.className = className;
	span.appendChild(textNode);
	return span;
}
function createInputField(type, name, id, className, width, iteration,value){
	var input = document.createElement('input');
	input.type = type;
	input.name = name + iteration;
	input.id = id + iteration;
	input.className = className;
	input.style.width = width;
	if(value != undefined)input.value = value;
	return input;
}
function createTextarea(name, id, className, width, cols, rows, iteration,value){
	var input = document.createElement('textarea');
	if(name != undefined)input.name = name + iteration;
	if(id != undefined)input.id = id + iteration;
	if(className != undefined)input.className = className;
	if(width != undefined && width != "")input.style.width = width;
	if(cols != undefined && cols != "")input.cols = cols;
	if(rows != undefined && rows != "")input.rows = rows;
	if(value != undefined)input.value = value;
	return input;
}
function createSelectField(name, id, className, width, iteration, firstOptionText, strTexts, strValues, selectvalue, onChangeFunction){
	var select = document.createElement('select');
	select.name = name + iteration;
	select.id = id + iteration;
	select.className = className;
	select.style.width = width;
	startindex = 0;
	if(firstOptionText != ""){
		select.options[startindex] = new Option(firstOptionText, "");
		startindex++;
	}
	if(strTexts != '' && strValues != ''){
		arrTexts = strTexts.split(",");
		arrValues = strValues.split(",");
		if(arrTexts.length != -1 && arrValues.length != -1){
			for (y=0; y<arrTexts.length; y++){ 
				select.options[y + startindex] = new Option(arrTexts[y], arrValues[y]);
				if(selectvalue != ""){
					if(""+selectvalue == ""+arrValues[y]){
						select.options[y + startindex].selected = true;
					}
				}
			}
		}
	}
	if(onChangeFunction != ""){
		select.onchange=onChangeFunction;
	}
	return select;
}
function createExtendedSelectField(name, id, className, width, iteration, firstOptionText, arrOptions, selectedvalue, onChangeFunction, arrOptionalAttributes){
	var select = document.createElement('select');
	select.name = name + iteration;
	select.id = id + iteration;
	select.className = className;
	select.style.width = width;
	var startindex = 0;
	if(firstOptionText.trim() != ""){
		select.options[startindex] = new Option(firstOptionText, "");
		startindex++;
	}
	if(arrOptions[0]){
		if(arrOptions[0].length > -1)
		{
			for(var i=0; i<arrOptions.length;i++){
				select.options[i + startindex] = new Option(arrOptions[i][0], arrOptions[i][1]);
				if(arrOptionalAttributes != ''){
					strOutput = "";
					for(var y=0; y<arrOptionalAttributes.length; y++)
					{
						select.options[parseInt(i + startindex)].setAttribute(arrOptionalAttributes[y][0], arrOptionalAttributes[y][1][i]);
						//strOutput +="select.options["+parseInt(i + startindex)+"]."+arrOptionalAttributes[y][0] +"="+ arrOptionalAttributes[y][1][i];
						//alert(strOutput);
					}
				}
				if(selectedvalue.trim() != '' && ""+selectedvalue.trim() == ""+arrOptions[i][1])
					select.options[i + startindex].selected = true;				
			}
		}
	}
	if(onChangeFunction != ""){
		select.onchange=onChangeFunction;
	}
	return select;
}
function createTableRow(location,tbl){
	var row = tbl.insertRow(location);
	return row;
}
function createTable(tablename,border,width,cellpadding,cellspacing){
	var tbl = document.createElement("table");
	tbl.border = border;
	tbl.width = width;
	if(cellpadding != undefined)tbl.cellPadding = cellpadding;
	if(cellspacing != undefined)tbl.cellSpacing = cellspacing;
	return tbl;
}

function getTable(tablename,border){
	var tbl = document.getElementById(tablename);
	tbl.border = border;
	return tbl;
}
function createHr(className,size,width,height){
	var hr = document.createElement('hr');
	hr.className = className;
	if(size != undefined)hr.size = size;
	if(width != undefined)hr.width = width;
	if(height != undefined)hr.height = height;
	return hr;
}
function checkEmptyFields(arrFields,teller){
	var isempty = true;
	for(i=0;i<arrFields.length;i++){
		if(document.getElementById(arrFields[i] + teller).type == 'text'){
			if(document.getElementById(arrFields[i] + teller).value != ''){
				isempty = false;
			}
		}
		else if(document.getElementById(arrFields[i] + teller).type == 'textarea'){
			if(document.getElementById(arrFields[i] + teller).value != ''){
				isempty = false;
			}
		}else if(document.getElementById(arrFields[i] + teller).type == 'checkbox'){
			if(document.getElementById(arrFields[i] + teller).checked != ''){
				isempty = false;
			}
		}else if(document.getElementById(arrFields[i] + teller).type == 'select-one'){
			if(document.getElementById(arrFields[i] + teller).value != ''){
				isempty = false;
			}
		}
	}
	if(isempty){
		for(i=0;i<arrFields.length;i++){
			yellowFade(document.getElementById(arrFields[i] + teller));
		}
		return false;
	}else{
		return true;
	}
}
// END JAVASCRIPTDOM FUNCTIONS

function MultiSelector(list_target, max, maxsize, numberof){
	var self = this;
	
	// Where to write the list
	this.list_target = list_target;
	// How many elements?
	this.count = 0;
	// Elementcount for message
	self.globalSelectorCount = 0;
	// How many elements?
	this.id = 0;
	// Is there a maximum?
	if( max ){
		this.max = max;
	} else {
		this.max = -1;
	};
	this.maxsize = maxsize;
	this.numberof = numberof;
	var iIndex = 0;
	/**
	 * Add a new file input element
	 */
	this.addElement = function(element, elname, sPrefix, sPostfix){
		// Make sure it's a file input element
		if( element.tagName == 'INPUT' && element.type == 'file' ){
			// Element name -- what number am I?
			element.name = elname + "_" + this.id;
			element.id = elname + "_" + this.id;
			element.index = this.id;
			this.id++;
			// Add reference to this object
			element.multi_selector = this;
			// What to do when a file is selected
			element.onchange = function(){
				// New file input
				var new_element = document.createElement( 'input' );
				new_element.type = 'file';
				new_element.className = 'normal';
				new_element.style.width = '100%';
				// Add new element
				this.parentNode.insertBefore( new_element, this );

				// Apply 'update' to element
				this.multi_selector.addElement( new_element,elname, sPrefix, sPostfix);

				// Update list
				this.multi_selector.addListRow( this , null, sPrefix, sPostfix);

				// Hide this: we can't use display:none because Safari doesn't like it
				this.style.position = 'absolute';
				this.style.left = '-1000px';

			};
			// If we've reached maximum number, disable input element
			if( this.max != -1 && this.count >= this.max ){
				element.disabled = true;
			};

			// File element counter
			this.count++;
			// Most recent element
			this.current_element = element;
			
		} else {
			// This can only be applied to file input elements!
			alert( 'Error: not a file input element' );
		};

	};
	/**
	 * Add a new row to the list of files
	 */
	this.addListRow = function(element,length,sPrefix,sPostfix){
		self.globalSelectorCount++;
		
		if(document.getElementById("lblNoFotos")){
			document.getElementById("lblNoFotos").style.visibility = (self.globalSelectorCount == 0) ? "visible" : "hidden";				
		}
		
		if(this.list_target.style.display == "none"){
			this.list_target.style.display = "block";
		}
		// Row div
		var new_row = document.createElement( 'div' );
		new_row.style.borderTop= "1px solid gray";
		new_row.style.margin = "5px";
		textwidth = '380px';
		if(parent.selectorTextWidth != undefined)
			textwidth = parent.selectorTextWidth;
		
		// Delete button
		var new_row_button = document.createElement('img');
		//new_row_button.type = 'image';
		new_row_button.src = 'images/delete.png';
		//new_row_button.value = 'Delete';
		new_row_button.numberof = this.numberof;
		new_row_button.style.cursor = "pointer";
		
		var new_row_text = document.createElement('span');
		new_row_text.style.width = textwidth;
		
		// References
		new_row.element = element;
		
		// Delete function
		new_row_button.onclick= function(){
			// Remove element from form
			this.parentNode.element.parentNode.removeChild( this.parentNode.element );
			// Substract one element 
			self.globalSelectorCount--;
			// Remove this row from the list
			this.parentNode.parentNode.removeChild( this.parentNode );
			// Decrement counter
			this.parentNode.element.multi_selector.count--;
			if(document.getElementById("lblNoFotos")){
				document.getElementById("lblNoFotos").style.visibility = (self.globalSelectorCount == 0) ? "visible" : "hidden";				
			}
			if(this.parentNode.element.multi_selector.count == 1){
				if(list_target.style.display == "block"){
					list_target.style.display = "none";
				}
			}
		//	document.getElementById(this.numberof).value=this.parentNode.element.multi_selector.count-1;

		// Re-enable input element (if it's disabled)
			this.parentNode.element.multi_selector.current_element.disabled = false;

			// Appease Safari
			//    without it Safari wants to reload the browser window
			//    which nixes your already queued uploads
			return false;
		};

		// Set row value
		if(element.value.length > this.maxsize){
			elvalue = "&nbsp;&nbsp;..." + element.value.substring(element.value.length - this.maxsize,element.value.length) + "&nbsp;&nbsp;";
		}else{
			elvalue = element.value;
		}
		sContent = "";
		if(sPrefix){sContent += sPrefix.replace(/{INDEX}/g,element.index);}
		sContent += "<div style='overflow:hidden;width:100%;height:14px;'>"+elvalue+"</div>";
		if(sPostfix){sContent += sPostfix.replace(/{INDEX}/g,element.index);}
		
		new_row_text.innerHTML = sContent;
		
		new_row_text.title = element.value;

		// Add button
		new_row.appendChild( new_row_text );
		
		new_row.appendChild( new_row_button );

		// Add it to the list
		this.list_target.appendChild( new_row );
		this.list_target.style.border = "1px solid black";
		this.list_target.style.padding = "5px";
		this.list_target.style.background = "#fff";
		if(document.getElementById(this.numberof).value ==''){
			document.getElementById(this.numberof).value = 1;
		}else{
			document.getElementById(this.numberof).value=parseInt(document.getElementById(this.numberof).value )+1 ;
		}
	};

};

/*******************/
/* XML FUNCTIONS */
/*******************/
function getValueFromXMLNode(node,name){
	nodevalue = ""
	if(node.getElementsByTagName(name)[0]){
		if(node.getElementsByTagName(name)[0].childNodes[0]){
			nodevalue = node.getElementsByTagName(name)[0].childNodes[0].nodeValue;
		}
	}
	return nodevalue;
}
function setValueIntoXMLNode(xmldoc, node, name, value){
	if(node.getElementsByTagName(name)[0]){
		if(node.getElementsByTagName(name)[0].childNodes.length == 0){
			node.getElementsByTagName(name)[0].appendChild(xmldoc.createTextNode(value));
		}else{
			node.getElementsByTagName(name)[0].childNodes[0].nodeValue = value;
		}
	}
}
function nodeExists(node, collection, compareOn)
{
	for(var i=0;i<collection.length;i++)
	{
		if(compareOn != ''){
			return (collection[i].getAttribute(compareOn) == node.getAttribute(compareOn))
		}else{
			if(collection[i].childNodes.length != 0 && node.childNodes.length != 0)
				return (String.compare(collection[i].childNodes[0].nodeValue, node.childNodes[0].nodeValue) == 0)
		}
	}
	return false;
}
function StringtoXML(text){
	if (window.ActiveXObject){
		var doc=new ActiveXObject('Microsoft.XMLDOM');
		doc.async='false';
		doc.loadXML(text);
	} else {
		var parser=new DOMParser();
		var doc=parser.parseFromString(text,'text/xml');
	}
	return doc;
}

function XMLtoString(doc){
	var string = doc.xml.escHtml();
	return string;
}

/*******************/

/*******************/
	
	
/***********************************/
// HELP FUNCTION
	function getElementHeight(Elem) {
		return Elem.offsetHeight;
	}

	function getElementWidth(Elem) {
		return Elem.offsetWidth;
	}

	function stayInWindow(el, x, y)
	{
		var theBody = document.getElementsByTagName("BODY")[0];
		var fullHeight = getViewportHeight();
		var fullWidth = getViewportWidth();
		var _x = parseInt(x);
		var _y = parseInt(y);
		bodyheight = parseInt((fullHeight < theBody.scrollHeight) ? fullHeight : theBody.scrollHeight);
		bodywidth = parseInt((fullWidth < theBody.scrollWidth) ? fullWidth : theBody.scrollWidth);
		el.style.left = (parseInt(_x+getElementWidth(el))+10 > bodywidth) ? _x-getElementWidth(el)-10 : el.style.left = _x+10;
		el.style.top = (parseInt(_y+getElementHeight(el))+20 > bodyheight) ? _y-getElementHeight(el)-20 : el.style.top = _y+10;
	}
	function removeHelp()
	{
		if(document.getElementById("divHelp"))
			document.body.removeChild(document.getElementById("divHelp"));
	}
	function getDBHelpInfo(pagid, anchor, triggerElement, width, deleteOnMouseOut)
	{
		if(xmlHttp){
			xmlHttp.abort();
		}
		if(xmlHttp==null){
			alert ("Your browser does not support AJAX!");
			return;
		}
		var url="getHelp.asp?modid=" + pagid + "&anchor=" + anchor; // no sid, the result is being cached automatically for performance
		xmlHttp.open("GET",url,false);
		xmlHttp.send();
		var text = xmlHttp.responseText;
		if(text.indexOf("error") > 0)
			text = "<table><tr><td width='20' class='normal'><img src='images/warning.png'/></td><td class='normal'>Er is een fout opgetreden bij het ophalen van dit help item.</td></tr></table>";
		return new getHelpInfo(text, triggerElement, width, deleteOnMouseOut);
	}
	function getHelpInfo(text, triggerElement, width, deleteOnMouseOut)
	{
		this._triggerElement = triggerElement;
		this._deleteOnMouseOut = deleteOnMouseOut;
		this._width = parseInt(width);
		
		if(text == '')
			text = "<span class='red' style='font-weight:bold'><i>Help info niet gevonden!</i></span>";
		
		div = createHelpContainer(text, this._width, this._deleteOnMouseOut);
		document.body.appendChild(div);
		div.setAttribute("id","divHelp");
		
		var coords = getMouseCoords();
		div.style.position="absolute";
		stayInWindow(div, coords[0], coords[1]);
		this._triggerElement.style.cursor="help";
		this._triggerElement.alt = "";
		
		if(this._deleteOnMouseOut){
			addEvent(this._triggerElement, "mouseout", removeHelp);
			document.getElementById("containerCloseBtn").style.display="none";
		}else{
			/*this._triggerElement.onmouseover=function(){return false;};
			document.getElementById("containerCloseBtn").style.display="block";
			document.getElementById("closeBtn").onclick=function(){
				this._triggerElement.onmouseover=function(){
					getHelpInfo(text, this._triggerElement, this._width, this._deleteOnMouseOut);
				};
				document.body.removeChild(div);
			}*/
		}
		
		//METHODS
		this.setWidth = function(width){
			this._width = width;
			div.style.width=this._width;
		}
		this.setDeleteOnMouseOut = function(val){
			this._deleteOnMouseOut=val;
		}
		this.setCursor = function(ctype){
			this._triggerElement.style.cursor="pointer";
		}
		this._triggerElement.onmousemove=function()
		{
			var coords = getMouseCoords();
			div.style.position="absolute";
			//div.style.left = (coords[0]+10)+"px";
			//div.style.top = (coords[1]+10)+"px";
			stayInWindow(div, coords[0], coords[1]);
		}
	}
	
	function createHelpContainer(text, width, hideCloseButton)
	{
			var table = "<table style='font-size:0px' cellpadding='0' cellspacing='0' border='0' width='100%'>"
			//topline
			table += "<tr><td width='10' valign='top'><img src='images/help/cor_top_lef.png'/></td><td width='*' style='background:url(&quot;images/help/bor_top.png&quot;) repeat-x left top'>&nbsp;</td><td width='10' valign='top'><img src='images/help/cor_top_rig.png'/></td></tr>"
			//CloseLine
			table += "<tr id='containerCloseBtn'><td width='10' style='background:url(&quot;images/help/bor_lef.png&quot;) repeat-y left top'></td><td style='background-color:#f3eba0; font-size:12px'>"
			//Closebutton
			table += "<img id='closeBtn' onMouseOver='this.style.cursor=&quot;pointer&quot;' src='images/close.gif' align='right' style='float:right' alt='Sluiten'/>"
			table += "</td><td width='10' style='background:url(&quot;images/help/bor_rig.png&quot;) repeat-y right top'></td></tr>";
			//contentline
			table += "<tr><td width='10' style='background:url(&quot;images/help/bor_lef.png&quot;) repeat-y left top'></td><td style='background-color:#f3eba0; id='helpContentColumn' font-size:10px' class='normal'>"+text+"</td><td width='10' style='background:url(&quot;images/help/bor_rig.png&quot;) repeat-y right top'></td></tr>";
			//bottomline
			table += "<tr><td width='10' valign='top'><img src='images/help/cor_btm_lef.png'/></td><td width='*' style='background:url(&quot;images/help/bor_btm.png&quot;) repeat-x left top'>&nbsp;</td><td width='10' valign='top'><img src='images/help/cor_btm_rig.png'/></td></tr>"
			table += "</table>";
			
					
		// OUTERDIV
		var outerdiv = document.createElement("div");
		outerdiv.style.margin="3";
		outerdiv.style.position="absolute";
		outerdiv.style.width=width;
		outerdiv.innerHTML = table;
				
		return outerdiv;
	}
	
	function getMouseCoords(e)
	{
		var IE = document.all?true:false;
		var tempX = 0;
		var tempY = 0;

		if (IE) { // grab the x-y pos.s if browser is IE
			tempX = event.clientX + document.body.scrollLeft;
			tempY = event.clientY + document.body.scrollTop;
		}
		else {  // grab the x-y pos.s if browser is NS
			tempX = e.pageX;
			tempY = e.pageY;
		}
	
		if (tempX < 0){tempX = 0;}
		if (tempY < 0){tempY = 0;}  
		
		return [tempX,tempY];
	}
/***********************************/

xmlHttp=GetXmlHttpObject();
var g_contacttype;
var g_elid;
function getContactData(elid, contacttype,searchvalue){
	g_contacttype = contacttype;
	g_elid = elid;
	getEl(elid).options.length = 0;
	if(searchvalue.length >= 3){
		getEl(elid).options[0] = new Option("Laden...","");
		if(xmlHttp){
			xmlHttp.abort();
		}
		yellowFade(getEl(elid));
		
		if(xmlHttp==null){
			alert ("Your browser does not support AJAX!");
			return;
		}
		var url="getAllContacts.asp?sid=" + Math.random() + "&contacttype=" + contacttype + "&searchvalue=" + searchvalue;
		xmlHttp.onreadystatechange=ContactDataStateChanged;
		xmlHttp.open("GET",url,true);
		xmlHttp.send();
	}else{
		getEl(elid).options[0] = new Option("--Gebruik bovenstaande filter--","");
	}
}

function ContactDataStateChanged(){
	if(xmlHttp.readyState==4){
		if (xmlHttp.status==200){
			tempXML = StringtoXML(xmlHttp.responseText.HTMLDecode());
			contacts = tempXML.getElementsByTagName("contact");
			for(i=0;i<contacts.length;i++){
				CON_ID = contacts[i].getAttribute("CON_ID");
				CON_Name = contacts[i].childNodes[0].nodeValue;
				getEl(g_elid).options[i+1] = new Option(CON_Name, CON_ID);
			}
			resultText = "";
			if(contacts.length == 1){
				resultText = "resultaat";
			}else{
				resultText = "resultaten";
			}
			getEl(g_elid).options[0].text = contacts.length + " " + resultText + " gevonden...";/**/
		}
	}
}

// Overlay loading div
var loaderVisible;
var innerloaderdiv;
var outerloaderdiv;
function showloader(text, smallwidth)
{
	return new top.showToploader(text,smallwidth);
}
function showToploader(text, smallwidth)
{	
	this._text = text;
	theBody = top.document.getElementsByTagName("BODY")[0];
	
	var brsVersion = parseInt(window.navigator.appVersion.charAt(0), 10);
	if (brsVersion <= 6 && window.navigator.userAgent.indexOf("MSIE") > -1) {
		for(var i = 0; i < document.forms.length; i++) {
			for(var e = 0; e < document.forms[i].length; e++){
				if(document.forms[i].elements[e].tagName == "SELECT") {
					document.forms[i].elements[e].style.setAttribute("display", "none");
				}
			}
		}
	}
	// Determine what's bigger, scrollHeight or fullHeight / width
	var fullHeight = getViewportHeight();
	var fullWidth = getViewportWidth();
	
	if (fullHeight > theBody.scrollHeight) {popHeight = fullHeight;} 
	else {popHeight = theBody.scrollHeight;}
	if (fullWidth > theBody.scrollWidth) {popWidth = fullWidth;}
	else {popWidth = theBody.scrollWidth;}
	
	div = document.createElement("DIV");
	div.style.zIndex=999999998;
	div.className = "popupMask";
	var innerdiv = document.createElement("DIV");
	innerdiv.style.zIndex=999999999;
	innerdiv.style.textAlign="center";
	innerdiv.style.position="absolute";
	innerdiv.style.backgroundColor="white";
	innerdiv.style.width=smallwidth;
	innerdiv.style.top="0px";
	innerdiv.style.height="150";
	innerdiv.style.paddingTop="35px";
	innerdiv.id="loaderBox";
	innerdiv.style.border="5px solid #333333";
	innerdiv.innerHTML = "<img src='images/loading.gif'/><p><span class='normal'>"+this._text+"</span></p><p class='small' style='color:red'>Sluit uw browser niet af gedurende dit proces.<br/>Er kunnen waardevolle gegevens verloren gaan.</p>";
	div.appendChild(innerdiv);
	div.style.display="block";
	innerdiv.style.paddingBottom="4px";
	
	div.style.height = popHeight + "px";
	div.style.width = popWidth + "px";
	
	innerloaderdiv = innerdiv;
	outerloaderdiv = div;
		
	theBody.appendChild(div);
	theBody.appendChild(innerdiv);
	
	loaderVisible = true;
	addLoaderEvents();
	centerloader(innerdiv, smallwidth, 150);
	
	
	//METHODS
	this.setText = function(text){
		this._text = text;
		this.refreshContent();
	}
	this.refreshContent = function(){
		innerdiv.innerHTML = "<img src='images/loading.gif'/><p><span class='normal'>"+this._text+"</span></p><p class='small' style='color:red'>Sluit uw browser niet af gedurende dit proces.<br/>Er kunnen waardevolle gegevens verloren gaan.</p>";
	}
	this.hideLoader = function(){
		var brsVersion = parseInt(window.navigator.appVersion.charAt(0), 10);
		if (brsVersion <= 6 && window.navigator.userAgent.indexOf("MSIE") > -1) {
			for(var i = 0; i < document.forms.length; i++) {
				for(var e = 0; e < document.forms[i].length; e++){
					if(document.forms[i].elements[e].tagName == "SELECT") {
						document.forms[i].elements[e].style.setAttribute("display", "inline");
					}
				}
			}
		}
		removeLoaderEvents();
		innerloaderdiv.parentNode.removeChild(innerloaderdiv);
		outerloaderdiv.parentNode.removeChild(outerloaderdiv);
	}

}

function centerloader(loader, width, height) {
	if (loaderVisible == true) {
		loader = innerloaderdiv;
		if (width == null || isNaN(width)) {
			width = loader.offsetWidth;
		}
		if (height == null) {
			height = loader.offsetHeight;
		}
		var theBody = document.getElementsByTagName("BODY")[0];
		var scTop = parseInt(getScrollTop(),10);
		var scLeft = parseInt(theBody.scrollLeft,10);
		var fullHeight = getViewportHeight();
		var fullWidth = getViewportWidth();
		setLoaderMaskSize();
		loader.style.marginTop = (scTop + (fullHeight / 2)-height/2) + "px";
		loader.style.marginLeft =  (scLeft + ((fullWidth - width) / 2)) + "px";
	}
}
function removeLoaderEvents(){
	removeEvent(window, "resize", centerloader);
	removeEvent(window, "scroll", centerloader);
	window.onscroll = "";
}
function addLoaderEvents(){
	addEvent(window, "resize", centerloader);
	addEvent(window, "scroll", centerloader);
	window.onscroll = centerloader;
}

function setLoaderMaskSize() {
	theBody = top.document.getElementsByTagName("BODY")[0];
	var fullHeight = getViewportHeight();
	var fullWidth = getViewportWidth();
	popHeight = (fullHeight > theBody.scrollHeight) ? fullHeight : theBody.scrollHeight;
	popWidth = (fullWidth > theBody.scrollWidth) ? fullWidth : theBody.scrollWidth;
	outerloaderdiv.style.height = popHeight + "px";
	outerloaderdiv.style.width = popWidth + "px";
}
function pauseScript(milliseconds) 
{
	var date = new Date();
	var curDate = null;
	do { curDate = new Date(); } 
	while(curDate-date < milliseconds);
} 
function setSelect(el, val)
{
	if(document.getElementById(el)){
		for(var i=0;i<getEl(el).options.length;i++)
		{
			if(""+getEl(el).options[i].value == ""+val){
				getEl(el).selectedIndex = i;
				break;
			}
		}
	}
}
function openDMSBrowser(width, height, el, fnct)
{ // Open DMS for file browsing
	var iLeft = Math.round( getViewportWidth() / 2);
	var iTop  = Math.round( getViewportHeight() / 2);

	var sOptions = "toolbar=no,status=no,resizable=yes,dependent=yes,scrollbars=yes" ;
	sOptions += ",width=" + width ;
	sOptions += ",height=" + height ;
	sOptions += ",left=" + iLeft ;
	sOptions += ",top=" + iTop ;
	
	window.open("dms_files_list.asp?pagid=&parid=&selector=3", "FCKBrowseWindow", sOptions);
	
	SetUrl = function(fileUrl)
	{
		el.value=fileUrl;
		if(typeof(el.onchange) == 'function')
			el.onchange();
	}
	SetFileXML = function(oXml)
	{
		if(fnct)
			fnct( oXml );
	}
}
function notify(message, width, height, depth, time){
	window.attachEvent("onload", 
		function(){
			showPopWin("popup.asp?openform=notification.asp&confpage=notification.asp&ajaxf=&message="+message+"&btnEdit=&btnDel=&refresh=", width, height, depth);
		}
	);
	if(time){
		if(time>0)
			setTimeout('window.parent.hidePopWin(false)', time*1000);
	}
}

function selectRow(sName, bSelected, sColor){
	if(!sColor){
		sColor = "#B9C9D1";
	}
	if(document.getElementById(sName)){
		if(bSelected){
			currBGColor = document.getElementById(sName).style.backgroundColor;
			document.getElementById(sName).style.backgroundColor = sColor;
		}else{
			document.getElementById(sName).style.backgroundColor = currBGColor ;
		}
	
	}
}


function triggerCollapsable(trigger,changeHeader, headerName){
	if(changeHeader)
		var newVal = trigger.parentNode.getElementsByTagName("input")[0].value;
	if(trigger.collapsed){
		// trigger.innerHTML = trigger.oldVal;
		if(trigger.parentNode.childNodes[1]){
			if(trigger.parentNode.childNodes[1].tagName=="DIV"){
				trigger.parentNode.childNodes[1].style.display="block";
				trigger.className = "trigger iconUp";
				trigger.collapsed = false;
			}
		}
	}else{
		trigger.oldVal = trigger.innerHTML;
		if(changeHeader)
			trigger.innerHTML = (newVal.length ==0) ?headerName:headerName+" - "+newVal;
		if(trigger.parentNode.childNodes[1]){
			if(trigger.parentNode.childNodes[1].tagName=="DIV"){
				trigger.parentNode.childNodes[1].style.display="none";
				trigger.className = "trigger iconDown";
				trigger.collapsed = true;
			}
		}
	}
}
function openCRMWindow(partskid, cplid, cpl, cplSysId, type, usrid, comid, usrcomid, usrname, comname, info){
	if(!info) info = "";
	var usrname = escape(usrname.replace(/_--_Q_--_/g, '"'));
	var comname = escape(comname.replace(/_--_Q_--_/g, '"'));
	var info = escape(info.replace(/_--_Q_--_/g, '"'));
	defaultwidth = 554;
	showPopWin('popup.asp?confpage=&openform=crm_task_form.asp&type=' + type + '&cpl=' + cpl + '&cplid=' + cplid + '&cplSysId=' + cplSysId + '&partskId=' + partskid + '&usrId=' + usrid + '&comId=' + comid + '&usrcomid=' + usrcomid + '&usrName=' + usrname + '&comName=' + comname + '&crmInfo=' + info +'&popupLinks=1', defaultwidth, 595, 1);
}
function DLL_SelectTasksFromContact(usrid, comid, usrcomid, usrname, company, el, info, showcompleted){
	var url="getTasksByContact.asp?sid=" + Math.random() + "&usrid=" + usrid + "&comid=" + comid + "&usrcomid=" + usrcomid + "&usrname=" + usrname + "&company=" + company + "&info=" + info + "&showCompleted=" + showcompleted;
	var taskLoader = new sack(url);
	taskLoader.element = el;
	taskLoader.onLoading = function(){}
	taskLoader.onCompletion = function(){}
	taskLoader.onError = function(){this.elementObj.innerHTML = "<div id='itemContainer'><div class='head'><span><img src='images/warning.png' /></span>Fout bij het laden van de taken</div><span class='normal'>Technische informatie:<br/><br/>"+this.responseStatus[1]+"<br/>"+this.response+"</span></div>";}
	taskLoader.runAJAX();
}
function DLL_SelectTasksFromCoupling(sysID, id, el, info, showcompleted){
	if(id){
		var url="getTasksByCoupling.asp?sid=" + Math.random() + "&cplSysId="+sysID+"&id="+id + "&info=" + info + "&showCompleted=" + showcompleted;
		var taskLoader = new sack(url);
		taskLoader.element = el;
		taskLoader.onLoading = function(){}
		taskLoader.onCompletion = function(){}
		taskLoader.onError = function(){this.elementObj.innerHTML = "<div id='itemContainer'><div class='head'><span><img src='images/warning.png' /></span>Fout bij het laden van de taken</div><span class='normal'>Technische informatie:<br/><br/>"+this.responseStatus[1]+"<br/>"+this.response+"</span></div>";}
		taskLoader.runAJAX();
	}
}
function toggleTabsBackground(el, flag){
	if(!HasClassName(el, 'here')){
		if(flag == 1){
			el.style.backgroundImage='url(images/tabbgover.gif)';
		}else{
			el.style.backgroundImage='url(images/tabbg.gif)';
		}
	}
}
function showWarningMessage(message, color, getOrPost, DoAfterCompleted){
	var JSGetSession = new sack("getJavaScriptSessionMessage.asp?message="+message+"&messageColor="+color+"&action="+getOrPost);
	JSGetSession.onCompletion = function(){
		if((this.response != '||') && (getOrPost == "GET")){
			document.getElementById("warningbackground").style.backgroundColor=this.response.split("||")[0];
			document.getElementById("warningmessage").innerHTML=this.response.split("||")[1];
			document.getElementById("warningrow").style.display="block";
		}
		if(typeof(DoAfterCompleted) == "function"){
			DoAfterCompleted();
		}
	}
	JSGetSession.onError = function(){}
	JSGetSession.runAJAX();		
}

function reloadTasksByFilter(usrid, comid, usrcomid, usrname, comname, info, el, sysID, cplid){
	
	showCompleted = "1";
	if(el.checked){
		showCompleted = "";
	}
	if(usrid != "" || comid != ""){
		DLL_SelectTasksFromContact(usrid, comid, usrcomid,  usrname, comname, 'CRM_Tasks', info, showCompleted);
	}else if(cplid != "" && sysID != ""){
		DLL_SelectTasksFromCoupling(sysID, cplid, 'CRM_Tasks', info, showCompleted)
	}

}

function addEventToOnLoad(event){
	if (window.addEventListener){
		window.addEventListener('load', event, false); // NB **not** 'onload'
	}
	else if(window.attachEvent){// Microsoft
		window.attachEvent('onload', event);
	}
}
