/*
	WillowInitPage 
	
	should be used to call onload functions. Functions can be registered through WillowRegisterOnloadFunction. Example:
	
	function ShowMe() {
		alert('this is an onload triggered function, through WillowInitPage');
	}
	
	WillowRegisterOnloadFunction(ShowMe);
*/

// for this to work, a small change has been made to the calender-setup.js. 
//	param_default("ifFormat",       WillowCalendarIfFormat);

/* startup variabelen /*(*/
var WillowCalendarIfFormat = "%Y/%m/%d";

/* jquery functions /**/

/* startup functions /**/

/* default willow functions /**/
function WillowTrim(val)
{
	// trim leading and trailing spaces
	return val.replace(/^\s+|\s+$/g, "");
}

function WillowRegisterCalendar(bttnId, textId) 
{
	// attempt to fetch the Calendar format from the server tag
	cf = document.getElementById('_WillowCalFormat');
	if (cf != null && cf.value != '') {
		WillowCalendarIfFormat = cf.value;
	} 

	b = document.getElementById(bttnId);
	t = document.getElementById(textId);
	bOk = true;
	
	if (b == null) {
		alert('WillowRegisterCalendar can\'t find the button element');
		bOk = false;
	}

	if (t == null) {
		alert('WillowRegisterCalendar can\'t find the text element');
		bOk = false;
	}

	if (bOk)
		Calendar.setup({inputField : textId, ifFormat: WillowCalendarIfFormat, button: bttnId });
				
	return false;
}

// function to load javascript
function WillowIncludeScript(filename) 
{
    var html_doc = document.getElementsByTagName('head').item(0);
    html_doc.appendChild(WillowCreateScriptTag(filename));
    return false;
}

function WillowCreateScriptTag(filename)
{
    var js = document.createElement('script');
    js.setAttribute('type', 'text/javascript');
    js.setAttribute('language', 'javascript');
    js.setAttribute('src', filename);
    return js;
}

function WillowInitPage() 
{
	if (_WillowOnLoadFocusId != null)
		WillowSetFocus(_WillowOnLoadFocusId);

	if (_WillowOnLoadRegColl != null) 
	{
		for (x in _WillowOnLoadRegColl)
		{
			funcRef = _WillowOnLoadRegColl[x];
			funcRef();
		}
	}

	WillowSetupFancyZoom();
}

function WillowUnloadPage() 
{
	if (_WillowOnUnloadRegColl != null) 
	{
		for (x in _WillowOnUnloadRegColl)
		{
			funcRef = _WillowOnUnloadRegColl[x];
			funcRef();
		}
	}
}

function WillowResizePage() 
{
	if (_WillowOnResize != null) 
	{
		for (x in _WillowOnResize)
		{
		    funcRef = _WillowOnResize[x];
		    funcRef();
		}
	}
}

var _WillowOnLoadRegColl = null;
var _WillowOnUnloadRegColl = null;
var _WillowOnLoadFocusId = null;
var _WillowDefaultButton = null;
var _WillowOnResize = null;

function WillowSetFocus(id) 
{
	o = document.getElementById(id);
	if (o != null)
		o.focus();
}

function WillowRegisterOnloadFunction(func) 
{
	if (_WillowOnLoadRegColl == null) {
		_WillowOnLoadRegColl = new Array();
	}
	
	_WillowOnLoadRegColl[_WillowOnLoadRegColl.length] = func;
}

function WillowRegisterOnUnloadFunction(func) 
{
	if (_WillowOnUnloadRegColl == null) {
		_WillowOnUnloadRegColl = new Array();
	}
	
	_WillowOnUnloadRegColl[_WillowOnUnloadRegColl.length] = func;
}

function WillowRegisterOnResizeFunction(func) 
{
        if (_WillowOnResize == null) {
                _WillowOnResize = new Array();
        }

        _WillowOnResize[_WillowOnResize.length] = func;
}

function WillowSetDefaultButton(obj) 
{
	if (obj != null && obj.id != null && obj.id.length > 0)
	{
		_WillowDefaultButton = obj.id;
	}
}

function WillowSubmitPage() 
{
	if (_WillowDefaultButton != null)
	{
		o = document.getElementById('WillowDefaultButtonContainter');
		if (o != null) 
		{
			res = true;
			if (_bWillowSkipDefaultButtonClick == false && o.onclick != null) 
			{
				res = o.click();
			}

			if (res)
				o.submit();
		}
	} 
	return true;
}

var _bWillowSkipDefaultButtonClick = false;

function WillowSubmitDefaultButton(obj) 
{
	if (_WillowDefaultButton != null) 
	{
		o = document.getElementById(_WillowDefaultButton);
		if (o != null) 
		{
			obj.name = o.name;

			// execute the onclick of the default button
			if (_bWillowSkipDefaultButtonClick == false && o.onclick != null && !o.click()) 
			{
				return false;
			}
			return true;			
		}
	}
	return false;
}

function WillowExecuteOnclick(objid) 
{
	elobj = document.getElementById(objid);
	if (elobj != null) 
	{
		if (elobj.onclick != null) 
		{
			return eval(elobj.click());
		}
	}
	
	return;
}

var _WillowOnChangeToMD5Changing = false;

function WillowOnChangeToMD5(element) 
{
	if (_WillowOnChangeToMD5Changing == false) {
		// make sure the current event isnt triggered again
		_WillowOnChangeToMD5Changing = true;
		element.value = hex_md5(element.value);
		_WillowOnChangeToMD5Changing = false;
	}
}

