if (typeof Base64 == "undefined") document.write("<script type='text/javascript' src='"+ BaseLocation + "../Includes/base64.js'></script>");		//Include Base64 to handle Ajax requests

function getForm(ID){
	return (document.forms[ID] == undefined)? document.Form1 : document.forms[ID];
}

// http://james.padolsey.com/javascript/get-document-height-cross-browser/
function getDocHeight() {
    var D = document;
    return Math.max(
        Math.max(D.body.scrollHeight, D.documentElement.scrollHeight),
        Math.max(D.body.offsetHeight, D.documentElement.offsetHeight),
        Math.max(D.body.clientHeight, D.documentElement.clientHeight)
    );
}


function getEventType(e) {
    // From: http: //www.quirksmode.org/js/events_properties.html
    if (!e) var e = window.event;
    return e.type;
}
function getEventTarget(e) {
    // From: http: //www.quirksmode.org/js/events_properties.html
    var targ;
    if (!e) var e = window.event;
    if (e.target) targ = e.target;
    else if (e.srcElement) targ = e.srcElement;
    if (targ.nodeType == 3) // defeat Safari bug
        targ = targ.parentNode;
    return targ;
}
function getEventIsRightClick(e) {
    // From: http://www.quirksmode.org/js/events_properties.html
    var rightclick;
    if (!e) var e = window.event;
    if (e.which) rightclick = (e.which == 3);
    else if (e.button) rightclick = (e.button == 2);
    return rightclick; // true or false
}

function protectpage(e) {
    // Prevents clicking, except for some elements which need this.
    var oElm, isValid;
    oElm = getEventTarget(e);

    isRightClick = getEventIsRightClick(e);

    isCurrentValid = (
            Element.match(oElm, 'textarea') ||
            Element.match(oElm, 'input') ||
            Element.match(oElm, 'button') ||
            Element.match(oElm, 'a') ||
            Element.match(oElm, 'iframe')   // iframe is used for rad editors
        )
    // Only left click is allowed on image hotspots
    if (!isRightClick) isCurrentValid = isCurrentValid || Element.match(oElm, 'area');

    if (isCurrentValid) { isValid= true; }
    else {
        // Also check parent elements, to handle for example: <a><em>..</em></a>
        isValid = (typeof (
            Element.up(oElm, 'textarea') ||
            Element.up(oElm, 'input') ||
            Element.up(oElm, 'button') ||
            Element.up(oElm, 'a')
        ) !== "undefined");
    }
    return isValid;
}

//****************************************************************************//
//  function:	popup()
// arguments:	url, popWidth, popHeight, ID, properties (string or object)
//    result:	popup window
//****************************************************************************//

