// --------------------------------------------------------------------------------------------------------
// jQuery extensions
// --------------------------------------------------------------------------------------------------------

function $$(id) {
	return document.getElementById(id);
}

(function($) {
	$.fn.enableRangeSelection = function(selector) {
		var form = this[0];
		var lastCheckbox = null;
		if (!selector) {
			selector = "input[type=checkbox]";
		}
		$(selector, form).click(function(event) {
			if (lastCheckbox != null && event.shiftKey) {
				var elements = $(selector, form)
				elements.slice(Math.min(elements.index(lastCheckbox), elements.index(event.target)), Math.max(elements.index(lastCheckbox), elements.index(event.target)) + 1).attr("checked", event.target.checked ? "checked" : "");
			}
			lastCheckbox = event.target;
		});
	}

	$.fn.enabledMaxLengthCheck = function(showCounter) {
		var limit = this.attr("maxlength");
		var id = this.attr("id");
		if (showCounter) {
			this.after("<div id='counter-"+id+"' class='csslabel'></div>");
		}
		this[0].updateCounter = function(e) {
			var value = $(this).val();
			if (value.length >= limit) {
				value = value.substring(0, limit);
				$(this).val(value);
			}
			$("#counter-"+id).html(value.length + '/' + limit);	
		}
		this.bind("keyup", this[0].updateCounter);
		this.bind("keydown", this[0].updateCounter);
		this.bind("change", this[0].updateCounter);
		this[0].updateCounter();
	}
}) (jQuery);

// --------------------------------------------------------------------------------------------------------
// helper functions
// --------------------------------------------------------------------------------------------------------

function StringBuffer() { 
	this.buffer = []; 
	this.length = 0;
} 

StringBuffer.prototype.append = function append(string) { 
	this.buffer.push(string); 
	this.length += string.length;
	return this; 
}; 

StringBuffer.prototype.toString = function toString() { 
	return this.buffer.join(""); 
}; 

function sfv(form, key, value) {
	value = unescape(value);
	if (value.indexOf("</option>") != -1 && form[key]) {
		form[key].length = 0;
		var match = new RegExp("<option (selected=\"true\" |)value=\"([^\"]*)\">([^\>]*)</option>", "img");
		var r;
		var si = -1;
		while ((r = match.exec(value)) != null) {
			if (r[1].length > 0) {
				si = form[key].length;
			}
			form[key][form[key].length] = new Option(r[3], r[2], r[1].length > 0);
		}
		if (si != -1) {
			form[key][si].selected = true;
		}
	} else if (form[key]) {
		if (form[key].type == "checkbox" || form[key].type == "radio") {
			if (value == "on") {
				form[key].checked = true;
			}
		} else if (form[key].type == "select-multiple") {
			var v = value.split(",");
			var o = form[key].options;
			for (var i = 0; i < o.length; i++) {
				for (var j = 0; j < v.length; j++) {
					if (o[i].value == v[j]) {
						o[i].selected = true;
						break;
					}
				}
			}
		} else {
			form[key].value = value;
		}
		/* Does not work in IE.
		if (form[key].onchange) {
			form[key].onchange();
		}
		*/
	} else {
		$("#"+key).html(value);
	}
}

var errorFocusSet = false;

function setError(form, key) {
	var e = document.getElementById(key+"_label");
	if (e != null) {
		if (e.className == "cssmandlabel") {
			e.className = "csserrormandlabel";
		} else {
			e.className = "csserrorlabel";
		}
	}
	if (!errorFocusSet) {
		if (form[key]) {
			form[key].focus();
			errorFocusSet = true;
		}
	}
}

function gst(form, key) {
	var text = key;
	if (form[key]) {
		text = form[key].value;
		text = replaceAll(text, "\\\\n", "\n");
	}
	return text;
}

function checkConfirm(form, type) {
	if (form[type] && !form[type].checked) {
		alert(gst(form, "ST_"+type));
	} else {
		return true;
	}
}

function doConfirm(form, type) {
	if (form[type] && !form[type].checked) {
		return confirm(gst(form, "ST_"+type));
	} else {
		return true;
	}
}

function addParam(name, value, url) {
	if (name.length > 0 && value != null && value.length > 0) {
		var param = name + "=" + escape(value);
		if (url.indexOf("?") == -1) {
			url += "?" + param;
		} else {
			url += "&" + param;
		}
	}
	return url;
}

function getFormElementValue(elem) {
	if (elem.type.indexOf("select") != -1) {	
		return elem.options[elem.selectedIndex].value;
	} else {
		return elem.value;
	}
}
		
function addFormParam(form, namePrefix, url) {
	var param = "";
	for (i = 0; i < form.elements.length; i++) {
		var name=form.elements[i].name;
		if (namePrefix != null && name.indexOf(namePrefix) != 0) {
			continue;
		}
		var value=getFormElementValue(form.elements[i]);
		if (name.length > 0 && value != null && value.length > 0) {
			value=escape(value);
			if (param.length > 0) {
				param += "&";
			}
			param += name + "=" + value;
		}
	}
	if (param.length > 0) {
		if (url.indexOf("?") == -1) {
			url += "?" + param;
		} else {
			url += "&" + param;
		}
	}
	return url;
}

//Returnerer antallet af valgte tabelrække ved at markere en checkbox eller radio
//Forudsætning : Der må kun være een kolonne med checkbox/radio
function countSelected(form) {
	var count = 0;
	if (form.name) {
		for (i = 0; i < form.elements.length; i++) {
			if ((form.elements[i].type == "checkbox" || form.elements[i].type == "radio") && form.elements[i].style.display != "none") {
				if (form.elements[i].checked) {
					count++;	
				}
			}
		}
	}
	return count;
}

function fixMenu() {
	$("#cssmenutable").before('<div id="fixedmenuhelper" style="position:fixed; top:0px; display: none;"></div>');
	$("#fixedmenu").before('<tr id="fixedmenureplacement" style="display: none"><td></td></tr>');

	var e = document.getElementById("fixedmenu");
	var distanceTop = getY(e);

	window.onscroll = function() {
		_fixMenu(distanceTop);
	};

	function getY(e) {
		var y = 0;
		while (e != null) {
			y += e.offsetTop;
			e = e.offsetParent;
		}
		return y;
	}

	function _fixMenu(distanceTop) {
		var e = document.getElementById("fixedmenu");
		var e2 = document.getElementById("fixedmenuhelper");
		var e3 = document.getElementById("fixedmenureplacement");

		if (e2.innerHTML == "") {
			e2.innerHTML = '<table id="fixedmenutable" width="100%" cellSpacing="0" cellPadding="0" border="0">'+e.innerHTML+'</table>';
			e3.style.height = e.offsetHeight+"px";
		}

		if (document.documentElement.scrollTop > distanceTop || self.pageYOffset > distanceTop) {
			e.style.display = "none";
			e2.style.display = "";
			e3.style.display = "";
		} else {
			if (document.documentElement.scrollTop < distanceTop || self.pageYOffset < distanceTop) {
				e.style.display = "";
				e2.style.display = "none";
				e3.style.display = "none";
			}
		}
	}
}

function maximizeWindow(win) {
	if (!win) {
		win = top;
	}
	win.window.moveTo(0,0);
	if (document.all) {
		win.window.resizeTo(screen.availWidth*0.9,screen.availHeight);
	} else if (document.layers||document.getElementById) {
		if (win.window.outerHeight < screen.availHeight || win.window.outerWidth < screen.availWidth){ 
			win.window.outerHeight = screen.availHeight;
			win.window.outerWidth = screen.availWidth*0.9;
		}
	}
}

function redirect(url) {
	if(document.images) {
		location.replace(url);
	} else { 
		location = url; 
	}
}

// --------------------------------------------------------------------------------------------------------
// public functions
// --------------------------------------------------------------------------------------------------------
function selectAll(form) {
	for (i = 0; i < form.elements.length; i++) {
		if (form.elements[i].type == "checkbox" && form.elements[i].style.display != "none") {
			form.elements[i].checked = true;
		}
	}
}

function deselectAll(form) {
	for (i = 0; i < form.elements.length; i++) {
		if (form.elements[i].type == "checkbox" && form.elements[i].style.display != "none") {
			form.elements[i].checked = false;
		}
	}
}

function toggleSelection(form) {
	var allSelected = true;
	for (var i = 0; i < form.elements.length; i++) {
		if (form.elements[i].type == "checkbox" && form.elements[i].style.display != "none") {
			if (!form.elements[i].checked) {
				allSelected = false;
				break;
			}
		}
	}
	if (allSelected) {
		deselectAll(form);
	} else {
		selectAll(form);
	}
}

// Place cursor in first error-field, if present, otherwise in field (atField), or in first 'not hidden', 'not readonly' field on atForm 
function placeCursor(atForm, atField) {
	if (test(atForm, atField)) {
		return;
	}
	if (errorFocusSet) {
		return;
	}
	if (!atForm) {
		atForm = placeCursor.lastForm;
	}
	placeCursor.lastForm = atForm;
	var i = 0;
	while (i < document.forms[atForm].elements.length && document.forms[atForm].elements[i].getAttribute('tabIndex') != 1) {
		i++;
	}
	if (i < document.forms[atForm].elements.length && document.forms[atForm].elements[i].getAttribute('tabIndex') ==1) {
		if (document.forms[atForm].elements[i].select) {
			document.forms[atForm].elements[i].select();
		}
	   	document.forms[atForm].elements[i].focus();
		return;
	}
	if (atField !=null) {
      	if (document.forms[atForm].elements[atField].select) {
			document.forms[atForm].elements[atField].select();
		}
      	document.forms[atForm].elements[atField].focus();
        return;
    }
	i = 0;
	while (document.forms[atForm].elements[i].type == 'hidden' || document.forms[atForm].elements[i].disabled == true) {
		i++;
	}
	if (i < document.forms[atForm].elements.length) {
		if (document.forms[atForm].elements[i].select) {
	     	document.forms[atForm].elements[i].select();
		}
     	document.forms[atForm].elements[i].focus();
	}
}

onloadQueue = new Array;
var oldOnLoadFunc = null;

function addOnloadFunc(func) {
	if (window.onload != onloadFunc) {
		if (window.onload != null) {
			oldOnLoadFunc = window.onload;
			onloadQueue[onloadQueue.length] = window.onload;
		}
		window.onload = onloadFunc;
	}
	if (func != null) {
		onloadQueue[onloadQueue.length] = func;
	}
}

function onloadFunc() {
	onloadQueuePos = 0;
	while (onloadQueuePos < onloadQueue.length) {
		onloadQueue[onloadQueuePos++]();
	}
	onloadQueue = new Array;
}

function doClear(form) {
	for (i = 0; i < form.elements.length; i++) {
		var e = form.elements[i];
		if (e.type == "checkbox" || e.type == "radio") {
			e.checked = false;
		} else if (e.type == "select" || e.type == "select-multiple") {
			e.selectedIndex = -1;
		} else if (e.type != "hidden") {
			e.value = "";
		}
	}
}

function replaceAll(astring, fromchar, tochar) {
	 var s;
	 s = astring + "";
	 while (s.indexOf(fromchar) >= 0) {
		 s = s.replace(fromchar, tochar);
	 };
	 return s;
};

// OpenOCES OpenLogon javascript
function onLogonOK(signature) {
	document.logindsForm.message.value=signature;
	document.logindsForm.result.value='ok';
	if (dsOK) {
		dsOK();
	}
}

function onLogonCancel() {
	if (dsCancel) {
		dsCancel();
	}
}

function onLogonError(msg) {
	if (dsError) {
		dsError();
	}
}

// --------------------------------------------------------------------------------------------------------
// Browser type
// --------------------------------------------------------------------------------------------------------
function Browsertype() {
	this.agt = navigator.userAgent.toLowerCase();
	this.major = parseInt(navigator.appVersion);  // version
	if (document.getElementById) {
		this.dom = 1;  // true for ie6, ns6
	} else {
		this.fom = 0;  
	}
	this.ns = (document.layers); //Netscape < 6
	this.ns4x = (this.ns && this.major >=4);
	this.ns6 = (this.dom && navigator.appName=="Netscape"); // Netscape >=6
	this.opera = this.agt.indexOf('opera')!=-1; // Opera
	this.ie = !this.ns6 && (document.all);   // Inernet Explorer
	if (document.all && !this.dom) {
		this.ie4 = 1;
	} else {
		this.ie4 = 0;
	}
	this.ie4x = (this.ie && this.major >= 4);
	this.ie5 = (document.all && this.dom);
}

var Browser = new Browsertype;

// -------------------------------------------------------------------------------------------------------------
// Printing functions, print in IE without printform
// -------------------------------------------------------------------------------------------------------------
function printWindow(win, showPrintPopup) {  
	// win not used
	if (Browser.ns || Browser.ns6 || Browser.opera || showPrintPopup) {
		try {
			printWithPopup();
		} catch (e) {
			win.print() ;  
		}
	} else {
		try {
			printWithoutPopup();
		} catch (e) {
			win.print() ;  
		}
		onload();
	}
}

function PrintButton_function(form) {
	printWindow(window, "false");
}

function presentFull(pos, format) {
	submit("search.html", "presentfull", ["request_attr_rec", pos, "format", format]);
}

function showSingleFull(keyno, format) {
	submit("search.html", "showfull", ["keyno_list", keyno, "format", format]);
}

function showYear(keyno, year) {
	submit("search.html", "showyear", ["keyno_year", keyno+"ZX"+year, "year", year]);
}

function showVolNum(keyno, year, vol, num) {
	submit("search.html", "showyear", ["keyno_year", keyno+"ZX"+year, "year", year, "vol", vol, "num", num, "serialselected", "1"]);
}

function continueSearch(query) {
	submit("search.html", "continuesearch", ["scode_ccl", query]);
}

function subjectSearch(link, query) {
	submit("search.html", "subjectsearch", ["link", link, "scode_subjecttree", query]);
}

function subjectNavi(link) {
	submit("search.html", "", ["link", link]);
}

function showSearch(key) {
	submit("search.html", "search-on-search-key", ["search_key", key]);
}

function toggleElement(id) {
	var e = document.getElementById(id);
	if (e.style.display == "none") {
		e.style.display = "";
	} else {
		e.style.display = "none";
	}
}

function addKeyValue(field, key, value) {
	key = escape(key);
	value = escape(value);
	if (field.value.length > 0) {
		field.value = field.value + " " + key + "=" + value;
	} else {
		field.value = field.value + key + "=" + value;
	}			
}

