function Util() { }

/* ----------------------------------------------------------------------
 *  html formatting
 * ---------------------------------------------------------------------- */

Util.tableDecorators = function(rowId, rowPrefix) {
	options = new Object();
	options.rowId = rowId;
	options.rowPrefix = rowPrefix;
	
	options.rowCreator = function(options) {
		row = document.createElement("tr");
		if (options.rowId != null) {
			row.id = options.rowPrefix + options.rowData[options.rowId];
		}
		if (options.rowIndex % 2 == 0) {
			row.className = "resultListLine1";
		} else {
			row.className = "resultListLine2";
		}
		return row;
	}
	
	options.cellCreator = function(options) {
		return document.createElement("td");
	}
	
	return options;
}


Util.formatMax = function(data, width) {
	if (data != null && data.length > width) {
		data = '<span title="' + data + '">' + 
            data.substring(0, width) + "..." +
            '</span>';
	}
	return data;
}


Util.alignRight = function(data) {
	var s = "";
	if (data != null) {
		s = "<div align='right'>" + data + "</div>";
	}
	return s;
}

Util.alignCenter = function(data) {
	var s = "";
	if (data != null) {
		s = "<div align='center'>" + data + "</div>";
	}
	return s;
}


/* ----------------------------------------------------------------------
 *  dom util functions
 * ---------------------------------------------------------------------- */
 
Util.removeChildren = function(parent) {
	while (parent.childNodes.length > 0) {
		parent.removeChild(parent.firstChild);
	}
}


/* ----------------------------------------------------------------------
 *  form entry
 * ---------------------------------------------------------------------- */
var g_formatSource;
var g_formCallbacks = new Object();
var g_lastFieldModified;
var g_overControlButtons = false;

Util.prepForm = function(form, callBackSubmit, callBackReset, callBackModified) {
	form.onsubmit = callBackSubmit;
	
	g_formCallbacks[form.id + "_submit"] = callBackSubmit;
	g_formCallbacks[form.id + "_reset"] = callBackReset;
	g_formCallbacks[form.id + "_modified"] = callBackModified;
	
	for (var i=0; i<form.elements.length; i++) {
		var el = form.elements[i];
		if (el.nodeName == "SELECT") {
			el.onchange = Util.formModified;
			el.onkeydown = Util.formModifiedKeyEvent;
		} else if (el.nodeName == "INPUT") {
			el.onkeydown = Util.formModifiedKeyEvent;
			switch (el.getAttribute("type")) {
			case "text":
				el.onchange = Util.formModified;
				break;
			case "radio":
				el.onclick = Util.formModified;
				break;
			case "checkbox":
				el.onclick = Util.formModified;
				break;
			case "submit":
				el.onmouseover = function() { g_overControlButtons = true };
				el.onmouseout = function() {g_overControlButtons = false };
				break;
			case "reset":
				el.onclick = callBackReset;
				el.onmouseover = function() { g_overControlButtons = true };
				el.onmouseout = function() { g_overControlButtons = false };
				break;
			case "button":
				el.onmouseover = function() { g_overControlButtons = true };
				el.onmouseout = function() {g_overControlButtons = false };
				break;
			}
        } else if (el.nodeName == "TEXTAREA") {
            el.onkeydown = Util.formModifiedKeyEvent;
	        el.onchange = Util.formModified;
		}
	}
}


Util.formModified = function(ev) {
	if (g_overControlButtons) {
		return;
	}
	
	var src = Util._findEventSource(ev);
	if (src == g_lastFieldModified && src.nodeName == "INPUT" &&
		src.getAttribute("type").indexOf("text") != -1) {
		return;
	}
	g_lastFieldModified = src;
	
	var value = src.value;
	if (value != null && value != "") {
		g_formatSource = src;
		var format = g_formatSource.getAttribute("format");
		if (format == "date") {
			HtmlUtil.formatDate(value, Util.handleFormat);
		} else if (format == "integer") {
			HtmlUtil.formatInteger(value, Util.handleFormat);
		} else if (format == "phone") {
			HtmlUtil.formatPhoneNo(value, Util.handleFormat);
		} else if (format == "time") {
			HtmlUtil.formatTime(value, Util.handleFormat);
		} else if (format == "date") {
			HtmlUtil.formatDate(value, Util.handleFormat );
		} else if (format == "float" ) {
            HtmlUtil.formatFloat(value, Util.handleFormat );
        }
	} else {
		Util._setFieldMessage(g_formatSource, "");
	}
	
	var cb_modified = g_formCallbacks[src.form.id + "_modified"];
	if (cb_modified != null) {
		cb_modified();
	}	
}