function WillowIE6PostbackFix(objid) 
{
	elobj = document.getElementById(objid);
	if (elobj != null) {
	
		if (elobj.onclick != null) {
			eval(elobj.click());
		}
	}
	
	return false;
}

function WillowSubmit(id) 
{
	if (typeof(id) == 'object')
		_WillowDefaultButton = id.id;
	else 
		_WillowDefaultButton = id;

	o = document.getElementById('WillowDefaultButtonContainter');
	if (o!=null)
		o.submit();
}

function WillowSubmitLinkbuttonWithoutClick(id) 
{
	o = document.getElementById(id);

	if (o != null) {
		//alert("gaan onclick uitvoeren van element " + id);
		valuelb = o.onclick();
	}
	//valuelb = o.href;
	//eval(valuelb);
}

function WillowGetCookie(cookieName) 
{
	// first we'll split this cookie up into name/value pairs
	// note: document.cookie only returns name=value, not the other components
	var a_all_cookies = document.cookie.split( ';' );
	var a_temp_cookie = '';
	var cookie_name = '';
	var cookie_value = '';
	var b_cookie_found = false; // set boolean t/f default f
	
	for ( i = 0; i < a_all_cookies.length; i++ )
	{
		// now we'll split apart each name=value pair
		a_temp_cookie = a_all_cookies[i].split( '=' );
		
		// and trim left/right whitespace while we're at it
		cookie_name = a_temp_cookie[0].replace(/^\s+|\s+$/g, '');
	
		// if the extracted name matches passed check_name
		if (cookie_name == cookieName)
		{
			b_cookie_found = true;
			// we need to handle case where cookie has no value but exists (no = sign, that is):
			if ( a_temp_cookie.length > 1 )
			{
				cookie_value = unescape( a_temp_cookie[1].replace(/^\s+|\s+$/g, '') );
			}
			// note that in cases where cookie is initialized but no value, null is returned
			return cookie_value;
			break;
		}
		a_temp_cookie = null;
		cookie_name = '';
	}

	if ( !b_cookie_found )
	{
		return "";
	}
	return "";
}	

function InsertTextAtCaret(obj, text)
{
	if (document.selection) 
	{
		obj.focus();
		sel = document.selection.createRange();
		sel.text = DropDownList1.options[DropDownList1.selectedIndex].text;
	} else if (obj.selectionStart || obj.selectionStart == '0') {
		//MOZILLA/NETSCAPE support
		var startPos = obj.selectionStart;
		var endPos = obj.selectionEnd;
		obj.value = obj.value.substring(0, startPos) + text + obj.value.substring(endPos, obj.value.length);
	} else {
		obj.value += text;
	}
}

function WillowInsertImgTag(path, photo, obj, ourl, osize, oalign) 
{
	result = '';
	//ourl = url; //document.getElementById('<willow type="literal"><value><controlid>txtimageurl</controlid></value></willow>');
	//osize = size; //document.getElementById('<willow type="literal"><value><controlid>ddlsize</controlid></value></willow>'); 
	//oalign = align ; //ocument.getElementById('<willow type="literal"><value><controlid>ddlalign</controlid></value></willow>'); 

	bUseUrl = false;
	imgurl = '';
	linkheader = '';
	linkfooter = '';

	if (ourl.value != '')
		bUseUrl = true;

	if (bUseUrl) {
		linkheader = '[url=' + ourl.value + ']';
		linkfooter = '[/url]';
	}

	switch (osize.options[osize.selectedIndex].value) {
		case '1':
			imgurl = path + '/' + photo;
			break;
		case '2':
			photo = WillowCallback.GetTumbnail(path, photo, '400x300').value;
			if (photo == '') {
				alert('Creating the tumbnail failed');
				return;
			}
			imgurl = path + '/' + photo;
			break;
		case '3':
			photo = WillowCallback.GetTumbnail(path, photo, '100x75').value;
			if (photo == '') {
				alert('Creating the tumbnail failed');
				return;
			}
			imgurl = path + '/' + photo;
			break;
		case '4':
			photo = WillowCallback.GetTumbnail(path, photo, '200x150').value;
			if (photo == '') {
					alert('Creating the tumbnail failed');
					return;
			}
			imgurl = path + '/' + photo;
			break;
	}

	switch (oalign.options[oalign.selectedIndex].value) {
		case '1':
			result = linkheader + '[img align=left]' + imgurl + '[/img]' + linkfooter;
			break;
		case '2':
			result = '\n\n[center]' + linkheader + '[img]' + imgurl + '[/img]' + linkfooter + '[/center]\n\n';
			break;
		case '3':
			result = linkheader + '[img align=right]' + imgurl + '[/img]' + linkfooter;
			break;
	}

	InsertTextAtCaret(obj, result);
}

function WillowSetDisplay(objname, val) 
{
	o = document.getElementById(objname);
	if (o != null) {
		o.style.display = val;
	}
}

function WillowSetEnabled(ctrlid, val) 
{
	o = document.getElementById(ctrlid);
	if (o != null) {
		o.disabled = (val == true? false : true);
	} else {
		alert('sorry, can\'t find control ' + ctrlid);
	}
}

function WillowSetReadonly(ctrlid, val) 
{
	o = document.getElementById(ctrlid);
	if (o != null) {
		o.readOnly = val;
	}
}

function WillowDisableAll(frm) 
{
	for (var i=0; i<frm.elements.length; i++) {
		if (frm.elements[i].type == 'button') {
			frm.elements[i].disabled = true;
		} else if (frm.elements[i].type == 'submit' && frm.elements[i].id != 'WillowDefaultButtonContainter') {
			frm.elements[i].disabled = true;
		}
	}
}

