/**
 * @author Andre Wyrwa
 */

function $(e) {
	return (typeof(e) == "string") ? document.getElementById(e) : e;
}

function ie() {
	return window.ActiveXObject;
}

function stopProp(e) {
	if (ie()) window.event.cancelBubble = true;
	if (e.stopPropagation) e.stopPropagation();
}

function getXML(n) {
	if (window.ActiveXObject) return n.innerText;
	return n.textContent;
}

function setXML(n, s) {
	if (ie()) n.innerText = s;
	else n.textContent = s;
}

function getContent(x) {
	if (ie()) s = x.xml;
	else {
		var w = new XWrap(x);
		var s = w.serialise();
	}
	s = s.replace(/(^\<[^\<\>]*\>)|(\<\/[^\<\>]*\>$)/g, "");
	return s;
}

function getArgs(a, d) {
	var a = [];
	for (i=d;i<a.length;i++) a[i-d] = a[i];
	return a;
}

Function.prototype.bind = function(o) {
	var _method = this;
	var a = getArgs(arguments, 1);
	a.unshift("");
	return function(e) {
		e = e || event;
		a[0] = e;
		return _method.apply(o, a);
	}
}

function AReq(u, d, f, m) {
	this._d = d;
	this._f = f;
	this._m = m.toUpperCase();
  	this._u = u;
	this._r = null;
	if (window.XMLHttpRequest) {
		try {this._r = new XMLHttpRequest();} 
		catch (e) {this._r = null;}
	} else if (ie()) {
		try {this._r = new ActiveXObject("Msxml2.XMLHTTP");}
		catch(e) {
			try {this._r = new ActiveXObject("Microsoft.XMLHTTP");} 
			catch (e) {this._r = null;}
		}
	}
}
		
	AReq.prototype.send = function() {
		var u = this._u;
		var m = this._m;
		//if (typeof(this._d) != "string") u += ((u.indexOf("?") < 0) ? "?" : "&") + "ajax=true&rand=" + Math.random();
		
		var r = this._r;
	 	if (r) {
			r.onreadystatechange = this.hsc.bind(this);
			if (m == "POST") {
				r.open(m, u);
				if (typeof(this._d) == "string") r.setRequestHeader('Content-Type','application/x-www-form-urlencoded');
				r.send(this._d);
			} else {
				r.open(m, u);
				r.send("");
			}
		}
	}
	
	AReq.prototype.hsc = function() {
		if (this._r.readyState == 4) {
			var w = new XWrap();
			w.parse(this._r.responseText);
			this._f.call(this, w);
		}
	}

// cross browser XML DOM implementation
function XWrap(x) {
	if (ie()) {
		this.d = new ActiveXObject("Microsoft.XMLDOM");
		this.d.async = "false";
		this.d.setProperty("SelectionLanguage", "XPath");
	} else {
		this.d = document.implementation.createDocument("","",null);
		this.d.async = "false";
		this.s = new XMLSerializer();
		this.p = new DOMParser();
	}
	if (x) this.d.appendChild(this.d.importNode(x,true));
}
	
	XWrap.prototype.setNS = function(n, u) {
		if (ie()) this.d.setProperty("SelectionNamespaces", n + "='" + u + "'");
	}

	XWrap.prototype.serialise = function() {
		return (ie()) ? this.d.xml : this.s.serializeToString(this.d);
	}
	
	XWrap.prototype.parse = function(s) {
		if (ie()) {
			this.d.loadXML(s);
			var e = this.d.parseError;
			if (e.errorCode) alert("Error:\n" + e.reason + "\nat:\n" + e.srcText);
		} else this.d = this.p.parseFromString(s, "text/xml");
	}
	