function addKeyValue2(strbuf, key, value) {
	key = escape(key);
	value = escape(value);
	if (strbuf.length > 0) {
		strbuf.append(" ");
	}
	strbuf.append(key);
	strbuf.append("=");
	strbuf.append(value);
}

function getElementValue(element) {
	if (element.type.indexOf("select") != -1) {
		if (element.length == 0) {
			return "";
		} else {
			var s = "";
			var i = 0;
			var found = false;
			for (i = 0; i < element.length; i++) {
				if (element.options[i].selected) {
					if (s.length > 0) {
						s += ",";
					}
					s += element.options[i].value;
					found = true;
				}
			}
			if (!found) {	// !!! IE7.0 hack. If a option has not been explicit selected there is no element.options[i].selected
				if (element.selectedIndex >= 0 && element.selectedIndex < element.length) {	// !!! IE6.0 hack. selectedIndex=-1
					s = element.options[element.selectedIndex].value;
				}
			}
			return s;
		}
	} else if (element.type.indexOf("checkbox") != -1) {
		if (element.checked) {
			return "on";
		} else {
			return "off";
		}
	} else if (element.type.indexOf("radio") != -1) {
		if (element.checked) {
			return "on";
		} else {
			return "off";
		}
	} else {
		return element.value;
	}

}

function addForm(field, form) {
	if (form) {
		var strbuf = new StringBuffer();
		strbuf.append(field.value);
		var length = form.elements.length;
		for (var i = 0; i < length; i++) {
			var e = form.elements[i];
			fieldValue = addKeyValue2(strbuf, e.name, getElementValue(e));
		}			
		field.value = strbuf.toString();
	}
}

function getDataStr(keyvalue) {
	var data = "";
	if (keyvalue != null) {
		var strbuf = new StringBuffer();
		for (i = 0; i < keyvalue.length; i += 2) {
			addKeyValue2(strbuf, keyvalue[i], keyvalue[i+1]);
		}			
		data = escape(strbuf.toString());
	}
	return data;
}

function getData(keyvalue, win) {
	if (win == null) {
		win = self;
	}
	win.document.submitForm.data.value = "";
	win.addData(win.document.submitForm.data);
	var strbuf = new StringBuffer();
	strbuf.append(win.document.submitForm.data.value);
	win.document.submitForm.data.value = "";
	if (extraKeyValue != null) {
		for (i = 0; i < extraKeyValue.length; i += 2) {
			addKeyValue2(strbuf, extraKeyValue[i], extraKeyValue[i+1]);
		}			
	}
	if (keyvalue != null) {
		for (i = 0; i < keyvalue.length; i += 2) {
			addKeyValue2(strbuf, keyvalue[i], keyvalue[i+1]);
		}			
	}
	var data = strbuf.toString();
	data = escape(data);
	return data;
}

function createRequestMap(paramList) {
	var map = {};
	var l = paramList.split("&");
	for (var i = 0; i < l.length; i++) {
		var kv = l[i].split("=");
		map[kv[0]] = unescape(kv[1]);
	}
	return map;
}

// --------------------------------------------------------------------------------------------------------
// Submission handling
// --------------------------------------------------------------------------------------------------------

function handleSubmit(event, form, defaultbutton) {
	code = event.keyCode;
	target = (Browser.ie || Browser.opera) ? event.srcElement : event.target; 
	if (code == 13 && !(target.href) && target.type != "textarea") {
		eval(defaultbutton+"_function(form)");
	}
}

var postSubmit = true;
var extraKeyValue = null;
var addData = true;

function submitData(target, doaction, keyvalue, srcWin, dstWin) {
	if (addData) {
		srcWin.document.submitForm.data.value = "";
		srcWin.addData(dstWin.document.submitForm.data);
	}
	if (srcWin != dstWin) {
		dstWin.document.submitForm.tokenid.value = srcWin.document.submitForm.tokenid.value;
	}
	var strbuf = new StringBuffer();
	strbuf.append(dstWin.document.submitForm.data.value);
	if (extraKeyValue != null) {
		for (i = 0; i < extraKeyValue.length; i += 2) {
			addKeyValue2(strbuf, extraKeyValue[i], extraKeyValue[i+1]);
		}			
	}
	if (keyvalue != null) {
		for (i = 0; i < keyvalue.length; i += 2) {
			addKeyValue2(strbuf, keyvalue[i], keyvalue[i+1]);
		}			
	}
	dstWin.document.submitForm.data.value = strbuf.toString();
	if (target != null && target != "") {
		dstWin.document.submitForm.action = target;
	} else if (target == null || target == "") {
		dstWin.document.submitForm.action = srcWin.location.href;
	}
	if (doaction != null) {
		dstWin.document.submitForm.doaction.value = doaction;
	}

	if (postSubmit) {
		dstWin.document.submitForm.submit();
	} else {
		dstWin.document.cookie = "doaction="+dstWin.document.submitForm.doaction.value;
		dstWin.document.cookie = "data="+dstWin.document.submitForm.data.value;
		if (dstWin.document.cookie.length == 0) {	// cookie disabled
			dstWin.location.replace(dstWin.document.submitForm.action+"?doaction="+dstWin.document.submitForm.doaction.value+"&data="+dstWin.document.submitForm.data.value);
		} else {
			if (dstWin.document.submitForm.action == "") {
				dstWin.location.replace(location.href);
			} else {
				dstWin.location.replace(dstWin.document.submitForm.action);
			}
		}
	}
}

function submit(target, doaction, keyvalue) {
	submitData(target, doaction, keyvalue, self, self);
}

function submitPopup(target, doaction, keyvalue, windowName, windowFeatures, size) {
	if (windowFeatures == "") {
		windowFeatures = "status=yes,scrollbars=yes,resizable=yes";
	}
	if (size != "max") {
		windowFeatures += ","+size;
	}
	var win = open("", windowName, windowFeatures);
	win.document.open("text/html", "replace");
	win.document.write('<form name="submitForm" method="post"><input name="doaction" type="hidden"><input name="data" type="hidden"><input name="tokenid" type="hidden"><input name="ispopup" value="1" type="hidden"></form>');
	win.document.close();
	submitData(target, doaction, keyvalue, self, win);
	if (size == "max") {
		maximizeWindow(win);
	}
	return win;
}

function openPatronSelfCreateInsert(ds, nemlogin) {
	if (nemlogin) {
		win = submitPopup("patronselfcreateinsert.html", "" , ["NemLogin", nemlogin], "NemLogin", "", "height=500,width=750");
	} else {
		win = submitPopup("patronselfcreateinsert.html", "" , ["DigitalSignatur", ds], "DS", "", "height=500,width=750");
	}
	win.focus();
}

function openHelp(helpid) {
	helpWin = open("help.html?helpid="+helpid, "help", "scrollbars=yes,resizable=yes,height=500,width=700");
	helpWin.focus();
}

function openPatronUpdate(tickno) {
	win = submitPopup("patronupdate.html","search",["patu_tickno",tickno], "Update", "", "max");
	win.focus();
}

function openBookingUpdate(bookingno) {
	win = submitPopup("bookingupdate.html","bookingno",["boou_bookingno",bookingno], "Update", "", "max");
	win.focus();
}

function openBookingView(bookingno) {
	win = submitPopup("bookingview.html","bookingno",["boou_bookingno",bookingno], "Update", "", "max");
	win.focus();
}

function openHoldingUpdate(copyno) {
	win = submitPopup("holdingupdate.html", "search_link", ["holrl_copyno",copyno], "holding", "", "max");
	win.focus();
}

function openRes(keyno) {
	win = submitPopup("reservation.html", "res-check", ["keyno", keyno], "rescheck", "", "height=550,width=550");
	win.focus();
}

function openControlRes(keyno, copyno) {
	win = submitPopup("reservation.html", "control-res-check", ["keyno", keyno, "copyno", copyno], "rescheck", "", "height=550,width=550");
	win.focus();
}

function openBooking(keyno) {
	with (new Date()) ddate = String(getDate() + "." + (getMonth()+1)+ "." +getFullYear());
	win = submitPopup("bookinginsert.html", "single-lookup", ["keyno", keyno, "boor_bookdatefrom", ddate], "booking", "", "max");
	win.focus();
}

function openMatStat(keyno) {
	win = submitPopup("matstat.html", "search", ["matstat_keyno",keyno], "matstat", "", "height=600,width=800");
	win.focus();
}

function openMatStatBooking(bookingno) {
	win = submitPopup("matstat.html", "search", ["matstat_bookingno",bookingno], "matstat", "", "height=600,width=800");
	win.focus();
}

function addToBasket(keyno) {
	var p = "doaction=add-single-to-basket&data="+getDataStr(["keyno", keyno])+"&tokenid="+document.submitForm.tokenid.value;
	//var u = new Ajax.Updater("bbutton_"+keyno, self.location.href, {asynchronous:true, evalScripts:true, onComplete:function(request) { }, parameters:p})
	$("#bbutton_"+keyno).load(self.location.href, createRequestMap(p));
}

function removeFromBasket(keyno, rowID) {
	var p ="doaction=remove-single-from-basket&data="+getDataStr(["keyno", keyno, "rowid", rowID])+"&tokenid="+document.submitForm.tokenid.value;
	var href = self.location.href;
	if (href.indexOf("basket.html") != -1) {
		//var u = new Ajax.Request(self.location.href, {asynchronous:true, evalScripts:true, onComplete:function(request) { Toggle.display(rowID); Toggle.display(rowID+"_separator") }, parameters:p})
		$.get(self.location.href, p, function() { 
			$("#"+rowID+",#"+rowID+"_separator").fadeOut(200, function(e) {
				$(this).hide();
			});
		});
	} else {
		//var u = new Ajax.Updater("bbutton_"+keyno, self.location.href, {asynchronous:true, evalScripts:true, onComplete:function(request) { }, parameters:p})
		$("#bbutton_"+keyno).load(self.location.href, createRequestMap(p));
	}
}

function mailRecord(keyno) {
	win = submitPopup("basket.html", "mail-single", ["keyno", keyno], "mailselected", "", "height=200,width=500");
	win.focus();
}

function printRecord(keyno) {
	win = submitPopup("basket.html", "print-single", ["keyno", keyno], "printselected", "", "height=400,width=400");
	win.focus();
}

function addSearchToBasket(form, name) {
	var message = gst(form, "ST_AddSearchToBasketMessage");
	name = prompt(message, name);
	if (name != null) {
		var p= "doaction=add-search-to-basket&data="+getData(["search_name", name])+"&tokenid="+document.submitForm.tokenid.value;
		//var u = new Ajax.Updater("search_basket", self.location.href, {asynchronous:true, evalScripts:true, onComplete:function(request) { }, parameters:p})
		$("#search_basket").load(self.location.href, createRequestMap(p));
	}
}

function removeSearchFromBasket(key) {
	var p = "doaction=remove-search-from-basket&data="+getDataStr(["search_key", key])+"&tokenid="+document.submitForm.tokenid.value;
	//var u = new Ajax.Request(self.location.href, {asynchronous:true, evalScripts:true, onComplete:function(request) { Toggle.display("search_basket_"+key) }, parameters:p})
	$.get(self.location.href, p, function() { 
		$("#search_basket_"+key).fadeOut(200, function(e) {
			$(this).hide();
		});
	});
}

function mailSearch(key) {
	win = submitPopup("basket.html", "mail-search", ["search_key", key], "mailselected", "", "height=200,width=500");
	win.focus();
}

function printSearch(key) {
	win = submitPopup("basket.html", "print-search", ["search_key", key], "printselected", "", "height=400,width=400");
	win.focus();
}

// --------------------------------------------------------------------------------------------------------
// Functions for keyDownHandler
// --------------------------------------------------------------------------------------------------------
var Ctrl =  false;
var Shift = false;
var Alt =   false;


document.onkeydown = KeyDownHandler;
document.onkeyup = KeyUpHandler;

// --------------------------------------------------------------------------------------------------------
// Fanger IE hjælp på F1
// --------------------------------------------------------------------------------------------------------
document.onhelp = function()
{
	Ctrl = window.event.ctrlKey;
	Alt = window.event.altKey;
	Shift = window.event.shiftKey;
	return HandleFunctionKeys(501);
}
	

function KeyUpHandler()
{
	if (Browser.ns6 || Browser.ns)
	{
		Ctrl = false;
		Alt = false;
		Shift = false;
	}	
}


function KeyDownHandler(e) //I Netscape får man et event-object med
{
	var Code = 0;	

	if (Browser.ns6 || Browser.ns)
	{
		Code = e.which;
		switch(Code)
		{
			case 17:
				Ctrl = true;
				break;
			case 18:
				Alt = true;
				break;
			case 16:
				Shift = true;
				break;
			case 112:  // F1
				Code = 501;
			default:
				if (Code > 20)
				{
					if (HandleFunctionKeys(Code))
					{
						return true;
					}
					else
					{
						return false;
					}
				}
		}
	}
	else //IE
	{
		Code = event.keyCode;
		Ctrl = window.event.ctrlKey;
		Alt = window.event.altKey;
		Shift = window.event.shiftKey;
		if (handleBarcodeKeycode(Code)) {
			return false;
		} else if (event.keyCode > 20) {
			if (HandleFunctionKeys(Code)) {
					return true;
			} else {
				event.keyCode = 0;
				event.returnValue = false;
				event.cancelBubble = true;
				return false;
			}
		}
	}
}	

function BarcodeEvent() {
	this.type = null;
	this.data = "";
}

BarcodeEvent.prototype.getType = function() {
	return this.type;
}

BarcodeEvent.prototype.setType = function(type) {
	this.type = type;
}

BarcodeEvent.prototype.getData = function() {
	return this.data;
}

BarcodeEvent.prototype.setData = function(data) {
	this.data = data;
}

BarcodeEvent.prototype.addData = function(data) {
	this.data += data;
}

BarcodeEvent.prototype.isComplete = function() {
	if (this.type == "copyno") {
		return true;
	} else if (this.type == "func") {
		return this.data.length == 4;
	} else {
		return true;
	}
}

BarcodeEvent.prototype.toString = function() {
	return "BarcodeEvent[type="+this.type+"; data="+this.data+"]";
}

var bEvent = null;
var hasShift = false;
var hasAlt = false;
var hasCtrl = false;