_ImgWillowWaitCursor = new Image();
_ImgWillowWaitCursor.src = 'image/waiting.gif';

function WillowShowWaitCursor() 
{
	o = document.getElementById('willowpagebody');
	if (o != null) {
		o.innerHTML += '<div style="position:absolute;top:0px;left:0px;width:100%;height:100%;z-index:9999;	opacity: 0.75;filter: alpha(opacity=75);-moz-opacity: 0.75;background: white url(\'' + _ImgWillowWaitCursor.src + '\') 50% 50% no-repeat;"></div>';
	}
}

function WillowGetCoords (element) 
{
	var coords = { x: 0, y: 0, width: 0, height: 0 };
	var os = $(element).offset();
	coords.x = os.left;
	coords.y = os.top;
	//coords.width = $(element).width();
	//coords.height = $(element).height();
	coords.width = element.offsetWidth;
	coords.height = element.offsetHeight;
	return coords;
}

function WillowSetCoords (element, coords) 
{
	if (element != null && coords != null) 
	{
		element.style.top = coords.x;
		element.style.top = coords.y;
		element.style.width = coords.width;
		element.style.height = coords.height;
	}
	return coords;
}

function WillowGetScreenSize() 
{
	var coord = { x: 0, y: 0 };

	if (parseInt(navigator.appVersion)>3) {
		if (navigator.appName=="Netscape") {
			coord.x = window.innerWidth;
			coord.y = window.innerHeight;
		}
		if (navigator.appName.indexOf("Microsoft")!=-1) {
			coord.x = document.body.offsetWidth;
			coord.y = document.body.offsetHeight;
		}
	}
	
	return coord;
}

function WillowGetLoginKey() 
{
	return WillowGetCookie("WillowCMS");
}

var WillowConfirmTitle = 'Confirm';
var WillowConfirmTextOk = 'Ok';
var WillowConfirmTextCancel = 'Cancel';
var _WillowConfirmStatusOk = false;

function WillowConfirmSetStatus(bValue) 
{
	if (bValue) {
		_WillowConfirmStatusOk = true;
	} else {
		_WillowConfirmStatusOk = false;
	}
}

function WillowConfirmStatus() 
{
	return _WillowConfirmStatusOk;
}

function WillowConfirm(element, text)
{ 
	if (!WillowConfirmStatus()) 
	{
		elcoords = WillowGetCoords(element);
		coords = WillowGetScreenSize();
		
		// create button
		windowID = "WillowConfirm";
		JSWindowsClose(windowID);
		
		content = document.createElement("div");
		content.id = "WillowConfirmDialogContent";
		content.innerHTML = "<center>" + text + "<br><br><div id=\"willowconfirmbttncontainer\"></div></center>";
		
		res = new JSWindow(WillowConfirmTitle, content, (coords.x / 2) - 200, elcoords.y - 10, windowID, 400, 'white', 0); 
		
		o = document.getElementById('willowconfirmbttncontainer');
		if (o != null) {
			// dynamisch buttons toevoegen
			var bttnok = document.createElement("button");
			bttnok.id = "jsbttonwillowconfirmok";
			bttnok.style.width = "80px";
			bttnok.innerHTML = "Ok";
			bttnok.onclick  = function() { WillowConfirmOk(windowID, element.id); };
			o.appendChild(bttnok);
			
			var spacer = document.createElement("span");
			bttnok.innerHTML = "&nbsp;";
			o.appendChild(spacer);
			
			var bttncancel = document.createElement("button");
			bttncancel.id = "jsbttonwillowconfirmcancel";
			bttncancel.style.width = "80px";
			bttncancel.innerHTML = WillowConfirmTextCancel;
			//bttncancel.onclick  = new Function("WillowConfirmCancel('" + windowID + "'); }");
			bttncancel.onclick  = function() { WillowConfirmCancel(windowID); };
			o.appendChild(bttncancel);
			
		}
	
		/* fix for ie7 */
		o = document.getElementById('jsbttonwillowconfirmok');
		if (o != null)
			o.style.display = 'inline';

		o = document.getElementById('jsbttonwillowconfirmcancel');
		if (o != null)
			o.style.display = 'inline';
		
		return true;
	}
	
	return false;
}

function WillowConfirmCancel(windowName)
 {
	WillowConfirmSetStatus(false);
	JSWindowsClose(windowName);
}

function WillowConfirmOk(windowName, elementId) 
{
	WillowConfirmCancel(windowName);
	WillowConfirmSetStatus(true);
	WillowSubmitLinkbuttonWithoutClick(elementId);
}

/*
<text>document.getElementById('preview').innerHTML = WillowCallback.GetWillowPreview(document.getElementById('</text>
<controlid>message</controlid>
<text>').value, document.getElementById('</text>
<controlid>contenttype</controlid>
<text>').value).value; return false;</text></onclick>
/**/


// http://www.bram.us/2008/02/01/javascript-isarray-check-if-an-elementobject-is-an-array/
// X-Browser isArray(), including Safari
function isArray(obj) 
{
	return obj.constructor == Array;
}

function isObject(obj)
{
	return (typeof(obj) == 'object');
}
	
var _WillowDynDropDownList = null;
var _WillowDynDDLElement = null;
var _WillowDynDDLContainer = null;
var _WillowDynDDLMouseOver = false;