Util.formModifiedKeyEvent = function(ev) {
	var src = Util._findEventSource(ev);
	var handle_event = true;
	var form_id = src.form.id;
	var cb_modified = g_formCallbacks[src.form.id + "_modified"];
	var cb_reset = g_formCallbacks[src.form.id + "_reset"];
	var cb_submit = g_formCallbacks[src.form.id + "_submit"];

	if (ev == null) {
		ev = window.event;
	}

	g_lastFieldModified = null;

	if (ev.keyCode < 41 && ev.keyCode != 8 && ev.keyCode != 32) {
		switch (ev.keyCode) {
		case 13:
			if (cb_submit != null && src.nodeName == "SELECT") {
				cb_submit();
				handle_event = false;
			}
			break;
		case 27:
			if (cb_reset != null) {
				cb_reset();
				handle_event = false;
			}
			break;
		case 37:
		case 38:
		case 39:
		case 40:
			if (cb_modified != null && src.nodeName == "SELECT") {
				cb_modified();
			}
			break;
		}
	} else if (!ev.ctrlKey || (ev.ctrlKey && (ev.keyCode == 86 || ev.keyCode == 88))) {
		if (cb_modified != null) {
			cb_modified();
		}
	}
	return handle_event;
}


Util.handleFormat = function(data) {
	if (data.error == null) {
		g_formatSource.value = data.dataObject;
		Util._setFieldMessage(g_formatSource, "");
	} else {
		Util._setFieldMessage(g_formatSource, data.error);
	}
}


/* ----------------------------------------------------------------------
 *  alerts, validation messages
 * ---------------------------------------------------------------------- */

var g_alertExpanded = false;
Util.showAlert = function(msg, ext, mode) {
	g_alertExpanded = false;
	$("dfldAlertExt").style.display = "none";

	Util.setValue("dfldAlert", msg);	
	$("dfldAlert").style.display = "inline";
	
	if (ext != null && ext.length > 0) {
		$("dfldAlertExt").innerHTML = "";
		var ol = document.createElement(ext.length > 1 ? "ol" : "ul");
		for (var i=0; i<ext.length; i++) {
			var li = document.createElement("li");
			ol.appendChild(li);
			var text = document.createTextNode(ext[i].message == null ? ext[i] : ext[i].message);
			li.appendChild(text);
		}
		$("dfldAlertExt").appendChild(ol);
		$("btnAlertExpand").style.display = "inline";
		$("btnAlertExpand").className = "btnSmall btnSmallExpandOn";
	} else {
		$("btnAlertExpand").style.display = "none";
	}
    
    switch (mode) {
    case "info":
        $("sectionAlert").className = "alert alertInfo";
        break;
    case "progress":
        $("sectionAlert").className = "alert alertProgress";
        break;
    default:
        $("sectionAlert").className = "alert";
    }  
	
	$("sectionAlert").style.display = "block";
}

Util.hideAlert = function() {
	$("sectionAlert").style.display = "none";
}

Util.toogleAlert = function(ev) {
	if (g_alertExpanded) {
		g_alertExpanded = false;
		$("btnAlertExpand").className = "btnSmall btnSmallExpandOn";
		$("dfldAlertExt").style.display = "none";
	} else {
		g_alertExpanded = true;
		$("btnAlertExpand").className = "btnSmall btnSmallExpandOff";
		$("dfldAlertExt").style.display = "block";
	}
	return false;
}