function handleBarcodeKeycode(code) {
	var consume = false;
	var event = bEvent;
	if (code == 16) {
		hasShift = true;
	} else if (code == 17) {
		hasCtrl = true;
	} else if (code == 18) {
		hasAlt = true;
	} else if (code == 120 || (code == 49 && hasShift /*&& hasAlt */ && hasCtrl)) { // key koden for F9 or 1
		hasShift = false;
		hasAlt = false;
		hasCtrl = false;
		if (!document.activeElement || !document.activeElement.name) {	// only if IE and activeElement is not a field
			if (oldOnLoadFunc != null) {	// placed here to prevent dropdowns in consuming first character
				oldOnLoadFunc();
			} else if (window.onload) {
				window.onload();
			}
		}
		bEvent = new BarcodeEvent();
		event = bEvent;
		setTimeout("bEvent = null", 1000);
		consume = true;
	} else if (event != null) {
		hasShift = false;
		hasAlt = false;
		hasCtrl = false;
		if (event.getType() == null) {
			if (code == 189) { // key koden for en '/' på et US tastatur, på et dansk tastatur skal man taste '-'
				event.setType("func");
				consume = true;
			} else {
				event.setType("copyno");
			}
		} else {
			event.addData(String.fromCharCode(code));
			consume = true;
		}
		if (event.isComplete()) {
			bEvent = null;
			handleBarcodeEvent(event);
		}
	}
	return consume;
}

function handleBarcodeEvent(event) {
	if (event.getType() == "copyno") {
		// moved up
	} else if (event.getType() == "func") {
		var data = event.getData().substr(0, 3);
		while (data.charAt(0) == "0") {
			data = data.substr(1);
		}
		var code = parseInt(data);
		if (isValidFunctionKey(code, self)) {
			var fString = "alt"+String.fromCharCode(code)+'()';
			setTimeout(fString, 0);
		}
	}
}


// --------------------------------------------------------------------------------------------------------
// Internet Explorer >= 5.0, Netscape >= 6.0 Mozilla >= 1.0
// Ikke Netscape 4.x, ikke Opera.

// Sæt de funktionstaster op, der skal have særlig funktion
// F1: 501 F2 - F12: 113 - 123
// a-z: 65-90 æ: 192 ø: 222 å: 221
// ½: 220 0-9: 48-57
// <: 226 ,: 188 .: 190 ´: 219 ': 191 ¨: 186
// /: 111 *: 106 - (num): 109 - (norm. tastatur): 189 + (num): 107 + (norm. tastatur): 187
// Pil V: 37 Pil Op: 38 Pil H: 39 Pil ned: 40 Ins: 45 Del: 46 Home: 36 End: 35 PgUp: 33 PgDn: 34
// Window venstre: 91 Window højre: 92 Lokalmenu: 93 Space: 32
//
// I IE >= 5.0 bliver de originale funktioner, der er på nogle af taster og tastekombinationer
// undertrykt. Dette sker ikke i Netscape eller Mozilla.'
// --------------------------------------------------------------------------------------------------------
function HandleFunctionKeys(No) {
	if (!Ctrl && !Shift && !Alt) {
		switch(No) {
			case 27:
				esc();
				return false;
			default:
				return true;
		}
	}
	
	if (Ctrl && !Shift && !Alt) { 
		switch(No) {
			case 38:
				ctrlup();
				return false;
			case 40:
				ctrldown();
				return false;
			default:
				return true;
		}
	}
	
	if (!Ctrl && !Shift && Alt && isValidFunctionKey(No, self)) { 
		setTimeout("alt"+String.fromCharCode(No)+"()", 0);
		return false;
	} else {
		return true;
	}
}

function isValidFunctionKey(no, w) {
	var v = false;
	switch (String.fromCharCode(no)) {
		case 'A' : if (w.altA) v = true; break;
		case 'B' : if (w.altB) v = true; break;
		case 'C' : if (w.altC) v = true; break;
		case 'D' : if (w.altD) v = true; break;
		case 'E' : if (w.altE) v = true; break;
		case 'F' : if (w.altF) v = true; break;
		case 'G' : if (w.altG) v = true; break;
		case 'H' : if (w.altH) v = true; break;
		case 'I' : if (w.altI) v = true; break;
		case 'J' : if (w.altJ) v = true; break;
		case 'K' : if (w.altK) v = true; break;
		case 'L' : if (w.altL) v = true; break;
		case 'M' : if (w.altM) v = true; break;
		case 'N' : if (w.altN) v = true; break;
		case 'O' : if (w.altO) v = true; break;
		case 'P' : if (w.altP) v = true; break;
		case 'Q' : if (w.altQ) v = true; break;
		case 'R' : if (w.altR) v = true; break;
		case 'S' : if (w.altS) v = true; break;
		case 'T' : if (w.altT) v = true; break;
		case 'U' : if (w.altU) v = true; break;
		case 'V' : if (w.altV) v = true; break;
		case 'W' : if (w.altW) v = true; break;
		case 'X' : if (w.altX) v = true; break;
		case 'Y' : if (w.altY) v = true; break;
		case 'Z' : if (w.altZ) v = true; break;
		case '0' : if (w.alt0) v = true; break;
		case '1' : if (w.alt1) v = true; break;
		case '2' : if (w.alt2) v = true; break;
		case '3' : if (w.alt3) v = true; break;
		case '4' : if (w.alt4) v = true; break;
		case '5' : if (w.alt5) v = true; break;
		case '6' : if (w.alt6) v = true; break;
		case '7' : if (w.alt7) v = true; break;
		case '8' : if (w.alt8) v = true; break;
		case '9' : if (w.alt9) v = true; break;
	}
	return v;
}

// --------------------------------------------------------------------------------------------------------
// Button functions
// --------------------------------------------------------------------------------------------------------
function CloseButton_function(form) {
	close();
}

function ShowPrevPageButton_function(form) {
	submit('', 'reshow', ['request_attr_rec', form.prevrec.value]);
}

function ShowNextPageButton_function(form) {
	submit('', 'reshow', ['request_attr_rec', form.nextrec.value]);
}

function ShowPrevRecordButton_function(form) {
	submit('', 'presentfull', ['request_attr_rec', form.prevrec.value]);
}

function ShowNextRecordButton_function(form) {
	submit('', 'presentfull', ['request_attr_rec', form.nextrec.value]);
}

function BackButton_function(form) {
	if (form.referer && form.referer.value.indexOf("patronstatus.html") != -1) {
		submit("patronstatus.html", "", null);
	} else if (document.searchresultnaviForm) {
		var nextrec = parseInt(document.searchresultnaviForm.nextrec.value);
		var defaultpage = parseInt(form.request_attr_defaultpage.value);
		var pagenum = Math.round((nextrec-1) / defaultpage - 0.5);
		submit("search.html", "reshow", ["format", "", "request_attr_rec", pagenum*defaultpage]);
	} else {
		history.back(1);
	}
} 

function SelectAllButton_function(form) {
	selectAll(form);
}

function DeselectAllButton_function(form) {
	deselectAll(form);
}

function MailSelectedButton_function(form) {
	win = submitPopup("search.html", "mail-result", null, "mailselected", "", "height=200,width=500");
	win.focus();
}

function RenewSelectedButton_function(form) {
	if (countSelected(form) == 0) {
		win = submitPopup("emptySelection.html", "", null, "info", "", "height=150,width=400");
		win.focus();
	} else if (countSelected(form) > 1) {
		win = submitPopup("tooManySelected.html", "", "", "", "", "height=150,width=400");		
		win.focus();
	} else {
		win = submitPopup("classrenew.html", "show-search", null, "Classrenew", "height=400,width=750");
		win.focus();
	}
}

function PublishSelectedButton_function(form) {
	if (countSelected(form) == 0) {
		win = submitPopup("emptySelection.html", "", null, "publish", "", "height=150,width=400");
		win.focus();
	} else {
		win = submitPopup("publish.html", "select-list", null, "publish", "", "height=600,width=800");
		win.focus();
	}
}

function ClassRenewSubmitButton_function(form) {
	submit("", "renew", null);
}

function ClassRenewCancelButton_function(form) {
	close();
}

function AddSelectedToBasketButton_function(form) {
	submit("", "add-selected-to-basket", null);
}

function PrintSelectedButton_function(form) {
	win = submitPopup("search.html", "print-result", null, "printselected", "", "height=400,width=400");
	win.focus();
} 

function MailBasketButton_function(form) {
	win = submitPopup("basket.html", "mail-basket", null, "mailselected", "", "height=200,width=500");
	win.focus();
}

function PrintBasketButton_function(form) {
	win = submitPopup("basket.html", "print-result", null, "printselected", "", "height=400,width=400");
	win.focus();
} 

function SearchSelectAllButton_function(form) {
	submit("search.html", "select-all", null);
} 

function SearchDeselectAllButton_function(form) {
	submit("search.html", "deselect-all", null);
} 

function EmptyBasketButton_function(form) {
	submit("basket.html", "empty-basket", null);
} 

function MailResultQuickPatronButton_function(form) {
	var win = open("quickpatron.html", "quickpatron", "scrollbars=yes,resizable=yes,height=600,width=600");
	win.focus();
	selectPatron = function(tickno, mailadr) {
		form.mailresult_email.value = mailadr;
		win.close();
	};
}

function MailResultSubmitButton_function(form) {
	submit("mailresult.html", "mail-result", null);
}

function MailResultCancelButton_function(form) {
	close();
}

function PrintButton_function(form) {
	print();
} 

function ReserveBasketButton_function(form) {
	win = submitPopup("reservation.html", "res-check", null, "rescheck", "", "height=550,width=550");
	win.focus();
}

function MenuCheckinButton_function(form) {
	submit('checkin.html', '', null);
}

function MenuMassCheckinButton_function(form) {
	submit('masscheckin.html', '', null);
}

function MenuCheckoutButton_function(form) {
	submit('checkout.html', '', null);
}

function MenuMassCheckoutButton_function(form) {
	submit('masscheckout.html', '', null);
}

function MenuClassCheckoutButton_function(form) {
	submit('classcheckout.html', '', null);
}

function MenuAdvancedCheckoutButton_function(form) {
	submit('advancedcheckout.html', '', null);
}

function EmptySearchBasketButton_function(form) {
	submit("basket.html", "empty-search-basket", null);
} 

function lookup(id, type, params) {
	var e = document.getElementById(id);
	if (e != null) {
		if (e.type == 'text') {
			var div = document.createElement("div");
			div["id"] = "dummy123";
			document.body.appendChild(div);
			var p = "doaction="+type+"&data="+getDataStr(params);
			/*
			new Ajax.Updater("dummy123", "lookup.html", {asynchronous:true, evalScripts:true, onComplete:function(request) { 
				var v = div.innerHTML;
				var i;
				if ((i = v.indexOf("<!-- Processed by"))) {
					v = v.substring(0, i);
				}
				e.value = v;
				document.body.removeChild(div) 
			}, parameters:p});
			*/
			$("#dummy123").load("lookup.html", createRequestMap(p), function() {
				var v = div.innerHTML;
				var i;
				if ((i = v.indexOf("<!-- Processed by")) != -1) {
					v = v.substring(0, i);
				}
				e.value = v;
				document.body.removeChild(div) 
			});
		} else {
			var p = "doaction="+type+"&data="+getDataStr(params);
			//new Ajax.Updater(id, "lookup.html", {asynchronous:true, evalScripts:true, onComplete:function(request) { }, parameters:p});
			$(e).load("lookup.html", createRequestMap(p));
		}
	}
}

// --------------------------------------------------------------------------------------------------------
// SearchForm buttons
// --------------------------------------------------------------------------------------------------------
function SearchButton_function(ref) {
	submit(null, 'search',  null);
}

function ResetButton_function(form) {
	submit('', '', null);
}

function ClearButton_function(form) {
	submit("search.html", "blank", null);
}

function ShowAdvancedButton_function(form) {
	submit('', '', ['advanced', 'true']);
}

function ShowSimpleButton_function(form) {
	submit('', '', ['advanced', 'false']);
}

function SearchWebButton_function(form) {
	openAXLPopup();
}

function ShowScanAuthorButton_function(form) {
	openScanPopup("lfo", form, "scode_author", false);
}

function ShowScanTitleButton_function(form) {
	openScanPopup("lti", form, "scode_title", false);
}

function ShowScanSubjectButton_function(form) {
	openScanPopup("lem", form, "scode_subject", false); 
}

function openScanPopup(scan_code, form, destfieldname, fromCatalog) {
	list = form.elements[destfieldname].value.split(",");
	scan_text = list[list.length-1].replace("\"", "").replace("\"", "");
	scantext = replaceAll(scan_text, "  ", " ");
	if (scantext.indexOf(" ") == 0) {
		scantext = scantext.substring(1,scantext.length)	
	}
	doaction = (scantext.length > 0) ? "scan" : "";
	win = submitPopup("scanpopup.html", doaction, ["scan_code", scan_code, "scan_text", scantext, "destformname", form.name, "destfieldname", destfieldname, "fromcatalog", fromCatalog], "scan", "", "height=600,width=700");
	win.focus();
}

function updateElement(id, target, doaction, params, fullsubmit, onCompleteFunction) {
	var url = target;
	var p = "doaction=";
	if (doaction != null) {
		p += doaction;
	}
	p += "&data=";
	if (fullsubmit) {
		p += getData(params);
	} else {
		p += getDataStr(params);
	}
	p += "&tokenid="+document.submitForm.tokenid.value;
	//new Ajax.Updater(id, url, {asynchronous:true, evalScripts:true, onComplete:function(request) { if (onCompleteFunction != null) { onCompleteFunction(request) } }, parameters:p})
	$("#"+id).load(url, createRequestMap(p), onCompleteFunction);
}

function openAXLPopup() {
	win = submitPopup("search.html", "axl-search", "", "AXLPopup", "", "");
	win.focus();
}

function resizeFrame(frame, extra) {
	var h = frame.contentWindow.document.body.scrollHeight;
	frame.height = h + extra;
}

function showBookcover(url, keynoList, isFull) {
	var surl = self.location.href;
	var p = surl.indexOf("/sites/");
	var p2 = surl.indexOf("/", p+7);
	var site = surl.substring(p+7, p2);
	surl = surl.substring(0, p);
	if (url == "") {
		url = surl+"/cover/";
	}
	url += "?site="+site
	if (keynoList.length > 0) {
		var j;
		for (j = 0; j < keynoList.length; j += 10) {
			var ckeyno = keynoList[j];
			var keyno = ckeyno.substring(0, ckeyno.indexOf('_'));
			var e = document.getElementById("cover:"+keyno);
			e["pos"] = j;
			if (e != null) {
				e.onload = function() { 
					var pos = this["pos"];
					this.className = this.className.substring(0, this.className.length-7);
					var i;
					for (i = pos+1; i < keynoList.length && i < pos+10; i++) {
						var ckeyno = keynoList[i];
						var keyno = ckeyno.substring(0, ckeyno.indexOf('_'));
						var e = document.getElementById("cover:"+keyno);
						e.onload = function() { 
							this.className = this.className.substring(0, this.className.length-7);
						};
						var src = url+"&keyno="+ckeyno;
						if (e.className.indexOf("bookcoverfull") != -1) {
							src += "&type=detail";
						}
						e.src = src;
					}
				};
				var src = url+"&keyno="+keynoList.slice(j, j+10);
				if (e.className.indexOf("bookcoverfull") != -1) {
					src += "&type=detail";
				}
				e.src = src;
			}
		}
	}
}