// element       = 
// contentid     = 
// callelementid = 
// query         = 
function WillowDynamicFillList(CallingControl, ListControl, RecId, RecValue) 
{
	//public string WillowDynCallbackCollection(string UrlHostname, string LoginKey, string CallerId, string[] FormVariables)
	if (CallingControl != null && ListControl != null && RecId != null && RecValue != null) 
	{
		DebugLog('WillowDynamicFillList called');
		_WillowDynDDLElement = ListControl;
		var response = null;
		var cursor = document.body.style.cursor;
		var limited = false;

		try
		{
			document.body.style.cursor = "wait";

			wfcs = null;			
			if (CallingControl.getAttribute("dynpar") == "limited")
				wfcs = WillowFormContentSerialize(false);
			else 
				wfcs = WillowFormContentSerialize(true);
				
			// add listcontrol value
			WillowFormContentSerAdd(wfcs, ListControl.name, ListControl.value);

			DebugLog('WillowDynamicFillList just before call');
			res = WillowCallback.WillowDynCallbackCollection(WillowCurrentDomainName(), WillowGetLoginKey(), CallingControl.name, wfcs);
			DebugLog('WillowDynamicFillList just after call');

			if (res != null)
				response = res;

			if (response != null && response.value != null && response.value != '')
			{
				var resobj = eval('(' + response.value + ')');

				if (resobj.exception != 'undefined' && resobj.exception != null)
				{
					DebugLog('WillowDynamicFillList call returned an exception');
					WillowShowDynCallbackException(resobj);
				} else if (resobj.dyncallback != null) { 

					// update input elements
					bRes = false;
					var oi = resobj.dyncallback.collection;

					if (oi != null && oi != '')
					{
						bRes = true;
						coords = WillowGetCoords(ListControl);

						if (_WillowDynDropDownList != null) 
						{
							_WillowDynDDLContainer.removeChild(_WillowDynDropDownList);
							_WillowDynDropDownList = null;
						}

						w = coords.width;//-2;
						_WillowDynDropDownList = document.createElement("div");
						_WillowDynDropDownList.id = ListControl.id + 'dyndropdownlist';
						_WillowDynDropDownList.style.position = "absolute";
						_WillowDynDropDownList.style.zIndex = "100";
						_WillowDynDropDownList.style.left = (coords.x + 1) +"px"; // + 1;
						_WillowDynDropDownList.style.top = (coords.y + coords.height - 1) + "px";
						_WillowDynDropDownList.style.width = (w<250?250:w) + "px";
						_WillowDynDropDownList.style.maxwidth = '250px';
						_WillowDynDropDownList.style.height = '5em';
						_WillowDynDropDownList.style.backgroundColor = "white";
						_WillowDynDropDownList.style.border = "1px solid silver";
						_WillowDynDropDownList.style.overflow = "auto";
						_WillowDynDropDownList.onmouseover = function() { WillowDynDDLSetMouseOver(true); };
						_WillowDynDropDownList.onmouseout = function() { WillowDynDDLSetMouseOver(false); };

						if (oi.record != null) // && oi.record.length > 0)
						{
							nrItems = 0;
							// fill the list
							
							if (isArray(oi.record) && oi.record.length > 0)
							{
								for (var i=0;i<oi.record.length;i++)
								{
									rec = oi.record[i];
									_WillowDynDropDownList.innerHTML += '<div class="liststyle' + (i%2?'Alternate':'')+ '" style="white-space: nowrap;cursor:hand;cursor:pointer;overflow:hidden;" onclick="WillowTextDDLItemSelected(\'' + rec[RecId] + '\');" onmouseover="WillowDynDDLSetMouseOver(true);" onmouseout="return;WillowDynDDLSetMouseOver(false);">' + rec[RecValue] + '</div>';
									nrItems++;
								}	
							} else {
								rec = oi.record;
								_WillowDynDropDownList.innerHTML += '<div class="liststyle" style="white-space: nowrap;cursor:hand;cursor:pointer;overflow:hidden;" onclick="WillowTextDDLItemSelected(\'' + rec[RecId] + '\');" onmouseover="WillowDynDDLSetMouseOver(true);" onmouseout="return;WillowDynDDLSetMouseOver(false);">' + rec[RecValue] + '</div>';
								nrItems++;
							}

							if (nrItems > 8) {
								_WillowDynDropDownList.style.height = (8 * 1.5) + 'em';
							} else {
								_WillowDynDropDownList.style.height = nrItems * 1.5 + 'em';
							}

							$(document.body).prepend(_WillowDynDropDownList);
							document.onmousedown = WillowDDLGetMouseDownEvent;
	
							//_WillowDynDDLContainer = document.getElementById('PageCurrent');
							//if (_WillowDynDDLContainer != null)
							//{
							//	_WillowDynDDLContainer.appendChild(_WillowDynDropDownList);
							//	document.onmousedown = WillowDDLGetMouseDownEvent;
							//} else {
							//	_WillowDynDropDownList = null;
							//}
						} else {
							DebugLog('Collection empty');
							alert ("Collection empty");
						}
					}

					if (!bRes)
						alert("No result");
				} else {
					alert("Unknown error");
				}


			}  else {
				alert("No result returned");
			}

		} catch (Error) {
			alert(Error.description);
			DebugLog('WillowDynamicFillList exception');
			DebugLog(Error.description);
			result = null;
		}

		document.body.style.cursor = cursor;

	} else {
		alert('WillowDynamicFillList parameters dont match');
	}
}

