/* APSRequest - (C) 2006-2010 Stegmann Systems GmbH (www.aps-info.de) */

var ajaxrequest = new Array();
var apssession = new Array();
var apsrequest_baseurl = "/db/apsisa.dll";
var searchstate = "NEW";
var Query = new Object();
Query.lastDDUpdate = new Object();
var suggestTimeout = 0;
var DrillChildsTimeout = 0;
var Details = new Object();
var APSSuggestDelay = 650;
var DrillChildResizeDelay = 50;
var SuggestCancel = false;
var LoadingCounter = 0;
var slider_offset = 0;
var slider_total = 0;
var slider_lpx = 0;
var slider_cmd = "";
var slider_count = 0;
var pb = false;
var SWFInstance = null;
var LP = "";
var WK = "";
var WKOrder = "";
var WKOrderPersistent = false;
var WKOrderDifferent = false;
var WKcmt = "";
var WKPaymentMethod = "";
var ExtraMenu = false;
var DMode='';
var listcount = 0;
var m_apsRequestHistory = Array();
var m_nMaxApsRequestHistorySize = 20; /* >=5 */

var m_bLoadTimedout = false;
var m_loadTimeoutRef;

var m_strLastInfoRequest = '';	

var SORT_ENABLED = true;
var m_sSortField = '';
var m_sSortDirection = '';
var m_strLastSearchDefineRequest = '';

function sortFieldChanged() {
	var sortFieldSelector = document.getElementById('sortFieldSelect');
	if (sortFieldSelector) {
		var iSelectedFieldIndex = sortFieldSelector.selectedIndex;
		var sSelectedFieldValue = sortFieldSelector.options[iSelectedFieldIndex].value;
		if (m_sSortField != sSelectedFieldValue) {
			m_sSortField = sSelectedFieldValue;
			if (m_strLastSearchDefineRequest != '') {
				APSRequest(m_strLastSearchDefineRequest);
			}
		}
	}
}



function getBodyWidth() {
	var iBodyWidth = window.innerWidth;
	if (bb.browser.ie) {
		iBodyWidth = document.body.clientWidth;
		if (iBodyWidth == 0) {
			iBodyHeight = document.documentElement.clientWidth;
		}
	}
	return iBodyWidth;
}

function getBodyHeight() {
	var iBodyHeight = window.innerHeight;
	if (bb.browser.ie) {
		iBodyHeight = document.body.clientHeight;
		if (iBodyHeight == 0) {
			iBodyHeight = document.documentElement.clientHeight;
		}
	}
	return iBodyHeight;
}


/**
 * @param {String} sDir ASC, DESC
 */
function sortDirectionChanged(sDir) {
	if (sDir != '') {
		sDir = sDir.toLowerCase();
	}
	if (sDir == 'asc' || sDir == 'desc') {
		if (sDir != m_sSortDirection) {
			m_sSortDirection = sDir;
			if (m_strLastSearchDefineRequest != '') {
				APSRequest(m_strLastSearchDefineRequest);
			}
		}
	}
}


function initProcessBar() {
	pb = new ProcessBar('pb');
	pb.container = document.getElementById('pb');
	pb.init();
}

function initAPSPreloaded() {
	initAPS(true);
}

/**
 * Lädt die Kommentarstatistiken für ein Dokument anhand seines doytpes und seiner docnumber
 */
function loadCommentStats(doctype, docnumber) {
	if (doctype && docnumber) {
		APSRequest("viewComments?dynDataDocStats=(/docs/" + encodeURIComponent(doctype) + "/" + encodeURIComponent(docnumber) + "/comments)&doctype=" + encodeURIComponent(doctype) + "&docnumber=" + encodeURIComponent(docnumber));
	}
}

/**
 * Speicher den postloginrequest für das login form mit der geg id
 * @param id ID des formulars
 * @param sRequest der nach dem erfolgreichen Login auszuführende Request 
 */
function storePostLoginRequest(sLoginFormid, sRequest) {
	var oLoginForm = document.getElementById(sLoginFormid);
	if (oLoginForm) {
		// Aps verhält sich bei & im Variablenwert nicht korrekt daher Ersetzung durch #
		sRequest = sRequest.replace(/\&/g, '#');
		oLoginForm["postLoginRequest"].value = sRequest;
	}
}

function submitLogin(formNode) {
	var sPostLoginRequest = formNode["postLoginRequest"].value;
	var sErrorResponseId = formNode["errorResponseId"].value;
	var sEMail = formNode["email"].value;
	var sPassword = formNode["password"].value;
	APSRequest('login?account=' + encodeURIComponent(sEMail) + '&pwd=' + encodeURIComponent(sPassword) + "&postLoginRequest=" + encodeURIComponent(sPostLoginRequest) + "&errorResponseId=" + encodeURIComponent(sErrorResponseId));
}

function changePassword(formNode) {
	var sResponseId = formNode["responseId"].value;
	var sPassword = formNode["password"].value;
	var sNewPassword = formNode["newpassword"].value;
	var sNewPassword2 = formNode["newpassword2"].value;
	var oResponseNode = document.getElementById(sResponseId);
	formNode["password"].style.borderColor = "#DDDDDD";
	formNode["newpassword"].style.borderColor = "#DDDDDD";
	formNode["newpassword2"].style.borderColor = "#DDDDDD";
	oResponseNode.style.display = "none";
	if (sPassword == '') {
		formNode["password"].style.borderColor = "#DC2521";
		oResponseNode.innerHTML = "Das aktuelle Passwort ist leer. Bitte &uuml;berpr&uuml;fen Sie Ihre Eingabe.";
		oResponseNode.style.display = "block";
	}
	if (sNewPassword != sNewPassword2) {
		formNode["newpassword"].style.borderColor = "#DC2521";
		formNode["newpassword2"].style.borderColor = "#DC2521";
		
		oResponseNode.innerHTML = "Die neuen Passw&ouml;rter sind nicht identisch. Bitte &uuml;berpr&uuml;fen Sie Ihre Eingabe.";
		oResponseNode.style.display = "block";	
	}
	else {
		APSRequest('changePassword?pwd='+encodeURIComponent(sPassword)+'&newpwd='+encodeURIComponent(sNewPassword)+'&responseId='+encodeURIComponent(sResponseId));
	}
}

function submitRegistration(formNode) {
	var sResponseId = formNode["responseId"].value;
	var sEMail = formNode["email"].value;
	APSRequest('register?account=' + encodeURIComponent(sEMail) + "&responseId=" + encodeURIComponent(sResponseId));
}

function resetPassword(formNode) {
	var sResponseId = formNode["responseId"].value;
	var sEMail = formNode["email"].value;
	APSRequest('resetPassword?account=' + encodeURIComponent(sEMail) + "&responseId=" + encodeURIComponent(sResponseId));
}


/**
 * Schickt den im Formular eingetragenen (vorgeschlagenen) Künstler an den APS Server
 */
function submitNewArtist() {
	var artistName = document.getElementById('upFormKunstler-name').value;
	var artistBirthday = document.getElementById('upFormKunstler-birthdate').value;
	var artistDescription = document.getElementById('upFormKunstler-description').value;
	APSRequest('submitSuggestedArtist?name=' + encodeURIComponent(artistName) + '&birthday=' + encodeURIComponent(artistBirthday) + '&description=' + encodeURIComponent(artistDescription));
}

/**
 * Schickt einen neuen 
 * Kommentar an den APS Server
 */
function submitNewComment(formNode) {
	var sParentNodePath = formNode["parentNodePath"].value;
	var sComment = formNode["comment"].value;
	var sDocType = formNode["doctype"].value;
	var sDocNumber = formNode["docnumber"].value;
	// Der Kommentar selbst darf keine spitzen Klammern und Ampersants enthalten
	sComment = htmlSpecialChars(sComment);
	//Sehr wohl aber richtext elemente
	sComment = sComment.replace(/[\n\r]+/g, "<br/>");
	APSRequest('submitComment?comment=' + encodeURIComponent(sComment) + "&parentNodePath=" + encodeURIComponent(sParentNodePath) + "&doctype=" + encodeURIComponent(sDocType) + "&docnumber=" + encodeURIComponent(sDocNumber));
}

/**
 * Ersetzt < durch &lt; & durch &amp; etc...
 * @param {String} sChars
 */
function htmlSpecialChars(sChars) {
	res = null;
	if (typeof(bb.string.escapeXml)=='function') {
		res = bb.string.escapeXml(sChars);
	}
	else {
		var div = document.createElement('div');
		var textNode = document.createTextNode(sChars);
		div.appendChild(textNode);
		res = div.innerHTML;
	}
	return res;
}


/**
 * initAPS
 * Initialisiert APS vie AJAX. Funktion wird am Ende der Index.html aufgerufen.
 */