function showSearchURL(message) {
	var freetext = "";
	var form = document.searchForm;
	for (i = 0; i < form.elements.length; i++) {
		var name = form.elements[i].name;
		if (name.indexOf("scode_") == 0) {
			var value = form.elements[i].value;
			if (freetext.length > 0) {
				freetext = freetext + " ";
			}
			freetext = freetext + name + "=" + value;
		}
	}

	var href = self.location.href;
	var pos = href.indexOf("sites/");
	if (pos != -1) {
		pos = href.indexOf("/", pos+6);
		if (pos != -1) {
			pos = href.indexOf("/", pos+1);
			if (pos != -1) {
				href = href.substring(0, pos+1);
				href += "search.html?doaction=search&data="+escape(freetext);
				prompt(message, href);
			}
		}
	}
	return false;
}

// --------------------------------------------------------------------------------------------------------
// Catalog buttons
// --------------------------------------------------------------------------------------------------------

function CatalogShowCreateButton_function(form) {
	var win = submitPopup("cataloginsert.html", "", null, "cataloginsert", "", "max");
	win.focus();
}
function CatalogShowCreateTOSButton_function(form) {
	var win = submitPopup("cataloginsertTOS.html", "", null, "cataloginsert", "", "max");
	win.focus();
}
function CatalogShowUpdateButton_function(form) {
	if (countSelected(form)== 1) {
		win = submitPopup("catalogupdate.html", "search", "", "catalog", "", "max");
		win.focus();
		return;
	}
	if (countSelected(form)< 1) {
		win = submitPopup("emptySelection.html", "", "", "", "", "height=150,width=400");		
		win.focus();
		return;
	}
	if (countSelected(form)> 1) {
		win = submitPopup("tooManySelected.html", "", "", "", "", "height=150,width=400");		
		win.focus();
		return;
	}
}
function CatalogShowUpdateKeynoButton_function(form) {
	if (countSelected(form)== 1) {
		win = submitPopup("catalogupdatekeyno.html", "", "", "catalog", "", "max");
		win.focus();
		return;
	}
	if (countSelected(form)< 1) {
		win = submitPopup("emptySelection.html", "", "", "", "", "height=150,width=400");		
		win.focus();
		return;
	}
	if (countSelected(form)> 1) {
		win = submitPopup("tooManySelected.html", "", "", "", "", "height=150,width=400");		
		win.focus();
		return;
	}
}
function CatalogCreateButton_function(form) {
	submit('cataloginsert.html','insert','');
}
function CatalogUpdateButton_function(form) {
	submit('catalogupdate.html','update','');
}
function CatalogUpdateKeynoButton_function(form) {
	submit('catalogupdatekeyno.html','update','');
}
function CatalogClearButton_function(form) {
	doClear(form);
}
function CatalogResetButton_function(form) {
	form.reset();
}
function CatalogHoldingInsertButton_function(form) {
	self.resizeBy(200, 0);
	submit("holdinginsert.html", "lookup_from_catalog", null);
}
function CatalogCancelButton_function(form) {
	close();
}
function CatalogSearchButton_function(form) {
	var keyno =  form.catalogsearchForm.cats_keyno.value;
	submit('catalogupdate.html', 'search',  ['cats_keyno', keyno]);

}

function openCheckedAuthorPopup(form, destfieldname, destfieldname2) {
	list = form.elements[destfieldname].value.split(",");
	scan_text = list[list.length-1].replace("\"", "").replace("\"", "");
	scan_text2 = form.elements[destfieldname2].value;
	scantext = scan_text + ' ' + scan_text2;
	scantext = replaceAll(scantext, "  ", " ");
	if (scantext.indexOf(" ") == 0) {
		scantext = scantext.substring(1,scantext.length)	
	}
	doaction = (scantext.length > 0) ? "scan" : "";
	win = submitPopup("scanpopupnoselect.html", doaction, ["scan_code", "lfo", "scan_text", scantext, "destformname", form.name, "destfieldname", destfieldname], "scan", "", "height=600,width=700");
	win.focus();
}

function openCheckedSubjectPopup(form, destfieldname) {
	list = form.elements[destfieldname].value.split(",");
	scan_text = list[list.length-1].replace("\"", "").replace("\"", "");
	scantext = replaceAll(scan_text, "  ", " ");
	if (scantext.indexOf(" ") == 0) {
		scantext = scantext.substring(1,scantext.length)	
	}
	doaction = (scantext.length > 0) ? "scan" : "";
	win = submitPopup("scanpopupnoselect.html", doaction, ["scan_code", "lem", "scan_text", scantext, "destformname", form.name, "destfieldname", destfieldname], "scan", "", "height=600,width=700");
	win.focus();
}

function CatalogCreateShowAuthorButton_function(form) {
	openCheckedAuthorPopup(form, "cati_author-surname", "cati_author-forename");
}
function CatalogCreateShowSubjectButton_function(form) {
	openCheckedSubjectPopup(form, "cati_checked-subject"); 
}
function CatalogCreateShowUncheckedSubjectButton_function(form) {
	openScanPopup("lem", form, "cati_unchecked-subject", true); 
}
function CatalogUpdateShowAuthorButton_function(form) {
	openCheckedAuthorPopup(form, "catu_author-surname", "catu_author-forename");
}
function CatalogUpdateShowSubjectButton_function(form) {
	openCheckedSubjectPopup(form, "catu_checked-subject"); 
}
function CatalogDeleteButton_function(form) {
	if (countSelected(form)== 1) {
		win = submitPopup("catalog.html", "delete", "", "catalog", "", "height=300,width=600");
		win.focus();
		return;
	}
	if (countSelected(form)< 1) {
		win = submitPopup("emptySelection.html", "", "", "", "", "height=150,width=400");		
		win.focus();
		return;
	}
	if (countSelected(form)> 1) {
		win = submitPopup("tooManySelected.html", "", "", "", "", "height=150,width=400");		
		win.focus();
		return;
	}
}
// --------------------------------------------------------------------------------------------------------
// Holding buttons
// --------------------------------------------------------------------------------------------------------
function HoldingShowAdvancedButton_function(form) {
	submit('', '', ['advanced', 'true']);
}
function HoldingShowSimpleButton_function(form) {
	submit('', '', ['advanced', '']);
}
function HoldingSearchButton_function(form) {
	submit('', 'search', ['advanced', '']);
}
function HoldingUpdateButton_function(form) {
	submit('holdingupdate.html','update','');
}
function HoldingQuickUpdateButton_function(form) {
	submit('holdingquickupdate.html','update','');
}
function HoldingMassUpdateButton_function(form) {
	submit('holdingmassupdate.html','update','');
}
function HoldingCreateButton_function(form) {
	submit('holdinginsert.html','insert','');
}
function HoldingDiscardButton_function(form) {
	submit('holdingdiscard.html','discard','');
}
function HoldingFindButton_function(form) {
//	keyno = form.holi_keyno.value;
	submit('holdinginsert.html', 'lookup_from_insert',  '');
}
function HoldingClearButton_function(form) {
	if ( form != document ) {
		doClear(form);
	} else {
		doClear(document.holdingsearchForm);
	}
}
function HoldingResetButton_function(form) {
	if ( form != document ) {
		form.reset();
	} else {
		document.holdingsearchForm.reset();
	}
}
function HoldingCloseButton_function(form) {
	close();
}
function HoldingCancelButton_function(form) {
	close();
}
function HoldingHistorySearchButton_function(form) {
	submit("holdinghistory.html", "search", null);
}
function HoldingHistoryDiscardButton_function(form) {
	submit("holdinghistory.html", "discard", null);
}
function HoldingShowCreateButton_function(form) {
	if (countSelected(form)>1) {
		win = submitPopup("tooManySelected.html", "", "", "", "", "height=150,width=400");		
		win.focus();
		return;
	}
	if (countSelected(form)==1 && form.name!='holdingsearchresultForm') {
		win = submitPopup("holdinginsert.html", "lookup", "", "holding", "", "max");
		win.focus();
	} else {
		win = submitPopup("holdinginsert.html", "", null, "holding", "", "max");
		win.focus();
	}
}
function HoldingShowCopyCreateButton_function(form) {
	if ( form != document ) {
		var copyno = "";
		if (form.name == 'holdingupdateForm') {
			copyno = form.holu_copyno.value;
			submit("holdinginsert.html", "search_from_update", "");
		} else {
			if (countSelected(form)==1) {
				win = submitPopup("holdinginsert.html", "search", "", "holding", "", "max");
				win.focus();
			}
			if (countSelected(form)< 1) {
				win = submitPopup("emptySelection.html", "", "", "", "", "height=150,width=400");		
				win.focus();
				return;
			}
			if (countSelected(form)> 1) {
				win = submitPopup("tooManySelected.html", "", "", "", "", "height=150,width=400");		
				win.focus();
				return;
			}
		}
	}
}

function HoldingMenuShowCopyCreateButton_function(form) {
	HoldingShowCopyCreateButton_function(form);
}

function HoldingShowQuickUpdateButton_function(form) {
	win = submitPopup("holdingquickupdate.html", "", "", "holding", "", "max");
	win.focus();
}

function HoldingShowMassUpdateButton_function(form) {
	if (countSelected(form) == 0) {
		win = submitPopup("emptySelection.html", "", "", "", "", "height=150,width=400");		
		win.focus();
	} else {
		win = submitPopup("holdingmassupdate.html", "search", "", "holding", "", "max");
		win.focus();
	}
}

function HoldingPrintBarcodeButton_function(form) {
	if (countSelected(form) == 0) {
		win = submitPopup("emptySelection.html", "", "", "", "", "height=150,width=400");		
		win.focus();
	} else {
		win = submitPopup("holding.html", "print-barcode", null, "print_barcode", "", "height=600,width=600");
		win.focus();
	}
}

function HoldingShowDiscardButton_function(form) {
	win = open("holdingdiscard.html", "holdingdiscard", "status=yes,scrollbars=yes,resizable=yes,height=350,width=700");
	win.focus();
}

function HoldingDoDiscardButton_function(form) {
	if (countSelected(form) > 0) {
		if (doConfirm(form, "confirmdiscard")) {
			submit("holding.html", "discard", "");	
		}
	} else {
		win = submitPopup("emptySelection.html", "", "", "", "", "height=150,width=400");
		win.focus();
	}
}

function HoldingShowHistoryButton_function(form) {
	win = submitPopup("holdinghistory.html", "", null, "holdinghistory", "status=yes,scrollbars=yes,resizable=yes,height=700,width=700");
	win.focus();
}

function HoldingShowSearchOnShelfButton_function(form) {
	win = submitPopup("holdinghistory.html", "", null, "holdinghistory", "status=yes,scrollbars=yes,resizable=yes,height=700,width=700");
	win.focus();
}
function HoldingShowSearchOnShelfButton_function(form) {
	submit("holding.html", "search-on-shelf", null);
}

function HoldingShowListButton_function(form) {
	win = open("holdinglist.html", "holdinglist", "status=yes,scrollbars=yes,resizable=yes,height=350,width=700");
	win.focus(); 
}

function HoldingShowHoldingButton_function(form) {
	if (countSelected(form) > 0) {
		submit("holding.html", 'search',  "");	
	} else {
		win = submitPopup("emptySelection.html", "", "", "", "", "height=150,width=400");		
		win.focus();
	}
}

function HoldingShowUpdateButton_function(form) {
	if (countSelected(form)== 1) {
		win = submitPopup("holdingupdate.html", "search", "", "holding", "", "max");
		win.focus();
		return;
	}
	if (countSelected(form)< 1) {
		win = submitPopup("emptySelection.html", "", "", "", "", "height=150,width=400");				
		win.focus();
		return;
	}
	if (countSelected(form)> 1) {
		win = submitPopup("tooManySelected.html", "", "", "", "", "height=150,width=400");		
		win.focus();
		return;
	}
}
function HoldingPrintHoldingButton_function(form) {
	if (countSelected(form)>= 1) {
		submit("holding.html","print","");
		return;
	}
	if (countSelected(form)< 1) {
		win = submitPopup("emptySelection.html", "", "", "", "", "height=150,width=400");		
		win.focus();
		return;
	}
}
function HoldingShowSearchAllResButton_function(form) {
	submit("holding.html", "search-all-res", null);
}
function HoldingShowSearchOnShelfResButton_function(form) {
	submit("holding.html", "search-on-shelf-res", null);
}
function HoldingResPrintButton_function(form) {
	printWindow(window, "false");
}

// --------------------------------------------------------------------------------------------------------
// MatStat buttons
// --------------------------------------------------------------------------------------------------------
function MatStatShowButton_function(form) {
	win = submitPopup("matstat.html", "search", "", "matstat", "", "height=600,width=600");
	win.focus();
}
function MatStatCloseButton_function(form) {
	close();
}
function MatStatPrintButton_function(form) {
	printWindow(window, "false");
}

// --------------------------------------------------------------------------------------------------------
// Booking buttons
// --------------------------------------------------------------------------------------------------------
function BookingSearchButton_function(form) {
	submit('', 'search', ['advanced', '']);
}

function BookingClearButton_function(form) {
	doClear(form);
}

function BookingResetButton_function(form) {
	form.reset();
}

function BookingShowPeriodButton_function(form) {
	win = submitPopup("bookingcalendar.html", "search","", "period", "", "max");
	win.focus();
}

function BookingCancelButton_function(form) {
	close();
}

function BookingCreateButton_function(form) {
	submit('bookinginsert.html','insert','');
}

function BookingUpdateButton_function(form) {
	submit('bookingupdate.html','update','');
}

function BookingSelectAllButton_function(form) {
	selectAll(form);
}

function BookingDeselectAllButton_function(form) {
	deselectAll(form);
}

function BookingFindButton_function(form) {
	submit('bookinginsert.html', 'lookup_from_insert',  '');
}
function BookingShowAdvancedButton_function(form) {
	submit('', '', ['advanced', 'true']);
}

function BookingShowSimpleButton_function(form) {
	submit('', '', ['advanced', '']);
}

function BookingSearchMyBookingsButton_function(form) {
	submit("booking.html", "search-my-bookings", "");
}