function WillowDynamicPopup(callingObj, content, width, height)
{
	if (_WillowDynDropDownList != null) 
	{
		_WillowDynDDLContainer.removeChild(_WillowDynDropDownList);
		_WillowDynDropDownList = null;
	}

	// if callingObj is an id, then get the element
	if (!isObject(callingObj))
		callingObj = document.getElementById(callingObj);

	var coords = WillowGetCoords(callingObj);
	var w = coords.width;

	_WillowDynDropDownList = document.createElement("div");
	_WillowDynDropDownList.id = callingObj.id + 'dddl';
	_WillowDynDropDownList.style.position = "absolute";
	_WillowDynDropDownList.style.zIndex = "100";
	_WillowDynDropDownList.style.left = (coords.x + 1) +"px"; // + 1;
	_WillowDynDropDownList.style.top = (coords.y + coords.height - 1) + "px";
	_WillowDynDropDownList.style.width = (width!=null?width:(w<250?250:w) + "px");
	_WillowDynDropDownList.style.maxwidth = '400px';
	_WillowDynDropDownList.style.height = (height!=null?height:'5em');
	_WillowDynDropDownList.style.backgroundColor = "white";
	_WillowDynDropDownList.style.border = "1px solid silver";
	_WillowDynDropDownList.style.overflow = "auto";
	_WillowDynDropDownList.onmouseover = function() { WillowDynDDLSetMouseOver(true); };
	_WillowDynDropDownList.onmouseout = function() { WillowDynDDLSetMouseOver(false); };
	_WillowDynDropDownList.innerHTML += content;	

	$(document.body).prepend(_WillowDynDropDownList);
	document.onmousedown = WillowDDLGetMouseDownEvent;
}

function WillowDynDDLSetMouseOver(stat) 
{
	_WillowDynDDLMouseOver = stat;
}

function WillowTextDDLFetchDynList() 
{
	if (_WillowDynDDLElement != null) 
	{
		_WillowDynDDLElement.value = val;
	}
	WillowTextDropDownClose();
}

function WillowTextDDLItemSelected(val) 
{
	if (_WillowDynDDLElement != null) 
	{
		_WillowDynDDLElement.value = val;
	}
	WillowTextDropDownClose();
}

// todo: check if _WillowDynDDLContainer contains _willowdyndropdownlist
function WillowTextDropDownClose() 
{
	if (_WillowDynDropDownList != null) 
	{
		document.body.removeChild(_WillowDynDropDownList);
		//_WillowDynDDLContainer.removeChild(_WillowDynDropDownList);
		_WillowDynDropDownList = null;
		document.onmousedown = '';
	}
}

function WillowDDLGetMouseDownEvent(s, e) 
{
	if (_WillowDynDDLMouseOver) 
	{
		return true;
	} else {
		_WillowDynDDLMouseOver = false;
		WillowTextDropDownClose();
	}
	return true;
}

function WillowDDLGetMouseDown() 
{
	if (!_WillowDynDDLMouseOver) 
	{
		WillowTextDropDownClose();
	}
}

function WillowSetupFancyZoom () 
{
	if (! document.getElementsByTagName) 
	{
		return;
	}

	var links = document.getElementsByTagName("a");
	var used = false;

	for (i = 0; i < links.length; i++) 
	{
		if (links[i].getAttribute("href")) 
		{
			if (links[i].getAttribute("href").search(/(.*)\.(jpg|jpeg|gif|png|bmp|tif|tiff)/gi) != -1) 
			{
				if (links[i].getAttribute("rel") == "zoom") 
				{
					links[i].onclick = function (event) { return zoomClick(this, event); };
					links[i].onmouseover = function () { zoomPreload(this); };
					used = true;
				}
			}
		}
	}

	if (used == true)
	{
		if(typeof insertZoomHTML == 'function') 
		{
			insertZoomHTML();
			zoomdiv = document.getElementById(zoomID);  
			zoomimg = document.getElementById(theID);
		}
	}
}

function WillowSetImageWithMaxX(elementId, filename, maxX) 
{
	el = document.getElementById(elementId);
	img = new Image();
	img.src = filename;

	if (el != null) {
		if (img.width > maxX) {
			el.style.width=maxX + 'px'; //'100%';
		}
		el.src = img.src;
	}
}

function WillowSetImageWithMaxY(elementId, filename, maxY) 
{
        img = new Image();
	//img.onload = function() { WillowSetLoadedSrcImageMaxY(elementId, filename, maxY); };
        img.src = filename;
	//img.onload = function() { WillowSetLoadedSrcImageMaxY(elementId, filename, maxY); };

	if (img.width > 0) 
	{
		WillowSetLoadedSrcImageMaxY(elementId, filename, maxY);
	} else {
		img.onload = function() { WillowSetLoadedSrcImageMaxY(elementId, filename, maxY); };
	}
}

function WillowSetLoadedSrcImageMaxY(elementId, filename, maxY) 
{
	el = document.getElementById(elementId);

        if (el != null) {
		img = new Image();
		img.src = filename;

                if (img.height > maxY) {
                        el.style.height=maxY + 'px';
                }
                el.src = img.src;
	}
}

function WillowCurrentDomainName() 
{
	if (document != null)
		return document.domain;
}

// postback the form and update the page
function WillowDynPostBack(callingObj)
{
	return WillowDynUpdateCurrentPage(callingObj, null);
}

// postback the form and update the page with extra value
function WillowDynPostBackValue(callingObj, val)
{
	return WillowDynUpdateCurrentPage(callingObj, val);
}

function WillowDynUpdateCurrentPage(callingObj, val)
{
	var bResult = false;
	result = WillowDynCallback(callingObj, val);

	if (result != null)
	{
		if (WillowDynCallbackParsing(result, callingObj))
			bResult = true;
	} else {
		alert("no result, doing nothing");
	}

	return bResult; //true;
}

