<!-- hide from old browsers

/******************************************************************************
* $Id: default.js 11 2010-03-12 15:12:18Z husi $
* Project      : Palextra Common
* Name         : default.js
* Description  : Default java script functions for common wishes
* Author       : Patrick Husi <patrick.husi@arpage.ch>
* Copyright    : (c) 2005 by Arpage AG
*                CH-8700 Kuesnacht
*                All rights reserved
******************************************************************************/

/*************************************************************************************************************
*** popup win funcions ***
**************************************************************************************************************/

var lastWin = null;
var lastLoc = null;
var lastTimeoutId = null;
function openPopupWin(loc, winType, parentElementId, specWidth, specHeight) {
	var features = "";
	var left = 120, top = 10, width = 630, height = 350;
	switch (winType) {
		case "picture" :
			features = "scrollbars=no,alwaysRaised=yes,";
			left = 240; top = 100; width = 480; height=350;
			break;
		case "resourcepool" :
			features = "scrollbars=yes,alwaysRaised=yes,";
			left = 240; top = 100; width = 780; height=666;
			break;
		case "notepad" :
			features = "scrollbars=no,alwaysRaised=yes,dependent=yes,resizable=no,";
			left = 240; top = 100; width = 400; height=250;
			break;
		case "scanscope" :
			features = "scrollbars=no,alwaysRaised=yes,resizable=no,";
			left = 240; top = 100; width = 900; height=680;
			break;
		case "idscanscope_server" :
			features = "scrollbars=yes,alwaysRaised=yes,dependent=yes,location=yes,";
			left = 300; top = 200; width = 650; height=680;
			break;
		case "help" :
			features = "scrollbars=yes,alwaysRaised=yes,";
			left = 240; top = 100; width = 580; height=450;
			break;
		default :
			alert("wrong type " + winType + "!");
			winType = "edit";
			features = "scrollbars=yes,";
			break;
	} // switch
	
	// Position adjustments
	if (specWidth != null)
		width = specWidth;
	if (specHeight != null)
		height = specHeight;
	if (parentElementId != null) {
		var dX = 0, dY = 0;
		if (window.screenX != null) {
			dX += window.screenX;
			dY += window.screenY;
		}
		if (window.pageXOffset != null) {
			dX -= window.pageXOffset;
			dY -= window.pageYOffset;
		} else if (document.body.scrollTop != null) {
			dX -= document.body.scrollLeft;
			dY -= document.body.scrollTop;
		}
		var position = getPosition(document.getElementById(parentElementId));
		left = position.x + dX + 50; top = position.y + dY + 130;
	}
	if (left + width > screen.availWidth) left = screen.availWidth - width;
	if (top + height > screen.availHeight) top = screen.availHeight - height;
	if (left < 0) left = 0;
	if (top < 0) top = 0;
	
	var myWin = window.open(loc, winType, 'dependent=no,resizable=yes,status=no,' + features + "left=" + left + ",top=" + top + ",width=" + width + ",height=" + height);
	if (myWin == null)
		return true;
	myWin.moveTo(left, top);
	myWin.resizeTo(width, height);
	if (myWin.focus != null)
		myWin.focus();
		
	// Checking if reload was ok, due bug in safari browser
	lastWin = myWin;
	lastLoc = loc;
	if (lastTimeoutId != null)
		clearTimeout(lastTimeoutId);
	//lastTimeoutId = setTimeout('checkLocation()', 1000);
	
	return false;
} // openPopupWin

// Checking if popupp has realy been reloaded
function checkLocation() {
	if (lastTimeoutId != null) {
		clearTimeout(lastTimeoutId);
		lastTimeoutId = null;
	}
	if (lastWin == null || lastWin.closed || lastWin.location.href == "about:blank")
		return;
	if (lastWin.location.href.indexOf(lastLoc) == -1) // endsWith
		window.location.reload();
}