Util.displayValidations = function(form, messages) {
	Util.hideValidations(form);
	if (messages == null) {
		return;
	}
	
	var form_name = form.getAttribute("name");
	var focus_set = false;
	for (var i=0; i<messages.length; i++) {
		var msg = messages[i].message;
		if (msg != null) {
			var field_name = messages[i].fieldName;
			var el_id;
			if (form_name != null && form_name != "") {
				el_id = "msg" + 
					form_name.substring(0,1).toUpperCase() + form_name.substring(1) + 
					field_name.substring(0,1).toUpperCase() + field_name.substring(1);
			} else {
				el_id = "msg" + 
					field_name.substring(0,1).toUpperCase() + field_name.substring(1);
			}
			var el = document.getElementById(el_id);
			if (el != null) {
				el.innerHTML = msg;
				el.style.display = "block";
			}
			
			if (form_name != null && form_name != "") {
				el_id = form_name + 
					field_name.substring(0,1).toUpperCase() + field_name.substring(1);
			} else {
				el_id = field_name;
			}
			el = document.getElementById(el_id);
			if (el == null) {
				el_id = "efld" + el_id.substring(0,1).toUpperCase() + el_id.substring(1);
				el = document.getElementById(el_id);
			}
			if (el != null && !focus_set) {
				// try to display tab of entry field
				var cn = el.parentNode;
				var tab;
				var tabber;
				while (cn != null) {
					if (cn.className != null && cn.className.indexOf("tabbertab") != -1) {
						tab = cn;
					}
					if (cn.tabber != null) {
						tabber = cn.tabber;
						break;
					}
					cn = cn.parentNode;
				}
				if (tab != null && tabber != null) {
					for (var j=0; j<tabber.tabs.length; j++) {
						if (tabber.tabs[j].div == tab) {
							tabber.tabShow(j);
							break;
						}
					}
				}

				el.focus();
				if (el.nodeName == "INPUT") {
					el.select();
				}
				focus_set = true;
			}
		}
	}
}

Util.hideValidations = function(form) {
	var elems = form.getElementsByTagName("DIV");
	for (var i=0; i<elems.length; i++) {
		var el = elems[i];
		if (el.id.indexOf("msg") == 0 && el.style.display != "none") {
			el.style.display = "none";
		}
	}
}

Util.displayDecorators = function(form, messages) {
	if (messages == null) {
		return;
	}

	var form_name = form.getAttribute("name");
	
	// ie bugfix, when a input field within the form has id="name"
	// then ie returns this field insteand of the form name, wow!
	if (typeof form_name != 'string') {
	    form_name = null;
	}

	for (var i=0; i<messages.length; i++) {
		var dec = messages[i].decorator;
		if (dec != null) {
			var field_name = messages[i].fieldName;
			var el_id;
			if (form_name != null && form_name != "") {
				el_id = "dec" + 
					form_name.substring(0,1).toUpperCase() + form_name.substring(1) + 
					field_name.substring(0,1).toUpperCase() + field_name.substring(1);
			} else {
				el_id = "dec" + 
					field_name.substring(0,1).toUpperCase() + field_name.substring(1);
			}
			var el = document.getElementById(el_id);
			if (el != null) {
				el.innerHTML = dec;
				el.style.display = "inline";
			}
		}
	}
}

Util.hideDecorators = function(form) {
	var elems = form.getElementsByTagName("SPAN");
	for (var i=0; i<elems.length; i++) {
		var el = elems[i];
		if (el.id.indexOf("dec") == 0 && el.style.display != "none") {
			el.style.display = "none";
		}
	}
}


/* ----------------------------------------------------------------------
 *  get/set overrides
 * ---------------------------------------------------------------------- */

Util.setValue = function(field, value) {
	var el = document.getElementById(field);
	if (el != null) {
		if (el.nodeName == "SELECT") {
			if (el.getAttribute("multiple")) {
				for (var i=0; i<value.length; i++) {
					var role = value[i];
					for (var j=0; j<el.options.length; j++) {
						var el_opt = el.options[j];
						if (el_opt.value == role) {
							el_opt.selected = true;
							break;
						}
					}
				}
			} else {
				value = value == null ? "N/S" : value;
			}
		} else if (el.nodeName == "INPUT") {
			if (el.type == "checkbox") {
				if (value == "true") {
					value = true;
				} else if (value == "false") {
					value = false;
				}
			}
		} 
		dwr.util.setValue(field, value);
	} else {
		var el = document.getElementsByName(field);
		if (el != null && el.length > 0) {
			// radio buttons
			for (var i=0; i<el.length; i++) {
				if (el[i].value == value) {
					dwr.util.setValue(el[i], true);
					break;
				}
			}
		} else {
			alert("field " + field + " not found in document");
		}
	}
}