var _debuglog = null;
var _debugLoggingEnabled = false;

function DebugLog(message)
{
	if (_debugLoggingEnabled)
	{
		if (_debuglog == null)
			_debuglog = document.getElementById('debug');

		var curTime = new Date();
		message = curTime.getHours() + ":" + curTime.getMinutes() + ":" + curTime.getSeconds() + " : " + message;

		if (_debuglog != null)
			_debuglog.innerHTML += "<p>" + message + "</p>";
		else 
			alert(message);
	}
}

function WillowDynCallbackParsing(response, callingObj)
{
	DebugLog("WillowDynCallbackParsing called");

	if (response != null && response.error != null)
	{
		DebugLog('error: ' + response.error);
		alert(response.error);
		return;
	}

	DebugLog("WillowDynCallbackParsing");
	
	if (response != null && response.value != null && response.value != '')
	{
		var resobj = eval('(' + response.value + ')');
	
		if (resobj != null && resobj.dyncallback != null)
		{
			// update input elements
			if (resobj.dyncallback.input != null)
			{
				DebugLog("WillowDynCallbackParsing::parsing resobj.dyncallback.input");

				if (isArray(resobj.dyncallback.input))
				{
					for (var i=0;i<resobj.dyncallback.input.length;i++)
					{
						var oi = resobj.dyncallback.input[i];
						o = document.getElementById(oi.id);

						if (o != null)
						{
							DebugLog(oi.value);
							o.value = oi.value;
						}
					}
				} else {
					DebugLog("WillowDynCallbackParsing::resobj.dyncallback.input is not an array");
				}
			}

			var pagecurrent = document.getElementById('PageCurrent');

			// todo: script
			// update script elements
			if (resobj.dyncallback.script != null)
			{
				DebugLog("WillowDynCallbackParsing::parsing resobj.dyncallback.script");

				if (isArray(resobj.dyncallback.script))
				{
					for (var i=0;i<resobj.dyncallback.script.length;i++)
					{
						var oi = resobj.dyncallback.script[i];
						
						// create script element
						// alert(oi);
						var tag = WillowCreateScriptTag(oi);
						$(document.body).prepend(tag);
					}
				} else {
					DebugLog("WillowDynCallbackParsing::resobj.dyncallback.input is not an array");
				}
			}

			if (resobj.dyncallback.page != null) 
			{
				DebugLog("WillowDynCallbackParsing::parsing resobj.dyncallback.page");
				var oi = resobj.dyncallback.page
				if (pagecurrent != null) 
				{
					// alert(oi);
					pagecurrent.innerHTML = oi;
				} else {
					DebugLog("WillowDynCallbackParsing::Can\'t find the container element");
					//break;
				}
			} else {
				DebugLog("WillowDynCallbackParsing::no page defined in callback");
			}
		} else {
			DebugLog("WillowDynCallbackParsing::resobj is null of geen response (resobj.dyncallback)");
		}
	} else {
		DebugLog("WillowDynCallbackParsing::response is null, or empty");
	}
}

function WillowDynCallbackActionResult(callingObj, val, useAllElements) 
{
	// callingObj the name of- or the calling object
	// val = null or a (string) value
	// useAllElements = true/false
	var result = { ok: false, iok: 0, error: null, ex: null };
	
	try
	{
		DebugLog('WillowDynCallbackActionResult just before call');
		
		if (callingObj != null)
		{
			// get object if only name is provided
			var callid = null;
			if (!isObject(callingObj))
				callid = callingObj;
			else
				callid = (callingObj.name == '' ? callingObj.id : callingObj.name);
				
			if (useAllElements == null)
				useAllElements = true;
			if (val == null)
				val = "";
		
			var res = WillowCallback.WillowDynCallbackActionResult(WillowCurrentDomainName(), WillowGetLoginKey(), callid, WillowFormContentSerialize(useAllElements), val);
			if (res != null)
			{
				// parse the result
				if (res != null && res.value != null && res.value.length > 0)
				{
					var resobj = eval('(' + res.value + ')');
					if (resobj != null && resobj.dyncallback != null)
					{
						if (resobj.dyncallback.result != null)
						{
							result.ok = (resobj.dyncallback.result.ok == "True" ? true : false);
							result.iok = (resobj.dyncallback.result.iok == "1" ? true : false);
							result.error = resobj.dyncallback.result.error;
							result.ex = resobj.dyncallback.result.ex;
						}
						
						if (resobj.dyncallback.element != null)
						{
						}						
					}
				} else {
					throw "Callback to server failed";
				}
			} else {
				throw "Callback to server failed";
			}

		} else {
			throw "No calling object or id given";
		}

	} catch (Error) {
		alert(Error);
		DebugLog('WillowDynCallback exception on calling WillowCallback.WillowDynCallback');
		DebugLog(Error);
		result = null;
	}
	
	return result;
}

function WillowDynCallback(callingObj, val) 
{
	DebugLog('WillowDynCallback called');
	var result = null;
	
	try
	{
		DebugLog('WillowDynCallback just before call');
		
		if (callingObj != null)
		{
			var callid = null;
			if (!isObject(callingObj))
				callid = callingObj;
			else
				callid = (callingObj.name == '' ? callingObj.id : callingObj.name);
				
			if (val == null)
				val = '';
		
			res = WillowCallback.WillowDynPostback(WillowCurrentDomainName(), WillowGetLoginKey(), callid, WillowFormContentSerialize(true), val);
			if (res != null)
				result = res;
		} else {
			throw (new exception("No calling object or id given"));
		}

	} catch (Error) {
		alert(Error.description);
		DebugLog('WillowDynCallback exception on calling WillowCallback.WillowDynCallback');
		DebugLog(Error.description);
		result = null;
	}

	return result;
}