function initAPS(preloaded) {
	if (preloaded == undefined) {
		preloaded = false;
	}
	m_sSortDirection = "";
	m_sSortField = "";
	Query.media = "";
	Query.mediaID = "";
	Query.archive = "";
	Query.archiveID = "";
	Query.base = "";
	Query.catalog = "";
	Query.maps = "";
	Query.mapstxt = "";
	Query.mapslvl = "";
    Query.lastDDUpdate.catalog = "";
    Query.lastDDUpdate.tastr = "";
    Query.lastDDUpdate.start = "";
    var b = BrowserDetect.browser;
	
	var appHost = location.protocol + '//' + location.host;
	if (location.port != "") {
		appHost += ':' + location.port;
	}
	appHost += "/";
	
	AppCookie.set('appHost', appHost);
	AppCookie.set('renderEngName', bb.browser.name);
	AppCookie.set('renderEngVer', bb.browser.version);
	
	var dosearch = true;
    if (!preloaded && location.search==='') {
		APSRequest("init?:media=ALL&:dmode=galery&:browser=" + escape(b));
	} else if (!preloaded && location.search.indexOf('?ARCHIV_')== 0) {
		var thearchive = location.search.substring(8);
		dosearch = false;
		APSRequest("archivselect?option=preloaded&:dmode=galery&:archiv=" + thearchive + "&:browser=" + escape(b));
	} else if (!preloaded && location.search.indexOf('?MEDIA_')== 0) { 
		var themedia = location.search.substring(7);
		dosearch = false;
		APSRequest("mediaselect?option=preloaded&:dmode=galery&:media=" + themedia + "&:browser=" + escape(b));
	} else {
		APSRequest("init?option=preloaded&:media=ALL&:dmode=galery&:browser=" + escape(b)+ "&pathname=" + escape(location.pathname));
	}
	
    
    if (preloaded) {
        var sInfotextFileName = location.pathname;
		if (typeof(sInfotextFileName)=='string') {
			if (sInfotextFileName.search(/\.[hH][tT][mM][lL]/) >= 0) {
				ExtraMenuSync(sInfotextFileName,null,true);
				var xmlfn = sInfotextFileName.replace(/\.html$/,".xml");
				xmlfn = xmlfn.replace(/^\//,"");
				ExtraMenuBreadcrumbResyncByFilename(xmlfn);
			}
		}
    }
	else {
		ExtraMenuStart();
	}
	initializeStatusfromCookie();
	if (location.search !== '' && location.search != '?NOSEARCH' && dosearch) {
		var sUrlQuery = location.search.replace(/^\?/,"");
		
		var aUrlQueryParams = sUrlQuery.split(/[\&\#]/);
		if (aUrlQueryParams.length >=1) {
			var sSearchQuery = decodeURIComponent(aUrlQueryParams[0]);
			var rQueryAnalyzer = /^(([+-]?)([\w-]*)([\:!]?)((['][^']+['])|([\"][^"]+["])|([^\s^"^'^\:!]+)))/;
			var sNewSearchQuery = "";
			var rResults = rQueryAnalyzer.exec(sSearchQuery)
			while (rResults != null) {
				var sGesamt = rResults[1]; //Gesamter Regex Treffer 
				var sConnector = rResults[2]; //Connector/Operator (+-)
				var sIndex = rResults[3]; //index
				var sIndexDesscSeparator = rResults[4]; //der trenner zwischen index und begriff (:)
				var sDesc = rResults[5]; //der suchbegriff
				var sDescInSingleQuotes = rResults[6]; //suchbegriff in ' ? (testbar mit if)
				var sDescInDoubleQuotes = rResults[7]; //suchbegriff in " ? (testbar mit if)
				var sDescWithoutQuotes = rResults[8]; //suchbegriff ohne anführunhszeichen ? (testbar mit if)

				var sNewSearchQuery = sNewSearchQuery + encodeURIComponent(" ") + sConnector + encodeURIComponent(sIndex) + sIndexDesscSeparator;
				if (sDescWithoutQuotes) {
					//Satzzeichen Substitution
					// var rReplaceChars = /[,\.\:\\\/\(\)\{\}\[\]\&\!\<\>\"]+/;
					var rReplaceChars = /[\.\:\\\/\(\)\{\}\[\]\&\!\<\>\"]+/;
					if (sDesc.search(rReplaceChars) >= 0) {
						sDesc = sDesc.replace(rReplaceChars, "");
					}
					/*
					if (sDescWithoutQuotes.search(rReplaceChars) >= 0) {
						sDesc = sDesc.replace(rReplaceChars, "");
					}*/
				}
				sNewSearchQuery = sNewSearchQuery + encodeURIComponent(sDesc);
				sSearchQuery = sSearchQuery.replace(sGesamt, "");
				sSearchQuery = sSearchQuery.replace(/^\s+/,"");
				sSearchQuery = sSearchQuery.replace(/^(\S+)\s+$/,"$1");
				rResults = rQueryAnalyzer.exec(sSearchQuery)
			}		
		}
		for (var i=1; i<aUrlQueryParams.length; i++) {
			sNewSearchQuery = sNewSearchQuery + "&" + aUrlQueryParams[i];
		}
		
		APSRequest("searchdefine?query=" + sNewSearchQuery, 1, true);
		
		//Alter Weg
		/*
		var s = unescape(location.search);
		s = s.replace(/^\?/, "");
		var numberParam = "&number=";
		if (s.indexOf(numberParam) != -1) {
			var q = s.substring(0, s.indexOf(numberParam));
			var no = s.substring(s.indexOf(numberParam) + numberParam.length);
			if (parseInt(no) == NaN) {
				no = 1;
			}
			APSRequest("searchdefine?query=" +encodeURI(q) + "&no=" + no, 1, true);
		}
		else {
			APSRequest("searchdefine?query=" + encodeURI(s), 1, true);
		}
		*/
		
	}
}

/**
 * setStatus
 * Aktualisierung der Statusfelder, mit AJAX-Feedback
 */
 function setStatus(text,katalog,zeit) {
	try {
		var div_status = document.getElementById("status");
		div_status["innerHTML"] = text;
		if (zeit !== '') {
			var tmpDate = new Date(zeit);
			var div_time = document.getElementById("time");
			minu = tmpDate.getMinutes().toString();
			if (minu.length == 1) {
				minu = '0' + minu;
			}
			div_time["innerHTML"] = tmpDate.getDate() + "." + parseInt(parseInt(tmpDate.getMonth()) + 1) + "." + tmpDate.getFullYear() + " " + tmpDate.getHours() + ":" + minu;
		}
		if (katalog !== '') {
			var div_katalog	= document.getElementById("katalogname");
			if (katalog == 'NONE') {
				div_katalog["innerHTML"] = '';
			} else {
				div_katalog["innerHTML"] = ': ' + katalog;
			}
		}
	} catch (ex) {
		
	}
}

function ShowLoading() {
	LoadingCounter++;
	if (LoadingCounter == 1 && pb) {
		pb.stoploop = false;
		pb.loop();
	}
	showDiv("loadingOverlay",true);
	showDiv("loadingContent",true);
}

function HideLoading() {
	LoadingCounter--;
	if (LoadingCounter <= 0) {
		pb.stoploop = true;
		showDiv("loadingOverlay",false);
		showDiv("loadingContent",false);
	}
}
/**
 * APSRequest
 * @param {string} cmd Der Requeststring
 * @param {string} session Session-ID
 */
function APSRequest(cmd,session,history) {
	if (typeof(session) == 'undefined') {
		session = 1;
	}
	if (!session) {
		session = 1;
	}
    if (session == 1) {
    	ShowLoading();
		SuggestCancel = true;
		showDiv('suggestBox',false);
	} else if (session == 2) {
		SuggestCancel = false;
	}
		
	if (session == 1 && !history) {
		if (cmd.search(/searchdefine|searchdefinenq/) >= 0) {
			addSearchHistory('query', cmd, Query);
		} 
		if (cmd.search(/searchreset/) >= 0) {
			addSearchHistory('searchreset','',Query);
			m_strLastSearchDefineRequest = '';
		}
		if (cmd.search(/catalogselect/) >= 0) {
			addSearchHistory('catalog', cmd, Query);
		}
		if (cmd.search(/mediaselect/) >= 0) {
			addSearchHistory('media', cmd, Query);
		}
		if (cmd.search(/archivselect/) >= 0) {
			addSearchHistory('archiv', cmd, Query);
		}
		if (cmd.search(/displaylichtpult/) >= 0) {
			addSearchHistory('lichtpult', cmd, Query);
		}
		if (cmd.search(/warenkorb/) >= 0) {
			addSearchHistory('warenkorb', cmd, Query);
		}
		if (cmd.search(/info/) >= 0) {
			addSearchHistory('info', cmd, Query);
		}
	}
	
	if (session == 1) {
		//Wenn die max. History Größe einen ungültigen Wert hat,
		//dann auf eine sinnvolle Größe setzen (5)
		if (typeof(m_nMaxApsRequestHistorySize) != 'number' || m_nMaxApsRequestHistorySize < 5) {
			m_nMaxApsRequestHistorySize = 5;
		}
		if (typeof(Array.push=='function')) {
			m_apsRequestHistory.push(cmd);
		}
		else {
			m_apsRequestHistory.xpush(cmd);
		}
		//Wenn die Request History größer wird als die Grenze erlaubt,
		//dann Array auf die korrekte max. Größe zurpcksetzen, indem
		//die ältesten Requests entfernt werden
		if (m_apsRequestHistory.length > m_nMaxApsRequestHistorySize) {
			m_apsRequestHistory = m_apsRequestHistory.slice(m_nMaxApsRequestHistorySize - m_apsRequestHistory.length);
		}
		if (listcount > 0) {
			if (cmd.search(/\?/) > 1) {
				cmd = cmd + '&:listcount=' + listcount;
			} else {
				cmd = cmd + '?:listcount=' + listcount;
			}
		}
		if (cmd.search(/searchdefine|searchdefinenq/) >= 0) {
			m_strLastSearchDefineRequest = cmd;
		}
		if (SORT_ENABLED && m_sSortField!= "" && m_sSortDirection != "") {
			if ((cmd.search(/\?/) > 1)) {
				cmd += '&sortby=' + m_sSortField + '&sort=' + m_sSortDirection;
			} else {
				cmd += '?sortby=' + m_sSortField + '&sort=' + m_sSortDirection;
			}
		}
	}
	URLRequest(apsrequest_baseurl + "/" + cmd, session,false,false);
	
}

/**
 * URLRequest
 * @param {string} url Aufzurufende URL
 * @param {string} session Session-ID
 * @return xmlhttp objekt
 */
function URLRequest(url,session,sync,hist) {
	if (url.search('info/') === 0) {
		var preExtIndex = url.search(/\.[xX][mM][lL]/);
		if (preExtIndex > 0 ) {
			m_strLastInfoRequest = AppCookie.get('appHost') + url.substring(0, preExtIndex) + ".html";
		}
		else {
			m_strLastInfoRequest = "";
		}
	}
	else {
		m_strLastInfoRequest = ""
	}
		
	var hr = false;
	if (!session) {
		session = 0;
	}
	if (typeof(hist) == 'undefined') {
		hist = false;
	}
	setStatus("Bitte warten ...","","");
	
	if (url.search(/\.xml/)>= 0 && hist!=true) {
		try {
			addSearchHistory('xml',url,Query);
		} catch (e){};
	}
	
	if (session > 0) {
		if (apssession.length < session + 1) {
			apssession[session] = "sid={02f71717-e5e9-49b1-b204-b80362c75aec};path=" + apsrequest_baseurl +";";
		}
		document.cookie = apssession[session];
	}
	if (window.XMLHttpRequest) {
		hr = new XMLHttpRequest();
		if (hr.overrideMimeType) {
			hr.overrideMimeType("text/xml");
		}
	} else {
		if (window.ActiveXObject) { // IE
			try {
				hr = new ActiveXObject("Msxml2.XMLHTTP");
			}
			catch (ex) {
				try {
					hr = new ActiveXObject("Microsoft.XMLHTTP");
				}
				catch (ex) {
					setStatus("Fehler: XMLHTTP nicht verfügbar [3].","","");
				}
			}
		}
	}
	if (!hr) {
		setStatus("Fehler: XMLHTTP nicht verfügbar [4].","","");
		return false;
	}

	if (!sync) {
		hr.onreadystatechange = function() {
			if (hr.readyState == 4) {
				if (hr.status == 200 || hr.status === 0) {
					var xmlDate = hr.getResponseHeader("Date");
					if (session > 0) {
						var xmlCookie = hr.getResponseHeader("X-APS-SID");
						apssession[session] = xmlCookie;
					}
					var xmlNode = hr.responseXML.documentElement;
					interpreteResult(xmlNode,url);
					setStatus("Bereit.","",xmlDate);
				} else {
					setStatus("Fehler " + hr.status + " aufgetreten.","","");
				}
				if (session == 1) {
					HideLoading();
				}
			}
			resizeDrillChilds();
		};
		hr.open("GET", url, true);
		hr.send(null);
		ajaxrequest[session] = hr;
	} else {
		hr.open("GET", url, false);
		hr.send(null);
		return hr.responseText;
	}
}

/**
 * interpreteResult
 * wertet den AJAX Response aus und arbeitet ihn ein
 * @param xmlNode der von XMLHTTPResult ausgewertete  Knoten
 */
function interpreteResult(xmlNode,url) {
	try {
	for (var i = 0; i < xmlNode.childNodes.length; i++) {
		var nodeName = xmlNode.childNodes[i].nodeName;
		switch (nodeName) {
			case 'ApsRequest': {
				var req = xmlNode.childNodes[i].getAttribute("request");
				if (req) {
					APSRequest(req);
				}
				break;
			}
			case 'setSortField': {
				var sSortField = xmlNode.childNodes[i].getAttribute("name");
				if (sSortField) {
					m_sSortField = sSortField;
				}
				break;
			}
			case 'setSortDirection': {				
				var sSortDir = xmlNode.childNodes[i].getAttribute("direction");
				if (sSortDir) {
					m_sSortDirection = sSortDir;
				}
				break;
			}
			case 'alert':
				alert(xmlNode.childNodes[i].firstChild.nodeValue);
				break;
			case 'loadURL':
				URLRequest(xmlNode.childNodes[i].firstChild.nodeValue,0,false,true);
				break;
			case 'ExtraMenuLoad':
				ExtraMenuLoadFile(xmlNode.childNodes[i].firstChild.nodeValue);
				break;
			case 'Logo':
				var ilogo = document.getElementById("Logo");
				var lsrc = xmlNode.childNodes[i].getAttribute("img");
				var atxt = xmlNode.childNodes[i].getAttribute("alttext");
				if (ilogo.src != lsrc) {
				   ilogo.src = lsrc;
				   ilogo.alt = atxt;
				}
				break;
			case 'Background':
				try {
					var sTop = 'url(' + xmlNode.childNodes[i].getAttribute("top") + ')';
					var sRight = xmlNode.childNodes[i].getAttribute("right");
				
					var iRight = document.getElementById("bgright");
					if (iRight.src != sRight) {
						iRight.src = sRight;
					}
				
					var iTop = document.getElementById("tabmenu");
					if (iTop.style.backgroundImage != sTop) {
						iTop.style.backgroundImage = sTop;
					}
				} 
				catch (e) {
				}
				
				break;
			case  'query_base':
			   	if (xmlNode.childNodes[i].childNodes.length === 0) {
			   		Query.base = "";
			   	} else {
					Query.base = unescape(trim(xmlNode.childNodes[i].firstChild.nodeValue));
			   	}
			   	break;
			case  'mediaID':
			   	if (xmlNode.childNodes[i].childNodes.length === 0) {
			   		Query.mediaID = "";
			   	} else {
					Query.mediaID = unescape(trim(xmlNode.childNodes[i].firstChild.nodeValue));
			   	}
			   	break;
			case  'query_media':
			   	if (xmlNode.childNodes[i].childNodes.length === 0) {
			   		Query.media = "";
			   	} else {
					Query.media = unescape(trim(xmlNode.childNodes[i].firstChild.nodeValue));
			   	}
			   	break;
			case  'query_catalog':
			   	if (xmlNode.childNodes[i].childNodes.length === 0) {
			   		Query.catalog = "";
			   	} else {
					Query.catalog = unescape(trim(xmlNode.childNodes[i].firstChild.nodeValue));
			   	}
			   	break;
			case  'archiveID':
			   	if (xmlNode.childNodes[i].childNodes.length === 0) {
			   		Query.archiveID = "";
			   	} else {
					Query.archiveID = unescape(trim(xmlNode.childNodes[i].firstChild.nodeValue));
			   	}
			   	break;
			case  'query_archive':
			   	if (xmlNode.childNodes[i].childNodes.length === 0) {
			   		Query.archive = "";
			   	} else {
					Query.archive = unescape(trim(xmlNode.childNodes[i].firstChild.nodeValue));
			   	}
			   	break;
			case   'query_maps':
			   	if (xmlNode.childNodes[i].childNodes.length === 0) {
			   		Query.maps = "";
			   		Query.mapstxt = "";
			   		Query.mapslvl = "";
			   	} else {
					Query.maps = unescape(trim(xmlNode.childNodes[i].firstChild.nodeValue));
				   	try {
				   		document.getElementById("query_maps").innerHTML = Query.mapstxt;
				   	} catch(ex) {};
			   	}
			   	break;
			case 'searchstate':
			   	if (xmlNode.childNodes[i].childNodes.length === 0) {
			   		searchstate = "NEW";
			   	} else {
					searchstate = trim(xmlNode.childNodes[i].firstChild.nodeValue);
			   	}
			   	break;
			case 'reRegisterSliderEvent':
				slider_offset = xmlNode.childNodes[i].getAttribute("offset");
				slider_total = xmlNode.childNodes[i].getAttribute("total");
				slider_lpx = xmlNode.childNodes[i].getAttribute("lpx");
				slider_cmd = xmlNode.childNodes[i].getAttribute("cmd");
				slider_count = xmlNode.childNodes[i].getAttribute("count");
				slider_mover = xmlNode.childNodes[i].getAttribute("moverid");
				try {
					slider_lichtpult = xmlNode.childNodes[i].getAttribute("LP");
					slider_LP = slider_lichtpult.split('|');
					slider_useLP = true;
				} catch (elp) {
					slider_useLP = false;
				}
			   	var mover = document.getElementById(slider_mover);
			   	addEvent(mover,"mousedown",initSlider);
			   	addEvent(mover,"mouseup",releaseSlider);
			   	
			   	fnReleaseCallback = function(iLeft) {
			   		var dok = Math.round(((iLeft - slider_offset) * slider_total / slider_lpx) + 1);
			   		if (slider_useLP) {
			   			APSRequest(slider_cmd + slider_LP[dok - 1]);
			   		} else {
				   		APSRequest(slider_cmd + "?no=" + dok);
				   	}
			   	};
				fnMoveCallback = function(iLeft, tooltip) {
			   		var dok = Math.round(((iLeft - slider_offset) * slider_total / slider_lpx) + 1);
			   		var todok;
			   		todok = dok + Number(slider_count) - 1;
			   		if (todok > slider_total) {
			   		   todok = slider_total;
			   		}
			   		if (dok == todok) {
						tooltip.innerHTML = 'Dokument: ' + dok;
			   		} else {
						tooltip.innerHTML = 'Dokument: ' + dok + " - " + todok;
					}
				};
				break;
			case 'RegisterSuggestEvent':
				try {
					var patterninput = document.getElementById("pattern");
					addEvent(patterninput,"keyup",RequestSuggest);
				} catch (ex) {
					window.status = "Error in RegisterSuggestEvent";
				}
				break;
			case 'refreshCatalog':
				DDRefresh(Query.base, false);
				break;
			case 'searchReset':
				Query.base = "";
				Query.catalog = "";
				Query.maps = "";
				Query.mapstxt = "";
				Query.mapslvl = "";
			    Query.lastDDUpdate.catalog = "";
			    Query.lastDDUpdate.tastr = "";
			    Query.lastDDUpdate.start = "";
			    searchstate = "NEW";
				break;
			case 'searchResetMA':
				Query.media = "";
				Query.archive = "";
				break;
			case 'suggesthits':
				try {
					if (!SuggestCancel) {
						var divsuggestBox = document.getElementById("suggestBox");
						if (xmlNode.childNodes[i].firstChild.nodeValue > 0) {
							divsuggestBox.style.display = "block";
						} else {
							divsuggestBox.style.display = "none";
						}
					}
				} catch (ex) {
				}
				break;
			case 'displayresultlist':
				var no = xmlNode.childNodes[i].getAttribute("no");
				APSRequest("displayresultlist?no=" + no);
				break;
			case 'displayresultdocument':
				var no = xmlNode.childNodes[i].getAttribute("no");
				APSRequest("displayresultdocument?no=" + no);
				break;
			case 'displayresultdocumentmap':
				var no = xmlNode.childNodes[i].getAttribute("no");
				APSRequest("displayresultdocumentmap?no=" + no);
				break;
			case 'displayresultzoom':
				var no = xmlNode.childNodes[i].getAttribute("no");
				var medium =  xmlNode.childNodes[i].getAttribute("medium");
				APSRequest("displayresultzoom?no=" + no + "&medium=" + medium);
				break;				
			case 'displayresultgalery':
				var no = xmlNode.childNodes[i].getAttribute("no");
				APSRequest("displayresultgalery?no=" + no);
				break;
			case 'displayresultmap':
				var no = xmlNode.childNodes[i].getAttribute("no");
				if (DMode=='map') {
					APSRequest("displayresultmap?no=" + no + "&map=reinit");
				} else {
					APSRequest("displayresultmap?no=" + no + "&map=init");
				}
				break;
			case 'loadCommentStats': {
				
				var doctype = xmlNode.childNodes[i].getAttribute("doctype");
				var docnumber = xmlNode.childNodes[i].getAttribute("docnumber");
				if (doctype && docnumber) {
					loadCommentStats(doctype, docnumber);
				}
				break;
			}	
			case 'scrollTop':
				window.scrollTo(0,0);
				break;
			case 'suggestRefresh':
				var sRtastr = xmlNode.childNodes[i].getAttribute("tastr");
				var sRsuggstart = xmlNode.childNodes[i].getAttribute("suggstart");
				var sRstart = xmlNode.childNodes[i].getAttribute("start");
				var sRsugg20 = xmlNode.childNodes[i].getAttribute("sugg20");
				var sRsuggcmd = xmlNode.childNodes[i].getAttribute("suggcmd");
				var sRmax = xmlNode.childNodes[i].getAttribute("max");
				var sRdir = xmlNode.childNodes[i].getAttribute("dir");
				var sInitialstart = xmlNode.childNodes[i].getAttribute("initialstart");
				APSSuggestNav(sRtastr,sRstart,sRdir,sRsuggstart,sRsugg20,sRsuggcmd,'',sRmax,sInitialstart);				
				break;
			case 'resetDetails':
			    resetDetails();
			    break;
			case 'displayDetail':
				var Detailid= xmlNode.childNodes[i].getAttribute("id");
				toggleDetail(Detailid,'','');
				break;
			case 'checkStatus':
				checkStatus();
				break;
			case 'WKLoadAdresses':
				WKLoadAdresses();
				break;
			case 'WKResetWK':
				WK='';
				WKcmt='';
				updateStatusCookie();
				refreshStatusHeadline();
				break;
			case 'resizeDrillChilds':
				resizeDrillChilds();
				break;
			case 'ExtraMenuSync':
				var path = xmlNode.childNodes[i].getAttribute("path");
				var def = xmlNode.childNodes[i].getAttribute("def");
				ExtraMenuSync(path,def,true);
				break;
			case 'MapInit':
				resizeMap();
				var lat = xmlNode.childNodes[i].getAttribute("lat");
				var lng = xmlNode.childNodes[i].getAttribute("lng");
				var zoom = xmlNode.childNodes[i].getAttribute("zoom");
				var map = xmlNode.childNodes[i].getAttribute("map");
				var lookup = xmlNode.childNodes[i].getAttribute("lookup") == 'true';
				mapinit(lat, lng, zoom, map, lookup);
				if (lookup) {
					maploadmarker();
				}
				break;
			case 'MapAddMarker':
				var lat = xmlNode.childNodes[i].getAttribute("lat");
				var lng = xmlNode.childNodes[i].getAttribute("lng");
				var motxt = xmlNode.childNodes[i].getAttribute("motxt");
				var cc = xmlNode.childNodes[i].getAttribute("colorcode");
				var dynload = xmlNode.childNodes[i].getAttribute("dynload") == 'true';
				var divid = xmlNode.childNodes[i].getAttribute("divid");				
				var des = "";
				if (document.importNode) {
					des = document.importNode(xmlNode.childNodes[i], true).innerHTML;
				} else {
					des = xmlNode.childNodes[i].childNodes[0].xml;
				}
				mapaddmarker(lat,lng,des,motxt,cc,dynload,divid);
				break;
			case 'MapDeleteMarker':
				mapdeletemarker();
				break;
			case 'MapGenerateMarker':
				mapgeneratemarker();
				break;
			case 'MapMarkerOverflow':
				mapmarkeroverflow();
				break;
			case 'SWFObject':
				var soswf = xmlNode.childNodes[i].getAttribute("swf");
				var soid = xmlNode.childNodes[i].getAttribute("id");
				var sowidth = xmlNode.childNodes[i].getAttribute("width");
				var soheight = xmlNode.childNodes[i].getAttribute("height");
				SWFInstance = null;
				SWFInstance = new SWFObject(soswf,soid,sowidth,soheight, "6", "#FFFFFF");
				SWFInstance.addParam("wmode","transparent");
				break;
			case 'SWFObjectAddVariable':
				var sok = xmlNode.childNodes[i].getAttribute("key");
				var sov = xmlNode.childNodes[i].getAttribute("value"); 			
				SWFInstance.addVariable(sok,sov);
				break;
			case 'SWFObjectWrite':
				var t = xmlNode.childNodes[i].getAttribute("target");
				SWFInstance.write(t);
				resizeZoomify();
				break;
			case 'DMode':
				DMode = xmlNode.childNodes[i].getAttribute("mode");
				break;
			case 'message': {
				var sDestId = xmlNode.childNodes[i].getAttribute("destination-id");
				var sMessage =  xmlNode.childNodes[i].textContent;
				if (bb.browser.ie) {
					sMessage = xmlNode.childNodes[i].innerText;
				}
				if (sDestId && sMessage) {
					var targetNode = document.getElementById(sDestId);
					if (targetNode) {
						var sOrgNodeName = targetNode.tagName.toLowerCase();
						targetNode.innerHTML = bb.string.escapeXml(sMessage);
						bb.command.show(targetNode);
					}
				}
				break;
			}
			case 'ReExecPreviousRequest': {
				//Führt den Request aus der VOR DIESEM lief
				var nBackSteps = parseInt(xmlNode.childNodes[i].getAttribute("no"));
				if (nBackSteps > 0) {
					nBacksteps++;
					if (m_apsRequestHistory.length>=nBackSteps) {
						var nPrevReqIndex = m_apsRequestHistory.length - nBackSteps;
						var sPreviousReq = m_apsRequestHistory[nPrevReqIndex]
					APSRequest(sPreviousReq);
				}
				} 
				break;
			}
			case 'init': {
				initAPS();
				break;
			}
			case 'permalink': {
				var sLink = xmlNode.childNodes[i].getAttribute("link");
				setPermaLink(sLink);
				break;
			}
			case 'scaleImages': {
				var maxSideLength = parseInt(xmlNode.childNodes[i].getAttribute("to"));
				var imgNodeName = xmlNode.childNodes[i].getAttribute("name");
				var imgScaleTimeout = xmlNode.childNodes[i].getAttribute("timeout");
				if (ImageScaler) {
					if (maxSideLength > 0 && imgNodeName) {
						ImageScaler.startResizeImagesInterval(imgNodeName, maxSideLength, imgScaleTimeout);
					}
				}
				break;
			}
			case 'modal': {
				var sTitle = xmlNode.childNodes[i].getAttribute("title");
				var sHTML = xmlNode.childNodes[i].innerHTML;
				if (!sHTML) {
					sHTML = bb.xml.serialize(xmlNode.childNodes[i].childNodes[0]);
				}
				var nLeft = parseInt(xmlNode.childNodes[i].getAttribute("left"));
				var nTop = parseInt(xmlNode.childNodes[i].getAttribute("top"));
				var nWidth = parseInt(xmlNode.childNodes[i].getAttribute("width"));
				var nHeight = parseInt(xmlNode.childNodes[i].getAttribute("height"));
				openModal(sTitle, sHTML, nLeft, nTop, nWidth, nHeight);
				break;
			}
			default:
				try {
 					var destContainer = document.getElementById(nodeName);
 					//var importedNode = importNode(xmlNode.childNodes[i],true);
 					var resultContainer = xmlNode.childNodes[i];
					
					// set container visible or hidden
					try {
	 					var visible = resultContainer.attributes.getNamedItem("visible");
	 					showDiv(destContainer, visible);
					} catch (e1) {}

					if (document.importNode) {
						// w3c way over importNode
						destContainer["innerHTML"] = "";
						var importedNode = document.importNode(resultContainer, true);
						while (importedNode.childNodes.length > 0) {
							destContainer.appendChild(importedNode.childNodes[0]);
						}
					} else {
						// old-fashioned HTML way...
						var rcxml=resultContainer.xml.replace(/^<[^<]+>/,'');
						rcxml = rcxml.replace(/<[^<.]+>$/,'');
						destContainer["innerHTML"] = rcxml;
					}
					if (nodeName == 'infotext' && m_strLastInfoRequest!='') {
						setPermaLink(m_strLastInfoRequest);
					}
					if (nodeName == 'infotext') {
						showDiv('browsing', false);
					}
					else if (nodeName == 'result') {
						showDiv('browsing', true);
					}
				} catch (ex) {
					setStatus(nodeName + " nicht gefunden.","","");
				}
//				try {
// 					var divName = document.getElementById(nodeName);
// 					//var importedNode = importNode(xmlNode.childNodes[i],true);
// 					var resultContainer = xmlNode.childNodes[i];
//					divName["innerHTML"] = "";
//					try {
//	 					//var visible = importedNode.attributes.getNamedItem("visible");
//	 					var visible = resultContainer.attributes.getNamedItem("visible");
//	 					showDiv(divName,visible);
//					} catch (e1) {}
////					while (importedNode.childNodes.length > 0) {
////						divName.appendChild(importedNode.childNodes[0]);
////					}
//					for (var j = 0; j < resultContainer.childNodes.length; ++j) {
//						divName.appendChild(importNode(resultContainer.childNodes[j], true));
//					}
//				} catch (e) {
//					setStatus(nodeName + " nicht gefunden.","","");
//				}
				break;
		}
	}
	
	//ExtraMenuSync(url);
	} catch (ex) {
		if (bb) {
			if (bb.console) {
				if (typeof(bb.console.log)=='function') {
					bb.console.log(ex.message);
				}				
			}
		}
	}
}

function setPermaLink(sLink) {
	if (sLink) {
		var oPermaLink = document.getElementById('permalink');
		if (oPermaLink) {
			oPermaLink.innerHTML = '<strong>Permalink: </strong>'+encodeURI(sLink);
			showDiv('permalink', true);
		}
	}
	else {
		showDiv('permalink', false);
	}
}

/**
 * showDiv
 * @param id ID des anzuzeigenden Elements
 * @param {boolean} visible Sichtbarkeit
 */
function showDiv(id,visible) {
	try {
		var divname = document.getElementById(id);
		if (visible) {
			divname.style.display = "block";
		}else {
			divname.style.display = "none";
		}
	} catch (ex) {
	}
	resizeDrillChilds();
}

function showHide(id) {
	try {
		var div = document.getElementById(id);
		if (div.style.display == 'none') {
			showDiv(id, true);
		} else {
			showDiv(id, false);
		}
	}
	catch(ex) {}
}

function toggleResultSection(blkid,headid) {
	var divname = document.getElementById(blkid);
	if (divname.style.display == "none") {
	    divname.style.display = "block";
	} else {
	    divname.style.display = "none";
	}
	var headname = document.getElementById(headid);
	if (headname.className == "expandedHeading") {
	   headname.className = "collapsedHeading";
	} else {
	   headname.className = "expandedHeading";
	}
	resizeDrillChilds();
}

function Bildkarte(imgurl,blkid,headid) {
	var divname = document.getElementById(blkid);
	if (divname.style.display == "none") {
	    divname.style.display = "block";
	    divname.innerHTML = '<img src="' + imgurl + '" onload="resizeDrillChilds()" onerror="this.src=\'images/no-image.jpg\'";/>';
	} else {
	    divname.style.display = "none";
	}
	var headname = document.getElementById(headid);
	if (headname.className == "expandedBildkarte") {
	   headname.className = "collapsedBildkarte";
	} else {
	   headname.className = "expandedBildkarte";
	}
	resizeDrillChilds();
}

/**
 * submitSearch
 * Eine Suche absetzen
 * @param suggestIndex wenn aus Suggest aufgerufen: Indexname
 * @param suggestPattern wenn aus Suggest aufgerufen: Descriptor 
 */
function submitSearch(suggestIndex,suggestPattern) {
	
	// Suggest abschalten
	showDiv("suggestBox",false);
	
	var inputPattern = trim(document.getElementById("pattern").value);
	
	try {
	    document.getElementById("submitButton").disabled = "disabled";
		document.getElementById("selector").disabled = "disabled";
		document.getElementById("pattern").disabled = "disabled";
		document.getElementById("ANDConnector").disabled = "disabled";
		document.getElementById("NANDConnector").disabled = "disabled";
		document.getElementById("NEWQUERY").disabled = "disabled";
	} catch (ex) {}
		
	var inputIndex = document.getElementById("selector").value;
	var opStr = "AND";
	var inputWords = new Array();
	
	inputPattern = trim(inputPattern);
	if (inputIndex == 'freitext' || inputIndex == 'motiv') {
		inputPattern = trim(inputPattern.replace(/[\:\"\'\,]/g,' '));
	}
	if (inputIndex == 'freitext') {
		inputPattern = inputPattern.replace(/(\S+)-(\S+)/g,'$1 $2');
	}
	if (arguments.length == 0) {
		if (inputPattern[0] == '"' ) {
			inputWords[0] = inputPattern;
		} else {
			inputWords = inputPattern.split(/\s/);
		}
	} else {
		inputPattern = suggestPattern;
		inputIndex = suggestIndex;
		inputWords[0] = '"' + inputPattern + '"';
	}
	try {
		if (inputOp = document.getElementById("NANDConnector").checked) {
			opStr = "NOT";
		}
	} catch (ex) {};
	
	try {
		if (document.getElementById("NEWQUERY").checked) {
			Query.base = '';
		    Query.lastDDUpdate.tastr = "";
		    Query.lastDDUpdate.start = "";
		    searchstate = "NEWQUERY";
		}
	} catch (ex) {};
	
	if (searchstate != 'NEW' && searchstate != 'NEWQUERY') {
		var querystring = "";
		for (var i = 0; i < inputWords.length;i++) {
			if (inputWords[i] != "") {
				querystring += " ";
				if (opStr == 'AND') {
					querystring += "+";
				} else {
					querystring += "-";
				}
				if (inputIndex == '_spaeter') {
					querystring +=  "_spaeter>" + escape(inputWords[i]);
				} else if (inputIndex == '_frueher') {
					querystring += "_frueher<" + escape(inputWords[i]);
				} else {
					querystring += inputIndex + ":" + escape(inputWords[i]);
				}
			}
		}
		basequery = escape(Query.base) + " " + querystring;
		querystring = escape(trim(Query.media + " " + Query.archive + " " + Query.maps) + " " ) + basequery + escape(" " + Query.catalog);
		if (querystring != '') {
			APSRequest("searchdefine?query=" + querystring);
		}
	} else {
		var querystring = "";
		for (var i = 0; i < inputWords.length;i++) {
			if (inputWords[i] != "") {
				querystring += " ";
				if (opStr == 'AND') {
					querystring += "+";
				} else {
					querystring += "-";
				}
					if (inputIndex == '_spaeter') {
						querystring +=  "_spaeter>" + escape(inputWords[i]);
					} else if (inputIndex == '_frueher') {
						querystring += "_frueher<" + escape(inputWords[i]);
					} else {
						querystring += inputIndex + ":" + escape(inputWords[i]);
					}
			}
		}
		basequery = escape(Query.base) + " " + querystring;
		querystring = escape(trim(Query.media + " " + Query.archive + " " + Query.maps) + " ") + basequery + escape(" " + Query.catalog);
		if (querystring !='%20 %20') {
			if (searchstate == 'NEW') {
				APSRequest("searchdefine?query=" + querystring);
			} else {
				APSRequest("searchdefinenq?query=" + querystring);
			}
		} else {
			try {
	    		document.getElementById("submitButton").disabled = false;
				document.getElementById("selector").disabled = false;
				document.getElementById("pattern").disabled = false;
				document.getElementById("ANDConnector").disabled = false;
				document.getElementById("NANDConnector").disabled = false;
				document.getElementById("NEWQUERY").disabled = false;
			} catch (ex) {}
		}	
	}
	if (Query.catalog) {
		DDRefresh(basequery,false);
	}
}


/**
 * trim
 * Einen String trimmen
 * @param instr der String
 * @return {string} der getrimmte String
 */
function trim(instr) {
	try {
		var r = instr.replace(/\s+/g," ");
		r = r.replace(/^\s+/,"");
		r = r.replace(/\s+$/,"");
		return r;
	} 
	catch (ex) {
		return '';
	}
}

/**
 * @param nTimeout {Number}
 * @param onTimeoutFunc {function}
 * @return {void}
 */
function initTimeout(nTimeout, onTimeoutFunc) {
	LOG ("initTimeout: " + nTimeout + ", " + onTimeoutFunc);
	m_bLoadTimedout = false;
	m_loadTimeoutRef = window.setTimeout("stopTimeout(true, onTimeoutFunc)", (nTimeout*1000));
}

/**
 * @param bHasTimedout {Boolean} default false
 * @param onTimeoutFunc
 * @return {void}
 */
function stopTimeout(bHasTimedout, onTimeoutFunc) {
	LOG ("stopTimeout: " + bHasTimedout + ", " + onTimeoutFunc);
	if (typeof(bHasTimedout) != 'boolean') {
		bHasTimedout = false;
	}
	m_bLoadTimedout = bHasTimedout;
	if (m_bLoadTimedout) {
		var tofunc = undefined;
		if (typeof(onTimeoutFunc) == 'string') {
			try  {
				tofunc = eval(onTimeoutFunc);
			}
			catch(exNSF) {
				tofunc = undefined;
			}	
		}
		else if (typeof(onTimeoutFunc) == 'function') {
			tofunc = onTimeoutFunc;
		}
		if (typeof(tofunc)=='function') {
			tofunc();
		}
	}
	clearTimeout(m_loadTimeoutRef);
	m_loadTimeoutRef = undefined;
}



function payPageIframeTimedout() {
	LOG("payPageIframeTimedout");
	closeModal();
}


/**
 * APSSuggest
 * Einen Suggest-Request absetzen
 */
 
function RequestSuggest(evt) {

	var keycode;
	
	if (evt.keyIdentifier) {
		keycode = evt.keyIdentifier.toUpperCase();
	}
	else if (evt.keyCode) {
		switch (evt.keyCode) {
			case 13: {
				//enter
				keycode = "ENTER";
				break;
			}
			case 27: {
				//esc
				keycode = "U+001B";
				break;
			}
			case 38: {
				//pfeil runter
				keycode = "DOWN";
				break;
			}
			case 33: {
				//bild rauf
				keycode = "PAGEUP";
				break;
			}
			case 34: {
				//bild runter
				keycode = "PAGEUP";
				break;
			}
			case 35: {
				//ende
				keycode = "END";
				break;
			}
			case 36: {
				//pos1
				keycode = "HOME";
				break;
			}
			case 40: {
				//pfeil hoch
				keycode = "UP";
				break;
			}
		}
	}
	switch (keycode) {
		case "U+001B": // ESC
			showDiv("suggestBox",false);
			return false;
			break;
		case "DOWN": // Down
			showDiv("suggestBox",false);
			return false;
			break;
		case "UP": // Up
			APSSuggest();
			return false;
			break;
		case "HOME": // Pos1
			var but = document.getElementById("SuggA");
			but.onclick();
			return false;
			break;
		case "END": // Ende
			var but = document.getElementById("Sugg4");
			but.onclick();
			return false;
			break;
		case "PAGEUP": // PgUp
			var but = document.getElementById("Sugg2");
			but.onclick();
			return false;
			break;
		case "PAGEDOWN": // PgDw
			var but = document.getElementById("Sugg3");
			but.onclick();
			return false;
			break;
		case 'ENTER': //
			submitSearch();
			return false;
			break;
		default:
			if (suggestTimeout > 0) {
			   clearTimeout(suggestTimeout);
			   suggestTimeout = 0;
			}
			suggestTimeout = setTimeout("APSSuggest()",APSSuggestDelay);
	}
}
function APSSuggest() {

	clearTimeout(suggestTimeout);
	
	var inputPattern = document.getElementById("pattern").value;
	var inputIndex = document.getElementById("selector").value;
	
	inputPattern = trim(inputPattern);
	var inputWords = inputPattern.split(/\s/);
	var basequerystring = "";
	
	if (Query.base||Query.media||Query.archive||Query.catalog) {
		var nq = false;
		try {
			nq = document.getElementById("NEWQUERY").checked;
		} catch (ex) {
			nq = false;
		}
		if (nq) {
		    // basequerystring = Query.media + ' ' + Query.archive + ' ' +  Query.catalog;
			// basequerystring = "&query=" + escape(basequerystring) ;
			basequerystring = "";
		} else {
		    basequerystring = trim(Query.media + ' ' + Query.archive + ' ' + Query.maps + ' ' + Query.base + ' ' + Query.catalog);
			basequerystring = "&query=" + escape(basequerystring) ;
		}
	}
	
	if (inputWords[0] != '') {
		APSRequest("suggest?tastr=" + inputIndex + "&start=" + escape(inputWords[0]) + "&max=20" + basequerystring,2);
	}	
}

/**
 * APSSuggestNav
 * APSSuggest-Navigation
 */
function APSSuggestNav(tastr,start,dir,suggstart,sugg20,suggcmd,thelkuplast,max,query) {
	var req = "suggest?";
	req += "tastr=" + tastr;
	req += "&start=" + escape(start);
	if (dir) {
		req += "&dir=" + dir;
	}
	if (suggstart) {
		req += "&suggstart=" + escape(suggstart);
	}
	if (sugg20) {
		req += "&sugg20=" + escape(sugg20);
	}
	req += "&suggcmd=" + suggcmd;
	if (thelkuplast) {
		req += "&thelkuplast=" + escape(thelkuplast);
	}
	req += "&max=" + max;
	if (query) {
	   req += "&query=" + escape(query);
	}
	APSRequest(req,2);
						
   
}

/**
 * getStyle
 * gibt den berechneten Stylesheetwert zurück
 */
function getStyle(elem, IEStyleProp, CSSStyleProp) {
	if (window.getComputedStyle) {
		var compStyle = window.getComputedStyle(elem, "");
		return compStyle.getPropertyValue(CSSStyleProp);
	} else if (elem.runtimeStyle) {
		return elem.runtimeStyle[IEStyleProp];
	} else if (elem.currentStyle) {
		return elem.currentStyle[IEStyleProp];
	}
	return "";
}

/**
 * resizeDrillChilds
 * Bei Resize das Drilldownmenü anpassen.
 */
function resizeDrillChilds() {
	resizeZoomify();
	resizeMap();
	resizeContent();
	resizeDrillChildsWorker();
	if (DrillChildsTimeout > 0) {
		clearTimeout(DrillChildsTimeout);
		DrillChildsTimeout = 0;
	}
	DrillChildsTimeout = setTimeout("resizeDrillChildsWorker()",DrillChildResizeDelay);
} 

function resizeDrillChildsWorker() {

	clearTimeout(DrillChildsTimeout);
	
	var debug = new Object();
	
	var slublogo = document.getElementById("slublogo");
	var search;
	var drillChilds = document.getElementById("drillChilds");
	if (drillChilds) {
		search = document.getElementById("search");
		if (search) {
			var iUpperHeight = 0;
			var iSlubLogoHeight = 0;
			var iSearchHeight = 0;

			if (slublogo.offsetHeight) {
				iSlubLogoHeight = slublogo.offsetHeight;
			} else if (slublogo.clientHeight) {
				iSlubLogoHeight = slublogo.clientHeight;
			}
			
			if (search.offsetHeight) {
				iSearchHeight = search.offsetHeight;
			} else if (search.clientHeight) {
				iSearchHeight = search.clientHeight;
			}
			
			debug['slublogo'] = iSlubLogoHeight;
			debug['search'] = iSearchHeight;
			
			iUpperHeight = iSlubLogoHeight + iSearchHeight;

			var catalog = document.getElementById("catalog");
			var childs = catalog.childNodes;
			for (var i = 0; i < childs.length; ++i) {
			
				if (childs[i] != drillChilds) {
					var iLiHeight = 0;
					// checking for nodeType == Element
					if (childs[i].nodeType == 1) {
						if (childs[i].offsetHeight) {
							iLiHeight += childs[i].offsetHeight;
						} else if (childs[i].clientHeight) {
							iLiHeight += childs[i].clientHeight;
						}

						debug['catalogLI' + i + "/" + childs[i].className] = iLiHeight;
						iUpperHeight += iLiHeight;
					}
				}
			}
			// 32px abzug, wegen margin von li[@class=capation]
			iUpperHeight += 32;
			var iBodyHeight;
			var browser = BrowserDetect.browser;
			var version = BrowserDetect.version + "";
			if (window.innerHeight) {
				iBodyHeight = window.innerHeight;
			} else if (document.documentElement && document.documentElement.innerHeight){
				iBodyHeight = document.documentElement.innerHeight;
			} else if (document.documentElement && document.documentElement.clientHeight){
				iBodyHeight = document.documentElement.clientHeight;
			} else if (document.body && document.body.clientHeight){
				iBodyHeight = document.body.clientHeight;
			} else if (document.getElementsByTagName("body")[0].clientHeight) {
				iBodyHeight = document.getElementsByTagName("body")[0].clientHeight;
			}

			if ( browser == "Explorer" && version.indexOf('5') != -1) {
				iUpperHeight -= 39; //IE5
			}

			if (browser == "Explorer" && version.indexOf('6') != -1) {
				iUpperHeight -= 11; //IE6
			}

			if (browser == "Explorer" && version.indexOf('7') != -1) {
				iUpperHeight -= 24; //IE7
				//window.status = iBodyHeight;
				//iBodyHeight -= 20;
			}

			drillChilds.style.top = iUpperHeight + "px";
			var iNewHeight = iBodyHeight - iUpperHeight;
			
			if (browser == "Explorer" && BrowserDetect.version < 7) {
				var structure = document.getElementById("structure");
				iStructureHeight = structure.clientHeight;
				iStructureOffsetY = parseInt(getStyle(structure, "top", "top"));
				iNewHeight = iStructureHeight + iStructureOffsetY - iUpperHeight;
			}

			if (browser == "XXXExplorer" && BrowserDetect.version == 7) {
				drillChilds.style.bottom = "0";
				// IE7 Bug: es gibt keine Client Height;
				// Falsch: document.documentElement.clientHeight 
//				iNewHeight -= 40;
			} else {
			
				try {
					drillChilds.style.height = iNewHeight + "px";
				} catch(ex) {
					
				}
				
			}
			
//			var sDebug = "";
//			for (p in debug) {
//				sDebug += p + ": " + debug[p] + "\n";
//			}
//			alert(sDebug);
		}
	}
}
window.onresize = resizeDrillChilds;

// The constructor function: creates a cookie object for the specified
// document, with a specified name and optional attributes.
// Arguments:
//   document: The Document object that the cookie is stored for. Required.
//   name:     A string that specifies a name for the cookie. Required.
//   hours:    An optional number that specifies the number of hours from now
//             that the cookie should expire.
//   path:     An optional string that specifies the cookie path attribute.
//   domain:   An optional string that specifies the cookie domain attribute.
//   secure:   An optional Boolean value that, if true, requests a secure cookie.
//
function Cookie(document, name, hours, path, domain, secure)
{
    // All the predefined properties of this object begin with '$'
    // to distinguish them from other properties which are the values to
    // be stored in the cookie.
    this.$document = document;
    this.$name = name;
    if (hours)
        this.$expiration = new Date((new Date()).getTime() + hours*3600000);
    else this.$expiration = null;
    if (path) this.$path = path; else this.$path = null;
    if (domain) this.$domain = domain; else this.$domain = null;
    if (secure) this.$secure = true; else this.$secure = false;
}

// This function is the store() method of the Cookie object.
Cookie.prototype.store = function () {
    // First, loop through the properties of the Cookie object and
    // put together the value of the cookie. Since cookies use the
    // equals sign and semicolons as separators, we'll use colons
    // and ampersands for the individual state variables we store 
    // within a single cookie value. Note that we escape the value
    // of each state variable, in case it contains punctuation or other
    // illegal characters.
    var cookieval = "";
    for(var prop in this) {
        // Ignore properties with names that begin with '$' and also methods.
        if ((prop.charAt(0) == '$') || ((typeof this[prop]) == 'function')) 
            continue;
        if (cookieval != "") cookieval += '&';
        cookieval += prop + ':' + escape(this[prop]);
    }

    // Now that we have the value of the cookie, put together the 
    // complete cookie string, which includes the name and the various
    // attributes specified when the Cookie object was created.
    var cookie = this.$name + '=' + cookieval;
    if (this.$expiration)
        cookie += '; expires=' + this.$expiration.toGMTString();
    if (this.$path) cookie += '; path=' + this.$path;
    if (this.$domain) cookie += '; domain=' + this.$domain;
    if (this.$secure) cookie += '; secure';

    // Now store the cookie by setting the magic Document.cookie property.
    this.$document.cookie = cookie;
};

// This function is the load() method of the Cookie object.
Cookie.prototype.load = function() { 
    // First, get a list of all cookies that pertain to this document.
    // We do this by reading the magic Document.cookie property.
    var allcookies = this.$document.cookie;
    if (allcookies == "") return false;

    // Now extract just the named cookie from that list.
    var start = allcookies.indexOf(this.$name + '=');
    if (start == -1) return false;   // Cookie not defined for this page.
    start += this.$name.length + 1;  // Skip name and equals sign.
    var end = allcookies.indexOf(';', start);
    if (end == -1) end = allcookies.length;
    var cookieval = allcookies.substring(start, end);

    // Now that we've extracted the value of the named cookie, we've
    // got to break that value down into individual state variable 
    // names and values. The name/value pairs are separated from each
    // other by ampersands, and the individual names and values are
    // separated from each other by colons. We use the split method
    // to parse everything.
    var a = cookieval.split('&');    // Break it into array of name/value pairs.
    for(var i=0; i < a.length; i++)  // Break each pair into an array.
        a[i] = a[i].split(':');

    // Now that we've parsed the cookie value, set all the names and values
    // of the state variables in this Cookie object. Note that we unescape()
    // the property value, because we called escape() when we stored it.
    for(var i = 0; i < a.length; i++) {
        this[a[i][0]] = unescape(a[i][1]);
    }

    // We're done, so return the success code.
    return true;
};

// This function is the remove() method of the Cookie object.
Cookie.prototype.remove = function() {
    var cookie;
    cookie = this.$name + '=';
    if (this.$path) cookie += '; path=' + this.$path;
    if (this.$domain) cookie += '; domain=' + this.$domain;
    cookie += '; expires=Fri, 02-Jan-1970 00:00:00 GMT';

    this.$document.cookie = cookie;
};

function DDSelect(catalog,tastr,start) {
   DDUpdate(catalog,tastr,start,'');
}

function DDUpdate(catalog,tastr,start,catalogquery) {
   var DDsearch = "";
   var DDthequery = "";
   if (Query.base || catalogquery) {
      if (!catalogquery) {catalogquery="";};
       var dt = ""; 
	   if (catalog == 'KUNSTLER') {
   			dt = " +xdbdoctype:kue";
   		}
      DDthequery = escape(trim(Query.media + " " + Query.maps + " " + Query.base) + " ") + catalogquery + dt;
      DDsearch = escape(Query.base) + " " + catalogquery;
   }
   Query.catalog = unescape(catalogquery);
   Query.lastDDUpdate.catalog = catalog;
   Query.lastDDUpdate.tastr = tastr;
   Query.lastDDUpdate.start = start;
   if (tastr != '') {
	   APSRequest('catalognavigate?:katalog=' + catalog + '&tastr=' + tastr + '&dir=exact&start=' + start + "&query=" + DDthequery,2);
   }
   DDsubmitSearch(DDsearch);   
}

function DDRefresh(basequery,sh) {
	var catalog = Query.lastDDUpdate.catalog;
   	var tastr = Query.lastDDUpdate.tastr;
   	var start = Query.lastDDUpdate.start;
   	var dt = "";
   	var thequery = '' 
	if (catalog == 'KUNSTLER') {
   		dt = " +xdbdoctype:kue";
	}
	if (sh) {
		thequery = "&" + basequery;
	} else {
		if (Query.catalog || Query.media) {
			thequery = escape(Query.media) + " " + escape(Query.maps) + " " + basequery + " " + escape(Query.catalog);
   		}
	}
	thequery = escape(unescape(thequery).replace(/\:/g, '!'));
	APSRequest('catalognavigate?:katalog=' + catalog + '&tastr=' + tastr + '&start=' + start + "&query=" + thequery + dt,2);
}   

function DDReset() {
	Query.catalog = "";
	Query.lastDDUpdate.catalog = "";
    Query.lastDDUpdate.tastr = "";
    Query.lastDDUpdate.start = "";
}

function DDResetCatalog() {
	Query.catalog='';
	APSRequest('cataloglist',2);
	if (Query.base) {
		APSRequest("searchdefine?query=" + escape(Query.base) + "&:katalog=NONE");
	} else {
		APSRequest("searchreset?:katalog=NONE");
	}
}

function DDsubmitSearch(querystring) {
    if (querystring) {
		// APSRequest("searchdefine?query=" + querystring);
		APSRequest("searchdefine?query=" + escape(unescape(querystring).replace(/(\S)\:(\S)/g, '$1!$2')));
	}
}

function CatalogSelect(id,tastr,catalogquery) {
	Query.archive = '';
	Query.archiveID = '';
	Query.media = '';
	Query.mediaID = '';
	
    var dquery = '';
    var wquery= '';
    if (Query.base) {
    	wquery = "&query=" + escape(Query.base);
	   	dquery = escape(Query.base);
    }
    
    Query.lastDDUpdate.catalog = id;
    Query.lastDDUpdate.tastr = tastr;
    Query.lastDDUpdate.start = "*";
	APSRequest('catalogselect?media=ALL&archiv=NONE&:katalog=' + id + '&start=*&tastr=' + tastr + wquery);
    Query.catalog = catalogquery;	

    // Einführungstext anzeigen, ansonsten Query nachladen.
    if (Query.base != '') {
	    DDsubmitSearch(dquery + escape(' ') + escape(catalogquery));
	}
}

if (!Array.xpush) {
	Array.prototype.xpush = function(elem) {
		this[this.length++] = elem;
	};
}

function ProcessBar(sInstance) {
	this.instance = sInstance;

	// settings
	this.width = 200;
	this.tdwidth = 3;
	this.height = 8;
	this.speed = 35;
	this.quality = 30;
	this.borderColor = '#000';
	this.startColor = '#FFFFFF';
	this.middleColor = '#5aa9ef';
	this.container;
	this.stoploop = true;

	// Fill colors array
	this.colors = new Array(this.startColor);
	nr = scr = parseInt("0x"+this.startColor.slice(1, 3));
	ng = scg = parseInt("0x"+this.startColor.slice(3, 5));
	nb = scb = parseInt("0x"+this.startColor.slice(5, 7));
	mcr = parseInt("0x"+this.middleColor.slice(1, 3));
	mcg = parseInt("0x"+this.middleColor.slice(3, 5));
	mcb = parseInt("0x"+this.middleColor.slice(5, 7));

	sr = Math.floor((mcr - scr) / (this.quality - 1));
	sg = Math.floor((mcg - scg) / (this.quality - 1));
	sb = Math.floor((mcb - scb) / (this.quality - 1));

	for (var i = 0; i < this.quality; ++i) {
		nr += sr;
		ng += sg;
		nb += sb;

		this.colors.xpush("#" + nr.toString(16) + ng.toString(16) + nb.toString(16));
	}

	for (var i = this.colors.length; i >= 0; --i) {
		this.colors.xpush(this.colors[i]);
	}

	// runtime vars
	this.tds = Math.floor(this.width / this.tdwidth);
	this.ca = this.colors.length;
	this.loops = this.ca;

	this.init = function() {
		this.build();
		this.loop();
	};

	this.build = function() {
		// build table
		var table;
		table = '<table align="center" style="height: '+this.height+'px; border: 1px solid '+this.borderColor+'" cellspacing="0" cellpadding="0"><tr>';
		for (var i = 1; i <= this.tds; ++i)	{
			table += "<td id='t["+i+"]' style='height: "+this.height+"px; width: "+this.tdwidth+"px'><\/td>";
		}
		table += "<\/tr><\/table>";

		this.container.innerHTML = table;
	};
	
	this.loop = function() {
		var apos = 0;
	    for (var i = this.loops - this.ca; i <= this.loops; ++i) {
			var pos = i;
			if( i <= 0 ) {
				pos = this.tds + i;
			}

			document.getElementById('t['+pos+']').style.backgroundColor = this.colors[apos];

			apos++;
	    }
	    this.loops++;

	    if( this.loops == this.tds ) {
			this.loops = 0;
	    }
	    
	    if (this.stoploop) {
	    	this.stoploop = false;
	    } else {
	       window.setTimeout(this.instance + ".loop()", this.speed);
	    } 
	};
}


var BrowserDetect = {
	init: function () {
		this.browser = this.searchString(this.dataBrowser) || "An unknown browser";
		this.version = this.searchVersion(navigator.userAgent)
			|| this.searchVersion(navigator.appVersion)
			|| "an unknown version";
		this.OS = this.searchString(this.dataOS) || "an unknown OS";
	},
	searchString: function (data) {
		for (var i=0;i<data.length;i++)	{
			var dataString = data[i].string;
			var dataProp = data[i].prop;
			this.versionSearchString = data[i].versionSearch || data[i].identity;
			if (dataString) {
				if (dataString.indexOf(data[i].subString) != -1)
					return data[i].identity;
			}
			else if (dataProp)
				return data[i].identity;
		}
	},
	searchVersion: function (dataString) {
		var index = dataString.indexOf(this.versionSearchString);
		if (index == -1) return;
		return parseFloat(dataString.substring(index+this.versionSearchString.length+1));
	},
	dataBrowser: [
		{ 	string: navigator.userAgent,
			subString: "OmniWeb",
			versionSearch: "OmniWeb/",
			identity: "OmniWeb"
		},
		{
			string: navigator.vendor,
			subString: "Apple",
			identity: "Safari"
		},
		{
			prop: window.opera,
			identity: "Opera"
		},
		{
			string: navigator.vendor,
			subString: "iCab",
			identity: "iCab"
		},
		{
			string: navigator.vendor,
			subString: "KDE",
			identity: "Konqueror"
		},
		{
			string: navigator.userAgent,
			subString: "Firefox",
			identity: "Firefox"
		},
		{
			string: navigator.vendor,
			subString: "Camino",
			identity: "Camino"
		},
		{		// for newer Netscapes (6+)
			string: navigator.userAgent,
			subString: "Netscape",
			identity: "Netscape"
		},
		{
			string: navigator.userAgent,
			subString: "MSIE",
			identity: "Explorer",
			versionSearch: "MSIE"
		},
		{
			string: navigator.userAgent,
			subString: "Gecko",
			identity: "Mozilla",
			versionSearch: "rv"
		},
		{ 		// for older Netscapes (4-)
			string: navigator.userAgent,
			subString: "Mozilla",
			identity: "Netscape",
			versionSearch: "Mozilla"
		}
	],
	dataOS : [
		{
			string: navigator.platform,
			subString: "Win",
			identity: "Windows"
		},
		{
			string: navigator.platform,
			subString: "Mac",
			identity: "Mac"
		},
		{
			string: navigator.platform,
			subString: "Linux",
			identity: "Linux"
		}
	]

};
BrowserDetect.init();

var debug = "";
function importNode(node, allChildren) {
	//alert(node);
//	return;
	debug += ".";	
	if (document.importNode) {
		//alert("Returning");
		return document.importNode(node, allChildren);
	} else {
		debug += "[" + node.nodeType + "]";
		switch (node.nodeType) {
			case 1: /* NODE_ELEMENT */
				var newNode = document.createElement(node.nodeName);
				/* does the node have any attributes to add? */
				if (node.attributes && node.attributes.length > 0) {
					for (var i = 0, il = node.attributes.length; i < il; ++i) {
						var nodeName = node.attributes[i].nodeName;
						var nodeValue = node.getAttribute(node.attributes[i].nodeName);
						/* if attrib is an eventhandler -> register event */
						if (nodeName.indexOf("on") == 0) {
							var sEvent = nodeName.replace(/^on/,'');
								debug += nodeName + ":" + nodeValue + "(" + sEvent + ")\n";
							
							//addEvent(newNode, sEvent, function(ex) {
								// pass the event reference to the window object
//								window.e = e;
//								eval(nodeValue);
 //							});
						}
						
						/* anyway add the attrib */
						else {
							newNode.setAttribute(nodeName, "\""+nodeValue+"\"");
						}
					}
				}

				/* are we going after children too, and does the node have any? */
				if (allChildren && node.childNodes && node.childNodes.length > 0) {
					var il = node.childNodes.length;
					for (var i = 0; i < il; ++i) {
						newNode.appendChild(importNode(node.childNodes[i], allChildren));
					}
				}
				return newNode;
				break;
	
			case 3: /* NODE_TEXT */
			case 4: /* NODE_CDATA_SECTION */
				return document.createTextNode(node.nodeValue);
				break;
		}
	}
	alert(debug);
	debug="";
}

function resetDetails() {
   Details = new Object;
}
function toggleDetail(divid,tastr,tdesc) {
	if (!Details[divid]) {
	   APSRequest('detail?tastr=' + tastr + '&tdesc=' + tdesc + '&no=1&divid=' + divid);
	   Details[divid] = "hidden";
	   return;
	} else if (Details[divid] == "hidden") {	
		Details[divid] = "visible";
		showDiv(divid,true);
	} else {
		Details[divid] = "hidden";
		showDiv(divid,false);
	}
	resizeDrillChilds();
}

/****
*
* Lichtpult & Warenkorb
*****/

function toggleStatus(collection,picture) {
	if (collection == "LP") {
		CollectionVar = LP;
		divname = "LP" + picture;
		activepicture = "images/img_addtoportfolio_active.gif";
		activetitle = "Bild/Medium aus dem Lichtpult entfernen";
		inactivepicture = "images/img_addtoportfolio.gif";
		inactivetitle = "Bild/Medium dem Lichtpult hinzufügen";
	} else {
		CollectionVar = WK;
		divname = "WK" + picture;
		activepicture = "images/img_buy_active.gif";
		activetitle = "Bild/Medium aus dem Warenkorb entfernen";
		inactivepicture = "images/img_buy.gif";
		inactivetitle = "Bild/Medium dem Warenkorb hinzufügen";
	}
	div = document.getElementById(divname);
	
	if (CollectionVar.indexOf(picture) < 0) {
	   div.src = activepicture;
	   div.title = activetitle;
	   if (CollectionVar != "") {
	      CollectionVar += "|";
	   }
	   CollectionVar += picture;
	} else {
	   div.src = inactivepicture;
	   div.title = inactivetitle;
	   if (CollectionVar.indexOf(picture) >= 0) {
		   c = CollectionVar.substring(0,CollectionVar.indexOf(picture) - 1) + CollectionVar.substring(CollectionVar.indexOf(picture) + picture.length,CollectionVar.length);
		   CollectionVar = c;
		   CollectionVar = CollectionVar.replace(/\|\|/g,"|");
		   if (CollectionVar === "|") {
				CollectionVar = "";
		   }
		   if (CollectionVar.indexOf("|") == 0) {
		      CollectionVar = CollectionVar.substring(1,CollectionVar.length);
		   }
	   }
	}
	
	if (collection == "LP") {
		LP = CollectionVar;
	} else {
		WK = CollectionVar;
	}
	
	updateStatusCookie();
	refreshStatusHeadline();
}

function checkStatus() {
	var LPpictures = new Array;
	var WKpictures = new Array;

		
	LPpictures = LP.split("|");
	WKpictures = WK.replace(/\[\d,\d,\d,\d\]/g,'').split("|");
	
	activepicture = "images/img_addtoportfolio_active.gif";
	activetitle = "Bild/Medium aus dem Lichtpult entfernen";
	for (var i= 0; i<LPpictures.length;i++) {
	    if (LPpictures[i] != "") {
		    divname = "LP" + LPpictures[i];
		    try {
	    	   div = document.getElementById(divname);
		       div.src = activepicture;
		       div.title = activetitle;
		    } catch (ex) {};
		}
	}
	
	activepicture = "images/img_buy_active.gif";
	activetitle = "Bild/Medium aus dem Warenkorb entfernen";
	for (var i= 0; i<WKpictures.length;i++) {
	    if (WKpictures[i] != "") {
		    divname = "WK" + WKpictures[i];
		    try {
	    	   div = document.getElementById(divname);
		       div.src = activepicture;
		       div.title = activetitle;
		    } catch (ex) {
	    	};
	    }
	}
}

function updateStatusCookie() {
	var nextYear = new Date();
	nextYear.setFullYear(nextYear.getFullYear() + 1);
	document.cookie = trim("WK=" + WK + ";expires=" + nextYear.toGMTString());
	document.cookie = trim("LP=" + LP + ";expires=" + nextYear.toGMTString());
	if (WKOrderPersistent) {
		document.cookie = trim("WKOrder=" + escape(WKOrder) + ";expires=" + nextYear.toGMTString());
	} else {
		document.cookie = trim("WKOrder=" + escape(WKOrder));
	}
	var WKcmttmp = WKcmt.replace(/\x0A/g,"$!$");
	document.cookie = "WKcmt=" + escape(trim(WKcmttmp));
	document.cookie = "WKPaymentMethod=" + WKPaymentMethod;
}

function initializeStatusfromCookie() {
	var allCookies = document.cookie;
	var cArray = allCookies.split(";");
	LP = "";
	WK = "";
	WKOrder = "";
	WKcmt = "";
	WKPaymentMethod = "";
	
	for (var i = 0; i < cArray.length; i++) {
		var ts = trim(cArray[i]);
		if (ts.indexOf("LP=") == 0) {
			LP = ts.substring(3,ts.length);
		} else if (ts.indexOf("WK=") == 0) {
			WK = ts.substring(3,ts.length);
		} else if (ts.indexOf("WKOrder=") == 0) {
			WKOrder = unescape(ts.substring(8,ts.length));
		} else if (ts.indexOf("WKPaymentMethod=") == 0) {
			WKPaymentMethod = ts.substring(16,ts.length);
		}
	}
	refreshStatusHeadline();
}

function refreshStatusHeadline() {
	var l = document.getElementById("lichtpult");
	var w = document.getElementById("warenkorb");
	
	var lc = 0;
	var wc = 0;
	
	if (LP.length > 5) {
		lc = LP.split("|").length;
	}
	if (WK.length > 5) {
		wc = WK.split("|").length;
	}
	
	l.innerHTML = "Lichtpult (" + lc + ")";
	w.innerHTML = "Warenkorb (" + wc + ")";
}

function ResetCollection(col) {
	if (col=='LP') {
	   LP = "";
	} else if (col=='WK') {
	   WK = "";
	}
	updateStatusCookie();
	refreshStatusHeadline();
	if (col=='LP') {
	   APSRequest("displaylichtpult?LP=");
	} else if (col=='WK') {
		APSRequest("warenkorb?WK=");
	}
}

function WKapplySettings() {
	var WKpictures = WK.replace(/\[\d,\d,\d,\d\]/g,'').split("|");
	var divno = document.getElementById("WKno"+WKpictures[0]).value;
	var divproduct = document.getElementById("WKproduct"+WKpictures[0]).value;
	var divformat = 1;
	try {
		divformat = document.getElementById("WKformat"+WKpictures[0]).value;
	} catch (ex) {
	}
	var divusage = document.getElementById("WKusage"+WKpictures[0]).value;
	for (var i = 1; i < WKpictures.length; i++) {
		try {
			document.getElementById("WKno"+WKpictures[i]).value = divno;	
			document.getElementById("WKproduct"+WKpictures[i]).value = divproduct;
			document.getElementById("WKusage"+WKpictures[i]).value = divusage;
			document.getElementById("WKformat"+WKpictures[i]).value = divformat;
		} catch (ex) {
		}
	}
}
function saveWarenkorb(step) {
	if (step<=1) {
		var WKpictures = WK.replace(/\[\d,\d,\d,\d\]/g,'').split("|");
		WK = "";	
		for (var i = 0; i < WKpictures.length; i++) {
			var divno 		= document.getElementById("WKno"+WKpictures[i]).value;
			var divproduct 	= document.getElementById("WKproduct"+WKpictures[i]).value;
			var divformat = 1;
			try {
				divformat = document.getElementById("WKformat"+WKpictures[i]).value;
			} catch (ex) {
				divformat = 1;
			}
			var divusage 	= document.getElementById("WKusage"+WKpictures[i]).value;
			WKpictures[i] += "[" + divno + "," + divproduct + "," + divformat + "," + divusage + "]";
			if (divno > 0) {
				if (WK != '') {
					WK += "|";
				}
				WK += WKpictures[i];
			}
		}
		updateStatusCookie();
		refreshStatusHeadline();
		if (step==1) {
			APSRequest('warenkorb');
		}
	} else if (step==2) {
		WKSaveAdresses();
		updateStatusCookie();
		APSRequest('warenkorb?step=2');
	}
}

function checkoutWarenkorb() {
	/* 1. Alle WK Elemente abfragen
		2. Neuen WK Cookie setzen
		3. Step 2 aufrufen
		Wichtig: Alle Bestellangaben haben definitive IDs
	*/
	saveWarenkorb(0);
	APSRequest('warenkorb?step=2');
}

function reloadStep1() {
	saveWarenkorb(0);
	APSRequest('warenkorb?step=1');
}


function wkGetSelectedPaymentMethod() {
	var sPaymentMethod = '';
	var radioBoxes = document.getElementsByName('wkPayType');
	for (var i=0; i<radioBoxes.length; i++) {
		if (radioBoxes[i].checked === true) {
			sPaymentMethod = radioBoxes[i].value;
			break;
		}
	}
	return sPaymentMethod;
}

function onPaymentMethodSelect() {
	var sPaymentMethod = wkGetSelectedPaymentMethod();
	switch(sPaymentMethod) {
		case 'invoice': {
			//ADF-292 Hinweis vorläufig entfernen
			setInnerHTML("checkPaymentMethodFeedback"/*, "<small><strong>Bitte beachten:</strong><br/>Die Zahlungsart \"Lieferung auf Rechung\" steht nur registrierten Firmenkunden der Deutschen Fotothek zur Verfügung.</small>"*/);
			break;
		}
		default: {
			setInnerHTML("checkPaymentMethodFeedback");
		}
	}
}

function setInnerHTML(sId, sHTML) {
	var container = document.getElementById(sId);
	if (container) {
		if (typeof(sHTML)!='string') {
			sHTML = ' ';
		}
		else if(sHTML.length == 0) {
			sHTML = ' ';
		}
		container.innerHTML = sHTML;
	}
	
}

function checkOrder() {
	var res = "";
	var es = document.getElementById("WKname1");
	if (trim(es.value) == '') {
		res += "Vorname";
	}
	es = document.getElementById("WKname2");
	if (trim(es.value) == '') {
		if (res != '') res += ', ';
		res += "Nachname";
	}
	es = document.getElementById("WKadr2");
	if (trim(es.value) == '') {
		if (res != '') res += ', ';
		res += "Anschrift";
	}
	es = document.getElementById("WKplzort");
	if (trim(es.value) == '') {
		if (res != '') res += ', ';
		res += "Postleitzahl & Ort";
	}
	es = document.getElementById("WKtel");
	if (trim(es.value) == '') {
		if (res != '') res += ', ';
		res += "Telefon (wird nur für Rückfragen verwendet)";
	}
	es = document.getElementById("WKemail");
	if (trim(es.value) == '' || es.value.length < 8 || es.value.indexOf('@') < 1 || es.value.indexOf('.') < 1) {
		if (res != '') res += ', ';
		res += "E-Mail";
	}
	email = es.value;
	var cbxPayType = document.getElementsByName('wkPayType');
	if (cbxPayType) {
		if (cbxPayType.length > 0) {
			var sPaymentMethod = wkGetSelectedPaymentMethod();
			if (trim(sPaymentMethod) == '') {
				if (res != '') res += ', ';
				res += "Zahlungsart";
			}
		}
	}
	if (document.getElementById("WKCbx1").checked) {
		var es = document.getElementById("WKREname1");
		if (trim(es.value) == '') {
			if (res != '') res += ', ';
			res += "Name (Rechnungsanschrift)";
		}
		es = document.getElementById("WKREadr2");
		if (trim(es.value) == '') {
			if (res != '') res += ', ';
			res += "Anschrift (Rechnungsanschrift)";
		}	
		es = document.getElementById("WKREplzort");
		if (trim(es.value) == '') {
			if (res != '') res += ', ';
			res += "Postleitzahl & Ort (Rechnungsanschrift)";
		}	
	}
	if (res == '') {
		document.getElementById("checkOrderFeedback").innerHTML = "";
		WKSaveAdresses();
		APSRequest('warenkorb?step=3&:orderemail=' + escape(email) + '&:paymentMethod=' + escape(sPaymentMethod));
	} else {
		document.getElementById("checkOrderFeedback").innerHTML = "Bitte prüfen Sie folgende Angaben: " + res + ".";
	}
	
	
	/*			 document.getElementById("WKname2").value + '|' +
			  	 document.getElementById("WKadr1").value  + '|' +
     			 document.getElementById("WKadr2").value  + '|' +
				 document.getElementById("WKadr3").value + '|' +
				 document.getElementById("WKplzort").value + '|' +
				 document.getElementById("WKland").value + '|' +
				 document.getElementById("WKtel").value + '|' +
				 document.getElementById("WKemail").value + '|' +
				 document.getElementById("WKREname1").value + '|' +
				 document.getElementById("WKREname2").value + '|' +
				 document.getElementById("WKREadr1").value + '|' +
				 document.getElementById("WKREadr2").value + '|' +
				 document.getElementById("WKREadr3").value + '|' +
				 document.getElementById("WKREplzort").value + '|' +
				 document.getElementById("WKREland").value + '|' +
				 document.getElementById("WKREtel").value + '|' +
				 document.getElementById("WKREemail").value + '|';
	*/
};

function WKtoggleAnschriften(adressdifferent) {
	var headingLI=document.getElementById("WKLI");
	var cbx1 = document.getElementById("WKCbx1");
	cbx1.checked = adressdifferent;
	if (adressdifferent) {
		headingLI.innerHTML = "Lieferanschrift";
		document.getElementById("WKRE").style.display = "block";
		document.getElementById("WKRE1").style.display = "block";
		document.getElementById("WKRE1b").style.display = "block";
		document.getElementById("WKRE2").style.display = "block";
		document.getElementById("WKRE2b").style.display = "block";
		document.getElementById("WKRE3").style.display = "block";
		document.getElementById("WKRE4").style.display = "block";
		document.getElementById("WKRE5").style.display = "block";
		document.getElementById("WKRE6").style.display = "block";
		document.getElementById("WKRE7").style.display = "block";
	} else {
		headingLI.innerHTML = "Liefer- und Rechnungsanschrift";
		document.getElementById("WKRE").style.display = "none";
		document.getElementById("WKRE1").style.display = "none";
		document.getElementById("WKRE1b").style.display = "none";
		document.getElementById("WKRE2").style.display = "none";
		document.getElementById("WKRE2b").style.display = "none";
		document.getElementById("WKRE3").style.display = "none";
		document.getElementById("WKRE4").style.display = "none";
		document.getElementById("WKRE5").style.display = "none";
		document.getElementById("WKRE6").style.display = "none";
		document.getElementById("WKRE7").style.display = "none";
	}

}

function WKLoadAdresses() {
	var t = WKOrder.split('|');
	if (t.length != 22) {
	   return -1;
	}
	document.getElementById("WKname1").value = t[0];
	document.getElementById("WKname2").value = t[1];
	document.getElementById("WKadr1").value = t[2];
	document.getElementById("WKadr2").value = t[3];
	document.getElementById("WKadr3").value = t[4];
	document.getElementById("WKplzort").value = t[5];
	document.getElementById("WKland").value = t[6];
	document.getElementById("WKtel").value = t[7];
	document.getElementById("WKfax").value = t[8];
	document.getElementById("WKemail").value = t[9];
	document.getElementById("WKREname1").value = t[10];
	document.getElementById("WKREname2").value = t[11];
	document.getElementById("WKREadr1").value = t[12];
	document.getElementById("WKREadr2").value = t[13];
	document.getElementById("WKREadr3").value = t[14];
	document.getElementById("WKREplzort").value = t[15];
	document.getElementById("WKREland").value = t[16];
	document.getElementById("WKREtel").value = t[17];
	document.getElementById("WKREfax").value = t[18];
	document.getElementById("WKREemail").value = t[19];
	WKOrderPersistent = t[20]=='1';
	document.getElementById("WKCbx2").checked = WKOrderPersistent;
	WKOrderDifferent = t[21]=='1';
	document.getElementById("WKCbx1").checked = WKOrderDifferent;
    document.getElementById("WKcmt").value = WKcmt;
	WKtoggleAnschriften(WKOrderDifferent);
	wkSetPaymentMethod(WKPaymentMethod);
}

function wkSetPaymentMethod(sMethod) {
	if (typeof(sMethod)=='string') {
		if (sMethod.length > 0) {
			var radioBoxes = document.getElementsByName('wkPayType');
			for (var i=0; i<radioBoxes.length; i++) {
				if (radioBoxes[i].value == sMethod) {
					radioBoxes[i].checked = true;
					onPaymentMethodSelect();
					break;
				}
			}
		}
	}
}

function WKSaveAdresses() {
	var result = document.getElementById("WKname1").value + '|' + 
				 document.getElementById("WKname2").value + '|' +
			  	 document.getElementById("WKadr1").value  + '|' +
     			 document.getElementById("WKadr2").value  + '|' +
				 document.getElementById("WKadr3").value + '|' +
				 document.getElementById("WKplzort").value + '|' +
				 document.getElementById("WKland").value + '|' +
				 document.getElementById("WKtel").value + '|' +
				 document.getElementById("WKfax").value + '|' +
				 document.getElementById("WKemail").value + '|' +
				 document.getElementById("WKREname1").value + '|' +
				 document.getElementById("WKREname2").value + '|' +
				 document.getElementById("WKREadr1").value + '|' +
				 document.getElementById("WKREadr2").value + '|' +
				 document.getElementById("WKREadr3").value + '|' +
				 document.getElementById("WKREplzort").value + '|' +
				 document.getElementById("WKREland").value + '|' +
				 document.getElementById("WKREtel").value + '|' +
				 document.getElementById("WKREfax").value + '|' +
				 document.getElementById("WKREemail").value + '|';
    if (document.getElementById("WKCbx2").checked) {
    	result += '1|';
    	WKOrderPersistent = true;
    } else {
    	result += '0|';
    	WKOrderPersistent = false;
    }
    if (document.getElementById("WKCbx1").checked) {
    	result += '1';
    	WKOrderDifferent = true;
    } else {
    	result += '0';
    	WKOrderDifferent = false;
    }
    WKOrder = result;
    WKcmt = document.getElementById("WKcmt").value;
    WKPaymentMethod = wkGetSelectedPaymentMethod();
	updateStatusCookie();
}



function CreateBookmarkLink(strTitle, strURL) {
        if (bb.browser.gecko) { 
        // Mozilla Bookmark
        window.sidebar.addPanel(strTitle, strURL,"");
    } 
    else if(bb.browser.ie) { 
        // IE Favorite
        window.external.AddFavorite( strURL, strTitle); 
    }
    else if(bb.browser.opera) { 
        // Opera Hotlist
        var mbm = document.createElement('a');
        mbm.setAttribute('rel','sidebar');
        mbm.setAttribute('href',strURL);
        mbm.setAttribute('title',strTitle);
        mbm.click();
    }
}
function ExtraMenuStart(fn) {
	if (!ExtraMenu) {
		if (typeof(fn)!='string') {
			fn = "extramenu.def";
		}
		ExtraMenuLoad(fn);
	}
	var InfoSection = document.getElementById("infomenu");
	
	var InfoHTMLStart = '<h4><a href="javascript:void(0)" onclick="ExtraMenuSelect(\'0.\');">' + ExtraMenu.Text["0."] + '</a></h4><ul>';
	var InfoHTMLMiddle = '';
	var InfoHTMLStop = '</ul>';

	for (i=1;ExtraMenu.Text[i + "."] != undefined;i++) {
		InfoHTMLMiddle += '<li><a href="javascript:void(0)" onclick="ExtraMenuSelect(\'' + i + '.\');">' + ExtraMenu.Text[i +"."] + '</a></li>';
	}
		
	InfoSection.innerHTML = InfoHTMLStart + InfoHTMLMiddle + InfoHTMLStop;
	
	return;
}
	
function ExtraMenuLoadFile(fn) {
	// Level zur ID feststellen
	var id="";
	var workid = "";
	var found = false;
	var testfn = fn;
	if (testfn.substring(0,1) == "/") {
		testfn = testfn.substring(1);
	}
	for (workid in ExtraMenu.File) {
		if (ExtraMenu.File[workid] == testfn)  {
			ExtraMenuBreadcrumb(workid);
			id = workid;
			found = true;
		}
	}
	if (found) {
		if (id != 0) {
			lvl = ExtraMenu.Level[id];
		} else {
			lvl = 0;
		}
		document.getElementById("result")["innerHTML"] = "";
		document.getElementById("browsing")["innerHTML"] = "";

		ExtraMenuBreadcrumb(id);
		URLRequest(ExtraMenu.File[id],0,false,false);

		
	} else {
		ExtraMenuClearBreadcrumb();
		URLRequest(fn,0,false,false);
	}	
	
	return false;
	
}
	
function ExtraMenuSelect(id) {
	// Level zur ID feststellen
	if (id != 0) {
		lvl = ExtraMenu.Level[id];
	} else {
		lvl = 0;
	}

	document.getElementById("result")["innerHTML"] = "";
	document.getElementById("browsing")["innerHTML"] = "";

	ExtraMenuBreadcrumb(id);
	
	URLRequest(ExtraMenu.File[id],0,false,false);
	
	return false;
	
}

function ExtraMenuBreadcrumbResyncByFilename(fn) {
	try {
		var lvl = "";
		if (ExtraMenu.File != undefined) {
			for (lvl in ExtraMenu.File) {
				if (ExtraMenu.File[lvl] == fn) {
					ExtraMenuBreadcrumb(lvl);
					return;
				}
			}
		}
	} 
	catch (e) {
	}
}
function ExtraMenuClearBreadcrumb() {
	try {
		document.getElementById("breadcrumb")["innerHTML"] = "";
	} 	catch(e) {
		alert("caught");
	}
}
function ExtraMenuBreadcrumb(id) {
	var x = id.split(".");
	var xh = "";
	var xl = "";
	if (id != "0.") {
		xh += '<a href="javascript:void(0)" onclick="ExtraMenuSelect(\'0.\');">' + ExtraMenu.Text["0."] + '</a> » ';
	}
	for (i = 0; i < x.length - 1; i++) {
		
		xl += x[i] + ".";
		if (i != (x.length - 2)) {
			xh += '<a href="javascript:void(0)" onclick="ExtraMenuSelect(\'' + xl + '\');">' + ExtraMenu.Text[xl] + '</a> » ';
		} else {
			xh += '<b>' + ExtraMenu.Text[xl] + '</b> » ';
		}
	}
	xh += '<br/>';
	if (id == "0.") {
		xl = "";
	} 
	for (i=1; ExtraMenu.Text[xl + i + "."] != undefined; i++) {
		if (i > 1) {
			xh += " - ";
		}
		xh += '<a href="javascript:void(0)" onclick="ExtraMenuSelect(\'' + xl + i + '.\');">' + ExtraMenu.Text[xl + i + '.'] + '</a>';
	}
	document.getElementById("breadcrumb")["innerHTML"] = xh;
	
}

function ExtraMenuCheckBreadcrumb(fn) {
	var id = "";
	for (id in ExtraMenu.File) {
		if (ExtraMenu.File[id] == fn)  {
			ExtraMenuBreadcrumb(id);
			return;
		}
	}
	document.getElementById("breadcrumb")["innerHTML"] = "";
}

function ExtraMenuLoad(fn) {
	// Aufbau der Extramenu - Variablenstruktur und des Levelstr.
	ExtraMenu = new Object;
	ExtraMenu.Text = new Object;
	ExtraMenu.File = new Object;
	ExtraMenu.Level = new Object;
	var menudef = URLRequest(fn,0,true,false);
	var lines = menudef.split(/\n/g);
	var lastlevel = 0;
	var levelcounter = new Array(0,0,0,0,0,0,0,0,0,0,0);
	for (i=0;i<lines.length;i++) {
		if (trim(lines[i]) != '') {
			e = lines[i].split(/=/);
			f = e[1].split(/:/);
			lvl = e[0];
			fil = f[0];
			txt = f[1];
			levelcounter[lvl] ++;
			if (lvl < lastlevel) {
			    for (j = lastlevel; j > lvl; j--) {
					levelcounter[j] = 0;
				}
			}
			lastlevel = lvl;
			levelstr = "";
			for (j = 1; j <= lvl; j++) {
				levelstr += levelcounter[j] + ".";
			}
			if (levelstr == "") {
				levelstr= '0.';
			}
			ExtraMenu.Text[levelstr] = txt;
			ExtraMenu.File[levelstr] = fil;
			ExtraMenu.Level[levelstr] = lvl;
		}
	}
}

function ExtraMenuSync(path,fn,force) {
	if (!force && path.indexOf(".xml") < 0) {
	   return;
	}
	var xmlfn = path.replace(/\.html$/,".xml");
	xmlfn = xmlfn.replace(/^\//,"");
	if (!ExtraMenu) {
		// Laden des Extramenüs, falls noch nicht vorhanden.
		if (!fn) {
		   fn = "extramenu.def";
		}
		ExtraMenuLoad(fn);
		ExtraMenuStart();
	}
	// Über ExtraMenu.File iterieren um levelstr zu finden
	levelstr = "";
	for (l in ExtraMenu.File) {
		if (ExtraMenu.File[l] == xmlfn) {
		   levelstr = l;
		   break;
		}
	}
	
	// Mit levelstr ExtraMenuSelect aufrufen
	if (levelstr != "") {
//		ExtraMenuSelect(levelstr);
	}
}

function resizeZoomify() {
	try {
		var swf = document.getElementById("theMovie");
		
		var iBodyHeight=0;
		var browser = BrowserDetect.browser;
		if (window.innerHeight) {
			iBodyHeight = window.innerHeight;
		} else if (document.documentElement && document.documentElement.innerHeight){
			iBodyHeight = document.documentElement.innerHeight;
		} else if (document.documentElement && document.documentElement.clientHeight){
			iBodyHeight = document.documentElement.clientHeight;
		} else if (document.body && document.body.clientHeight){
			iBodyHeight = document.body.clientHeight;
		} else if (document.getElementsByTagName("body")[0].clientHeight) {
			iBodyHeight = document.getElementsByTagName("body")[0].clientHeight;
		}
		if (iBodyHeight > 600) { 
			swf.style.height = iBodyHeight - 200 + "px";
		} else {
			swf.style.height = "400px";
		}
	} catch (ex) {}
}

function resizeMap() {
	try {
		var map = document.getElementById("map");
		
		var iBodyHeight;
		var browser = BrowserDetect.browser;
		if (window.innerHeight) {
			iBodyHeight = window.innerHeight;
		} else if (document.documentElement && document.documentElement.innerHeight){
			iBodyHeight = document.documentElement.innerHeight;
		} else if (document.documentElement && document.documentElement.clientHeight){
			iBodyHeight = document.documentElement.clientHeight;
		} else if (document.body && document.body.clientHeight){
			iBodyHeight = document.body.clientHeight;
		} else if (document.getElementsByTagName("body")[0].clientHeight) {
			iBodyHeight = document.getElementsByTagName("body")[0].clientHeight;
		}
		if (iBodyHeight > 600) { 
			map.style.height = iBodyHeight - 200 + "px";
		} else {
			map.style.height = "400px";
		}
	} catch (ex) {}
}

function resizeContent() {
	try {
		//alert('resizeContent');
		var cnt = document.getElementById("content");
		// var str = document.getElementById("structure");
	
		var iBodyHeight;
		var iBodyWidth;
		if (window.innerHeight) {
			iBodyHeight = window.innerHeight;
			iBodyWidth = window.innerWidth;
		} else if (document.documentElement && document.documentElement.innerHeight){
			iBodyHeight = document.documentElement.innerHeight;
			iBodyWidth = document.documentElement.innerWidth;
		} else if (document.documentElement && document.documentElement.clientHeight){
			iBodyHeight = document.documentElement.clientHeight;
			iBodyWidth = document.documentElement.clientWidth;
		} else if (document.body && document.body.clientHeight){
			iBodyHeight = document.body.clientHeight;
			iBodyWidth = document.body.clientWidth;
		} else if (document.getElementsByTagName("body")[0].clientHeight) {
			iBodyHeight = document.getElementsByTagName("body")[0].clientHeight;
			iBodyWidth = document.getElementsByTagName("body")[0].clientWidth;
		}
		
		var iContentWidth = iBodyWidth - 270 -8 -4 - 1 -171;
		
		var norows = Math.floor((iBodyHeight -103 -44 + 16) /163); // Höhe- Header - Slider + Galeryzwischenraum
		var nocols = Math.floor((iContentWidth + 4) / 134);
		
		if (listcount != norows * nocols) {
			listcount = norows * nocols;
			//APSRequest('set?:listcount=' + listcount,1,false);			
		}
		
		
	
	} catch (ex) {}
	
}

function CoordinateLookup(level) {
	var coordstring = "";
	var boundstring = "";
	if (Query.maps) {
		coordstring = escape(' ' + Query.maps);
		boundstring=coordstring.replace(/^\%20\+koordinaten\d\%5B/,'');
	} else {
		boundstring = mapgetbounds() + ',' + level;
		coordstring = escape(' +koordinaten' + level) + '[' + boundstring;
	}
	var querystring = escape(trim(Query.media + " " + Query.archive) + " ") + coordstring + " " + escape(Query.base)  + escape(" " + Query.catalog);
//	var querystring = escape(trim(Query.media + " " + Query.archive) + " ") + escape(Query.base)  + escape(" " + Query.catalog);
	APSRequest("coordinatelookup?tastr=koordinaten" + level + "&start=" + boundstring + "&query=" + querystring);
}

function submitLocationSearch(lat,lng,level,id,motxt) {
	var coordstring = escape(' +koordinaten' + level) + '[' + lat + ',' + lng + ',' + lat + ',' + lng + ',' + level;
	var querystring = escape(trim(Query.media + " " + Query.archive) + " ") + coordstring + " " +  escape(Query.base)  + escape(" " + Query.catalog);
	Query.mapstxt = motxt;
	Query.mapslvl = level;
	APSRequest("maplookup?query=" + querystring + "&target=" + id,3);
}

function submitLocationQuery(query,dmode,no) {
	var querystring = query;
	APSRequest("searchdefine?query=" + querystring + "&dmode="+ dmode + "&no=" + no);
}	

function maplookupnavigate(no,id) {
	APSRequest("maplookupnavigate?no=" + no + "&target=" + id,3);
}

/* Search History mit Backbase */

var SH = new Array();

function addSearchHistory(atype, a1, a2) {
	i = SH.length;
	SH[i] = new Object;
	SH[i].requesttype = atype;
	SH[i].param1 = a1;
	SH[i].param2 = CopyQuery(a2);
	if (bb.history) {
		bb.history.add('|' + i, document.title + " (" + i + ")");
	}
}

function APSHistory(evnt) {
	if (evnt.bookmark == "|home" || evnt.bookmark =='') {
		initAPS();
	} else {
		i = evnt.bookmark.substr(1);
		if (!(i >= 0)) {return;};
		switch(SH[i].requesttype) {
			case 'searchreset':
				initAPS();
				break;
			case 'plain':
				Query = CopyQuery(SH[i].param2);
				APSRequest(SH[i].param1 + "&:media="+ Query.mediaID + "&:archiv=" + Query.archiveID,1,true);
				break;
			case 'archiv':
				Query = CopyQuery(SH[i].param2);
				APSRequest(SH[i].param1 + "&:media="+ Query.mediaID,1,true);
				break;
			case 'media':
				Query = CopyQuery(SH[i].param2);
				APSRequest(SH[i].param1 + "&:archiv=" + Query.archiveID,1,true);
				break;
			case 'query':
				Query = CopyQuery(SH[i].param2);
				APSRequest(SH[i].param1 + "&:media="+ Query.mediaID + "&:archiv=" + Query.archiveID,1,true);
				var t = SH[i].param1.replace(/searchdefine\?/,'');
				DDRefresh(t,true);
			case 'info':
			case 'warenkorb':
			case 'lichtpult':
			case 'catalog':
				Query = CopyQuery(SH[i].param2);
				APSRequest(SH[i].param1,1,true);
				break;
			case 'xml':
				Query = CopyQuery(SH[i].param2);
				ExtraMenuCheckBreadcrumb(SH[i].param1);
				URLRequest(SH[i].param1,1,false,true);
				break;
		}
	} 
}

function closeModal() {
	setInnerHTML('modalContainer', '');
	showDiv('modalContainer',false);
	showDiv('appOverlay',false);
}

function openModal(sTitle, sHTML, nLeft, nTop, nWidth, nHeight) {
	var nModalLeftMargin=75; //pos links (in px)
	if (typeof(nLeft)=='number') {
		if (nLeft > 0) {
			nModalLeftMargin = nLeft;
		}
	}
	var nModalTopMargin=75; //pos oben (in px)
	if (typeof(nTop)=='number') {
		if (nTop > 0) {
			nModalTopMargin = nTop;
		}
	}
	var nWinWidth=getBodyWidth()-(2*nModalLeftMargin); //breite in px
	if (typeof(nWidth)=='number') {
		if (nWidth > 0) {
			nWinWidth = nWidth;
		}
	}
	
	var nWinHeight=getBodyHeight()-(2*nModalTopMargin); //höhe in px
	if (typeof(nHeight)=='number') {
		if (nHeight > 0) {
			nWinHeight = nHeight;
		}
	}
	
	var sModalDlgHtml = '<table border="0" cellpadding="0" cellspacing="0" style="border:2px solid rgb(240,240,240);width:'+nWinWidth+'px;height:'+nWinHeight+'px;opacity:1;filter: alpha(opacity=100);filter:progid:DXImageTransform.Microsoft.Alpha(opacity=100);position:absolute;left:'+nModalLeftMargin+'px;top:'+nModalTopMargin+'px;" id="modalDlg">'
	sModalDlgHtml += '<tr height="30px">'
	sModalDlgHtml += '<td height="30px" style="font-family: Verdana, Helvetica, Arial;text-align:left;background-color:rgb(240,240,240);font-weight:bold;padding-left:5px;">'
	sModalDlgHtml += (typeof(sTitle)=='string')?sTitle:'undefined';
	sModalDlgHtml += '</td>'
	sModalDlgHtml += '<td height="30px" style="font-family: Verdana, Helvetica, Arial;text-align:right;background-color:rgb(240,240,240);font-weight:bold;cursor:pointer;padding-right:5px" onclick="closeModal()">X</td>'
	sModalDlgHtml += '</tr>'
	sModalDlgHtml += '<tr>'
	sModalDlgHtml += '<td colspan="2" valign="top" style="padding:0px;background-color:rgb(240,240,240);width:'+nWinWidth+'px;height:'+(nWinHeight-30)+'px">'
	sModalDlgHtml += sHTML	
	sModalDlgHtml += '</td>'
	setInnerHTML('modalContainer', sModalDlgHtml);
	showDiv('appOverlay', true);
	showDiv('modalContainer', true);
}


function CopyQuery(q) {
	var r = new Object;
	r.lastDDUpdate = new Object;
	r.lastDDUpdate.tastr = q.lastDDUpdate.tastr;
	r.lastDDUpdate.catalog = q.lastDDUpdate.catalog;
	r.lastDDUpdate.start = q.lastDDUpdate.start;
	r.catalog = q.catalog;
	r.media = q.media;
	r.mediaID = q.mediaID;
	r.base = q.base;
	r.archive = q.archive;
	r.archiveID = q.archiveID;
	r.maps = q.maps;
	r.mapstxt = q.mapstxt;
	r.mapslvl = q.mapslvl;
	
	return r;
}