Util.getValue = function(field) {
	var value = null;
	var el = document.getElementById(field);
	if (el != null) {
		value =	dwr.util.getValue(field);
		if (el.nodeName == "SELECT") {
			if (el.getAttribute("multiple")) {
				value = new Array();
				for (var i=0; i<el.options.length; i++) {
					var el_opt = el.options[i];
					if (el_opt.selected && el_opt.value != "N/S") {
						value[value.length] = el_opt.value;
					}
				}
			} else {
				value = value == "N/S" ? null : value;
			}
		}
	} else {
		var els = document.getElementsByName(field);
		if (els != null && els.length > 0) {
			// radio buttons
			for (var i=0; i<els.length; i++) {
				if (els[i].checked) {
					value = els[i].value;
					break;
				}
			}
		} else {
			alert("field " + field + " not found in document");
		}
	}
	
	return value;
}

Util.addOptions = function(field, records, keyName, valueName, emptyDesc, emptyValue) {
	dwr.util.removeAllOptions(field);

	if (emptyDesc != null) {
		var obj = new Object();
		if (emptyValue == null) {
			obj.key = "N/S";
		} else {
			obj.key = emptyValue;
		}
		obj.value = emptyDesc;	
		var arr = new Array();
		arr[0] = obj;
	    dwr.util.addOptions(field, arr, "key", "value");	
	}
	
	dwr.util.addOptions(field, records, keyName, valueName);	
}


Util.addOptionsKeepSelection = function(field, records, keyName, valueName, emptyDesc, emptyValue) {
	// save current option
	var sel_option;
	for (var i=0; i<$(field).options.length; i++) {
		var el_opt = $(field).options[i];
		if (el_opt.selected && el_opt.value != "N/S") {
			sel_option = el_opt;
			break;
		}
	}
	
	// clear and add new list
	Util.addOptions(field, records, keyName, valueName, emptyDesc, emptyValue);
	
	// re-set current selected option
	if (sel_option != null) {
		// check if value is still in list
		var still_there = false;
		for (var i=0; i<$(field).options.length; i++) {
			var el_opt = $(field).options[i];
			if (el_opt.value == sel_option.value) {
				still_there = true;
				break;
			}
		}
		
		// add selection back into list
		if (!still_there) {
			var obj = new Object();
			obj.key = sel_option.value;
			obj.value = sel_option.text;	
			var arr = new Array();
			arr[0] = obj;
			dwr.util.addOptions(field, arr, "key", "value");	
		}

		// set value
		Util.setValue(field, sel_option.value);
	}
}


Util.setValues = function(data, form) {
	var form_name = null;
	if (form != null) {
		form_name = form.getAttribute("name");
	}
	for (var property in data) {
		var el_name;
		if (form_name != null && form_name != "") {
			el_name = form_name + 
				property.substring(0,1).toUpperCase() + property.substring(1);
		} else {
			el_name = property;
		}
		if ($(el_name) != null || document.getElementsByName(el_name).length >= 1) {
			Util.setValue(el_name, data[property]);
		}
	}
}


Util.getValues = function(data, form) {
	var form_name = null;
	if (form != null) {
		form_name = form.getAttribute("name");
	}
	for (var property in data) {
		var el_name;
		if (form_name != null && form_name != "") {
			el_name = form_name + 
				property.substring(0,1).toUpperCase() + property.substring(1);
		} else {
			el_name = property;
		}
		if ($(el_name) != null || document.getElementsByName(el_name).length >= 1) {
			data[property] = Util.getValue(el_name);
		}
	}
	return data;
}


/* ----------------------------------------------------------------------
 *  audio playing
 * ---------------------------------------------------------------------- */

Util.playAudio = function(id, url) {
	var mime_type = "application/x-mplayer2"; //default
	var agt = navigator.userAgent.toLowerCase();
	if (navigator.mimeTypes && agt.indexOf("windows") == -1) {
		//non-IE, no-Windows
  		var plugin = navigator.mimeTypes["audio/mpeg"].enabledPlugin;
  		if (plugin) {
  			mime_type = "audio/mpeg" //Mac/Safari & Linux/FFox
  		}
	}

	var plugin_html = "" +
	    '<object ' +
	    '  type="' + mime_type + '"' +
	    '  data="' + url + '"' +
	    '  width="300" height="45">' +
	    '  <param name="src" value="' + url + '"/>' +
		'  <embed src="' + url + '" autostart=true width="300" height="45">';
	    '</object>';

	el = document.getElementById(id);
	if (el != null) {
		el.innerHTML = plugin_html;
	} else {
		alert("element with id " + id + " not found");
	}
}