if (!ie()) {
	Element.prototype.selectNodes = function(s) {
		var d = (this.ownerDocument) ? this.ownerDocument : new XPathEvaluator();
		var r = d.createNSResolver(d.documentElement);
		var o = d.evaluate(s, this, r, XPathResult.ORDERED_NODE_ITERATOR_TYPE, null);
		var a = [];
		if (o) while (x = o.iterateNext()) a.push(x);
		return a;
	}
	
	Element.prototype.selectSingleNode = function(s) {
		var d = (this.ownerDocument) ? this.ownerDocument : new XPathEvaluator();
		var r = d.createNSResolver(d.documentElement);
		var r = d.evaluate(s, this, r, XPathResult.FIRST_ORDERED_NODE_TYPE, null);
		return (r) ? r.singleNodeValue : null;
	}
}

	function urify(o) {
		var s = ""; var d = "";
		for (var k in o) {
			s += d + k + "=" + encodeURIComponent(o[k]);
			d = "&";
		}
		return s;
	}

	function loadAsync(c, p, l, q) {
		var c = c || "setValue";
		var u = "/callbacks/"+c+".php";
		var l = (p && p.list) ? p.list : l;
		if (q) u += "?" + urify(q);
		var o = {};
		if (l) {
			o.list_id = l;
			var a = ['type', 'renderer', 'filter', 'extenders', 'constraint', 'constraints', 'search', 'criteria', 'offset', 'limit', 'sorter', 'mode', 'selected', 'parameters'];
			for (var i=0; i<a.length; i++) o['list_'+a[i]] = $(o.list_id+'_list_'+a[i]).value;
		}
		if (p) for (var k in p) o[k] = p[k];
		o['window'] = window.name;
		var r = new AReq(u, urify(o), runXML, "POST");
		r.send();
		
		r.s = document.createElement("img");
		r.s.setAttribute("width", "20");
		r.s.setAttribute("height", "20");
		r.s.src = "/images/spinner_tiny.gif";
		return r.s;
	}
	
	function replaceBySpinner(n, s) {
		n.style.display = "none";
		n.parentNode.insertBefore(s, n);
	}

	function runXML(x) {
		var x = x.d.documentElement;
		if (x) a = x.selectNodes("./action");
		if (!a.length) return;
		for (var i=0; i<a.length; i++) {
			var y = a[i].selectNodes("./*");
			var p = {};
			for (var j=0; j<y.length; j++) p[y[j].nodeName] = getContent(y[j]);
			switch (a[i].getAttribute("type")) {
				case "addItem":	addItem(p['list'], p['id'], p['order'], p['item']);	break;
				case "replaceItem": replaceItem(p['list'], p['id'], p['item']); break;
				case "removeItem": removeItem(p['list'], p['id']); break;
				case "replaceNode": replaceNode(p['id'], p['content']); break;
				case "setValue": setValue(p['id'], p['value']);	break;
				case "setContent": setContent(p['id'], p['content']); break;
				case "setVisibility": setVisibility(p['id'], p['visibility']); break;
				case "setDisplay": setDisplay(p['id'], p['display']); break;
				case "setDisabled":	setDisabled(p['id'], p['disabled']); break;
				case "setChecked":	setChecked(p['id'], p['checked']); break;
				case "setAttribute": setAttribute(p['id'], p['attribute'], p['value']);break;
				case "refreshList": if ($(p['list']+"_list")) loadAsync('findItems', {}, p['list']); break;
				default:
					var f = window[a[i].getAttribute("type")];
					if (f) f(p);
					break;
			}
		}
		
		if (this.s && this.s.nextSibling) {
			this.s.nextSibling.style.display = "";
			this.s.parentNode.removeChild(this.s);
			this.s = null;
		}
		
		runScripts(x);
	}
	
	function toEl(h) {
		var t = document.createElement("div");
		t.innerHTML = h;
		var n = t.firstChild;
		t.removeChild(n); t = null;
		return n;
	}

	function addItem(l, sId, o, h) {
		var l = $(l + '_list');
		if (l) {
			var n = toEl(h);
			if (o != "desc") l.appendChild(n);
			else l.insertBefore(n, l.firstChild);
		}
	}
	
	function replaceItem(l, sId, h) {
		replaceNode(l+"_item_"+sId, h);
	}

	function replaceNode(sId, h) {
		var n = $(sId);
		if (n) {
			n.parentNode.replaceChild(toEl(h), n);
		}
	}

	function removeItem(l, sId) {
		var n = $(l + "_item_" +sId);
		if (n) n.parentNode.removeChild(n);
	}
	
	function getValue(o) {
		o = $(o);
		if (o) {
			switch (o.nodeName.toLowerCase()) {
				case "select": return o.options[o.selectedIndex].value; break;
				case "ul":
					var a = document.getElementsByName(o.id);
					if (a && a.length > 0) {
						for (var i=0; i<a.length; i++) {
							if (a[i].checked) return a[i].value;
						}
					}
					break;
				default: return o.value; break;
			}
		}
	}

	function setValue(sId, v) {
		var n = $(sId);
		if (n) switch (n.nodeName.toLowerCase()) {
			case "input": n.value = v; break;
			case "select":
				for (var i = 0; i < n.options.length; i++) {
					if (n.options[i].value == v) {
						n.selectedIndex = i;
						break;
					}
				}
				break;
			case "ul":
				var a = document.getElementsByName(sId);
				for (var i=0; i<a.length; i++) {
					if (a[i].value == v) a[i].checked = true;
					else if (a[i].getAttribute("type") == "radio") a[i].checked = false;
				}
				break;
			default: n.innerHTML = v; break;
		}
	}

	function parseFormToObject(f) {
		var p = {};
		for (var s in f) {
			if (f[s] && (f[s].form == f || f[s].length)) {
				if (typeof(f[s].nodeName) != "undefined") {
					p[f[s].name] = getValue(f[s]);
				} else if (f[s].length > 0 && typeof(f[s][0]) != "undefined" && f[s][0].type == "radio") {
					for (var i in f[s]) {
						if (f[s][i].checked) {
							p[f[s][i].name] = getValue(f[s][i]);
							break;
						}
					}
				}
			}
		}
		return p;
	}

	function setContent(sId, h) {
		var n = $(sId);
		if (n) {
			if (n.nodeName.toLowerCase() == "select" && ie()) {
				n.innerHTML = "";
				n.outerHTML = n.outerHTML.replace(/\<\/SELECT\>/, h + "</SELECT>"); 
			} else n.innerHTML = h;
			n = null;
		}
	}
	
	function setAttribute(n, a, v) {
		n = $(n); if (n) n.setAttribute(a, v);
	}

	function setVisibility(n, v) {
		n = $(n); if (n) n.style.visibility = v;
	}

	function setDisplay(n, v) {
		n = $(n); if (n) n.style.display = v;
	}

	function setDisabled(sName, v) {
		var a = document.getElementsByName(sName);
		for (var i=0; i<a.length; i++) a[i].disabled = (v == "true");
	}
	
	function setChecked(sId, v) {
		n = $(sId);	if (n) n.checked = (v == "true");
	}
	
	function toggleList(sName, sId) {
		var l = $(sName);
		if (l) {
			for (var i=0; i<l.childNodes.length; i++) {
				var n = l.childNodes[i];
				n.style.display = (n.id == sName+"_"+sId) ? "block" : "none";
			}
		}
	}
	
	function selectItem(l, sId, sName) {
		var n = $(l+"_list_selected");
		if (n) {
			var no = $(l + "_item_" + n.value);
			if (no) no.className = "repeatable";
			n.value = sId;
			var nn = $(l+"_item_"+sId);
			if (nn) nn.className = "repeatable selected_item";
		}

		var nm = $(l+"_list_mode");
		if (nm && nm.value == "lookup") {
			var nt = $(l+"_popup_toggle");
			var nl = $(l);
			nl.defaultValue = nl.value = sName;
			if (nt && nl == document.activeElement) nt.focus();
		}

		if (typeof(doOnSelectItem) == "function") doOnSelectItem(l, sId, sName);
	}
	
	function setListFilter(l, sFilter) {
		setValue(l+"_list_filter", sFilter);
		setValue(l+"_list_selected", "");
		loadAsync('findItems', {}, l);
		if (typeof(doOnSetFilter) == "function") doOnSetFilter(l, sFilter);
	}

	function setDate(l, t, f, sName, sId, v, c) {
		var p = {Y:[1,"0000",""],m:[1,"00","-"],d:[1,"00","-"],H:[2,"00"," "],i:[2,"00","-"],s:[2,"00","-"]};
		var v = "";
		for (var s in p) {
			var n = $(sName+"_"+s);
			v += p[s][2];
			if (n) v += (p[s][0] == 1) ? n.options[n.selectedIndex].value : n.value || p[s][1]; 
			else v += p[s][1];
		}
		loadAsync(c, {table: t, field: f, id: sId, value: v});
	}
	
	function getSelectedItem(l) {
		return getValue(l+"_list_selected");
	}

	function getSelected(s) {
		var s = (typeof(s) != "string") ? s = s.name : s + "[]"; 
		var a = document.getElementsByName(s);
		var v = d = "";
		for (var i=0; i<a.length; i++) {
			if (a[i].checked) {
				v += d + a[i].value;
				d = ",";
			}
		}
		return v;
	}

	function getBitmask(s) {
		var s = (typeof(s) != "string") ? s = s.name : s + "[]"; 
		var a = document.getElementsByName(s);
		var v = 0;
		for (var i=0; i<a.length; i++) if (a[i].checked) v += Number(a[i].value);
		return v;
	}
	
	function resetLookup(n) {
		n.value = n.defaultValue;
	}
	
	function handleLookupBlur(e, o) {
		e = e || event;
		if (o.value == '') o.value = o.defaultValue;
		var n = $(o.id+'_list_selected');
		if (o.value != o.defaultValue) n.value = "0";
		setTimeout('toggle(\''+o.id+'_popup\', \'off\');', 100);
		setValue(o.id+"_lookup_focussed", "-1");
		o.parentNode.style.zIndex = 1;
	}
	
	function handleLookupFocus(e, o) {
		e = e || event;
		o.defaultValue = o.value;
		setValue(o.id, '');
		refreshLookup(o.id);
		toggle(o.id+'_popup', 'on');
		o.parentNode.style.zIndex = 100000;
	}
	
	function handleLookupKey(e, o) {
		e = e || event;
		var sId = o.id;
		var k = e.keyCode || e.which;
		switch (k) {
			case 34: //PgDown
				setValue(o.id+"_lookup_focussed", "-1");
				loadAsync('findItems', {set:'next'}, o.id);
				break;
			case 33: //PgUp
				setValue(o.id+"_lookup_focussed", "-1");
				loadAsync('findItems', {set:'prev'}, o.id);
				break;
			case 27:
			case 13:
				var n = $(o.id+"_popup_toggle");
				if (n) n.focus();
				return false;
				break;
			case 40://down
				var n = $(o.id+"_lookup_focussed");
				if (n) {
					var nl = $(o.id+"_list");
					var a = nl.selectNodes("./div");
					if (a.length > 0) {
						var i = n.value;
						if (i >= 0) a[i].style.backgroundColor="";
						i++;
						if (i > a.length-1) i = 0;
						a[i].style.backgroundColor="#ffdd8c";
						n.value = i;
					}
				}
				break;
			case 38: //up
				var n = $(o.id+"_lookup_focussed");
				if (n) {
					var nl = $(o.id+"_list");
					var a = nl.selectNodes("./div");
					if (a.length > 0) {
						var i = n.value;
						if (i >= 0) a[i].style.backgroundColor = "";
						i--;
						if (i < 0) i = a.length - 1;
						a[i].style.backgroundColor = "#ffdd8c";
						n.value = i;
					}
				}
				break;
			default:
				//setValue(o.id+'_list_selected', '0');
				setValue(o.id+"_lookup_focussed", "-1");
				refreshLookup(o.id);
				break;
		}
	}
	
	function catchLookupKeyDown(e, o) {
		var e = e || window.event;
		var keyCode = e.keyCode || e.which;
		var n = $(o.id);
		switch (keyCode) {
			case 27:
				resetLookup(o);
				return false;
				break;
			case 13:
				var nf = $(o.id+"_lookup_focussed");
				if (nf) {
					var i = nf.value;
					if (i >= 0) {
						var nl = $(o.id+"_list");
						var a = nl.selectNodes("./div");
						if (a[i]) {
							a[i].style.backgroundColor="";
							a[i].selectNodes("./div")[0].onclick();
						}
					}
				}
				return false;
				break;
		}
	}

	function refreshLookup(l) {
		var n = $(l);
		if (n) {
			setValue(l+"_list_criteria", n.value);
			setValue(l+"_lookup_create", n.value);
			loadAsync("findItems", {}, l);
		}
		return false;
	}

	function toggle(sId, s) {
		var n = $(sId);
		if (n) {
			if (!s) s = (n.style.display != "block") ? "on" : "off";
			n.style.display = (s == "on") ? "block" : "none";
			var o = $(sId+"_toggle");
			if (o) o.className = "toggle toggle_"+s;
		}
	}

	function reload(u) {
		if (u) window.location.href = u;
		else window.location.reload();
	}

	function switchItem(l, sId, m, n) {
		n = $(n);
		var s = loadAsync('redraw', {id:sId, mode:m}, l);
		replaceBySpinner(n, s);
		s = null;
	}

	function removeFrame(sId) {
		var o = $(sId);
		if (o.contentDocument) var d = o.contentDocument;
		else if (o.contentWindow) var d = o.contentWindow.document;
		else var d = window.frames[sId].document;
		if (d.location.href == "about:blank") return;
		var w = new XWrap();
		w.parse(d.body.innerHTML);
		runXML(w);
		setTimeout("$('"+sId+"').parentNode.removeChild($('"+sId+"'));", 10);
	}
	
	function createFrame(u) {
		var oTime = new Date();
		var sId = "asyncFrame_" + oTime.getTime();
		h = "<iframe src='"+u+"' name='"+sId+"' id='"+sId+"' style='display:none;' onload='removeFrame(\""+sId+"\");'></iframe>";
		document.body.appendChild(toEl(h));
		return sId;
	}
 
	function uploadAsync(f, u) {
		var sId = createFrame(u);
		f.setAttribute('enctype', "multipart/form-data");
		f.setAttribute('target', sId);
		return true;
	}
 
 	function initList(l) {
		if (typeof(window.lists) == 'undefined' || window.lists == null) window.lists = [];
		window.lists.push(l);
		loadAsync('initList', {}, l);
	}
	
	function initLists() {
		if (typeof(window.lists) != 'undefined' && window.lists != null) for (var i=0;i<window.lists.length;i++);
		window.lists = null;
	}
	 
	function runScripts(n) {
		if (n.tagName.toLowerCase() == 'script') eval(getContent(n)); //run the script
		else {
			var a = n.selectNodes(".//*");
			for (var i = 0; i < a.length; i++) {
				if (a[i].nodeName.toLowerCase() == "script") eval(getContent(a[i]));
			}
		}
	}