/*
	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";
var willow = new WillowJSObject();

/* Willow /**/
function WillowJSObject() {
	// containers
	this.AlertRegister=null;		// register for alert messages

	// public booleans
	this.debug = false;

	// private booleans
	this.onloadExecuted = false;	// boolean to limit onload execution to one
	
	// setup
	$(document).ready(function(){
		willow.onload();
	});

	// functions
	this.onload = function()
	{
		if (!this.onloadExecuted)
		{
			this.onloadExecuted = true;

			if (_WillowOnLoadRegColl != null) 
			{
				for (x in _WillowOnLoadRegColl)
				{
					funcRef = _WillowOnLoadRegColl[x];
					funcRef();
				}
			}
		
			// fancy zoom setup
			WillowSetupFancyZoom();
			
			// onload attribute
			var jq = $('[onwillowload]');
			if (jq != null)
				jq.each(function(i) { eval(this.getAttribute("onwillowload")) });
			// setup altSubmit
			jq = $('[altSubmit]');
			if (jq != null)
				jq.keypress(function(e) { WillowCheckEnter(this, e); } );
			// masked inputs
			jq = $('[mask]');
			if (jq != null)
				jq.each(function (i) { $(this).mask(this.getAttribute("mask")) });
			
			// display registrated alerts
			if (this.AlertRegister != null) 
			{
				for (x=0; x<this.AlertRegister.length; x++)
					alert(this.AlertRegister[x]);
			}
			
			// set focus
			if (_WillowOnLoadFocusId != null)
				this.setFocus(_WillowOnLoadFocusId);
		}
	}
	
	this.setFocus = function(id) 
	{
		o = document.getElementById(id);
		if (o != null)
			o.focus();
	}
	
	this.getJQObj = function(obj)
	{
		if (obj != null)
		{
			// get object if only name is provided
			if (!isObject(obj))
			{
				obj = $('#' + obj);
			} else if (!(obj instanceof jQuery)) {
				obj = $(obj);
			}
			return obj;
		} 
		return null;
	}

	this.debugLog = function(message)
	{
		if (this.debug)
		{
			$.log(message);
		}
	}

	this.RegisterAlertMessage = function(txt)
	{
		if (txt != null && txt.length > 0)
		{
			if (this.AlertRegister == null) 
			{
				this.AlertRegister = new Array();
			}
			this.AlertRegister[this.AlertRegister.length] = txt;
		}
	}
	
	// trim leading and trailing spaces
	this.trim = function(val)
	{
		return val.replace(/^\s+|\s+$/g, "");
	}
	
	this.removeSpaces = function(val)
	{
		return val.split(' ').join('');
	}
	
	//function loadScript(url, callback){
	this.loadScript = function(url)
	{
		this.loadScriptCallback(url, null);
	}
	
	this.loadScriptCallback = function(url, callback)
	{
	    var script = document.createElement("script")
	    script.type = "text/javascript";
	
		if (callback != null)
		{
		    if (script.readyState){  //IE
		        script.onreadystatechange = function(){
		            if (script.readyState == "loaded" ||
		                    script.readyState == "complete"){
		                script.onreadystatechange = null;
		                callback();
		            }
		        };
		    } else {  //Others
		        script.onload = function(){
		            callback();
		        };
		    }
	    }

	    script.src = url;
	    document.getElementsByTagName("head")[0].appendChild(script);
	}

	// storage for the objects to filter the json selects
	var _selectJSONarray = Array();

	this.selectJSONFilter = function(selectobj)
	{
		if (selectobj != null)
		{
			for (var i=0; i<_selectJSONarray.length; i++)
			{
				if (selectobj == _selectJSONarray[i]._obj)
					return _selectJSONarray[i];
			}
			
			var spt = new SelectPrototype(selectobj);
			_selectJSONarray[_selectJSONarray.length] = spt;
			return spt;
		}
		return null;		
	}
	
	this.loginExpiredCheck = function(message, url)
	{
		$.post(
			"/remote/loginexpiredcheck", 
			function(data) {
				if (data != null && data.result != null)
				{
					switch (data.result.value)
					{
					case "1":
						if (confirm(message))
							document.location.href(url);
						break;
					}
				}
			}
		);		
	}
	
	// Get CFEditor configurations
	this.ckeditConfig = function(toolbarid, iHeight)
	{
		if (toolbarid == null) toolbarid="";
		if (iHeight == null || iHeight == 0) iHeight = 250;
		
		switch (toolbarid.toLowerCase())
		{
		case "basic":
			return {
				toolbar: CKEDITOR.config.toolbar_Basic,
				height : iHeight,
				theme : 'default',
				skin : 'v2'
			};
			break;
		case "full":
			return {
				toolbar: CKEDITOR.config.toolbar_Full,
				height : iHeight,
				theme : 'default',
				skin : 'v2'
			};
			break;
		case "small":
			return {
				toolbar:
				[
					['Bold', 'Italic', '-', 'NumberedList', 'BulletedList', '-', 'Link', 'Unlink'],
					['UIColor']
				],
				height : iHeight,
				theme : 'default',
				skin : 'v2'
			};
			break;
		case "willow":
			return {
				toolbar:
				[
					['Source','-','Undo','Redo','-','Find','Replace','-','SelectAll','RemoveFormat','-','Cut','Copy','Paste','PasteText','PasteWord','-','SpellCheck'],
					['Bold','Italic','Underline','StrikeThrough','-','Subscript','Superscript'],
					'/',
					['OrderedList','UnorderedList','-','Outdent','Indent','Blockquote'],
					['JustifyLeft','JustifyCenter','JustifyRight','JustifyFull'],
					['Link','Unlink','Anchor'],
					['Image','Table','SpecialChar'],
					['TextColor','BGColor'],
					['FitWindow','ShowBlocks','-','About']
				],
				height : iHeight,
				theme : 'default',
				skin : 'v2'
			};

		default:
			return {
				toolbar:
					[
						['Source'],
						['Cut','Copy','Paste','PasteText','PasteFromWord','-','Print', 'SpellChecker', 'Scayt'],
						['Undo','Redo','-','Find','Replace','-','SelectAll','RemoveFormat'],
						'/',
						['Bold','Italic','Underline','Strike','-','Subscript','Superscript'],
						['NumberedList','BulletedList','-','Outdent','Indent','Blockquote','CreateDiv'],
						['JustifyLeft','JustifyCenter','JustifyRight','JustifyBlock'],
						['Link','Unlink','Anchor'],
						['Image','Table','HorizontalRule','Smiley','SpecialChar','PageBreak'],
						'/',
						['Styles','Format','Font','FontSize'],
						['TextColor','BGColor'],
						['Maximize', 'ShowBlocks','-','About']
					],
				height : iHeight,
				theme : 'default',
				skin : 'v2'
			};
			break;
		}
		return null;
	}
	


}