function GetValueFromJSON(response)
{
	result = null;
	if (response != null && response.value != null && response.value != '')
	{
		var resobj = eval('(' + response.value + ')');

		if (resobj.exception != 'undefined' && resobj.exception != null)
		{
			// DebugLog('WillowDynCallbackElementValue call returned an exception');
			WillowShowDynCallbackException(resobj);
		} else if (resobj.dyncallback != null && resobj.dyncallback.result != null) { 
			var oi = resobj.dyncallback.result;
			if (oi != null)
				result = oi;
		}
	}
	return result;
}

function WillowDynCallbackElementValue(callingObj) 
{
	DebugLog('WillowDynCallbackElementValue called');
	var result = null;

	try
	{
		DebugLog('WillowDynCallbackElementValue just before call');
		res = WillowCallback.WillowDynCallbackElementValue(WillowCurrentDomainName(), WillowGetLoginKey(), callingObj.name, WillowFormContentSerialize(true));
		if (res != null)
			result = res;

	} catch (Error) {
		alert(Error.description);
		DebugLog('WillowDynCallbackElementValue exception on calling WillowCallback.WillowDynCallbackElementValue');
		DebugLog(Error.description);
		result = null;
	}

	return result;
}

// returns html
function WillowDynCallbackElement(callingObj, useAllElements) 
{
	return WillowDynPostbackValueGetElement(callingObj, useAllElements, null);
}

function WillowDynPostbackValueGetElement(callingObj, useAllElements, val)
{
	DebugLog('WillowDynCallbackElementValue called');
	var result = null;
	var limited = false;

	try
	{
		if (callingObj.getAttribute("dynpar") == "limited")
			limited = true;
			
		var callid = null;
		if (!isObject(callingObj))
			callid = callingObj;
		else
			callid = (callingObj.name == '' ? callingObj.id : callingObj.name);

		if (val == null)
			val = '';

		DebugLog('WillowDynCallbackElementValue just before call');
		response = WillowCallback.WillowDynCallbackElement(WillowCurrentDomainName(), WillowGetLoginKey(), callid, WillowFormContentSerialize(useAllElements), limited, val);

		if (response != null && response.value != null && response.value != '')
		{
			var resobj = eval('(' + response.value + ')');

			if (resobj.exception != 'undefined' && resobj.exception != null)
			{
				DebugLog('WillowDynCallbackElementValue call returned an exception');
				WillowShowDynCallbackException(resobj);

			} else if (resobj.dyncallback != null) { 

				// update input elements
				bRes = false;
				var oi = resobj.dyncallback.element;

				if (oi != null)
				{
					result = oi;
				}
			} else {
				alert("Result from server incorrect");	
			}
		} else {
			alert("Connection to server not established");
		}

	} catch (Error) {
		DebugLog('WillowDynCallbackElement exception on calling WillowCallback.WillowDynCallbackElement');
		DebugLog(Error.description);
		result = null;
	}

	return result;
}

// function _bWillowFormContentSerializeBase64 = true;

// WillowFormContentSerialize(bool AllElements) 
function WillowFormContentSerialize(useAllElements) 
{
	DebugLog('WillowFormContentSerialize called:' + useAllElements);

	var form = new Array;

	if (useAllElements==true)
	{
		var inputs = document.getElementsByTagName('input');
		_WillowFillArrayWithControlValue(form, inputs);

		inputs = document.getElementsByTagName('textarea');
		_WillowFillArrayWithControlValue(form, inputs);

		inputs = document.getElementsByTagName('select');
		_WillowFillArrayWithControlValue(form, inputs);
	} else {
		// only willow needed elements (hidden)
		var inputs = document.getElementsByTagName('input');

		for (element in inputs) 
		{
			if (inputs[element].type == "hidden" && inputs[element].name.length > 0)
				WillowFormContentSerAdd(form, inputs[element].name, inputs[element].value);
				//form[form.length] = inputs[element].name + '=' + Base64.encode(inputs[element].value);
		}
	}
	return form;
}

function WillowFormContentSerAdd(form, elname, val)
{
	form[form.length] = elname + '=' + (val!=null&&val.length>0?Base64.encode(val):"");
}

function _WillowFillArrayWithControlValue(form, inputs)
{
	if (inputs != null && inputs.length > 0)
	{
		for (element in inputs) 
		{
			if (element !=null && inputs[element] != null && inputs[element].type != null) 
			{
				switch (inputs[element].type)
				{
					case "submit":
					case "button":
						break;
					case "checkbox":
						if (inputs[element].name.length > 0)
							WillowFormContentSerAdd(form, inputs[element].name, (inputs[element].checked? inputs[element].value : ""));
							//formVals[formVals.length] =  inputs[element].name + '=' + Base64.encode(inputs[element].checked? inputs[element].value : "");
						break;
					default:
						if (inputs[element].name.length > 0)
							WillowFormContentSerAdd(form, inputs[element].name, inputs[element].value);
							//formVals[formVals.length] = inputs[element].name + '=' + Base64.encode(inputs[element].value);
						break;
				}

			}
		}
	}
}