function BookingShowCreateButton_function(form) {
	with (new Date()) ddate = String(getDate() + "." + (getMonth()+1)+ "." +getFullYear());
	if (countSelected(form)< 1) {
		win = submitPopup("bookinginsert.html", "", ["boor_bookdatefrom", ddate], "booking", "", "max");
		win.focus();
	}else{
		win = submitPopup("bookinginsert.html", "lookup", ["boor_bookdatefrom", ddate], "booking", "", "max");
		win.focus();
	}
}

function BookingShowUpdateButton_function(form) {
	if (countSelected(form)== 1) {
		win = submitPopup("bookingupdate.html","","", "Update", "", "max");
		win.focus();
		return;
	}
	if (countSelected(form)< 1) {
		win = submitPopup("emptySelection.html", "", "", "", "", "height=150,width=400");
		win.focus();
		return;
	}
	if (countSelected(form)> 1) {
		win = submitPopup("tooManySelected.html", "", "", "", "", "height=150,width=400");		
		win.focus();
		return;
	}
}

//This function accessed by search page, using keyno value
function BookingShowBookingButton_function(form) {
	if (countSelected(form)>= 1) {
		submit("booking.html", "keyno-search", "");
	}
	if (countSelected(form)< 1) {
		win = submitPopup("emptySelection.html", "", "", "", "", "height=150,width=400");		
		win.focus();
		return;
	}
}

function BookingDeleteSelectedButton_function(form) {
	if (countSelected(form)< 1) {
		win = submitPopup("emptySelection.html", "", "", "", "", "height=150,width=400");		
		win.focus();
		return;
	}
	submit('','booking-delete','');
}

function BookingListSelectedButton_function(form) {
	printWindow(this, false);
}

function BookingDeliveryNotesButton_function(form) {
	if (countSelected(form)< 1) {
		win = submitPopup("emptySelection.html", "", "", "", "", "height=150,width=400");		
		win.focus();
		return;
	}
	win = submitPopup("bookingdeliverynotes.html", "print-booking-delivery", null, "", "", "height=550,width=700");
	win.focus();
}

function BookingRecallSelectedButton_function(form) {
	if (countSelected(form)< 1) {
		win = submitPopup("emptySelection.html", "", "", "", "", "height=150,width=400");		
		win.focus();
		return;
	}
	win = submitPopup("booking.html", "print-recall", null, "Patronstatus", "", "height=400,width=750");
	win.focus();
}

function BookingCheckoutToSelectedButton_function(form) {
	if (countSelected(form) == 0) {
		win = submitPopup("emptySelection.html", "", null, "info", "", "height=150,width=400");
		win.focus();
	} else if (countSelected(form) > 1) {
		win = submitPopup("tooManySelected.html", "", "", "", "", "height=150,width=400");		
		win.focus();
	} else {
		submit("classcheckout.html", "search-bookingno", null);
	}
}

function BookingRenewSelectedButton_function(form) {
	if (countSelected(form) == 0) {
		win = submitPopup("emptySelection.html", "", null, "info", "", "height=150,width=400");
		win.focus();
	} else if (countSelected(form) > 1) {
		win = submitPopup("tooManySelected.html", "", "", "", "", "height=150,width=400");		
		win.focus();
	} else {
		win = submitPopup("classrenew.html", "renew-from-booking", null, "Classrenew", "height=400,width=750");
	}
}

// Transfers values of the 2 fields bookdatefrom & bookdateto to either openers.
function BookingTransferPeriodButton_function(form) {
	if (form.boor_bookdateto.value=="" || form.bookdatefrom.value=="") {
		setFocus();
	} else {
		if (opener.document.forms["bookingupdateForm"]) {
			opener.document.forms["bookingupdateForm"].boor_bookdateto.value = form.boor_bookdateto.value;
			opener.document.forms["bookingupdateForm"].boor_bookdatefrom.value = form.bookdatefrom.value;
		} else {
			opener.document.forms["bookinginsertForm"].boor_bookdateto.value = form.boor_bookdateto.value;
			opener.document.forms["bookinginsertForm"].boor_bookdatefrom.value = form.bookdatefrom.value;
		}
		close();
	}
}
function BookingClearPeriodButton_function(form) {
	doClear(form);
}

function BookingResetPeriodButton_function(form) {
	form.reset();
}

function BookingPrintButton_function(form) {
	if (document.getElementById("WorkingText")) {
		document.getElementById("WorkingText").style.visibility="visible";
	}
	submit('bookinglist.html','print',"");
}

function sortBooking(column, order) {
	document.submitForm.data.value = "";
	addForm(document.submitForm.data, document.bookingSearchData);
	addData = false;
	submit("booking.html", "sort", ["sortcolumn", column, "sortorder", order]);
}

var oldBookingCancelButton_function = null;

function updateBookingCalendar(direction, fromdate) {
	var bc = document.getElementById("WorkingText");
	if (bc == null) {
		return;
	}
	if (oldBookingCancelButton_function == null) {
		oldBookingCancelButton_function = BookingCancelButton_function;
		BookingCancelButton_function = function() {
			// disable button.
		}
	}
	if (bc != null) {
		bc.style.visibility = "";
	}
	var params = [];
	if (direction != null) {
		params.push("direction");
		params.push(direction);
	}
	if (fromdate != null) {
		params.push("hiddenbookdatefrom");
		params.push(fromdate);
	}
	var f = null;
	if (bc != null) {
		f = function() {
			bc.style.visibility = "hidden";
			if (oldBookingCancelButton_function != null) {
				BookingCancelButton_function = oldBookingCancelButton_function;
				oldBookingCancelButton_function = null;
			}
		};
	}
	updateElement("bookingcalendar", "lookup.html", "bookingcalendar", params, true, f);
}

var bCalendarForm = null;	// to be initialized by the lsp
var lastBookingDateField = null;

// input id = celle nummer, isodate = ISO dato format (20031224)
function bCalendarSetDate(id, isodate, isFromDate){
	var d, s, y, m;
	d =  parseInt(isodate.substring(6,8),10);
	m = parseInt(isodate.substring(4,6),10);
	y =  parseInt(isodate.substring(0,4),10);
	id = parseInt(id,10);
	//javascriopt date operer er med month 0 -11
	var ddate =  new Date(y,m-1,d);
	ddate.setDate(ddate.getDate() + id);
	//formater til (24.12.2003)
	s = ddate.getDate() + "." + (ddate.getMonth()+1) + "." + ddate.getFullYear();
	if (isFromDate) {
		bCalendarForm.boor_bookdatefrom.value=s;
		bCalendarForm.boor_bookdateto.focus();
	} else {
		bCalendarForm.boor_bookdateto.value=s;
		bCalendarForm.boor_bookdatefrom.focus();
	}
	return s;
}

function bCalendarDoClick(event, id, isodate) {
	if (bCalendarForm.boor_bookdatefrom.disabled) {
		lastBookingDateField = null;
		return;
	}
	var isFromDate = true;
	isFromDate = (lastBookingDateField != "bookdateto");
	bCalendarSetDate(id, isodate, isFromDate);
}

function BookingPeriodForwardButton_function(form){
	submit("", "search", ['direction','forward']);
}

function BookingPeriodBackButton_function(form){
	submit("", "search", ['direction','back']);
}

// --------------------------------------------------------------------------------------------------------
// Patronstatus buttons
// --------------------------------------------------------------------------------------------------------

function InfoShowSchoolbagsCheckbox_function(form) {
	setTimeout(function(){_InfoShowSchoolbagsCheckbox(form)}, 0);
}

function _InfoShowSchoolbagsCheckbox(form) {
	submit('','','');
}

function InfoRenewSelectedButton_function(form) {
	submit('','loan-renew','');
}

function InfoRenewAllButton_function(form) {
	selectAll(form);
	submit('','loan-renew','');
}

function InfoRenewSelectedSchoolBagButton_function(form) {
	submit('','schoolbag-renew','');
}

function InfoRenewAllSchoolBagButton_function(form) {
	selectAll(form);
	submit('','schoolbag-renew','');
}

function InfoResUpdateButton_function(form) {
	submit('','resres-update','');
}

function InfoReqUpdateButton_function(form) {
	submit('','resreq-update','');
}

function InfoResCancelButton_function(form) {
	submit('','res-cancel','');
}

function InfoResDeleteButton_function(form) {
	submit('','resres-delete','');
}

function InfoIntloanDeleteButton_function(form) {
	submit('','intloan-delete','');
}

function InfoIntloanFullfillCancelButton_function(form) {
	submit('','intloanfullfill-cancel','');
}

function InfoIntloanFullfillDeskCancelButton_function(form) {
	submit('','intloanfullfilldesk-cancel','');
}

function InfoReqDeleteButton_function(form) {
	submit('','resreq-delete','');
}

function InfoAccountPayButton_function(form) {
	if (countSelected(form) < 1) {
		win = submitPopup("emptySelection.html", "", "", "", "", "height=150,width=400");		
		win.focus();
		return;
	}
	win = submitPopup("patronstatus.html", "account-prepare-pay", null, "Pay", "", "height=650,width=650");
	win.focus();
}

function PreparePaymentCreateButton_function(form) {
	if (document.getElementById("WorkingText")) {
		document.getElementById("WorkingText").style.visibility="visible";
	}
	submit('patronstatus.html','account-begin-pay', null);
}
function PreparePaymentClearButton_function(form) {
	doClear(form);
}

function PreparePaymentCancelButton_function(form) {
	close();
}

function PrepareLIBPaymentClearButton_function(form) {
	doClear(form);
}

function PrepareLIBPaymentCancelButton_function(form) {
	close();
}

function RetryPaymentOkButton_function(form) {
	submit('patronstatus.html', 'retry-pay', null);
}

function RetryPaymentCancelButton_function(form) {
	close();
}

function SchoolInfoSubmitButton_function(form) {
	submit("", "patron-logout", ["dest", "patronstatus.html"]);
}

// --------------------------------------------------------------------------------------------------------
// Patronadmin buttons
// --------------------------------------------------------------------------------------------------------
function PatronSearchButton_function(form) {
	submit('patronadmin.html', 'search', ['advanced', '']);
}

function PatronResetButton_function(form) {
	form.reset();
}

function PatronSelectAllButton_function(form) {
	selectAll(form);
}

function PatronDeselectAllButton_function(form) {
	deselectAll(form);
}

function PatronClearButton_function(form) {
	doClear(form);
}

function PatronShowAdvancedButton_function(form) {
	submit('', '', ['advanced', 'true']);
}

function PatronShowSimpleButton_function(form) {
	submit('', '', ['advanced', '']);
}

function PatronShowCreateButton_function(form) {				
	win = submitPopup("patroninsert.html", "", null, "Patron", "", "max");
	win.focus();
}

function PatronCreateButton_function(form) {
	submit('patroninsert.html','insert','');
}

function PatronUpdateButton_function(form) {
	$("#patron_teams option").attr("selected", "true");
	submit('patronupdate.html','update','');
}

function PatronShowUpdateButton_function(form) {
	if (countSelected(form)== 1) {
		win = submitPopup("patronupdate.html","update-button","", "Update", "", "max");
		win.focus();
		return;
	}
	if (countSelected(form)< 1) {
		win = submitPopup("emptySelection.html", "", "", "", "", "height=150,width=400");		
		win.focus();
		return;
	}
	if (countSelected(form)> 1) {
		win = submitPopup("tooManySelected.html", "", "", "", "", "height=150,width=400");		
		win.focus();
		return;
	}
}

function PatronDeleteSelectedButton_function(form) {
	if (countSelected(form)== 1) {
		if (doConfirm(form, "confirmdelete")) {
			submit("patronadmin.html", "patron-delete", ["advanced", ""]);
		}
	}
	if (countSelected(form)< 1) {
		win = submitPopup("emptySelection.html", "", "", "", "", "height=150,width=400");		
		win.focus();
		return;
	}
	if (countSelected(form)> 1) {
		win = submitPopup("tooManySelected.html", "", "", "", "", "height=150,width=400");		
		win.focus();
		return;
	}
}

function PatronMenuShowCopyCreateButton_function(form) {
	PatronShowCopyCreateButton_function(form);
}

function PatronShowCopyCreateButton_function(form) {
	$("#patron_teams option").attr("selected", "true");
	if (form != document) {
		if (form.name == 'patronupdateForm') {
			submit("patroninsert.html", "search_from_update", "");
		} else {
			if (countSelected(form) == 1) {
				win = submitPopup("patroninsert.html", "search", "", "patron", "", "max");
				win.focus();
			} else if (countSelected(form) < 1) {
				win = submitPopup("emptySelection.html", "", "", "", "", "height=150,width=400");
				win.focus();
			} else if (countSelected(form) > 1) {
				win = submitPopup("tooManySelected.html", "", "", "", "", "height=150,width=400");
				win.focus();
			}
		}
	}
}

var select_list = "";

function PatronStatusSelectedButton_function(form) {
	if (countSelected(form)< 1) {
		win = submitPopup("emptySelection.html", "", "", "", "", "height=150,width=400");		
		win.focus();
		return;
	}
	if ( form != document ) {
		select_list = "";
		var i;
		for (i = 0; i < form.elements.length; i++) {
			if (form.elements[i].type == "checkbox") {
				if (form.elements[i].checked) {
					if (select_list.length > 0) {
						select_list += ",";
					}
					tickno = form.elements[i].name;
					lngPos = tickno.lastIndexOf(':');//find last occurence of char ':', thaz wear de num starz
					real_tickno = tickno.substring(lngPos + 1, tickno.length);
					select_list += real_tickno;
				}
			}
		}
	}
 	if ( select_list != "" ) {
		win = submitPopup("patronstatusmass.html", "", ["patm_tickno",select_list], "Patronstatus", "", "height=400,width=750");
		win.focus();
	}
}

function PatronShowPrintRecallButton_function(form) {
	win = submitPopup("patronadmin.html", "show-printrecall", null, "Patronstatus", "", "height=500,width=750");
	win.focus();
}

function PatronListSelectedButton_function(form) {
	if (countSelected(form) == 0) {
		win = submitPopup("emptySelection.html", "", null, "info", "", "height=150,width=400");
		win.focus();
	} else {
		win = submitPopup("patronclasslist.html", "print-patron-list", null, "CL", "", "max");
		win.focus();
	}
}

function PatronStatusScreenButton_function(form) {
	if (countSelected(form) == 1) {
		win = submitPopup("patronadmin.html", "show-patronstatus", null, "info", "", "max");
		win.focus();
	} else if (countSelected(form) < 1) {
		win = submitPopup("emptySelection.html", "", null, "info", "", "height=150,width=400");
		win.focus();
	} else if (countSelected(form) > 1) {
		win = submitPopup("tooManySelected.html", "", null, "info", "", "height=150,width=400");
		win.focus();
	}
}