function popup(url, popWidth, popHeight, ID, properties) {
	var leftPosition = (screen.availWidth) ? (screen.availWidth) / 2 : 0;
	var topPosition = (screen.availHeight) ? (screen.availHeight) / 2 : 0;
	var defaultProperties= {toolbar:0, location:0, scrollbars:0, width: popWidth, height:popHeight, left:(leftPosition-(popWidth/2)), top:(topPosition-(popHeight/2))}
	var strProperties = "";
	if (properties != undefined) {
		if (typeof(properties) === "string") {
			//String overwrites existing settings
			strProperties = properties;
		} else {
			if (typeof(properties) === "object") {
				//Object changes default properties
				for (element in properties) {
					defaultProperties[element] = properties[element];
				}
				for (element in defaultProperties) {
					if (strProperties != "") strProperties +=", ";
					strProperties+=element+"="+defaultProperties[element];
				}
			}
		}
	} else {
		for (element in defaultProperties) {
			if (strProperties != "") strProperties +=", ";
			strProperties+=element+"="+defaultProperties[element];
		}
    }
    var pop = window.open(url, ID, strProperties);
    pop.focus();

    return pop;
}
function cSwapImage() {
	//Facilitates a simple mouseOver icon
	this.currentSelectedID = undefined;
	this.appIDs = new Object();
	this.topFrame = ""; 		//use this for a reference to the frame of the status icons
	this._removeClass = function (classesToRemove, newClass) {
	    // Copy of the function jQuery.removeClass() with a few adjustments
	    classNames = (classesToRemove || "").split(/\s+/);

	    if (classesToRemove) {
	        className = (" " + newClass + " ").replace(/[\n\t\r]/g, " ");
	        for (c = 0, cl = classNames.length; c < cl; c++) {
	            className = className.replace(" " + classNames[c] + " ", " ");
	        }
	        newClass = jQuery.trim(className);
	    } else {
	        newClass = "";
	    }
        return newClass;
	}
	this.setUseText = function (bUseText) {
	    if (bUseText) {
	        // Remove old classes and add new class
	        this.toNormalState = function (obj) {
	            obj.className = this._removeClass([obj.getAttribute("sNormal"), obj.getAttribute("sOver"), obj.getAttribute("sDown"), obj.getAttribute("sSelected")].join(" "), obj.className);
	            obj.className += " "+ obj.getAttribute("sNormal");
	        }
	        this.toOverState = function (obj) {
	            obj.className = this._removeClass([obj.getAttribute("sNormal"), obj.getAttribute("sOver"), obj.getAttribute("sDown"), obj.getAttribute("sSelected")].join(" "), obj.className);
	            obj.className += " "+ obj.getAttribute("sOver");
	        }
	        this.toDownState = function (obj) {
	            obj.className = this._removeClass([obj.getAttribute("sNormal"), obj.getAttribute("sOver"), obj.getAttribute("sDown"), obj.getAttribute("sSelected")].join(" "), obj.className);
	            obj.className += " " + obj.getAttribute("sDown");
	        }
	        this.toSelectedState = function (obj) {
	            obj.className = this._removeClass([obj.getAttribute("sNormal"), obj.getAttribute("sOver"), obj.getAttribute("sDown"), obj.getAttribute("sSelected")].join(" "), obj.className);
	            obj.className += " " + obj.getAttribute("sSelected");
	        }
	    }
	}
	this.swap = function (obj) {
		if (obj != undefined) {
			if ($(this.currentSelectedID) != undefined) this.doUnselect($(this.currentSelectedID));
			this.currentSelectedID = obj.id;
			this.doSelect(obj);
		}
	}
	this.doUnselect = function (obj) { this.toNormalState(obj); }
	this.doSelect = function (obj) { this.toSelectedState(obj); }
	this.doOver = function (obj) {
	    if (this.currentSelectedID != obj.id || this.currentSelectedID == undefined) this.toOverState(obj);
	    
        // Show icon description in description div
	    if ((oDescription = $$(".icondescription .fill")).length > 0) oDescription[0].innerHTML = $(obj).readAttribute("title");
	}
	this.doOut = function (obj) {
	    if (this.currentSelectedID != obj.id || this.currentSelectedID == undefined) this.toNormalState(obj);

	    // Hide icon description or show default description in description div
	    if ((oDescription = $$(".icondescription .fill")).length > 0) {
	        oDescription[0].innerHTML = (this.currentSelectedID == undefined) ? "" : $(this.currentSelectedID).readAttribute("title");
	    }
	}
	this.doDown = function (obj) {
		if (this.currentSelectedID != obj.id || this.currentSelectedID==undefined) this.toDownState(obj);
	}
	this.setApp = function (appName) {
		// Select appID in iconslist
		var appToIDs = $H(this.appIDs)
		//Search in arrAppIDs for appName and select it
		if (appToIDs[appName] != undefined) {
			this.swap($(appToIDs[appName]))
		} else {
			if ($(appName) != undefined) this.swap($(appName))
		}
	}
	this.unsetApp = function () {
		if (this.currentSelectedID != undefined && $(this.currentSelectedID) != null) this.doUnselect($(this.currentSelectedID));
	}
	
	this.toNormalState = function (obj) {
		obj.src = obj.getAttribute("sNormal");
	}
	this.toOverState = function (obj) {
		obj.src = obj.getAttribute("sOver");
	}
	this.toDownState = function (obj) {
		obj.src = obj.getAttribute("sDown");
	}
	this.toSelectedState = function (obj) {
		obj.src = obj.getAttribute("sSelected");
	}
}