// Closing a popup window
function closeWindow(openerURL, keepInCurrentWindow) {
	if (keepInCurrentWindow != null && keepInCurrentWindow == 'true') {
		if (openerURL != '')
			location.href = openerURL.replace(/&amp;/gi, "&");
		else
			location.reload(true);
	} else {
		if (window.opener != null) {
			if (openerURL != null) {
				if (openerURL != '') {
					window.opener.location.href = openerURL.replace(/&amp;/gi, "&");
				} else {
					if (window.opener.reloadMe != null) {
						window.opener.reloadMe();
					} else {
						window.opener.location.reload(true);
					}
				}
			} // if
			window.opener.focus();
		} // if
		close();
	} // if
} // closeWindow

// Reloading current document
var reloadURL = "";
function reloadMe() {
	if (reloadURL != null && reloadURL != '') {
		var oldHref = location.href.replace(/#.*$/, '');
		var newHref = reloadURL.replace(/#.*$/, '');
		location.replace(reloadURL);
		if (oldHref.indexOf(newHref) != -1)
			location.reload(true);
	} else {
		location.reload(true);
	}
}

// Loads a new page in the current window
var ignoreClick = false;
function loadPage(page, target) {
	if (ignoreClick) {
		ignoreClick = false;
		return;
	}
	if (target == null || target == '')
		location.href = page;
	else
		window.open(page, target);
}

/*************************************************************************************************************
*** div, id and content funcions ***
**************************************************************************************************************/

// Gets the div object reference
function getRefToDiv(divID) {
	if (document.layers) // Netscape layers
		return document.layers[divID];
	if (document.getElementById) // DOM; IE5, NS6, Mozilla, Opera
		return document.getElementById(divID);
	if (document.all) // Proprietary DOM; IE4
		return document.all[divID];
	if (document[divID]) // Netscape alternative
		return document[divID];
	return false;
}

// Sets the content of a div element
function setDivContent(myReference, newContent, nameOfIframe) {
	if (myReference == null)
		return;
	if (typeof(myReference.innerHTML) != null) {
		// used by the IE series, Konqueror, Opera 7+ and Gecko browsers
		myReference.innerHTML = newContent;
	} else if (myReference.document && myReference.document != window.document) {
		// used by layers browsers
		myReference.document.open();
		myReference.document.write(newContent);
		myReference.document.close();
	} else if (window.frames && window.frames.length && window.frames[nameOfIframe]) {
		// used by browsers like Opera 6-
		// if we attempt to rewrite the iframe content before
		// it has loaded we will only produce errors
		myReference = window.frames[nameOfIframe].window;
		myReference.document.open();
		myReference.document.write(newContent);
		myReference.document.close();
	}
}

// Display status text
function doStatus(text) {
	if (text == null)
		text = "";
	self.defaultStatus = text;
	self.status = text;
	return true;
} // doStatus

// Gets the absolute position of an object
function getPosition(element) {
	var elem = element, x=0, y=0;

	// Going through tag and parent tags
	while ((typeof(elem) == "object") && (typeof(elem.tagName) != "null")) {
		y += elem.offsetTop;
		x += elem.offsetLeft;
		if (elem.tagName.toUpperCase() == "BODY")
			break;
		if (typeof(elem) == "object" && typeof(elem.offsetParent) == "object")
			elem = elem.offsetParent;
	}

	/* Objekt mit x und y zurueckgeben */
	position = new Object();
	position.x = x;
	position.y = y;
	return position;
}

/*************************************************************************************************************
*** tabs and register ***
**************************************************************************************************************/

// shows or hides a tab
function setTabVisibility(activeTab, tabsArray, tabName) {
	if (tabName == null || tabName == '')
		tabName = "content";
	var newActiveElementTab = document.getElementById("tab-" + activeTab);
	if (newActiveElementTab == null || newActiveElementTab.className == tabName + "-tabdisabled")
		return;
		
	for (var i = 0; i < tabsArray.length; i++) {
		var currentTab = tabsArray[i];
		var elementTab = document.getElementById("tab-" + currentTab);
		var elementContent = document.getElementById("content-" + currentTab);
		if (elementTab == null || elementTab.className == tabName + "-tabdisabled") {
			if (elementContent != null)
				elementContent.style.display = "none";
			continue;
		}
		if (activeTab == currentTab) {
			elementTab.className = tabName + "-tabsel";
			elementContent.style.display = "";
		} else {
			elementTab.className = tabName + "-tab";
			elementContent.style.display = "none";
		}
	}
} // setTabVisibility

function showElements(elements) {
	for (var i = 0; i < elements.length; i++) {
		var element = document.getElementById(elements[i]);
		if (element != null)
			element.style.display = "";
	}
} // showElements

function hideElements(elements) {
	for (var i = 0; i < elements.length; i++) {
		var element = document.getElementById(elements[i]);
		if (element != null)
			element.style.display = "none";
	}
} // hideElements

/*************************************************************************************************************
*** form validation ***
**************************************************************************************************************/

// Checks an input text field
function checkTextField(formName, fieldName, commentFieldId, minLen, maxLen, regExp) {
	// parsing and checking for errors
	if (document.forms[formName] == null) {
		alert("form \"" + formName + "\" doesn't exist");
		return false;
	}
	var field = document.forms[formName].elements[fieldName];
	var isError = !isNaN(parseInt(minLen)) && field.value.length < parseInt(minLen) || !isNaN(parseInt(maxLen)) && field.value.length > parseInt(maxLen);
	var regExpError = false;
	if (regExp != null && regExp != '') {
		var checkFieldRegExp = new RegExp(regExp);
		regExpError = !field.value.match(checkFieldRegExp);
		isError = isError || regExpError;
	}
	// errors field
	var errorsField = document.forms[formName].elements['errors'];
	if (errorsField != null) {
		if (errorsField.value.indexOf('-' + fieldName + '-') != -1) {
			if (!isError) {
				var fieldRegExp = new RegExp('-' + fieldName + '-');
				errorsField.value = errorsField.value.replace(fieldRegExp, '');
			}
		} else {
			if (isError) {
				errorsField.value += '-' + fieldName + '-';
			}
		}
	}
	// The comment field
	var commentField = getRefToDiv(commentFieldId);
	if (commentField != null) {
		if (field.value.length == 0)
			setDivContent(commentField, "Maximal " + maxLen + " Zeichen");
		else if (regExpError)
			setDivContent(commentField, "Ung&uuml;ltiges Format");
		else
			setDivContent(commentField, field.value.length + " von maximal " + maxLen + " Zeichen");
		if (isError)
			commentField.style.color = "#FF9900";
		else
			commentField.style.color = "";
	}
	// The save image
	setSubmitButton(formName, isError);
	// The result
	return !isError;
} // checkTextField

// Checks a date field
function checkDateField(formName, fieldName, commentFieldId, type, min, max){
	// parsing and checking for errors
	if (document.forms[formName] == null) {
		alert("form \"" + formName + "\" doesn't exist");
		return false;
	}
	var field = document.forms[formName].elements[fieldName];
	var isError = !isNaN(parseInt(minLen)) && field.value.length < parseInt(minLen) || !isNaN(parseInt(maxLen)) && field.value.length > parseInt(maxLen);
	var regExpError = false;
	if (regExp != null && regExp != '') {
		var checkFieldRegExp = new RegExp(regExp);
		regExpError = !field.value.match(checkFieldRegExp);
		isError = isError || regExpError;
	}
	// errors field
	var errorsField = document.forms[formName].elements['errors'];
}

// Checks a number of an input text field
function checkNumberField(formName, fieldName, commentFieldId, type, min, max) {
	// parsing and checking for errors
	if (document.forms[formName] == null) {
		alert("form \"" + formName + "\" doesn't exist");
		return false;
	}
	var field = document.forms[formName].elements[fieldName];
	var correctedValue = field.value.replace(/[^\d\.\-]/g, '');
	var parsedValue;
	if (type == 'double')
		parsedValue = parseFloat(correctedValue);
	else
		parsedValue = parseInt(correctedValue);
	if (isNaN(parsedValue)) {
		if (field.value != correctedValue)
			field.value = correctedValue;
	} else if (field.value != parsedValue)
		field.value = parsedValue;
	var isError = isNaN(parsedValue) || !isNaN(parseInt(min)) && field.value < parseInt(min) || !isNaN(parseInt(max)) && field.value > parseInt(max);
	// errors field
	var errorsField = document.forms[formName].elements['errors'];
	if (errorsField != null) {
		if (errorsField.value.indexOf('-' + fieldName + '-') != -1) {
			if (!isError) {
				var fieldRegexp = new RegExp('-' + fieldName + '-');
				errorsField.value = errorsField.value.replace(fieldRegexp, '');
			}
		} else {
			if (isError) {
				errorsField.value += '-' + fieldName + '-';
			}
		}
	}
	// The comment field
	var commentField = getRefToDiv(commentFieldId);
	if (commentField != null) {
		if (isError) {	
			if (!isNaN(parseInt(min)) && !isNaN(parseInt(max)))
				setDivContent(commentField, "Zwischen " + tsep(min) + " und " + tsep(max));
			else if (!isNaN(parseInt(min)))
				setDivContent(commentField, "Mindestens " + tsep(min));
			else if (!isNaN(parseInt(max)))
				setDivContent(commentField, "Maximal " + tsep(max));
			commentField.style.color = "#FF9900";
		} else {
			setDivContent(commentField, "&#160;");
			commentField.style.color = "";
		}
	}
	// The save image
	setSubmitButton(formName, isError);
	// The result
	return !isError;
} // checkNumberField

// enables or disables the submit button
function setSubmitButton(formName, isError) {
	var saveButtonImageName = "image-save-" + formName;
	var saveButtonImage = (saveButtonImageName != null && saveButtonImageName != '') ? document.images[saveButtonImageName] : null;
	if (saveButtonImage != null) {
		var errorsField = document.forms[formName].elements['errors'];
		var isFormError = isError || errorsField != null && errorsField.value != '';
		if (isFormError) {
			if (saveButtonImage.src.indexOf('save.gif') != -1)
				saveButtonImage.src = saveButtonImage.src.replace(/save.gif/, 'save_disabled.gif');
		} else {
			if (saveButtonImage.src.indexOf('save_disabled.gif') != -1)
				saveButtonImage.src = saveButtonImage.src.replace(/save_disabled.gif/, 'save.gif');
		}
	}
} // setSubmitButton

/*************************************************************************************************************
*** table functions: different row colors, sorting ***
**************************************************************************************************************/

// Row color style definitions
var CLASSNAME_ROW_ODD = "table1-bg1";
var CLASSNAME_ROW_EVEN = "table1-bg2";
var CLASSNAME_ROW_SELECTED = "table1-selected";

// Resets the row colors of a table after sorting
function setDifferentRowColorsToTable(sorteableTable, classnameRowOdd, classnameRowEven) {
	if (classnameRowOdd == null || classnameRowOdd == '')
		classnameRowOdd = CLASSNAME_ROW_ODD;
	if (classnameRowEven == null || classnameRowEven == '')
		classnameRowEven = CLASSNAME_ROW_EVEN;
	var rows = sorteableTable.tBody.rows;
	var l = rows.length;
	for (var i = 0; i < l; i++) {
		removeClassName(rows[i], i % 2 ? classnameRowOdd : classnameRowEven);
		addClassName(rows[i], i % 2 ? classnameRowEven : classnameRowOdd);
	}
}

// Mark a table row as selected
function setRowSelected(elementId) {
	var element = (elementId != null)?document.getElementById(elementId):this;
	if (element == null)
		return;
	addClassName(element, CLASSNAME_ROW_SELECTED);
} // setOptions

// Mark a table row as unselected
function setRowUnselected(elementId) {
	var element = (elementId != null)?document.getElementById(elementId):this;
	if (element == null)
		return;
	removeClassName(element, CLASSNAME_ROW_SELECTED);
} // setOptions

// adds a class to a specific element. I.e used for sorteable tables with different row colors.
function addClassName(el, sClassName) {
	var s = el.className;
	var p = s.split(" ");
	var l = p.length;
	for (var i = 0; i < l; i++) {
		if (p[i] == sClassName)
			return;
	}
	p[p.length] = sClassName;
	el.className = p.join(" ");
}

// removes a class to a specific element I.e used for sorteable tables with different row colors.
function removeClassName(el, sClassName) {
	var s = el.className;
	var p = s.split(" ");
	var np = [];
	var l = p.length;
	var j = 0;
	for (var i = 0; i < l; i++) {
		if (p[i] != sClassName)
			np[j++] = p[i];
	}
	el.className = np.join(" ");
}

/*************************************************************************************************************
*** DOM functions ***
**************************************************************************************************************/

/**
 * Returns the text content of a node or an empty string if the node desn't exist
 * 
 * @param node The parent node
 * @elementName The name of the child element
 */
function getNodeText(node, elementName) {
	var element = node.getElementsByTagName(elementName)[0].firstChild;
	if (element != null)
		return element.nodeValue;
	else
		return "";
}

/**
 * Returns the node searched by the xpath expression
 * 
 * @param node The root node
 * @param tagsTree XPath expression. Only [@attr = 'value'] conditions are allowed
 * @return The node found or null if no such node exists
 */
function getElementByTagTree(node, tagsTree) {
	var tags = tagsTree.split("/");
	var theNode = node;
	for (var i = 0; i < tags.length && theNode != null; i++) {
		var tagName = tags[i];
		var condition = null;
		var condPos = tagName.indexOf("[");
		if (condPos != -1 && tagName.indexOf("]") == tagName.length - 1) {
			condition = tagName.substring(condPos + 1, tagName.length - 1);
			tagName = tagName.substring(0, condPos);
		}
		
		var theNodes = theNode.getElementsByTagName(tagName);
		if (theNodes != null) {
			if (condition != null) {
				theNode = null;
				for (var j = 0; j < theNodes.length && theNode == null; j++) {
					if (checkNodeCondition(theNodes[j], condition)) {
						theNode = theNodes[j];
					}
				}
			} else {
				theNode = theNodes[0];
			}
		} else {
			return null;
		}
	}
	return theNode;
}

/**
 * Helper function for getElementByTagTree to check if a condition is valid 
 * for a specific node
 * 
 * @param node The node to check
 * @param condition The condition. Format: [@attr = 'value']
 * @return The result (true or false)
 */
function checkNodeCondition(node, condition) {
	if (node == null)
		return false;
	if (condition == null || condition == '')
		return true;
		
	// The condition
	var search = new RegExp("^(\\@)([\\w-]+)\\s*=\\s*\\'([\\w-]+)\\'", "gi");
	var conditionResult = search.exec(condition);
	if (conditionResult == null)
		return false;
	var attributeName = conditionResult[2];
	var attributeValue = conditionResult[3];
	
	// Checking
	var theAttributeValue = node.getAttribute(attributeName);
	return (theAttributeValue != null && theAttributeValue == attributeValue);
}

/**
 * Serializes the content of a node and all sub nodes
 * 
 * @param node The node to check
 * @param condition The condition. Format: [@attr = 'value']
 * @return Text content
 */
function serializeNode(node) {
	if (typeof XMLSerializer != 'undefined') {
		return new XMLSerializer().serializeToString(node);
	} else if (typeof node.xml != 'undefined') {
		return node.xml;
	} else if (typeof printNode != 'undefined') {
		return printNode(node);
	} else if (typeof Packages != 'undefined') {
		try {
			var stringWriter = new java.io.StringWriter();
			Packages.org.apache.batik.dom.util.DOMUtilities.writeNode(node, stringWriter);
			return stringWriter.toString();
		}
		catch (e) {
			// might want to handle problem here
			return "";
		}
	}
	else {
		// might want to handle problem here
		return "";
	}
}

/*************************************************************************************************************
*** common functions ***
**************************************************************************************************************/

/**
 * Returns an array with all query string parameters
 * 
 * @return The array
 */
function getArgsArr() {
	var query = location.search.substring(1);
	var pairs = query.split("&");
	var args  = new Object;
	for (var i = 0; i < pairs.length; i++) {
		var pos = pairs[i].indexOf('=');
		if (pos == -1)
			continue;
		var argname = pairs[i].substring(0, pos);
		var value = pairs[i].substring(pos + 1);
		value = value.replace(/\+/g, " ");
		args[argname] = unescape(value);
	}
	return args;
}

/**
 * Number formatting, includes thousands and decimal separators
 * 
 * @param n The number
 * @return The string with separators
 */
function tsep(n) {
	var ts = "'"; // thousands separator
	var ds = "."; // decimal separator

	var numString = String(n), prefixString = numString, suffixString = "";
	var i = numString.indexOf(".");
	if (i != -1) { // if ".", then split:
		prefixString = numString.substring(0, i);
		suffixString = ds + numString.substring(i + 1);
	}
	return prefixString.replace(/(\d)(?=(\d{3})+([.]|$))/g, "$1" + ts) + suffixString;
}

/**
 * Dynamically loading an external JavaScript or CSS file
 *
 * @param filename Filename of the js or css to load
 * @param filetype filetype css or js
 */
function loadjscssfile(filename, filetype) {
	// File already exists?
	var fileId = filename.replace(/^.*\//, "");
	if (document.getElementById(fileId) != null)
		return;
	
	// Base direcorty of current js
	var i, base, src = "default.js", script = document.getElementById(src);
	if (script.src.match(src)){ base = script.src.replace(src, "");}

	// Importing file
	var fileref = null;
	if (filetype == "js") { // if filename is a external JavaScript file
		fileref = document.createElement('script');
		fileref.setAttribute("type","text/javascript");
		fileref.setAttribute("src", base + filename);
		fileref.setAttribute("id", fileId);
	} else if (filetype == "css") { // if filename is an external CSS file
		fileref = document.createElement("link");
		fileref.setAttribute("rel", "stylesheet");
		fileref.setAttribute("type", "text/css");
		fileref.setAttribute("href", base + filename);
		fileref.setAttribute("id", fileId);
	}
	if (typeof fileref != "undefined")
		document.getElementsByTagName("head")[0].appendChild(fileref);
}

/**
 * Sets the the specific window height for ie6
 *
 * @param windowId The if of the window
 * @param Window height in percon of the browser height
*/
function checkWindowHeight(windowId, percentHeight) {
	var window = document.getElementById(windowId);
	if (window != null && dojo.isIE <= 6) {
		window.style.height = document.documentElement.clientHeight * percentHeight / 100;
	}
}

/******************************************************************************
*** Dojo sliding ***
******************************************************************************/

function toggleSlideContent(sliderName) {
	dojo.require("dojo.fx");
	var slider = document.getElementById(sliderName);
	if (slider.style.display && slider.style.display == 'none') {		
		dojo.fx.wipeIn({node: slider, duration: 500}).play();
	} else {
		dojo.fx.wipeOut({node: slider, duration: 500}).play();
	}
}

// end hiding from old browsers -->