function WillowInitPage()
{
	//willow.onload();
}

function WillowUnloadPage() 
{
	if (_WillowOnUnloadRegColl != null) 
	{
		for (x in _WillowOnUnloadRegColl)
		{
			funcRef = _WillowOnUnloadRegColl[x];
			funcRef();
		}
	}
}

/* jquery functions /**/
JSON=null;

/* default willow functions /**/
function WillowTrim(val)
{
	return willow.trim(val);
}

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 WillowCloseUploadProgressBar(obj)
{
	if (obj!=null) { eval($('#'+obj.name).attr('onwillowcancel') || function(){}); }
}

// function to load javascript
function WillowIncludeScript(filename) 
{
	return willow.loadScript(filename)
}

// condition
function collCondition(field, comparison, value)
{
	this.where = "&";
	this.field = field;
	this.comp = comparison;
	this.value = value;
	
	// test if its a match 
	this.match = function(record) {
		// get the value from the record
		var val = record[this.field];
		
		if (this.comp == "=" && this.value == val)
			return true;
		else if (this.comp == "!=" && this.value != val)
			return true;
	
		return false;
	}
}

// ------ select prototyping -------------------------------------------------------
function SelectPrototype(selectobj)
{
	this._obj = selectobj;
	this._collection = null;
	this._filtered = false;
	
	this.willowCollection = function() {
		// check if _collection is set
		if (this._collection == null)
		{
			// check if we have a jsoncollection
			var jcoll = this._obj.getAttribute("jsoncollection");
			if (jcoll != null && jcoll.length > 0)
			{
				this._collection = eval('(' + jcoll + ')');
			}
		}
		return this._collection;
	}
	
	this.getRecord = function(index) {
		if (index == null)
			index = this._obj.selectedIndex;
	
		var wc = this.willowCollection();
		if (wc != null && wc.wjc != null && wc.wjc.collection != null)
		{
			if (!this._filtered && wc.wjc.allowempty == "1")
				index--;
			return wc.wjc.collection[index];
		}
		return null;
	}

	// filter the current visible items
	this.filter = function(filterArray, bIgnoreAddEmpty) {
		if (bIgnoreAddEmpty == null)
			bIgnoreAddEmpty=true;

		// filter is an array of collCondition objects?
		// collCondition.match(record);
		this._filtered = false;
		var wc = this.willowCollection();
		if (wc != null && wc.wjc != null && wc.wjc.collection.length > 0)
		{
			var result = Array();
			// step through the records
			for (var i=0; i<wc.wjc.collection.length; i++)
			{
				var record = wc.wjc.collection[i];
				if (filterArray == null || filterArray.length == 0)
				{
					// if filter is empty, the fill with all records
					result[result.length] = record;
				} else {
					// match record with filter
					this._filtered = true;
					var filterCollMatch = true;
					for(var j=0; j<filterArray.length; j++)
					{
						var curfilter = filterArray[j];
						var m = curfilter.match(record);
						if (curfilter.where == "&" && (m == true && filterCollMatch == true))
							filterCollMatch = true;
						else if (curfilter.where == "|" && (m == true || filterCollMatch == true))
							filterCollMatch = true;
						else 
							filterCollMatch = false;
							
						if (!filterCollMatch)
							break;
					}
					
					if (filterCollMatch)
						result[result.length] = record;
				}
			}
		
			// fill options with result
			var ifield = wc.wjc.indexfield;
			var vfield = wc.wjc.valuefield;
			var allowEmpty = wc.wjc.allowempty;
			var curval = null;
			if (this._obj.selectedIndex >= 0 && this._obj.options != null && this._obj.options.length>0)
			{
				curval = this._obj[this._obj.selectedIndex].value;
			}

			// clear the options list
			this._obj.options.length = 0;
			// fill the options list
			for(var i=0; i<result.length; i++)
			{
				//if (!this._filtered && i == 0 && allowEmpty == "1")
				//(!this._filtered || (this._filtered && !bIgnoreAddEmpty)) && 
				if (i == 0 && allowEmpty == "1")
					if ((this._filtered && bIgnoreAddEmpty==false) || !this._filtered)
						this._obj.options[this._obj.options.length] = new Option('', '');
			
				var opt = document.createElement('option');
				opt.text = result[i][vfield];
				opt.value = result[i][ifield];
				this._obj.options[this._obj.options.length] = opt;
			}
			
			// set the last value as selected
			if (curval != null)
			{
				for(var i=0; i<this._obj.options.length; i++)
				{
					if (this._obj.options[i].value == curval)
					{
						this._obj.selectedIndex = i;
						break;
					}
				}
			}
			return true;
		}
		return false;
	}
}
// ------ end select prototyping ---------------------------------------------------