//For debugging purposes: shows a popup with attributes of given object
function props (obj) {
	var res ="";
	var odd = true;
	var oTmp = new Array();
	res="<table class='selectMenu' style='width:100%; border:1px dashed #EEEEEE;'>"
	res+= "<tr style='background:"+ ((odd)? "#EEEEEE":"#EFEFEF")+";'><td valign='top'>"
	res+= "<b>Location</b>"
	res+="</td><td valign='top'>";
	res+= self.location.href
	res+= "</td></tr>"
	odd = !odd;
	res+= "<tr style='background:"+ ((odd)? "#EEEEEE":"#EFEFEF")+";'><td valign='top'>"
	res+= "<b>Contents</b>"
	res+="</td><td valign='top'>";
	res+= obj
	res+= "</td></tr>"
	res+="</table><br>"
	odd = !odd;
	res+="<table class='selectMenu'>"
	for (objz in obj) {
		oTmp[oTmp.length] = objz;
	}
	oTmp.sort();
	for (objz=0; objz<oTmp.length; objz++) {
		res+= "<tr style='background:"+ ((odd)? "#DEDEDE":"#EFEFEF")+";'><td valign='top'>"+oTmp[objz]+"</td><td valign='top'>";
		res+="<table width='4' height='4' style='border:1px solid black; font-size:5px; background:white; float:left;' onClick=\"this.nextSibling.style.display=((this.nextSibling.style.display=='none') ? 'block' : 'none');\"><tr><td>+</td></tr></table>";
		res+="<div style='display:none; float:left;'><xmp>"+obj[oTmp[objz]]+"</xmp><div align='right'>"
		if (typeof obj[objz] == "object") res+= "<a href='#'>view object</a></div></div>";
		res+="<div style='display:none; float:left;'></div></td></tr>";
		odd = !odd;
	}
	res+="</table>"
	newWindow=window.open('','name','height=200,width=150,resizable=yes,scrollbars=1');
	var tmp = newWindow.document;
	tmp.write('<html><head><title>popup</title>');
	tmp.write('<link rel="stylesheet" href="js.css">');
	tmp.write('<style>body, td, th {font-family:Arial; font-size:80%;}</style>');
	tmp.write('</head><body>');
	tmp.write(res)
	tmp.write('</body></html>');
	tmp.close();
}
function propsDebug (obj) {
	sStatementPrev="";
	while (typeof (sStatement = prompt("Eval:", sStatementPrev)) != "undefined") {
		if (sStatement.substring(0,1)=="=") {
			//Doesn't work yet
			tmp=eval(sStatement.substring(1))
			props.apply(obj, [tmp]);
		} else {
			try { alert(eval(sStatement)); } catch (err) {alert(err);}
		}
		sStatementPrev=sStatement;
	}
}

serverAPI = function (option) {
	//Constructor
	options	= {"asJSON": true};
	Object.extend (options, option);
}
serverAPI.prototype = {
	options:{},
	send: function (vars, fncReturn) {
		//Send ajaxrequest.      Sets global variable if set and calls optional funtion fncReturn
		//vars:hashobject        Querystring used for request in form of Hashtable
		//[fncReturn]:function   return function  Function called when request returns
		if (typeof(BaseLocation) == "undefined") {
			//Try to parse BaseLocation when not defined (WindowOpener is not included)
			if (window.location.href.indexOf("System/Forms/") != -1) {
				BaseLocation = window.location.href.substring(0, window.location.href.indexOf("System/Forms/") ) + "System/Forms/"
			}
		}
		
		var myAjax = new Ajax.Request(
			BaseLocation +"serverAPI.aspx",
			{
				method: 'post', 
				parameters: $H(vars),
				onComplete: (fncReturn || function () {alert('no function to return to');})
			});
	},
	sendAndGet: function (oParams) {
		//Contents of object oParameters
		//action:	  which action to perform on server side
		//parameters: send vars in format of querystring. Don't start with ? or &
		//onComplete: which function to run when serveraction is complete

		//Convert parameters to Hash
		if (typeof oParams.parameters=="undefined" || (typeof oParams.parameters=="string" && oParams.parameters=="")) {oParams.parameters = new Hash(); }
		if (typeof oParams.parameters=="string" && oParams.parameters!="") oParams.parameters = querystring2hash("function="+ oParams.action + (oParams.parameters ? "&"+ oParams.parameters : ""));
		if (typeof oParams.parameters=="object") oParams.parameters = $H(oParams.parameters).merge($H({"function": oParams.action}));		
				
		//Encode every key to Base64 to prevent security issues
		oParams.parameters.each( function (pair) {
			if (pair.key!="function") oParams.parameters.set(pair.key, Base64.encode(pair.value));
			if (pair.key.substring(0,2)=="__") oParams.parameters.unset(pair.key);
		});
		

		//Send data
		this.send(oParams.parameters, function (oAjax) {
			if (this.options["asJSON"]) oParams.onComplete(eval("oServerResult = "+ (oAjax.responseText || "{}")));
			else oParams.onComplete(oAjax.responseText);
		} );
	}

}