function PatronCancelButton_function(form) {
	close();
}

function PatronPrintButton_function(form) {
	var patm_tickno = form.patm_tickno.value;
	if (document.getElementById("WorkingText")) {
		document.getElementById("WorkingText").style.visibility="visible";
	}
	submit('patronstatusmass.html','print','');
}

function PatronCloseButton_function(form) {
	close();
}

function PatronPrintRecallPrintButton_function(form) {
	if (document.getElementById("WorkingText")) {
		document.getElementById("WorkingText").style.visibility="visible";
	}
	submit("patronadmin.html", "printrecall", null);
}

function PatronPrintRecallCloseButton_function(form) {
	close();
}

function UniLoginUploadButton_function(form) {
	if (document.getElementById("WorkingText")) {
		document.getElementById("WorkingText").style.visibility="visible";
	}
	form.submit();
}

function CheckoutToSelectedButton_function(form) {
	if (countSelected(form) == 0) {
		win = submitPopup("emptySelection.html", "", null, "info", "", "height=150,width=400");
		win.focus();
	} else {
		submit("classcheckout.html", "search", null);
	}
}

function PatronSendSMSButton_function(form) {
	if (countSelected(form) == 0) {
		win = submitPopup("emptySelection.html", "", null, "info", "", "height=150,width=400");
		win.focus();
	} else {
		win = submitPopup("patronsendsms.html", "search-patron", null, "sendsms", "", "height=700,width=700");
		win.focus();
	}
}

function PatronSendSMSSendButton_function(form) {
	submit("patronsendsms.html", "send", null);
}

function PatronSendSMSCancelButton_function(form) {
	close();
}

function PatronUniLoginUploadButton_function(form) {
	submit("patronadmin_unilogin.html", "", null);
}

function openQuickPatron(ticknoField, pinField) {
	var win = open("quickpatron.html", "quickpatron", "scrollbars=yes,resizable=yes,height=600,width=600");
	win.focus();
	if (pinField) {
		selectPatron = function(tickno) {
			ticknoField.value = tickno;
			pinField.focus();
			win.close();
		};
	} else {
		selectPatron = function(tickno) {
			win.close();
			self.submit("", "patron-login", ["tickno", tickno]);
		};
	}
}

function QuickPatronSubmitButton_function(form) {
	submit("quickpatron.html", "search", null);
}

function QuickPatronClearButton_function(form) {
	doClear(form);
}

function QuickPatronCancelButton_function(form) {
	close();
}

function addTeam() {
	var l = $("select#patron_teams option").filter(function() {
		return this.selected;
	});
	if (l.size() > 0) {
		$("select#all_teams").append(l);
		$("select#all_teams option:last").get(0).scrollIntoView(false);
	}
}

function removeTeam() {
	var l = $("select#all_teams option").filter(function() {
		return this.selected;
	});
	if (l.size() > 0) {
		$("select#patron_teams").append(l);
		$("select#patron_teams option:last").get(0).scrollIntoView(false);
	}
}

// --------------------------------------------------------------------------------------------------------
// Team buttons
// --------------------------------------------------------------------------------------------------------

function TeamSearchButton_function(form) {
	submit("team.html", "search", ["advanced", ""]);
}

function TeamResetButton_function(form) {
	form.reset();
}

function TeamSelectAllButton_function(form) {
	selectAll(form);
}

function TeamDeselectAllButton_function(form) {
	deselectAll(form);
}

function TeamClearButton_function(form) {
	doClear(form);
}

function TeamCancelButton_function(form) {
	close();
}

function TeamShowAdvancedButton_function(form) {
	submit("", "", ["advanced", "true"]);
}

function TeamShowSimpleButton_function(form) {
	submit("", "", ["advanced", ""]);
}

function TeamShowCreateButton_function(form) {
	win = submitPopup("teaminsert.html", "", null, "Team", "", "height=650,width=650");
	win.focus();
}

function TeamShowUpdateMembersButton_function(form) {
	if (countSelected(form) > 0) {
		win = submitPopup("teamupdate.html", "show-update-members", null, "Team", "", "height=650,width=650");
		win.focus();
	} else {
		win = submitPopup("emptySelection.html", "", "", "", "", "height=150,width=400");		
		win.focus();
	}
}

function TeamShowUpdateButton_function(form) {
	if (countSelected(form) == 1) {
		win = submitPopup("teamupdate.html", "search", null, "Team", "", "height=650,width=650");
		win.focus();
	} else if (countSelected(form) == 0) {
		win = submitPopup("emptySelection.html", "", "", "", "", "height=150,width=400");		
		win.focus();
	} else {
		win = submitPopup("tooManySelected.html", "", "", "", "", "height=150,width=400");
		win.focus();
	}
}

function TeamInsertButton_function(form) {
	submit("teaminsert.html", "insert", null);
}

function TeamUpdateButton_function(form) {
	submit("teamupdate.html", "update", null);
}

function TeamUpdateMembersButton_function(form) {
	submit("teamupdate.html", "update-members", null);
}

function TeamDeleteSelectedButton_function(form) {
	if (countSelected(form) == 0) {
		win = submitPopup("emptySelection.html", "", "", "", "", "height=150,width=400");		
		win.focus();
	} else {
		submit("team.html", "delete", null);
	}
}

function openTeamUpdate(teamid) {
	win = submitPopup("teamupdate.html", "search_link", ["teamsl_teamid", teamid], "Team", "", "height=650,width=650");
	win.focus();
}

function searchTeam(teamid) {
	submitData("team.html", "search", ["teams_teamid", teamid], opener, opener);
	close();
}

// --------------------------------------------------------------------------------------------------------
// PatronSelfCreate buttons
// --------------------------------------------------------------------------------------------------------
function PatronSelfCreateInsertButton_function(form) {
	if (checkConfirm(form, "confirminsert")) {
		if (form.psci_NemLogin && form.psci_NemLogin.value == "YES") {
			submit("patronselfcreateinsert.html", "nemlogin", ["selfcreate", "1", "insert", "1", "DigitalSignatur", "NO", "NemLogin", "YES"]);
		} else {
			var digitalsignatur =  form.psci_DigitalSignatur.value;
			submit('patronselfcreateinsert.html','insert',['DigitalSignatur',digitalsignatur]);
		}
	}
}

function PatronSelfCreateContinueButton_function(form) {	
	if (form.nemlogin) {
		self.location.href = "?doaction=nemlogin&data=selfcreate%3d1%20NemLogin%3dYES%20DigitalSignatur%3dNO";
	} else if (checkConfirm(form, "confirminsert")) {
		submit('patronselfcreateinsert.html','',['DigitalSignatur','YES','continue','YES']);
	}
}

function PatronSelfCreateClearButton_function(form) {
	doClear(form);
}

function PatronSelfCreateCancelButton_function(form) {
	close();
}

function PatronSelfCreateResetButton_function(form) {
	form.reset();
}

// --------------------------------------------------------------------------------------------------------
// Reservation buttons
// --------------------------------------------------------------------------------------------------------
function ReservationCreateButton_function(form) {
	if (checkConfirm(form, "confirminsert")) {
		submit("", "res-reserve", null);
	}
}
function ReservationClearButton_function(form) {
	doClear(form);
}
function ReservationCancelButton_function(form) {
	close();
}
function ReservationLapsedButton_function(form) {
	submit("reservation_from_menu.html", "res-lapsed", null);
}
function ReservationExpiredButton_function(form) {
	submit("reservation_from_menu.html", "res-expired", null);
}
function ReservationListSearchButton_function(form) {
	submit("reservation_from_menu.html", "search", null);
}
function ReservationDeleteSelectedButton_function(form) {
	if (countSelected(form)>= 1) {
	  	submit("reservation_from_menu.html", "delete", null);
		return;
	}
	if (countSelected(form)< 1) {
		win = submitPopup("emptySelection.html", "", "", "", "", "height=150,width=400");		
		win.focus();
		return;
	}
}
function ReservationPrintButton_function(form) {
	printWindow(window, "false");
}
function ReservationSearchButton_function(form) {
	submit("reservation_from_menu.html", "search", null);
}
function ReservationShowSimpleButton_function(form) {
	submit("reservation_from_menu.html", "show-simple", null);
}
function ReservationShowAdvancedButton_function(form) {
	submit("reservation_from_menu.html", "show-advanced", null);
}


// --------------------------------------------------------------------------------------------------------
// Scan buttons
// --------------------------------------------------------------------------------------------------------
function ScanButton_function(form) {
	submit("", "scan", null);
}
function ScanCloseButton_function(form) {
	close();
}
function ScanResetButton_function(form) {
	submit("", "scan-reset", null);
}

function ScanShowNextPageButton_function(form) {
	submit("", "scan-navi", null);
}

function scan(term, fromCatalog) {
	if (fromCatalog) {
		term = term.toLowerCase();
	} else {
		term += "@";
	}
	destformname = document.scanresultForm.destformname.value;
	destfieldname = document.scanresultForm.destfieldname.value;
	destfield = opener.document.forms[destformname].elements[destfieldname];
	list = destfield.value.split(",");
	destfield.value = "";
	for (i = 0; i < list.length-1; i++) {
		destfield.value += list[i]+",";
	}
	if (fromCatalog) {
		if (term.indexOf(" ")==-1) { 
			destfield.value += term;
		} else {
			destfield.value += "\""+term+"\"";
		}
	} else {
		destfield.value += "\""+term+"\"";
	}
	opener.document.forms[destformname].elements[destfieldname].focus();
	close();
}

function scanSearch(term) {
	submit("search.html", "search", ["scode_ccl", document.scanresultForm.scanresult_code.value+"="+term]);
}

// --------------------------------------------------------------------------------------------------------
// Patron/Group login buttons
// --------------------------------------------------------------------------------------------------------

function LoginLoginButton_function(form) {
	submit("", "patron-login", null);
}

function QuickLoginButton_function(form) {
	submit("", "patron-login", null);
}

function QuickLogoutButton_function(form) {
	if (form.group.value == "pub") {
		submit("search.html", "patron-logout", null);
	} else {
		submit("", "patron-logout", null);
	}
}

function LoginCancelButton_function(form) {
	close();
}

function GroupLoginLoginButton_function(form) {
	submit("", "group-login", null);
}

// --------------------------------------------------------------------------------------------------------
// Settings buttons
// --------------------------------------------------------------------------------------------------------

function SettingsPatronUpdateButton_function(form) {
	submit("", "update", null);
}

function SettingsPatronResetButton_function(form) {
	form.reset();
}

function SettingsPatronCancelButton_function(form) {
	submit("", "", null);
}

function SettingsEditButton_function(form) {
	submit("", "edit", ["form", "patron"]);
}

function SettingsEditAbsentButton_function(form) {
	submit("", "edit", ["form", "absent"]);
}

function SettingsEditPincodeButton_function(form) {
	submit("", "edit", ["form", "pincode"]);
}

function SubscriptionConfirmInsertButton_function(form) {
	submit("", "insert-subscription", null);
}

function SubscriptionConfirmCancelButton_function(form) {
	submit("", "", null);
}

// --------------------------------------------------------------------------------------------------------
// Preference buttons
// --------------------------------------------------------------------------------------------------------

function PreferenceUpdateButton_function(form) {
	submit("", "update", null);
}

function PreferenceResetButton_function(form) {
	form.reset();
}

// --------------------------------------------------------------------------------------------------------
// Lists buttons
// --------------------------------------------------------------------------------------------------------

function showList(listno) {
	submit("search.html", "search-on-listno", ["listno", listno]);
}

// --------------------------------------------------------------------------------------------------------
// Material selection buttons
// --------------------------------------------------------------------------------------------------------

function MSOpenOneList(listno) {
	submit("ms.html", "show-list", ["mslistno", listno]);
}

function MSOpenOneRecord(listno, keyno, pos, count) {
	if ($("#mslist").attr("sorted")) {
		var row = $("#row"+keyno).get(0);
		pos = row.rowIndex-1;
		count = parseInt(document.mslistform.reccount.value);
		win = submitPopup("ms.html", "show-record", ["mslistno", listno, "keyno", keyno, "pos", pos, "count", count, "usekeyno", "1"], "ms" + listno + keyno, "", "max");
		win.focus();
	} else {
		win = submitPopup("ms.html", "show-record", ["mslistno", listno, "keyno", keyno, "pos", pos, "count", count], "ms" + listno + keyno, "", "max");
		win.focus();
	}
}

function MSUpdateButton_function(form) {
	submit('ms.html','update','');
}

function MSCancelButton_function(form) {
	close();
}

function MSShowBudgetBalanceButton_function(form) {
	win = submitPopup("ms.html", "show-budgetbalance", null, "budgetbalance", "", "max");
	win.focus();
}

function MSShowOrderedButton_function(form) {
	win = submitPopup("ms.html", "show-ordered", null, "ordered", "", "max");
	win.focus();
}

function MSShowPrevRecordButton_function(form) {
	var pos = parseInt(form.pos.value);
	pos--;
	if (form.usekeyno.value == "1") {
		var id = $("#mslist tbody tr:nth-child("+(pos+1)+")", opener.document).attr("id");
		if (id) {
			var keyno = id.substring(3);
			submit("ms.html", "show-record-at-pos", ["pos", pos, "keyno", keyno]);
		}
	} else {
		submit("ms.html", "show-record-at-pos", ["pos", pos]);
	}
}

function MSShowNextRecordButton_function(form) {
	var pos = parseInt(form.pos.value);
	pos++;
	if (form.usekeyno.value == "1") {
		var id = $("#mslist tbody tr:nth-child("+(pos+1)+")", opener.document).attr("id");
		if (id) {
			var keyno = id.substring(3);
			submit("ms.html", "show-record-at-pos", ["pos", pos, "keyno", keyno]);
		}
	} else {
		submit("ms.html", "show-record-at-pos", ["pos", pos]);
	}
}

function MSOrderSelectedButton_function(form) {
	if (countSelected(form) == 1) {
		win = submitPopup("ms.html", "order-selected", null, "orderselected", "", "max");
		win.focus();
	} else if (countSelected(form) == 0) {
		win = submitPopup("emptySelection.html", "", "", "", "", "height=150,width=400");		
		win.focus();
	} else {
		win = submitPopup("tooManySelected.html", "", "", "", "", "height=150,width=400");
		win.focus();
	}
}

function orderReference(keyno) {
	win = submitPopup("ms.html", "order", ["keyno", keyno], "orderselected", "", "max");
	win.focus();
}