// JSON Collection functions
function WillowSelectJSONCollectionGetValue(obj, propName)
{
	var rec = obj.getRecord();
	if (rec != null)
	{
		return rec[propName];
	}
}
// end JSON Collection functions

// http://jennifermadden.com/javascript/stringEnterKeyDetector.html
// adepted to use the WillowDefaultButton code
function WillowCheckEnter(callingObj, e)
{
	var altSubmit = callingObj.getAttribute("altSubmit");
	if (altSubmit != null && altSubmit.length > 0)
	{
		switch (e.which)
		{
		case 13: 
			//if generated character code is equal to ascii 13 (if enter key)
			WillowMasqAsDefButtonSubmit(document.getElementById(altSubmit));
			return false;
		} 
	}
	
	return true;
}

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 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('WillowDefaultButtonContainer');
		if (o != null) 
		{
			res = true;
			if (_bWillowSkipDefaultButtonClick == false && o.onclick != null) 
			{
				res = o.click();
			}

			if (res)
				o.submit();
		}
	} 
	return true;
}

var _bWillowSkipDefaultButtonClick = false;

// dont call this directly, this is used by the first (real default) button in the page
function WillowSubmitDefaultButton(obj) 
{
	if (_WillowDefaultButton != null) 
	{
		// get the defined default button
		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 WillowMasqAsDefButtonSubmit(submitObj)
{
	// store the id of this button
	//WillowSetDefaultButton(submitObj);
	//submitObj.form.submit();
	return WillowSubmit(submitObj);
}

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('WillowDefaultButtonContainer');
	if (o!=null)
		return o.form.submit;
		
	return false;
}

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 != 'WillowDefaultButtonContainer') {
			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');
}
	