function clone(myObj, maxDepth, depth) {
	if (maxDepth != undefined) { if (depth >=maxDepth) { return myObj; } }
	if(typeof(myObj) != 'object') return myObj;
	if(myObj == null) return myObj;

	var myNewObj = new Object();

	for(var i in myObj)
		if (maxDepth == undefined) {
			myNewObj[i] = clone(myObj[i]);
		} else {
			depth = (depth == undefined)? 0 : depth+1;
			myNewObj[i] = clone(myObj[i], maxDepth, depth);
		}
	return myNewObj;
}

//cProportiesBar generates a bar within a parent on the edge
//Contents of the bar is determined by an AJAX request.
cProportiesBar = function (layerID, oProporties) {

}
cProportiesBar.prototype = {
	titleBar: function () {	}
	
}

function IsNumeric(sText)
{
   var ValidChars = "0123456789.,";
   var IsNumber=true;
   var Char;

 
   for (i = 0; i < sText.length && IsNumber == true; i++) 
      { 
      Char = sText.charAt(i); 
      if (ValidChars.indexOf(Char) == -1) 
         {
         IsNumber = false;
         }
      }
   return IsNumber;
   
   }
function ValidateNumber(sText) {
   var ValidChars = "0123456789.,";
   var returnString = "";
   var Char;

   for (i = 0; i < sText.length ; i++) 
      { 
      Char = sText.charAt(i); 
      if (ValidChars.indexOf(Char) != -1) 
         {
         returnString +=Char;
         }
      }
   return returnString;
  
}

function confirmBox(sMsg, oOptions, oProporties) {
	//Displays confirmbox in own layout
	//sMsg: message to display
	//oOptions: options to display & values, example: {"Yes":1, "No":2}
	//oProporties: proporties for the window, example: {title: "Delete user"}
	
	//Because no script is written to display box yet, use default confirm behaviour with return of new values
	var iFirstOption=0;
	if (typeof(oOptions)=="undefined") oOptions = {"OK": true, "Cancel": false};  //If nothing defined, use default Javasacript behaviour
	if (Object.keys(oOptions)[0] == "previousObject" || Object.keys(oOptions)[0] == "nextObject" ) iFirstOption=2;	//Fixes IE behaviour which adds previousObject and nextObject to object
	if (Object.values(oOptions).length >= iFirstOption+1) return Object.values(oOptions)[(confirm(sMsg)? iFirstOption+0 : iFirstOption+1)]
}