// --------------------------------------------------------------------------------------------------------
// Checkin/checkout buttons
// --------------------------------------------------------------------------------------------------------

function CheckinSubmitButton_function(form) {
	if (document.getElementById("WorkingText")) {
		document.getElementById("WorkingText").style.visibility="visible";
	}
	form.checkin_copyno.disabled=true;
	submit("", "checkin", null);
}

function CheckinClearPatronButton_function(form) {
	doClear(form);
}

function CheckinReceiptButton_function(form) {
	if (document.getElementById("WorkingText")) {
		document.getElementById("WorkingText").style.visibility="visible";
	}
	submit("", "checkin-receipt", null);
}

function CheckinQuickPatronButton_function(form) {
	openQuickPatron(form.checkin_copyno, form.checkin_pin);
}

function MassCheckinSubmitButton_function(form) {
	submit("", "checkin", null);
}

function MassCheckinClearButton_function(form) {
	doClear(form);
}

function CheckoutSubmitButton_function(form) {
	if (document.getElementById("WorkingText")) {
		document.getElementById("WorkingText").style.visibility="visible";
	}
	form.checkout_tickno.disabled=true;
	if (form.checkout_pin) {
		form.checkout_pin.disabled=true;
	}
	submit("", "checkout", null);
}

function CheckoutClearPatronButton_function(form) {
	doClear(form);
}

function CheckoutReceiptButton_function(form) {
	if (document.getElementById("WorkingText")) {
		document.getElementById("WorkingText").style.visibility="visible";
	}
	submit("", "checkout-receipt", null);
}

function CheckoutQuickPatronButton_function(form) {
	openQuickPatron(form.checkout_tickno, form.checkout_pin);
}

function MassCheckoutSubmitButton_function(form) {
	submit("", "checkout", null);
}

function MassCheckoutClearButton_function(form) {
	doClear(form);
}

function ClassCheckoutSubmitButton_function(form) {
	submit("", "checkout", null);
}

function ClassCheckoutClearButton_function(form) {
	doClear(form);
}

function ClassCheckoutReceiptButton_function(form) {
	printWindow(this, false);
}

function RenewSubmitButton_function(form) {
	if (document.getElementById("WorkingText")) {
		document.getElementById("WorkingText").style.visibility="visible";
	}
	form.renew_copyno.disabled=true;
	submit("", "renew", null);
}

function AdvancedCheckoutSubmitButton_function(form) {
	submit("", "checkout", null);
}

function AdvancedCheckoutClearButton_function(form) {
	doClear(form);
	submit("", "clear-loansession", null);
}

function AdvancedCheckoutQuickPatronButton_function(form) {
	openQuickPatron(form.checkout_tickno, form.checkout_pin);
}

// --------------------------------------------------------------------------------------------------------
// Menu buttons
// --------------------------------------------------------------------------------------------------------

function MenuSimpleSearchButton_function(form) {
	submit("search.html", "blank", null);
}

function MenuListsButton_function(form) {
	submit("lists.html", "", null);
}

function MenuMSButton_function(form) {
	submit("ms.html", "", null);
}

function SetupSaveButton_function(form) {
	submit("setup.html", "save", null);
}

function SetupResetButton_function(form) {
	form.reset();
}

function MenuPublishButton_function(form) {
	submit("publish.html", "", null);
}

function MenuPublishCreatePlanButton_function(form) {
	win = submitPopup("publish.html", "open-insert-plan", null, "publish", "", "height=600,width=800");
	win.focus();
}

function MenuPublishUpdatePlanButton_function(form) {
	var count = $("input[name^=search_planno:][checked]").size();
	if (count == 1) {
		win = submitPopup("publish.html", "open-selected-plan", null, "publish", "", "height=600,width=800");
		win.focus();
	} else if (count == 0) {
		win = submitPopup("emptySelection.html", "", "", "publish", "", "height=150,width=400");		
		win.focus();
	} else {
		win = submitPopup("tooManySelected.html", "", "", "publish", "", "height=150,width=400");
		win.focus();
	}
}

function MenuPublishDeletePlanButton_function(form) {
	var count = $("input[name^=search_planno:][checked]").size();
	if (count > 0) {
		if (confirm(gst(form, "ST_confirmdeleteplan"))) {
			win = submit("publish.html", "delete-plan", null);
			win.focus();
		}
	} else if (count == 0) {
		win = submitPopup("emptySelection.html", "", "", "publish", "", "height=150,width=400");		
		win.focus();
	}
}

function MenuPublishCreateListButton_function(form) {
	var count = $("input[name^=search_planno:][checked]").size();
	if (count == 1) {
		win = submitPopup("publish.html", "open-insert-list", null, "publish", "", "height=600,width=800");
		win.focus();
	} else if (count == 0) {
		win = submitPopup("emptySelection.html", "", "", "publish", "", "height=150,width=400");		
		win.focus();
	} else {
		win = submitPopup("tooManySelected.html", "", "", "publish", "", "height=150,width=400");
		win.focus();
	}
}

function MenuPublishUpdateListButton_function(form) {
	var count = $("input[name^=search_listno:][checked]").size();
	if (count == 1) {
		win = submitPopup("publish.html", "open-selected-list", null, "publish", "", "height=600,width=800");
		win.focus();
	} else if (count == 0) {
		win = submitPopup("emptySelection.html", "", "", "publish", "", "height=150,width=400");		
		win.focus();
	} else {
		win = submitPopup("tooManySelected.html", "", "", "publish", "", "height=150,width=400");
		win.focus();
	}
}

function MenuPublishDeleteListButton_function(form) {
	var count = $("input[name^=search_listno:][checked]").size();
	if (count > 0) {
		if (confirm(gst(form, "ST_confirmdeletelist"))) {
			win = submit("publish.html", "delete-list", null);
			win.focus();
		}
	} else if (count == 0) {
		win = submitPopup("emptySelection.html", "", "", "publish", "", "height=150,width=400");		
		win.focus();
	}
}

function openPublishPlan(planno) {
	win = submitPopup("publish.html", "open-plan", ["planno", planno], "publish", "", "height=600,width=800");
	win.focus();
}

function openPublishList(planno, listno) {
	win = submitPopup("publish.html", "open-list", ["planno", planno, "listno", listno], "publish", "", "height=600,width=800");
	win.focus();
}

function PublishPlanUpdateButton_function(form) {
	submit("publish.html", "update-plan", null);
}

function PublishPlanCreateButton_function(form) {
	submit("publish.html", "insert-plan", null);
}

function PublishPlanResetButton_function(form) {
	form.reset();
}

function PublishPlanClearButton_function(form) {
	doClear(form);
}

function PublishPlanCancelButton_function(form) {
	close();
}

function PublishListUpdateButton_function(form) {
	submit("publish.html", "update-list", null);
}

function PublishListCreateButton_function(form) {
	submit("publish.html", "insert-list", null);
}

function PublishListResetButton_function(form) {
	form.reset();
}

function PublishListClearButton_function(form) {
	doClear(form);
}

function PublishListCancelButton_function(form) {
	close();
}

function PublishSelectListOkButton_function(form) {
	if (form.publishselectlist_planno.value == "") {
		alert(gst(form, "ST_PublishSelectPlanErrorText"));
	} else {
		submit("publish.html", "publish", null);
	}
}

function PublishSelectListCancelButton_function(form) {
	close();
}

function MenuScanButton_function(form) {
	submit("scan.html", "", null);
}

function MenuPatronStatusButton_function(form) {
	submit("patronstatus.html", "", null);
}

function MenuPatronStatusPopupButton_function(form) {
	win = submitPopup("patronstatus.html", "", null, "info", "", "");
	win.focus();
}

function PatronStatusShowPatronButton_function(form) {
	win = submitPopup("patronupdate.html", "search-current", null, "Update", "", "max");
	win.focus();
}

function PatronStatusPrintBonButton_function(form) {
	submit("patronstatus.html", "print-bon", null);
}

function MenuBasketButton_function(form) {
	submit("basket.html", "", null);
}

function MenuSettingsButton_function(form) {
	win = submit("settingspatronupdate.html", "", null);
}

function MenuPreferenceButton_function(form) {
	submit("preference.html", "", null);
}

function MenuSetupButton_function(form) {
	submit("setup.html", "", null);
}

function MenuPatronSelfCreateInsertButton_function(form) {
	win = submitPopup("patronselfcreateexplanation.html", "", null, "settings", "", "height=400,width=600");
	win.focus();
}

function MenuPatronButton_function(form) {
	submit('patronadmin.html', '', ['advanced', 'true']);
}

function MenuTeamButton_function(form) {
	submit('team.html', '', ['advanced', 'true']);
}

function MenuBookingButton_function(form) {
	submit('booking.html', '', ['advanced', 'true']);
}

function MenuHoldingButton_function(form) {
	submit('holding.html', '', ['advanced', 'true']);
}

function MenuReservationButton_function(form) {
	submit("reservation_from_menu.html", "show-advanced", null);
}

function MenuHelpButton_function(form) {
	openHelp("MenuHelp");
}

function MenuLogoutButton_function(form) {
	submit("search.html", "patron-logout", null);
}

function MenuBIBLINKButton_function(form) {
	win=window.open("http://bibliotek.dk","aName","toolbar=yes, location=yes, directories=no, status=no, menubar=yes, scrollbars=yes, resizable=no, copyhistory=yes, width=800, height=600")
    win.focus();
}

// --------------------------------------------------------------------------------------------------------
// Message buttons
// --------------------------------------------------------------------------------------------------------

function MessageDialogCloseButton_function(form) {
	close();
}

function MessageDialogYesButton_function(form) {
	var doaction = form.olddoaction.value;
	var data = form.olddata.value;
	opener.document.submitForm.data.value = data;
	addData = false;
	close();
	submitData("", doaction, ["forceflag", "true"], opener, opener);
}

function MessageDialogNoButton_function(form) {
	close();
}

function MessagePopupYesButton_function(form) {
	var doaction = form.olddoaction.value;
	var data = form.olddata.value;
	document.submitForm.data.value = data;
	addData = false;
	submit("", doaction, ["forceflag", "true"]);
}

function MessagePopupNoButton_function(form) {
	close();
}

function ConfirmButton_function(form) {
	submit("", "confirm", null);
}

// --------------------------------------------------------------------------------------------------------
// Message
// --------------------------------------------------------------------------------------------------------

function Message(content, errortype) {
	this.content = content;
	this.errortype = errortype;
	this.type = "";
}

function Message(content, errortype, type, approvableaction, olddoaction, olddata) {
	this.content = content;
	this.errortype = errortype;
	this.type = type;
	this.approvableaction = approvableaction;
	this.olddoaction = olddoaction;
	this.olddata = olddata;
}

var messageQueuePos = 0;
var messageQueue = new Array;

function addMessage(msg) {
	messageQueue[messageQueue.length] = msg;
}

function showNextMessage() {
	if (messageQueuePos < messageQueue.length) {
		showMessage(messageQueue[messageQueuePos++]);
	}
}

function showMessage(msg) {
	w = 600;
	h = 300;
	x = self.screenX + (self.outerWidth - w) / 2;
	y = self.screenY + (self.outerHeight - h) / 2;
	mwin = submitPopup("messagepopup.html", "", ["message", msg.content, "type", msg.type, "errortype", msg.errortype, "approvableaction", msg.approvableaction, "olddoaction", msg.olddoaction, "olddata", msg.olddata], "messagepopup", "status=no,location=no,scrollbars=no,resizable=no,titlebar=no", "height=" + h + ",width=" + w + ",screenX=" + x + ",screenY=" + y);
	/*
	mwin = open("", "messagepopup", "status=no,location=no,scrollbars=no,resizable=no,titlebar=no", "height=" + h + ",width=" + w + ",screenX=" + x + ",screenY=" + y);
	d = mwin.document;
	d.open();
	d.writeln(unescape(msg.content));
	mwin.document.close();
	*/
	mwin.focus();
}

// --------------------------------------------------------------------------------------------------------
// Printjob
// --------------------------------------------------------------------------------------------------------

function PrintJob(txt, title, type, showPrintPopup, showPrint) {
	this.txt = txt;
	this.title = title;
	this.type = type;
	this.showPrintPopup = showPrintPopup;
	this.showPrint = showPrint;
	this.win = null;
}

var printQueuePos = 0;
var printQueue = new Array;
var printPopup = null;
var printjob = null;

function addPrintJob(printjob, first) {
	if (first) {
		var l = printQueue.length;
		for (var i = l; i > printQueuePos; i--) {
			printQueue[i] = printQueue[i-1];
		}
		printQueue[printQueuePos] = printjob;
	} else {
		printQueue[printQueue.length] = printjob;
	}
}

function printNextPrintJob() {
	if (printQueuePos < printQueue.length) {
		printPrintJob(printQueue[printQueuePos++]);
	} else {
		if (printPopup != null) {
			printPopup.close();
		}
		return;
	}
}

function printPrintJob(pj) {
	printjob = pj;
	printstyle = "css"+printjob.type;
	txt = unescape(printjob.txt);
	isWin = false;
	if (printjob.showPrint || Browser.opera || Browser.ns) {
		printjob.win = open("", "printjobWin", "scrollbars=yes,resizable=yes,height=500,width=600");
		isWin = true;
		printPopup = printjob.win;
	} else {
		var id = "id"+(new Date().getTime());
		$("body").append('<iframe id="'+id+'" src="" width="0" height="0" frameborder="0" scrolling="no"></iframe>').get(0);
		printjob.win = $("#"+id).get(0).contentWindow;
	}
	d = printjob.win.document;
	d.open();
	d.writeln("<html>");
	d.writeln("<head>");
	d.write("<title>");
	d.write(printjob.title);
	d.writeln("</title>");
	href = self.location.href;
	href = href.substring(0, href.lastIndexOf("/"));
	href += "/print.css";
	d.writeln("<link rel='STYLESHEET' href='" + href + "' type='text/css' />");
	d.writeln("</head>");
	if (isWin) {
		if (printjob.showPrint) {
			d.writeln("<body>");
		} else {
			d.writeln("<body onload='opener._printPrintJob2(); return false;'>");
		}
	} else {
		d.writeln("<body onload='parent._printPrintJob2(); return false;'>");
	}
	d.writeln("<pre class='" + printstyle + "'>");
	d.writeln(txt);
	d.writeln("</pre>");
	d.writeln("</body>");
	d.writeln("</html>");
	d.close();
}

function _printPrintJob2() {
	if (Browser.ns6 || Browser.opera) {
		setTimeout(_printPrintJob3, 0);
	} else {
		_printPrintJob3();
	}
}