function WillowSwitchDisplay(button, elementId) 
{
	result = false;
	o = document.getElementById(elementId);

	if (o != null) 
	{
		switch (o.style.display) 
		{
			case "none":
				// not visible, lets show it
				o.style.display = "block";
				button.parentNode.style.background = "url('image/folder.open.png') 0% 0% no-repeat;";
				result = true;
				break;
			default:
				// visible, lets hide it
				o.style.display = "none";
				button.parentNode.style.background = "url('image/folder.close.png') 0% 0% no-repeat;";
				result = false;
				break;
		}
	}
	return result;
}

function WillowCaseAllUpper(ctrl) 
{
	ctrl.value = ctrl.value.toUpperCase();
}

function WillowCaseFirstUpper(ctrl) 
{
	ctrl.value = ctrl.value.charAt(0).toUpperCase() + ctrl.value.substr(1).toLowerCase();
}

function WillowCaseAllLower(ctrl) 
{
	ctrl.value = ctrl.value.toLowerCase();
}

// container for multiple WillowGoogleMap objects
var WillowGMapContainer = new Array();

function WillowGoogleMapMarker()
{
	this.id = '';
	this.markerEnum = 0;
	this.marker = null;
	this.infoWindow = '';

	this.onDragEnd = null;

	this.showInfo = function()
	{
		this.marker.openInfoWindowHtml('<html><body>' + unescape(this.infoWindow) + '</body></html>');
	}

	this.dragEnd = function()
	{
		if (this.onDragEnd != null)
		{
			eval(this.onDragEnd);
		}
	}
}

function WillowGoogleMap() 
{
	this.gmap = null;
	this.gmapEnum = 0;
	this.mapId = '';
	this.mappingElement = null;
	this.defZoom = 13;
	this.markers = new Array();

	this.scrollWheel = true;
	this.mapTypeControl = false;
	this.largeMapControl = false;

	this.centerPnt = null;

	this.init = function() 
	{
		if (GBrowserIsCompatible()) 
		{
			this.gmap = new GMap2(document.getElementById(this.mappingElement)); 

			if (this.scrollWheel)
				this.gmap.enableScrollWheelZoom();
			if (this.centerPnt != null)
				this.gmap.setCenter(this.centerPnt, this.defZoom);
			if (this.mapTypeControl)
				this.gmap.addControl(new GMapTypeControl());
			if (this.largeMapControl)
				this.gmap.addControl(new GLargeMapControl());

			this.gmapEnum = WillowGMapContainer.length;
			WillowGMapContainer[this.gmapEnum] = this;

			WillowRegisterOnUnloadFunction(GUnload);
		}
	}

	this.center = function(lat, lng) 
	{
		if (this.gmap != null)
		{
			this.gmap.setCenter(new google.maps.LatLng(lat, lng), this.defZoom);
		} else {
			
			this.centerPnt = new google.maps.LatLng(lat, lng); 

		}
	}

	this.getMarker = function(markerId)
	{
		for (x in this.markers)
		{
			// filter on id or on marker pointer
			if (this.markers[x].id == markerId || this.markers[x].marker == markerId)
				return this.markers[x];
		}
		return null;
	}

	// add the marker to the collection, if the marker id doesn't exists
	this.addMarker = function(wgmmarker)
	{
		if (this.gmap != null && wgmmarker.id.length > 0)
		{
			// check if marker id exists?
			var marker = this.getMarker(wgmmarker.id);

			// non existing, add to collection
			if (marker == null) 
			{
				nr = this.markers.length;
				this.markers[nr] = wgmmarker;
				wgmmarker.markerEnum = nr;

				// add marker to map
				this.gmap.addOverlay(wgmmarker.marker);
			}
		}
	}

	// markerId, lat, lng, drag, infowindow
	// if marker exists, use that one
	this.newMarker = function(mrkObj)
	{
		var wgmarker = null;

		if (this.gmap != null && mrkObj != null)
		{
			var bExists = true;
			var bDrag = WillowStrToBool(mrkObj.marker.draggable);

			// test if marker exists
			wgmarker = this.getMarker(mrkObj.marker.id);
			if (wgmarker == null)
			{
				wgmarker = new WillowGoogleMapMarker();
				wgmarker.id = mrkObj.marker.id; //markerId;
				bExists = false;
			}

			wgmarker.infoWindow = mrkObj.marker.infowindow;
			wgmarker.marker = new GMarker(new google.maps.LatLng(mrkObj.marker.lat, mrkObj.marker.lng), {draggable: bDrag });
			// add drag end
			if (bDrag && mrkObj.marker.ondragend != null) 
				wgmarker.onDragEnd = mrkObj.marker.ondragend;

			// add the marker to the collection and remember the index nr, if not existing
			if (!bExists)
				this.addMarker(wgmarker);

			var nr = wgmarker.markerEnum;
			var gmapnr = this.gmapEnum;

			if (bDrag)
			{
				GEvent.addListener(wgmarker.marker, "dragstart", function() { WillowGMapContainer[gmapnr].markers[nr].marker.closeInfoWindow(); } );
				GEvent.addListener(wgmarker.marker, "dragend", function() { WillowGMapContainer[gmapnr].markers[nr].dragEnd(); } );
				mrkObj.marker.enableDragging();
			}

			if (mrkObj.marker.infowindow != null && mrkObj.marker.infowindow.length > 0)
			{
				nr = this.gmapEnum;
				GEvent.addListener(wgmarker.marker, "click", function() { WillowGMapContainer[gmapnr].markers[nr].showInfo(); } );
			}
		}

		return wgmarker;
	}
}

function WillowStrToBool(val)
{
	var bRes = false;

	if (val != null)
	{
		if (val == "true" || val == "True" || val == "TRUE")
			bRes = true;
		else if (val == 1 || val == "1")
			bRes = true;
	}

	return bRes;
}