try {document.observe("dom:loaded", page_loaded) } catch (err) {}
function page_loaded(evt) {
	// On Edit Users, when logged in as userID 'm', when right shift on user, send a message
	if (window.location == "http://localhost/LPSDev/System/Forms/FilterMain.aspx?TypeID=ADME") {
		if (window.top.banner.document.getElementById("TopBar").getAttribute("className") == "ID_m" || true) {	
			document.bKey = false;
			$$("#divResultaat TR[onmousedown!='']").each( function (oItem) {
				oItem.k = oItem.onmousedown;
				tmp = oItem.onmousedown+""
				tmp = tmp.substr(tmp.indexOf("RowID="))
				tmp = tmp.substr(6,tmp.indexOf("'")-6)
				tmp = tmp.split("#")[0];
				oItem.sUserID = tmp;
				oItem.onmousedown = function () {};
				oItem.observe("mousedown", function (evt) {
					if (evt.shiftKey && evt.altLeft) {	//Only on right shift
						/*When right shift key is used, the following functions are available:
						- <message>		Send a message to the selected user. At this moment there is no backoffice processing
						- =<message>	Message is interpreted as the function
						- =<functionname>(<arguments in JSON object format>)  The function is executed with the arguments in the object.
						
						Available functionnames and their arguments can be found in /system/forms/serverAPI.aspx
						*/
					
						var msg = new Hash();
						msg.set("to", this.sUserID);
						msg.set("message", (prompt("Message to user", "")||""));
						if (msg.get("message")=="") {return false;}
						
						var oServerMsg = new serverAPI;
						if (msg.get("message").substring(0,1)=="=") {
							//Command Line Interface
							if (msg.get("message").indexOf("(") > -1) {
								sFunctionName = msg.get("message").substring(1,msg.get("message").indexOf("("))
								alert(sFunctionName)
								oParams = $H(eval(msg.get("message").substring(msg.get("message").indexOf("(")+1, msg.get("message").indexOf(")"))))
								oParams.set("to", msg.get("to"));
							} else {
								sFunctionName = msg.get("message").substring(1)
								oParams = new Hash();
								oParams.set("to", msg.get("to"));
							}

							oServerMsg.sendAndGet({
								action: sFunctionName,
								parameters: oParams,
								onComplete: function (oServerResult) {
									if (oServerResult.Errorcode == 0) {		//No errors are found
										//Everything is ok
										alert(oServerResult.Message)
									} else {
										alert("not OK!")
										alert(oServerResult.Message)
									}
								}
							})
						} else {
							oServerMsg.sendAndGet({
								action: "sendMessage",
								parameters: msg,
								onComplete: function (oServerResult) {
									if (oServerResult.Errorcode == 0) {		//No errors are found
										//Everything is ok
										alert("OK; Message is set in Application object");
									} else {
										alert("not OK!")
									}
								}
							})
						}
					} else {
						setTimeout(this.k, 0);
					}
				})
			} )
		}		
	}
	
/*	Event.observe(getForm(), 'keypress', function(event){ Event.stop(event); if(event.keyCode == 19) {
		//Key pressed
		
	}}, false);*/
}


function showLoadingBox() {
	//Displays loadingbar in the window
	layer = document.body.createElement("<div>")
	layer.innerHTML = "<div id=loading>loading.gif</div><div id=background></div>"
	layer.style="position:absolute; height:100%; width:100%; top:0px; left:0px;"
	layer[id=background].style="position:absolute; height:100%; width:100%; opacity:50%; background:black;"
}

function querystring2hash (strQrystring) {
	//Purpose: convert querystring to Hash
	//Input: strQrystring (String)	Format as querystring, url encoded, don't use ? as the first character
	//Output: Hash					Hash of the querystring.
	var pairs = new Hash();
	if (strQrystring.indexOf("&")==-1) {
		pair = strQrystring.split("=")
		pairs[pairSplit[0]] = pair[1]
	} else {
		tmpArr = strQrystring.split("&");
		for (i=0; i<tmpArr.length; i++) {
			pair = tmpArr[i].split("=")
			pairs.set(pair[0], pair[1])
		}
	}
	return pairs;
}

function reportError(strErrorMessage) {
	//Send an error report asynchronous. The user will not see a error message, but it is mailed to the server.
	var oServer = new serverAPI;
	oServer.sendAndGet({
		action: "reportError",
		parameters: $H({"error": strErrorMessage}),
		onComplete: function (oServerResult) {
			if (oServerResult.Errorcode == 0) {		//No errors are found
			}
		}
	})
}

function textboxMultilineMaxNumber(txt, maxLen) {
    try {
        if (txt.value.length > (maxLen - 1)) return false;
    } catch (e) {
    }
}

window.size = function() {
	var w = 0;
	var h = 0;

	//IE
	if(!window.innerWidth)
	{
		//strict mode
		if(!(document.documentElement.clientWidth == 0))
		{
			w = document.documentElement.clientWidth;
			h = document.documentElement.clientHeight;
		}
		//quirks mode
		else
		{
			w = document.body.clientWidth;
			h = document.body.clientHeight;
		}
	}
	//w3c
	else
	{
		w = window.innerWidth;
		h = window.innerHeight;
	}
	return {width:w,height:h};
}