function _printPrintJob3() {
	printjob.win.focus();
	printWindow(printjob.win, printjob.showPrintPopup);
	printNextPrintJob();
}


// --------------------------------------------------------------------------------------------------------
// List navigation
// --------------------------------------------------------------------------------------------------------

listNavigationSavedRowClass = null;
listNavigationSavedRow = null;
listNavigationTable = null;

// The parameter form is the for that contains the "list" (table)
// Each row (tr) is required to have an id called "row" + row-index and one checkbox.
// The form must not contain other types of input-fields.
function enableListNavigation(form, count, selectFirstRow) {
	/* performance not ok	
	listNavigationTable = $("tr[id*=row]", form).parents("table").get(0);
	$("tr[id*=row] a, tr[id*=row] input, tr[id*=row] td", form).focus(function() {
		selectRow(findRow(this));
	}).blur(function() {
		unselectRow(findRow(this));
	});
	*/
}

function findRow(e) {
	var row = null;
	while (e != listNavigationTable && e.id.indexOf("row") != 0) {
		e = e.parentNode;
	}
	if (e.id.indexOf("row") == 0) {
		row = e;
	}
	return row;
}

function selectRow(row, focus) {
	if (row == listNavigationSavedRow) {
		return;
	}
	if (listNavigationSavedRow != null) {
		listNavigationSavedRow.className = listNavigationSavedRowClass;
	}
	listNavigationSavedRow = row;
	if (focus) {
		$("input[type!=hidden]", row).focus();
	}
	if (listNavigationSavedRow != null) {
		listNavigationSavedRowClass = listNavigationSavedRow.className;
		listNavigationSavedRow.className = "cssresultselectedrow";
	}
}

function unselectRow() {
	if (listNavigationSavedRow != null) {
		listNavigationSavedRow.className = listNavigationSavedRowClass;
	}
	listNavigationSavedRow = null;
	listNavigationSavedRowClass = null;
}

function ctrldown() {
	if (listNavigationTable != null) {
		var newRow = null;
		if (listNavigationSavedRow == null) {
			newRow = $("tr input[type=checkbox]", listNavigationTable).parents("tr").get(0);
		} else {
			newRow = $(listNavigationSavedRow).nextAll().find("input[type=checkbox]").parents("tr").get(0);
			if (!newRow) {
				newRow = $("tr input[type=checkbox]", listNavigationTable).parents("tr").get(0);
			}
		}
		selectRow(newRow, true);
	}
}

function ctrlup() {
	if (listNavigationTable != null) {
		var newRow = null;
		if (listNavigationSavedRow == null) {
			newRow = $("tr input[type=checkbox]:last", listNavigationTable).parents("tr").get(0);
		} else {
			newRow = $(listNavigationSavedRow).prevAll().find("input[type=checkbox]").parents("tr").get(0);
			if (!newRow) {
				newRow = $("tr input[type=checkbox]:last", listNavigationTable).parents("tr").get(0);
			}
		}
		selectRow(newRow, true);
	}
}

function esc() {
}

// 0-hit search

function search_ddelibraweb(target, site) {
	if (target == "_blank") {
		var win = open("", replaceAll(replaceAll(replaceAll(site, ":", ""), ".", ""), "/", ""), "");
		win.document.open("text/html", "replace");
		win.document.write('<form name="submitForm" method="post"><input name="doaction" type="hidden"><input name="data" type="hidden"><input name="tokenid" type="hidden"></form>');
		win.document.close();
		submitData(site, "search", null, self, win);
		win.focus();
	} else {
		submit(site, "search", null);
	}
}

// test functions

function test(formName, fieldName) {
	var endTime = new Date().getTime();
	// do some testing
	var functionName = getCookie("webtest_function"+self.name);
	if (functionName == "loantest") {
		var t = new LoanTest();
		t.test(endTime);
		return true;
	} else if (functionName == "searchtest") {
		var t = new SearchTest();
		t.test(endTime);
		return true;
	}
	return false;
}

function loanTest() {
	if (self.name == "") {
		self.name = new Date().getTime();
	}
	if (document.submitForm.tokenid.value == "" || document.loginForm.tickno) {
		alert("Husk at logge på.");
		return;
	}
	var countStr = prompt("Antal gennemløb.", "10");
	if (countStr == null) {
		return;
	}
	var count = parseInt(countStr);
	//var copyno = prompt("Indtast materialenr.", "514270791,511876982,512184588,512628907,511637325,512584934,511894883,513620616,513572840,513385080");
	var copyno = prompt("Indtast materialenr.", "");
	if (copyno == null) {
		return;
	}
	var t = new LoanTest(count, copyno);
	t.test();
	
}

function LoanTest(count, copyno) {
	var name = self.name;
	if (count && copyno) {
		setCookie("webtest_function"+name, "loantest", null, "/sites");
		setCookie("webtest_copyno"+name, copyno, null, "/sites");
		setCookie("webtest_count"+name, ""+count, null, "/sites");
		setCookie("webtest_cnum"+name, "0", null, "/sites");
		setCookie("webtest_num"+name, "0", null, "/sites");
		setCookie("webtest_time"+name, "0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0", null, "/sites");	// 14 number for checkout

		deleteCookie("webtest_starttime"+name, "/sites");
	}

	this.test = function(endTime) {
		var functionName = getCookie("webtest_function"+name);
		if (functionName == null || functionName == "") {
			return;
		}
		var transaction = getCookie("webtest_transaction"+name);
		var time = getCookie("webtest_time"+name).split(",", 100);
		if (endTime) {
			var startTime = parseInt(getCookie("webtest_starttime"+name));
			var requestTime = endTime-startTime;
			var processTime = findProcessTime(document.body.innerHTML);
			var i = 0;
			if (transaction == "checkin") {
				i = 14;
			}
			time[i+0] = parseInt(time[i+0])+requestTime;
			requestTime = requestTime/1000;
			requestTime = Math.min(Math.round(requestTime-0.5), 5);
			time[i+1+requestTime] = parseInt(time[i+1+requestTime])+1;
			time[i+7] = parseInt(time[i+7])+processTime;
			processTime = processTime/1000;
			processTime = Math.min(Math.round(processTime-0.5), 5);
			time[i+8+processTime] = parseInt(time[i+8+processTime])+1;
			setCookie("webtest_time"+name, ""+time, null, "/sites")
		}
		var count = parseInt(getCookie("webtest_count"+name));
		var num = parseInt(getCookie("webtest_num"+name));
		if (num < count*2) {
			if (document.submitForm.name.value == "" || document.loginForm.tickno) {
				alert("Husk at logge på.");
				this.cleanup();
				return;
			} else {
				var transaction = "";
				if (num % 2 == 0) {
					transaction = "checkout";
				} else {
					transaction = "checkin";
				}
				setCookie("webtest_transaction"+name, transaction, null, "/sites");

				var cnum = parseInt(getCookie("webtest_cnum"+name));
				var copynoList = getCookie("webtest_copyno"+name).split(",", 1000);
				var copyno = copynoList[cnum];
				cnum++;
				if (cnum >= copynoList.length) {
					cnum = 0;
					num++;
					setCookie("webtest_num"+name, ""+num, null, "/sites")
				}
				setCookie("webtest_cnum"+name, ""+cnum, null, "/sites")
				var startTime = new Date().getTime();
				setCookie("webtest_starttime"+name, ""+startTime, null, "/sites");
				if (transaction == "checkout") {
					submit("checkout.html", "checkout", ["checkout_tickno", copyno]);
				} else {
					submit("checkin.html", "checkin", ["checkin_copyno", copyno]);
				}
			}
		} else {
			this.cleanup();
			var r = "<h2>Loantest:</h2>";
			r += "<div><span style='font-weight:bold'>Tid: </span>"+new Date()+"</div>";
			r += "<div><span style='font-weight:bold'>URL: </span>"+self.location.href+"</div>";
			r += "<br/><table border='1' cellpadding='1'><tr>";
			r += "<td></td>";
			r += "<td>Tid Ialt</td>";
			r += "<td>Udlån</td>";
			r += "<td>Udlån<1</td>";
			r += "<td>Udlån<2</td>";
			r += "<td>Udlån<3</td>";
			r += "<td>Udlån<4</td>";
			r += "<td>Udlån<5</td>";
			r += "<td>Udlån>5</td>";
			r += "<td>Ialt</td>";
			r += "<td>Aflv</td>";
			r += "<td>Aflv<1</td>";
			r += "<td>Aflv<2</td>";
			r += "<td>Aflv<3</td>";
			r += "<td>Aflv<4</td>";
			r += "<td>Aflv<5</td>";
			r += "<td>Aflv>5</td>";
			r += "<td>Ialt</td>";
			r += "</tr><tr>";
			r += "<td>Browser</td>";
			r += "<td>"+(parseInt(time[0])+parseInt(time[14]))+"ms</td>";
			r += "<td>"+time[0]+"ms</td>";
			r += "<td>"+time[1]+"</td>";
			r += "<td>"+time[2]+"</td>";
			r += "<td>"+time[3]+"</td>";
			r += "<td>"+time[4]+"</td>";
			r += "<td>"+time[5]+"</td>";
			r += "<td>"+time[6]+"</td>";
			r += "<td>"+(parseInt(time[1])+parseInt(time[2])+parseInt(time[3])+parseInt(time[4])+parseInt(time[5])+parseInt(time[6]))+"</td>";
			r += "<td>"+time[14]+"ms</td>";
			r += "<td>"+time[15]+"</td>";
			r += "<td>"+time[16]+"</td>";
			r += "<td>"+time[17]+"</td>";
			r += "<td>"+time[18]+"</td>";
			r += "<td>"+time[19]+"</td>";
			r += "<td>"+time[20]+"</td>";
			r += "<td>"+(parseInt(time[15])+parseInt(time[16])+parseInt(time[17])+parseInt(time[18])+parseInt(time[19])+parseInt(time[20]))+"</td>";
			r += "</tr><tr>";
			r += "<td>Server</td>";
			r += "<td>"+(parseInt(time[7])+parseInt(time[21]))+"ms</td>";
			r += "<td>"+time[7]+"ms</td>";
			r += "<td>"+time[8]+"</td>";
			r += "<td>"+time[9]+"</td>";
			r += "<td>"+time[10]+"</td>";
			r += "<td>"+time[11]+"</td>";
			r += "<td>"+time[12]+"</td>";
			r += "<td>"+time[13]+"</td>";
			r += "<td>"+(parseInt(time[8])+parseInt(time[9])+parseInt(time[10])+parseInt(time[11])+parseInt(time[12])+parseInt(time[13]))+"</td>";
			r += "<td>"+time[21]+"ms</td>";
			r += "<td>"+time[22]+"</td>";
			r += "<td>"+time[23]+"</td>";
			r += "<td>"+time[24]+"</td>";
			r += "<td>"+time[25]+"</td>";
			r += "<td>"+time[26]+"</td>";
			r += "<td>"+time[27]+"</td>";
			r += "<td>"+(parseInt(time[22])+parseInt(time[23])+parseInt(time[24])+parseInt(time[25])+parseInt(time[26])+parseInt(time[27]))+"</td>";
			r += "</tr></table>";
			document.getElementById("cssbodycontent").innerHTML = r;
		}
	}

	this.cleanup = function() {
		deleteCookie("webtest_function"+name, "/sites");
		deleteCookie("webtest_transaction"+name, "/sites");
		deleteCookie("webtest_copyno"+name, "/sites");
		deleteCookie("webtest_count"+name, "/sites");
		deleteCookie("webtest_cnum"+name, "/sites");
		deleteCookie("webtest_num"+name, "/sites");
		deleteCookie("webtest_time"+name, "/sites");
		deleteCookie("webtest_starttime"+name, "/sites");
	}
}

function netTest() {
	var c = prompt("Antal gennemløb", 10)
	if (c != null) {
		var t = new NetTest(c);
		t.test();
	}
}

function NetTest(count) {
	var num = 0;
	var requestTime = 0;
	var processTime = 0;
	var startTime = 0;

	this.test = function() {
		var obj = this;
		if (num < count) {
			num++;
			document.getElementById("cssbodycontent").innerHTML = num;
			startTime = new Date().getTime();
			//var u = new Ajax.Request("search.html", {asynchronous:true, evalScripts:true, onComplete:function(request) { obj._test(request.responseText) }, parameters:"t="+new Date().getTime()});
			$.get("search.html", "t="+new Date().getTime(), function(html, status) { 
				obj._test(html)
			});
		} else {
			var r = "<h2>Nettest:</h2>";
			r += "<div><span style='font-weight:bold'>Tid: </span>"+new Date()+"</div>";
			r += "<div><span style='font-weight:bold'>URL: </span>"+self.location.href+"</div>";
			r += "<div><span style='font-weight:bold'>Tid for browser: </span>"+requestTime+"ms</div>";
			r += "<div><span style='font-weight:bold'>Tid på server: </span>"+processTime+"ms</div>";
			r += "<div><span style='font-weight:bold'>Antal gennemløb: </span>"+count+"</div>";
			document.getElementById("cssbodycontent").innerHTML = r;
		}
	}

	this._test = function(html) {
		var endTime = new Date().getTime();
		requestTime += (endTime-startTime);
		var time = findProcessTime(html);
		if (time != -1) {
			processTime += time;
		}
		this.test();
	}
}

function findProcessTime(html) {
	var time = 0;
	var p = 0;
	// <!-- Processed by Apache Cocoon 2.1.10 in 328 milliseconds. -->
	// <!-- Processed by Apache Cocoon 2.1.10 in 1.297 seconds. -->
	if ((p = html.indexOf("Processed by Apache Cocoon")) != -1) {
		if ((p = html.indexOf(" in ", p+26)) != -1) {
			var timeStr = html.substring(p+4, html.indexOf(" ", p+4));
			if ((html.indexOf("milliseconds", p+4)) != -1) {
				time = parseInt(timeStr);
			} else {
				time = parseFloat(timeStr)*1000;
			}
		}
	}
	return time;
}

function setCookie(name, value, expire, path) {
	document.cookie = name + "=" + escape(value) + ((!expire) ? "" : ("; expires=" + expire.toGMTString())) + "; path=" + ((!path) ? "/" : path);
}

function getCookie(name, defaultValue) {
	var value = ((!defaultValue) ? "" : defaultValue);
	var match = new RegExp("(^|.*; )"+name+"=\"*([^\";]*)\"*", "img");
	var r;
	if ((r = match.exec(document.cookie)) != null) {
		value = unescape(r[2]);
	}
	return value;
}

function deleteCookie(name, path) {
	var d = new Date();
	d.setFullYear(1970, 0, 1);
	setCookie(name, "", d, path);
}