function WillowShowDynCallbackException(obj)
{
	if (obj != null && obj.exception != null)
	{
		alert(obj.exception.message);
	}
}
	
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)
{
	DebugLog('WillowDynamicPopup');

	if (_WillowDynDropDownList != null) 
	{
		_WillowDynDDLContainer.removeChild(_WillowDynDropDownList);
		_WillowDynDropDownList = null;
	}

	// create element
	_wddl = document.createElement("div");
	_WillowDynDropDownList = _wddl;
	_wddl.innerHTML += content;
	_wddl.id = callingObj.id + 'dddl';
	_wddl.style.position = "absolute";
	_wddl.style.zIndex = "10000";
	_wddl.style.backgroundColor = "white";
	_wddl.style.border = "1px solid silver";
	_wddl.style.overflow = "auto";
	_wddl.onmouseover = function() { WillowDynDDLSetMouseOver(true); };
	_wddl.onmouseout = function() { WillowDynDDLSetMouseOver(false); };
	$(_wddl).hide();
	$(document.body).prepend(_WillowDynDropDownList);

	// if callingObj is an id, then get the element
	var bDef = true;
	if (!isObject(callingObj))
	{
		switch (callingObj)
		{
		case "":
		case "center":
			bDef = false;
			
			// wont use width/height
			width = $(_wddl).outerWidth(true);
			height = $(_wddl).outerHeight(true);
			
			height = ($(window).height() - height) / 2;
			_wddl.style.top = ($(window).scrollTop() + (height<0?0:height)) + 'px';
			
			width = ($(window).width() - width) / 2;
			_wddl.style.left = ($(window).scrollLeft() + (width<0?0:width)) + 'px';
			
			DebugLog("left,top=" + _wddl.style.left + ',' + _wddl.style.top);
			break;
		default:
			callingObj = document.getElementById(callingObj);
			break;
		}
	}
	
	if (bDef && callingObj != null)
	{
		var wddl = $(_wddl);
		var coords = WillowGetCoords(callingObj);
		var w = coords.width;

	    wddl.css("top", (coords.y + coords.height - 1) + "px");
	    wddl.css("left", (coords.x + 1) +"px");
		wddl.css("width", (width!=null?width:(w<250?250:w) + "px"));
		wddl.css("maxwidth", '400px');
		wddl.css("height", (height!=null?height:'5em'));
	}
	
	document.onmousedown = WillowDDLGetMouseDownEvent;
	$(_wddl).show();
}

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 = true;

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);
	}/**/
	willow.debugLog(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 el = { enabled: true, value: '' }
	var result = { ok: false, iok: 0, error: null, ex: null, element:el };
	
	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)
						{
							result.element.enabled = (resobj.dyncallback.element.enabled == "True" ? true : false);
							result.element.value = resobj.dyncallback.element.value;
						}						
					} else {
						throw "Callback to server failed";
					}
				} 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 != '')
	{
		//alert("debug:" + 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
	{
		var callid = null;
		if (!isObject(callingObj))
			callid = callingObj;
		else
			callid = (callingObj.name == '' ? callingObj.id : callingObj.name);
	
		DebugLog('WillowDynCallbackElementValue just before call');
		res = WillowCallback.WillowDynCallbackElementValue(WillowCurrentDomainName(), WillowGetLoginKey(), callid, 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('WillowDynPostbackValueGetElement called');
	var result = null;
	var limited = false;

	try
	{
		var callid = null;
		if (!isObject(callingObj))
		{
			callid = callingObj;
		} else {
			callid = (callingObj.name == '' ? callingObj.id : callingObj.name);
			if (callingObj.getAttribute("dynpar") == "limited")
				limited = true;
		}

		if (val == null)
			val = '';

		DebugLog('WillowDynPostbackValueGetElement 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('WillowDynPostbackValueGetElement call returned an exception');
				WillowShowDynCallbackException(resobj);
				result = null;

			} 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 + "\n" + Error.message);
		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();
}

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;
}
