var isIE = navigator.userAgent.indexOf("MSIE") > -1
		&& navigator.userAgent.indexOf("Opera") == -1;
var isMoz = navigator.userAgent.indexOf('Mozilla/5.0') > -1
		&& !(navigator.userAgent.indexOf('WebKit') > -1);
var isIE8 = isIE && navigator.userAgent.indexOf("MSIE 8.0") > -1;
var isIE9 = isIE && navigator.userAgent.indexOf("MSIE 9.0") > -1;

var HeightCorrector = 50;
var WidthCorrector = 6;

var inputElementNames = new Array("input", "textarea", "select");

/**
 * extracts the uri of the current page
 */
function getURI()
{
	var loc = window.location + "";
	return loc.match(/(\/[^\/?#]+)+/)[0];
} 

/**
 * convenience function for executing remote action through ajax
 */
function executeRemoteAction(action, params, callback)
{
	var page_request;
	if (window.XMLHttpRequest) // if Mozilla, Safari, IE 7 etc
	{
		page_request = new XMLHttpRequest();
	}
	// if IE < 7
	else if (window.ActiveXObject)
	{ 
		try {
			page_request = new ActiveXObject("Msxml2.XMLHTTP");
		} 
		catch (e)
		{
			try{
				page_request = new ActiveXObject("Microsoft.XMLHTTP");
			}
			catch (e){}
		}
	}
	else
		return false; // object could not be created (should not happen...)

	// set feedback function
	page_request.onreadystatechange=function() 
	{
		if (page_request.readyState == 4)
		{
			if(page_request.status != 200)
			{
				alert(page_request.status + ": " + page_request.statusText);
			}
			else
			if(callback)
			{
				callback(page_request.responseText);
			}
		}		
	}

	try
	{
		// get da bitch
		page_request.open('POST', "/RemoteActionProcessor/"+getURI()+"?RemoteAction_ID="+encodeURIComponent(action), true);
      	page_request.setRequestHeader("Content-type", "application/x-www-form-urlencoded");
//      	page_request.setRequestHeader("Content-length", params.length);		
		page_request.send(params);
	}
	catch(e)
	{
		alert('<b>Error</b>: ' + e);
	}
}

/**
* convenience function for updating AjaxBlock
*/
function updateBlock(id, params, callback)
{
	if(params)
		params = "&"+params;
	else
		params = "";
	loadIntoElement("/AjaxContentDisplayer/"+getURI()+"?AjaxBlock_ID="+encodeURIComponent(id)+params, 
		document.getElementById(id), callback);
}


function loadIntoElementReadyHandler(block, page_request, callback) 
{
	var text = page_request.responseText;
	if(text && text.length > 0)
	{
		if(text.search(/^\s*eval\(.*\)\s*$/) > -1) // if text is like eval([javascript]), execute
			eval(text);
		else
		{
			block.innerHTML = text;
			var scripts = block.getElementsByTagName('script');
			for(var i = 0; i < scripts.length; ++i)
			{
				eval(scripts[i].text);
			}
		}	
	}
	else
		if(page_request.status != 200)
		{
			block.innerHTML = page_request.statusText;
		}
		else
			block.innerHTML = '';	
	
	if(callback)
		setTimeout(callback, 0); // ensure callback is only executed after element is rendered
}

/**
 * load page from url into a html block element
 */
function loadIntoElement(url, block, callback)
{
	// defer displaying of loading information, so for very small ajax blocks we don't 
	// flash. but don't defer to much so loading information still appears to user instanous
	var timer = setTimeout("showLoading()", 200);

	var page_request;
	if (window.XMLHttpRequest) // if Mozilla, Safari, IE 7 etc
	{
		page_request = new XMLHttpRequest();
	}
	// if IE < 7
	else if (window.ActiveXObject)
	{ 
		try {
			page_request = new ActiveXObject("Msxml2.XMLHTTP");
		} 
		catch (e)
		{
			try{
				page_request = new ActiveXObject("Microsoft.XMLHTTP");
			}
			catch (e){}
		}
	}
	else
		return false; // object could not be created (should not happen...)

	// set feedback function
	page_request.onreadystatechange=function()
	{
		if (page_request.readyState == 4)
		{
			loadIntoElementReadyHandler(block, page_request, callback);
			clearTimeout(timer);
			hideLoading();
		}
	}

	// ensure correct mime type if possible (use text plain for best compatibility)
	if(page_request.overrideMimeType)
		page_request.overrideMimeType('text/plain');

	try
	{
		// get da bitch
		page_request.open('GET', url, true);
		page_request.send(null);
	}
	catch(e)
	{
		block.innerHTML = '<b>Error</b>: ' + e;
	}
}

// gets the inner width of a window
function GetInnerSize () {
	var x,y;
	if (self.innerHeight) // all except Explorer
	{
		x = self.innerWidth;
		y = self.innerHeight;
	}
	else if (document.documentElement && document.documentElement.clientHeight)
		// Explorer 6 Strict Mode
	{
		x = document.documentElement.clientWidth;
		y = document.documentElement.clientHeight;
	}
	else if (document.body) // other Explorers
	{
		x = document.body.clientWidth;
		y = document.body.clientHeight;
	}
	return [x,y];
}

// resizes windows inner dimension 
function ResizeToInner (w, h) {
	if(isIE)
	{
		// make sure we have a final x/y value
		// pick one or the other windows value, not both
		var x = window.screenLeft || window.screenX;
		var y = window.screenTop || window.screenY;
		// for now, move the window to the top left
		// then resize to the maximum viewable dimension possible
		window.moveTo(0,0);
		window.resizeTo(screen.availWidth,screen.availHeight);
		// now that we have set the browser to it's biggest possible size
		// get the inner dimensions.  the offset is the difference.
		var inner = GetInnerSize();
		var ox = screen.availWidth-inner[0];
		var oy = screen.availHeight-inner[1];
		// now that we have an offset value, size the browser
		// and position it
		window.resizeTo(w+ox, h+oy);
		window.moveTo(x,y);
	}
	else
	{
		window.innerWidth = w;
		window.innerHeight = h;
	}
}

function RemoveSpaces(inp) {
	var buffer = '';
	for (z=0; z < inp.length; z++)
		if(inp.charAt(z) != ' ') buffer = buffer + inp.charAt(z);
	return buffer;
}

function generateClubLogin(ClubName)
{
	var ClubLogin = RemoveSpaces(ClubName);

	if(ClubLogin.length > 20)
		ClubLogin = ClubLogin.substring(0, 19);

	return ClubLogin.toLowerCase();
}

function generateUserName(Name, Prename)
{
	var ThisUserName = Name;
	if(Name.length >= 10)
		ThisUserName = Name.substring(8);
	if(Prename == null || Prename.trim() == "")
		return ThisUserName;
	else
		return Prename.toUpperCase().charAt(0)+ThisUserName;
}

function setFocus(element)
{
	if(!element) // if element is invalid, return
		return;

	if(!element.disabled
		&& !(element.style.visibility == 'hidden')
		&& !(element.style.display == 'none'))
	{
		element.focus();
	
		if(isIE)
		{
			if(element.oldClassName == null)
				element.oldClassName = element.className;
			element.className = "inputfocus";
		}
	
		if(element.select)
			element.select();
	}
}

function PageLoaded()
{
	if(isIE)
		setFocusOnInputs()

	if(window.hasFileInput)
		registerOnClickListener();
	
	if(document.getElementById('FixedBottomBar'))
		document.getElementById('Content').style.marginBottom = '3em';

	hideLoading();
}

function setFocusOnInputs()
{
	var inputs = document.getElementsByTagName("input");

	for(var i = 0; i < inputs.length; i++)
	{
		var input = inputs[i];
		if(input.type == "text"
			|| input.type == "password")
		{
			if(input.oldClassName == null)
				input.oldClassName = input.className;

			input.oldFocus = (input.onfocus)?input.onfocus:function(){};
			input.onfocus = function() { this.className = "inputfocus"; this.oldFocus(); };

			input.oldBlur = (input.onblur)?input.onblur:function(){};
			input.onblur = function() { this.className = this.oldClassName; this.oldBlur(); };
		}
	}

	inputs = document.getElementsByTagName("textarea");

	for(i = 0; i < inputs.length; i++)
	{
		var input = inputs[i];

		if(input.oldClassName == null)
			input.oldClassName = input.className;

		input.oldFocus = (input.onfocus)?input.onfocus:function(){};
		input.onfocus = function() { this.className = "inputfocus"; this.oldFocus(); };

		input.oldBlur = (input.onblur)?input.onblur:function(){};
		input.onblur = function() { this.className = this.oldClassName; this.oldBlur(); };
	}
}

function onInputFocus()
{
	doInputFocus(this);
}

function doInputFocus(element)
{
	element.oldClassName = element.className;
	element.className = "inputfocus";
}

function onInputBlur()
{
	this.className = this.oldClassName;
}

function filterKey(event, keycode, fun)
{
	var pressedcode;
	if(window.event)
		pressedcode = window.event.keyCode;
	else
		pressedcode = event.which;	

	if(pressedcode == keycode)
	{
		fun();
		return false;
	}
	else
		return true;
}

function hideLoading()
{
	document.body.style.cursor = 'auto';
	if(document.getElementById('Loading') != null)
		document.getElementById('Loading').style.visibility = 'hidden';
}

function showLoading()
{
	if(document.getElementById('Loading') != null)
		document.getElementById('Loading').style.visibility = 'visible';
}

function showHelp(Page)
{
	showHelpWindow('/Help?Page='+Page);
}

function showHelpWindow(URL)
{
	var width = Math.round(window.screen.availWidth*0.7);
	var height = Math.round(window.screen.availHeight*0.6);
	var left = Math.round((window.screen.width-width)/2);
	var top = Math.round((window.screen.height-height)/2 - (window.screen.height*0.1));

	window.open(URL,'_help','status=no,scrollbar=1,scrollbars=yes,resizable=yes,screenX='+left+',screenY='+top+',left='+left+',top='+top+',width='+width+',height='+height);
}

function showDownload(Page)
{
//	var left = Math.round((window.screen.width-300)/2);
//	var top  = Math.round((window.screen.height-400)/2);
	
	if(!document.getElementById("__DlWin"))
	{
		var iframe;
		if(isIE)
			iframe = document.createElement('<IFRAME name="DlWin" src="'+Page+'">');
		else
			iframe = document.createElement('IFRAME');
	    iframe.src = Page;
	    iframe.style.width = '100%';
	    iframe.style.height = '100%';
	    iframe.opener = window;
	    var div = document.createElement('DIV');
	    div.id = '__DlWin';
	    div.style.display = 'none';
	    div.style.overflow = 'hidden';
	    div.appendChild(iframe);
	    document.getElementsByTagName('BODY')[0]
	    	.appendChild(div);

		$("#__DlWin").dialog ( { 
			modal: true,
			autoOpen: false,
			height: 260,
			width: 350
		} );
	}
	else
	{
	    var div = document.getElementById("__DlWin");
	    div.firstChild.src = "about:blank";
	    div.firstChild.src = Page;
	}

	$("#__DlWin").dialog("open");
    
}

function closeDownloadWin() 
{
	window.parent.$('#__DlWin').dialog('close');
    var div = document.getElementById("__DlWin");
}

function showPrint(Page)
{
	var width = Math.round(window.screen.availWidth*0.7);
	var height = Math.round(window.screen.availHeight*0.9);
	var left = Math.round((window.screen.width-width)/2);
	var top = Math.round((window.screen.height-height)/2 - (window.screen.height*0.1));

	window.open(Page,'PrintWin','width='+width+',height='+height+',status=no,scrollbar=yes,scrollbars=yes,screenX='+left+',screenY='+top+',left='+left+',top='+top+',resizable=yes');
}

//used for hiding and showing elements
function show_hide(controller, id, display)
{
	var shown = controller.state == 'shown';

	if(shown)
	{
		document.getElementById(id).style.display = 'none';
		controller.src = "/img/def/show.gif";
		controller.state = 'hidden';
	}
	else
	{
		document.getElementById(id).style.display = display;
		controller.src = "/img/def/hide.gif";
		controller.state = 'shown';
	}
}


/**
 * Functions used by PrintWindow
 */
function resizePrintWindow()
{
	var Table = document.getElementById("PrintTable");

	var width = Table.offsetWidth+Table.offsetLeft+30;
	var height = Table.offsetHeight+Table.offsetTop+50;

	if(width > window.screen.availWidth-20)
		width = window.screen.availWidth-20;
	if(height > window.screen.availHeight-20)
		height = window.screen.availHeight-20;

	window.resizeTo(width, height);
}

/**
 * Functions used by DownloadWindow
 */

function resizeDownloadWindow()
{
}

function doDownload(url)
{
	 window.location.replace(url);
	 window.parent.$('#__DlWin').dialog('close');
}

function doSend(url)
{
	 window.parent.$('#__DlWin').dialog('close');
	 window.parent.location.replace(url);
}

/**
 * Functions used by NumberInput-Element
 */

function increase(input)
{
	if(input.value == '')
		input.value = 1;
	else
		if(!isNaN(input.value))
			input.value = (parseInt(input.value)+1);

	return false;
}

function decrease(input)
{
	if(input.value == '')
		input.value = 0;
	else
		if(!isNaN(input.value))
			input.value = (parseInt(input.value)-1);

	return false;
}


/**
 * Functions used by DBTable
 */

var AlterDirection = 0;
var MaxRows = new Object();
var TotalRows = new Object();
var Position = new Object();

function AlterMaxRows(tableID)
{
	var id;
	if(!tableID) // backwards combat
		id = "DBTable_PositionIndicator";
	else
		id = tableID+"_positionIndicator";

	if(AlterDirection != 0
			&& (AlterDirection > 0 || MaxRows[tableID] > 5)
			&& Position[tableID]+MaxRows[tableID] < TotalRows[tableID])
	{
		MaxRows[tableID] += AlterDirection;

		document.getElementById(id).innerHTML =
			(Position[tableID]+1)+"-"+(Position[tableID]+MaxRows[tableID]);
		if(tableID)
			setTimeout("AlterMaxRows('"+tableID+"')", 140);
		else
			setTimeout("AlterMaxRows()", 140);
	}
}

function AlterMaxRows_Start(tableID, direction)
{
	MaxRows[tableID] = parseInt(document.forms['DBTable_NavigationForm_'+tableID].DBTableNavigation_MaxRows.value);
	TotalRows[tableID] = parseInt(document.forms['DBTable_NavigationForm_'+tableID].DBTableNavigation_TotalRows.value);
	Position[tableID] = parseInt(document.forms['DBTable_NavigationForm_'+tableID].DBTableNavigation_Position.value);

	AlterDirection = direction;
	AlterMaxRows(tableID);
}

function AlterMaxRows_Finish(tableID)
{
	if(AlterDirection != 0)
	{
		AlterDirection = 0;

		document.forms['DBTable_NavigationForm_'+tableID].DBTableNavigation_MaxRows.value = MaxRows[tableID];

		if(tableID)
		{
			try
			{
				dbTableReload(document.forms['DBTable_NavigationForm_'+tableID], tableID);
			}
			catch (e)
			{
				// only submit form if ajax failed
				showLoading();
				document.forms['DBTable_NavigationForm_'+tableID].submit();
			}
		}
		else
		{
			// for backward compatibility to old DBTable
			showLoading();
			document.forms['DBTable_NavigationForm_'+tableID].submit();	
		}
	}
}

// reloads dbtable either by ajax or normally
function dbTableOrderByClick(tableID, el)
{
	var form = document.forms['DBTable_OrderByForm_'+tableID];
	try
	{
		form.buttonClicked = el.name;
		dbTableReload(form, tableID);
	}
	catch (e)
	{
  	// only submit form if ajax failed
		showLoading();
		  var h=document.createElement('input');
		  input.type = 'hidden';
		  input.name = el.name+'.x';
		  input.value = 'c';
		form.appendChild(h);
	  form.submit();
	}
}

// reloads the dbtable using ajax scripting
function dbTableReload(form, tableID, addParams)
{
	var params = form.buttonClicked+".x=c"
	
	// iterate through elements
	for (var i=0; i < form.elements.length; i++) {
	   var element = form.elements[i];
	   params += "&"+element.name+"="+encodeURIComponent(element.value);
	}		
	if(addParams)
		params += addParams;

	// now load new table using block displayer
	var table = document.getElementById(tableID);
	loadIntoElement("/DBTableBrowser/"+getURI()+"?DBTable_ID="+tableID+"&"+params, 
		table, function() { 
			setDBTableOnClickEvents(tableID); 
			if(table.colNoStart) dbTableFixColumn(tableID); 
		});
	
	return false;
}

function dbTableFixColumn(id, colNoStart) {
	 
	var containerDiv = document.getElementById(id);
	if(colNoStart)
	{
		containerDiv.colNoStart = colNoStart
	}
	else
		{
			colNoStart = containerDiv.colNoStart;
		}
	
	var containerTable = containerDiv.getElementsByTagName('table')[0];

	var table = containerTable.getElementsByTagName('table')[0];

	table.parentNode.style.verticalAlign = 'top';
	table.parentNode.style.height = (table.clientHeight + 22) + 'px';
	table.parentNode.style.width = (table.clientWidth + 0) + 'px';
	table.parentNode.style.maxWidth = '100%';

	var fixedTable = table.cloneNode(false);

	var rows = table.getElementsByTagName('tr');
	// get max column count
	var maxColno = 0;
	for(var rowno = 0; rowno < rows.length; rowno++)
	{
		var row = rows[rowno];

		var cols = row.childNodes;
		var colno = 0;
		for(var no = 0; no < cols.length; no++)
		{
			var col = cols[no];
			if(col.tagName && (col.tagName.toLowerCase() == 'td' || col.tagName.toLowerCase() == 'th'))
			{
				colno += col.colSpan;
			}
		}
		if(colno >= maxColno)
			maxColno = colno;
	}
	
	// iterate through table and move fixed columns to new table
	var width = 0;
	var heights = new Array();
	for(var rowno = 0; rowno < rows.length; rowno++)
	{
		var row = rows[rowno];

		var fixedRow = row.cloneNode(false);
		fixedTable.appendChild(fixedRow);

		var cols = row.childNodes;
		var colno = 0;
		var cwidth = 0; 
		var maxheight = 0;
		for(var no = 0; no < cols.length; no++)
		{
			var col = cols[no];
			if(col.tagName && (col.tagName.toLowerCase() == 'td' || col.tagName.toLowerCase() == 'th'))
			{
				var paddingTop = col.style.paddingTop;
				if(!paddingTop)
					paddinTop = table.cellPadding;
				if(!paddingTop)
					paddinTop = 0;

				var paddingBottom = col.style.paddingBottom;
				if(!paddingBottom)
					paddingBottom = table.cellPadding;
				if(!paddingBottom)
					paddingBottom = 0;
					
				if(table.cellSpacing && !isMoz) // we only need corrections for browsers != mozilla
				{
					paddingTop += table.cellSpacing;
					paddingBottom += table.cellSpacing;
				}

				var height = col.clientHeight - paddingTop - paddingBottom;
				heights[rowno] = height;

				if(colno >= colNoStart)
				{
					col.style.whiteSpace = "nowrap";
					
					cwidth += col.clientWidth;
					
					col.style.height = height + 'px';
	
					fixedRow.appendChild(col);
				}

				if(height > maxheight)
					maxheight = height;
				
				colno += col.colSpan;
			}
		}
		if(cwidth > width)
			width = cwidth;
		row.style.height = maxheight + 'px';
		// add additional invisible cols
		while(colno < maxColno)
		{
			var col = document.createElement('td');
			col.style.visibility = 'hidden';
			col.style.height = height + 'px';
			col.innerHTML = '&nbsp;';
			fixedRow.appendChild(col);
			colno++;
		}			
	}
	
	for(var rowno = 0; rowno < rows.length; rowno++)
	{
		var row = rows[rowno];

		var cols = row.childNodes;
		var colno = 0;
		for(var no = 0; no < cols.length; no++)
		{
			var col = cols[no];
			if(col.tagName && (col.tagName.toLowerCase() == 'td' || col.tagName.toLowerCase() == 'th'))
			{
				col.style.height = heights[rowno]+'px';
			}
		}
	}
	
	var cdiv = document.createElement('div');
	cdiv.style.position = 'relative';
	cdiv.style.left = 0;
	cdiv.style.top = 0;
	cdiv.style.right = 0;
		
	var tabdiv = document.createElement('div');
	tabdiv.style.position = 'absolute';
	tabdiv.style.overflowX = 'auto';
	tabdiv.style.left = 0;
	tabdiv.style.top = 0;
	tabdiv.style.right = width + 'px';

	tabdiv.style.border = 0;
	tabdiv.style.padding = 0;
	tabdiv.style.margin = 0;

	var coldiv = document.createElement('div');
	coldiv.style.position = 'absolute';
	coldiv.style.right = 0;
	coldiv.style.top = 0;
	coldiv.style.width = width + 'px';
	coldiv.style.overflow = 'hidden';
//	coldiv.style.textAlign = 'right';

	coldiv.style.border = 0;
	coldiv.style.padding = 0;
	coldiv.style.margin = 0;

	cdiv.appendChild(tabdiv);
	cdiv.appendChild(coldiv);

	table.parentNode.insertBefore(cdiv, table);

	tabdiv.appendChild(table);
	coldiv.appendChild(fixedTable);
}

function setDBTableOnClickEvents(tableId) {
	var el = document.getElementById(tableId);
	for(var e = 0; e < inputElementNames.length; e++)
	{
		var inputs = el.getElementsByTagName(inputElementNames[e]);
		for(var i = 0; i < inputs.length; i++)
		{
			var input = inputs[i];
			var valIndexOf = input.name.indexOf("_val_");
			if(input.name.substring(0, tableId.length) == tableId
					|| valIndexOf > -1) {
				var fullId = input.name.substring(0, valIndexOf);
				input.onkeypress = function (evt) {
					if (!evt)
						var evt = window.event;						
					if(evt.keyCode == 13)
					{
						// recalculate fullid again, as somehow closure doesnt seem to work!
						document.getElementById("upd_"+this.name.substring(0, 
								this.name.indexOf("_val_"))).click();
					}
				};
			}
		}
	}
}


/**
 * Special functions for specific servlets
 */


//members.data.Duplicates
function changeRequired(req)
{
	var opt = document.FilterForm.Opt;
	for(var i = 0; i < opt.length; i++)
		if(opt[i].value == req.value)
		{
			if(req.checked)
				opt[i].checked = false;
			break;
		}
}

//members.data.Duplicates
function changeOptional(opt)
{
	var req = document.FilterForm.Req;
	for(var i = 0; i < req.length; i++)
		if(req[i].value == opt.value)
		{
			if(opt.checked)
				req[i].checked = false;
			break;
		}
}

//register_CreateTable
function set(opt, index, dest, value)
{
	if(opt.selectedIndex == index)
		dest.value = value;
}


/*
 * Functions for calendar
 */

function selected(cal, date) {
	cal.sel.value = date;

	if(cal.dateClicked)
		closeHandler(cal);
}

function closeHandler(cal) {
	cal.hide();                        // hide the calendar
	setFocus(cal.sel);
}

function inputKey(input, event)
{
	if(event.keyCode == 32)
	{
		return showCalendar(input, input);
	}
	else
		return true;
}

function createCalendar()
{
	if (_dynarch_popupCalendar == null)
	{
		// first-time call, create the calendar.
		var cal = new Calendar(1, null, selected, closeHandler);
		// uncomment the following line to hide the week numbers
		// cal.weekNumbers = false;
		_dynarch_popupCalendar = cal;                  // remember it in the global var
		cal.setRange(1900, 2070);        // min/max year allowed.
		cal.create();
//		if (format != null)
//			_dynarch_popupCalendar.setDateFormat(format);  // set the specified date format
	}
}

function parseDate(val)
{
	createCalendar();
	return Date.parseDate(val, _dynarch_popupCalendar.dateFormat);	
}

function showCalendar(button, el, callback)
{
	createCalendar();
	
	_dynarch_popupCalendar.onSelected =
		function (cal, date) { selected(cal, date); if(cal && callback) callback(); };
	_dynarch_popupCalendar.parseDate(el.value);      // try to parse the text in field
	_dynarch_popupCalendar.sel = el;                 // inform it what input field we use
	_dynarch_popupCalendar.showAtElement(button);    // show the calendar below the button

	return false;
}

/*
 * function used by textare
 */
function encforceTextAreaSize(event, obj, len)
{
	var code;
	if(window.event)
		code = window.event.keyCode;
	else
		code = event.which;	
	
	if(obj.value.length > len)
		obj.value = obj.value.substring(0, len);
	
	return (obj.value.length <= len) || (code == 8) || (code == 0x007F); // delete and backspace allowed
}

/*
 * Functions for Member selection
 */
function showMembersSelectWindow(form, field, title, filter, params)
{
	var id = '__'+form+"_"+field;
	var usedIDs = document.forms[form].elements[field].value

	// generate querystring
	var qs = "?=";
	if(usedIDs.length > 0)
		qs += "&UsedIDs="+usedIDs;
	if(params)
		qs += "&"+params;

	if(!document.getElementById(id))
	{
	    var div = document.createElement('DIV');
	    div.id = id;
	    div.style.overflow = 'hidden';
	    document.getElementsByTagName('BODY')[0]
	    	.appendChild(div);
	}
	else
	{
		document.getElementById(id).innerHTML = '';
		$("#"+id).dialog ( "destroy" ); 
	}

	$("#"+id).dialog ( { 
//		modal: true,
		title: title,
		autoOpen: false,
		height: 330,
		width: 440,
		minHeight: 300,
		minWidth: 440
	} );
	
	var timer = setTimeout("showLoading()", 200);
	executeRemoteAction(id, qs,
		function (html) {
			memberSelectWindowCallback(id, html, timer);
		}
	);
	
	$("#"+id).dialog ("open");
	
}

function closeMemberSelectWindow(form, field) 
{
	var id = '__'+form+"_"+field;
	window.parent.$('#'+id).dialog('close');
}

function memberSelectWindowCallback(id, html, timer)
{
	var el = document.getElementById(id); 
	el.innerHTML = html;
	$("#"+id).dialog ( "option", "width", "auto" );
	$("#"+id).dialog ( "option", "height", "auto" );
	var scripts = el.getElementsByTagName('script');
	for(var i = 0; i < scripts.length; ++i)
	{
		eval(scripts[i].text);
	}
	if(timer)
		clearTimeout(timer);
	hideLoading();
}

//used in recipent select window to add members to main window
function addMembers(formName, fieldName) {
	var id = '__'+formName+"_"+fieldName;
	var destform = document.forms[formName];
	var destfield = destform.elements[fieldName];
	var linksfield = document.getElementById(formName+fieldName+"_Link");
	
	var srcform = document.forms["__MembersSelectForm"];
	var srcfield = srcform.Members;

	var html = linksfield.innerHTML;
	var ids = destfield.value;

	if(ids == '')
		html = '';

	var members = srcfield.options;
	for(var i = members.length - 1; i >= 0; --i)
	{
		if(members[i].selected)
		{
			var text = members[i].text;
			var comma = text.indexOf(', ');
			if(comma > -1)
				text = text.substring(comma)+' '+text.substring(0,comma);
			text = text.replace(',', ' ');
			var mid = members[i].value;

			if(ids.length > 0)
			{
				ids += ',';
				html += ', ';
			}

			ids += mid;
			html +=  // no space between , for parameters; otheriwse parsing in removeMember wouldn't work no more!
				"<a href=\"javascript:removeMember('"+formName+"','"+fieldName+"',"+mid+")\">"+text+"</a>";

			srcfield.remove(i);
		}
	}

  var usedIdsField = srcform.UsedIDs;
  if(usedIdsField.value.length > 0)
    usedIdsField.value += ','+ids;
  else
    usedIdsField.value = ids;

	if(ids.length > 0)
	{
		destfield.value = ids;
		linksfield.innerHTML = html;
	}

	// call evnt function if exists
	if(window.onAddMembersFinish)
		window.onAddMembersFinish();
}


function removeMember(form, field, id) {
	var textfield = document.getElementById(form+field+"_Link");
	var idfield = document.forms[form].elements[field];
	var txt = textfield.innerHTML;
	var ids = idfield.value;

	var cid = '';
	var i;
	var li = 0;
	var pos = 0;
	for(i = 0; i < ids.length; i++)
	{
		if(ids.charAt(i) != ',')
			cid += ids.charAt(i);
		else
		{
			if(cid == id)
				break;

			li = i+1;
			cid = '';
			pos++;
		}
	}

	if(cid == id)
	{
		// delete text entry
		var tpos = 0;
		for(j = 0; j < pos; j++)
			tpos = txt.indexOf(', ', tpos)+1;

		var ntpos = txt.indexOf(', ', tpos);
		if(ntpos == -1)
			txt = txt.substring(0, tpos-1);
		else
			txt = txt.substring(0, tpos)+txt.substring(ntpos+1, txt.length);

		// delete id entry
		ids = ids.substring(0,li)+ids.substring(i+1, ids.length);
		if(ids.charAt(ids.length-1) == ',')
			ids = ids.substring(0, ids.length-1);
	}

	if((ids.length == '') && document.getElementById('Default'+field))
		txt = document.getElementById('Default'+field).innerHTML;

	idfield.value = ids;
	textfield.innerHTML = txt;

	// call event function if exists
	if(window.onRemoveMemberFinish)
	{
		if(id)
			onRemoveMemberFinish(id);
		else
			onRemoveMemberFinish();
	}
}

function clearMembers(form, field) {
	var textfield = document.getElementById(form+field+"_Link");
	var idfield = document.forms[form].elements[field];

	textfield.innerHTML = "";
	idfield.value = "";
	
	// call event function if exists
	if(window.onRemoveMemberFinish)
		onRemoveMemberFinish();
}

/*
 * Functions for Sendmail
 */
function showRecipentSelectWindow(field,name)
{
	var usedIDs = '';
	var form = document.EMailForm;
	if(form.To.value.length > 0)
		usedIDs = form.To.value;

	var params = '';
	if(usedIDs.length > 0)
		params = "&UsedIDs="+usedIDs;

	showMembersSelectWindow('EMailForm', field, name, "EMail <> ''");
}


/**
 * check if send button can be enabled
 */
function checkSendingEnabled()
{
	var form = document.EMailForm;
	var enabled = form.Subject.value.length > 0;
	enabled = enabled &&
		form.To.value.length;

	form.Send.disabled = !enabled;
}

/***
 ** Below is stuff related to file upload
 */
window.fileUploadTimer = new Array();
window.fileUploadInputs = new Object();
function uploadFile(el, maxSize)
{
	var name = el.name;

	// remove possible error message from last time
    document.getElementById(name+'_error').style.display = 'none'; 	
	// safe input element for later use
	window.fileUploadInputs[name] = el.cloneNode(false);
	
	/** prepare upload form */
	var form = document.createElement('form');
	if(isIE)
		form = document.createElement('<form method="POST" enctype="multipart/form-data">');
	form.enctype = "multipart/form-data";
	form.target = name+"_frame";
	form.action = "/FileUploadProcessor?maxSize="+maxSize+"&name="+encodeURIComponent(name);
	form.method = "POST";

	form.style.display = 'none';
	form.appendChild(el);

	// add form to document, otherwise submit won't work
	document.body.appendChild(form);

	/** prepare frame **/
	var frame = document.createElement('div');
	frame.innerHTML = '<iframe name="'+name+'_frame"></iframe>'; // ie wants it that way...
	frame.style.display = 'none';

	document.body.appendChild(frame);

	/** update status **/
	document.getElementById(name+"_status").style.display = 'inline-block';

	/** start upload **/
	window.fileUploadTimer.push(name);
	window.fileUploadTimer[name] = true;
	// submit and then remove
	setTimeout(function() { form.submit(); document.body.removeChild(form); }, 10);
	// start updating
	var updateStatus = function() { 
		if(window.formWaiting)
			showLoading();
		if(window.fileUploadTimer[name])
		{
			var param = '';
			if(isIE) // fucking ie needs this stupid shit as it ignores all cache-control headers
				param = 't='+(new Date().getTime());
			setTimeout(function () { updateBlock(name+"_status", param, updateStatus); }, 500); 
		}
	};
	updateStatus();
}

// delete's uploaded file
function deleteFile(name)
{
	loadIntoElement("/FileUploadProcessor?id=" + encodeURIComponent(name),
			document.getElementById(name+"_status"),
		function() {
		    document.getElementById(name+'_status').style.display = 'none';
		    document.getElementById(name+'_delete').style.display = 'none'; 
		    document.getElementById(name+'_input').appendChild(window.fileUploadInputs[name]);
		}
	);
	
}

// checks if any file uploads prevent form from being submited
function checkFormSubmission(button)
{
	if(fileUploadsFinished())
		return true;
	else
	{
		window.formWaiting = true;
		var checkTimer = function() {
			if(!fileUploadsFinished())
				setTimeout(checkTimer, 100);
			else
				button.click();
		};
		checkTimer();
		return false;
	}	
}

// check if extension corresponds to allowed ones
function checkExtension(el, exts)
{
	var filename = el.value;
	var regex = new RegExp("^.*\.("+exts+")$", "i");
	return regex.test(filename);
}

// checks if any file uploads are running
function fileUploadsFinished()
{
	var up = window.fileUploadTimer;
	if(!up)
		return true;
	for(var i = 0; i < up.length; i++)
	{
		if(up[up[i]])
			return false;
	}
	return true;
} 

// registers onclick listener for file upload
function registerOnClickListener()
{
	// add handler to all submit buttons
	var inputs = document.getElementsByTagName("input");

	for(var i = 0; i < inputs.length; i++)
	{
		 var input = inputs[i];
		 if(input.type == "submit"
		 || input.type == "image")
		 {
			var oldonclick = (input.onclick)?input.onclick:function(){};
		 	input.onclick = function() { if(checkFormSubmission(input)) { oldonclick(); } else { return false; } };
		 }
	}  
}

// called when file has been uploaded to set state accordingly
function uploadFinished(name, filename)
{
	window.fileUploadTimer[name] = false;
    document.getElementById(name+'_delete').style.display = 'inline-block'; 
    document.getElementById(name+'_status').innerHTML 
    	+= '<input type="hidden" name="'+name+'" value="'+filename+'">';
}

//called when file was not correctly uploaded 
function uploadError(name, errorText)
{
	window.fileUploadTimer[name] = false;
    document.getElementById(name+'_status').style.display = 'none';
    document.getElementById(name+'_error').style.display = 'block'; 
    document.getElementById(name+'_error').innerHTML = errorText; 
    document.getElementById(name+'_input').appendChild(window.fileUploadInputs[name]);
}

// focuses first text input element
function focusFirstTextinput(form)
{
	var el = $("form[name='"+form+"'] input:visible:first");
	el.focus();
}

// gets all sub input elements
function collectQueryString(el)
{
	var qs = "";
	for(var e = 0; e < inputElementNames.length; e++)
	{
		var inputs = el.getElementsByTagName(inputElementNames[e]);
		for(var i = 0; i < inputs.length; i++)
		{
			var input = inputs[i];

			// only use enabled
			if(input.disabled)
				continue;
			// only use checked values for checkbox and radio
			if((input.type == 'radio' || input.type == 'checkbox')
					&& !input.checked)
				continue;
			
			if(qs.length > 0)
				qs += "&";
			qs += input.name+"="+encodeURIComponent(input.value);
		}
	}
	return qs;
}


/**
 * dynamically load javascript file
 */
function loadScript(filename, callback)
{
	if(!window.__loadedScripts)
		window.__loadedScripts = new Object();
	if(window.__loadedScripts[filename])
	{
		if(window.__loadedScripts[filename].loaded)
			callback();
		else
		{
			var oldOnLoad = window.__loadedScripts[filename].node.onload; 
			window.__loadedScripts[filename].node.onload = function()
			{
				oldOnLoad();
				callback();
			};
		}
		return;
	}
	
    var scriptNode = document.createElement('SCRIPT');
    scriptNode.type = 'text/javascript';
    if(callback)
	{
    	scriptNode.onload = function() {
    		window.__loadedScripts[filename].loaded = true;
    		callback();
    	}; 
    }
    scriptNode.src = '/' + filename;

	window.__loadedScripts[filename] = 
		{ loaded: false, node: scriptNode };
 
    var headNode = document.getElementsByTagName('HEAD');
    if (headNode[0] != null)
        headNode[0].appendChild(scriptNode);
}

/**
 * dynamically load css file
 */
function loadCss(filename) {
	
	var fileref = document.createElement("link")
	fileref.setAttribute("rel", "stylesheet")
	fileref.setAttribute("type", "text/css")
	fileref.setAttribute("href", '/' + filename)
		
	var headNode = document.getElementsByTagName('HEAD');
	if (headNode[0] != null) {
	    headNode[0].appendChild(fileref); 
	}
}


/**
 * used by RemoteAutocompleteInput to register itself with textinput
 */
function registerRemoteAutocomplete(id, callback) {
	
//	loadCss('jquery-ui/jquery-ui.css');	
//	loadScript('jquery-ui.js', function() {
	$(document).ready(function() {
		$('#'+id).autocomplete({
			source: function (query, response) { 
				executeRemoteAction(id, 'query='+encodeURIComponent(query.term), 
						function (txt) {
							response(eval(txt)); 
						}
				)
			}, 
			select: function (event, item) {
				if(callback)
					callback(event, item);
			},
			delay: 200
		}).data( "autocomplete" )._renderItem = function( ul, item ) {
			var label = item.label;
			if(!item.label)
				label = item.value;
			var el = $( "<li></li>" )
				.data( "item.autocomplete", item );
			var htmlCode = "<a>" + item.label;
			if(item.desc)
				htmlCode += "<div class=\"desc\">"+item.desc+"</div>";
			el.append(htmlCode + "</a>");
			return el.appendTo( ul );
		};
	});
//	});
}