Util.stopAudio = function(id) {
	el = document.getElementById(id);
	if (el != null) {
		el.innerHTML = "";
	} else {
		alert("element with id " + id + " not found");
	}
}



/* ----------------------------------------------------------------------
 *  window handling
 * ---------------------------------------------------------------------- */

var g_taskWindow;
Util.showTaskWindow = function() {
	if (g_taskWindow == null || g_taskWindow.closed) {
		g_taskWindow = window.open("/TelWeb/lookup/tasks.jsp", "taskWindow",
			"scrollbars=yes, menubar=no, height=300, width=700, resizable=yes," +
			"toolbar=no, location=no, status=no", true);
	}
	g_taskWindow.focus();
	return g_taskWindow;
}
Util.showTaskWindowNoReturn = function() {
	Util.showTaskWindow();
}


var g_popupWindow;
Util.showPopupWindow = function(url, height, width) {
	if (g_popupWindow == null || g_popupWindow.closed) {
		if (height == null) {
			height = 600;
		}
		if (width == null) {
			width = 500;
		}
	
		g_popupWindow = window.open(url, "lookupWindow",
			"scrollbars=yes, menubar=no, height=" + height + 
			", width=" + width + ", resizable=yes," +
			"toolbar=no, location=no, status=no");
	} else {
		g_popupWindow.location = url;
	}
	g_popupWindow.focus();
	return g_popupWindow;
}

Util.hidePopupWindow = function() {
	if (g_popupWindow != null) {
		g_popupWindow.close();
		g_popupWindow = null;
	}
}


/* ----------------------------------------------------------------------
 *  load other javascript into current browser
 * ---------------------------------------------------------------------- */
Util.loadScript = function(src) {
	var document_scripts = document.getElementsByTagName("script");
	
	for (var i = 0; i < document_scripts.length; i++) {
		var document_script = document_scripts[i];
		if (document_script.src == src) {
			return false;
		}
	}
	
	var script = document.createElement('script');
	script.type = 'text/javascript';
	script.src = src;
	document.getElementsByTagName('head')[0].appendChild(script);
}


/* ----------------------------------------------------------------------
 *  private functions
 * ---------------------------------------------------------------------- */

Util._setFieldMessage = function(src, msg) {
	if (src != null) {
		var field_name = src.id;
		if (field_name.indexOf("efld") == 0) {
			field_name = field_name.substring(4);
		}
		var msg_id = "msg" + 
			field_name.substring(0,1).toUpperCase() + field_name.substring(1);
		var msg_el = document.getElementById(msg_id);
		if (msg_el != null) {
			if (msg != "") {
				msg_el.innerHTML = msg;
				msg_el.style.display = "block";
			} else {
				msg_el.style.display = "none";
			}
		}
	}
}

Util._findEventSource = function(ev) {
	if (ev == null) {
		ev = window.event;
	}
	var src = ev.target;
	if (src == null) {
		src = ev.srcElement;
	}
	return src;
}

Util.help = function() {
	alert( document.location );
}


/* ----------------------------------------------------------------------
 *  async http functions
 * ---------------------------------------------------------------------- */

Util.asyncGET = function(url,handlerOK,handlerError) {
    var xmlhttp = null;
    
    var handler = function () {    
		if (xmlhttp.readyState==4) {// 4 = "loaded"
	        if (xmlhttp.status==200) {// 200 = "OK"	          
	           handlerOK(xmlhttp.responseText);
	        } else {
	           handlerError(xmlhttp.statusText);
	        }
        }
	}
	
	if (window.XMLHttpRequest) {// code for Firefox, Opera, IE7, etc.
	  xmlhttp=new XMLHttpRequest();
	} else if (window.ActiveXObject) {// code for IE6, IE5
	  xmlhttp=new ActiveXObject("Microsoft.XMLHTTP");
	}
	
	
	if (xmlhttp != null) {
      xmlhttp.onreadystatechange=handler;
	  xmlhttp.open("GET",url,true);
	  xmlhttp.send(null);
	} else {
	  alert("Your browser does not support XMLHTTP.");
	}
	
	return handler;
}
