// THIS CODE IS NOT APPROVED FOR USE IN/ON ANY OTHER UI ELEMENT OR PRODUCT COMPONENT. 
// Copyright (c) 2007 Renderspace. All rights reserved.


/************************************************/
// utility functions
/************************************************/



/************************************************/
// general functions


function getNumberSign(number) {
	if (number > 0) return +1;
	if (number < 0) return -1;
	return 0;
}


/************************************************/
// text functions

function getIsEmpty(text) { // checks if string is empty, or consists only from spaces
    if ((text == null) || (typeof(text) != "string") || (text.length == 0)) return true;
    for (var i = text.length - 1; i >= 0; i--) {
        if (text.charAt(i) != ' ') return false;
    }
    return true;
}


function prepareText(text) {
//	if (navigator.userAgent && (navigator.userAgent.indexOf("MSIE") < 0)) {
//	    return convertUtf8ToAscii7(text);
//	}
	return text;
}


function getCharWidth(ch) {
    if (ch <= 0x01FF) return charWidths_0000_01FF[ch]; // for most common chars
    
    for (var charTableIndex = charWidths.length - 1; charTableIndex > 0; charTableIndex--) { // ignore first table, as it used in above line
        if ((ch >= charWidths[charTableIndex].min) && (ch <= charWidths[charTableIndex].max)) {
            return charWidths[charTableIndex].list[ch - charWidths[charTableIndex].min];
        }
    }
    
	return 0;
}


function getTextWidth(text, fontHeight, fromOffset, toOffset) {
	if (text == null) return 0;
	var w = 0;
	if ((fromOffset == null) || (fromOffset < 0)) fromOffset = 0;
	if ((toOffset == null) || (toOffset < 0)) toOffset = text.length;
	for (var i = fromOffset; i < toOffset; i++) {
		w += getCharWidth(text.charCodeAt(i));
	}
	return (w * fontHeight) / 24;
}


function getCharIndexAtXOffset(text, fontHeight, xOffset) {
	if (text == null) return 0;
	xOffset *= 24 / fontHeight;
	if (xOffset < 0) return 0;
	var w = 0;
	var i;
	var len = text.length;
	for (i = 0; i < len; i++) {
		w += getCharWidth(text.charCodeAt(i));
		if (w >= xOffset) return i + 1;
	}
	return len + 1;
}


function truncateTextToWidth(word, fontHeight, maxWidth) {
	if (word == null) return null;
	var w = 0;
	maxWidth *= 24 / fontHeight;
	var len = word.length;
	for (var i = 0; i < len; i++) {
		w += getCharWidth(word.charCodeAt(i));
		if (w > maxWidth - 3*charWidths_0000_01FF[46 /* '.' */]) return word.substring(0, i) + '...';
	}
	return word;
}


function escapeXmlText(text) {
	if (text == null) return '';
	text = text.replace(/&/g, "&amp;");
	text = text.replace(/\"/g, "&quot;");
	text = text.replace(/\'/g, "&apos;");
	text = text.replace(/</g, "&lt;");
	text = text.replace(/>/g, "&gt;");
	return text;
}


function formatNumber(value, numDecimals, decimalChar) {
	if (numDecimals < 1) numDecimals = 1;
	if (numDecimals > 8) numDecimals = 8;
	if (decimalChar == null) decimalChar = ".";
	var factor = 1;
	for (var i = 0; i < numDecimals; i++) factor *= 10;
	value = Math.floor(factor * value) / factor;
	value = value.toString();
	var dotPos = value.indexOf(".");
	if (dotPos < 0) dotPos = value.indexOf(",");
	if (dotPos >= 0) {
		value = value.substring(0, dotPos) + decimalChar + value.substring(dotPos + 1);
		var numZerosToAdd = numDecimals - (value.length - dotPos);
		while (numZerosToAdd >= 0) {
			value += "0";
			numZerosToAdd--;
		}
	}
	else {
		value += decimalChar;
		for (var i = 0; i < numDecimals; i++) value += "0";
	}
	return value;
}


/************************************************/
// event and interactive functions


var isWaitCursor = false;
var currentCursor = null;
var prevCursor = null;

function setCursor(type, doResetWait) {
	if (type != null) {
		currentCursor = type;
		if (type == "wait") {
			isWaitCursor = true;
			updateCursor();
		}
	}
	if ((doResetWait != null) && doResetWait) isWaitCursor = false;
}


function updateCursor() {
	var cursor = currentCursor;
	if (isWaitCursor) cursor = "wait";
	else if (cursor == null) cursor = "default";

	if (cursor != prevCursor) {
		document.documentElement.style.cursor = cursor;
		rootControl.style.cursor = cursor;
		prevCursor = cursor;
	}
}


function getMousePosition(mouseEventArgs) {
	var mx = 0, my = 0;
	
	if (!mouseEventArgs) mouseEventArgs = window.event;
	if (mouseEventArgs.layerX || mouseEventArgs.layerY) {
		mx = mouseEventArgs.layerX;
		my = mouseEventArgs.layerY;
	}
	else if (mouseEventArgs.clientX || mouseEventArgs.clientY) { // works on IE6,FF,Moz,Opera7
		mx = mouseEventArgs.clientX + document.documentElement.scrollLeft;
		my = mouseEventArgs.clientY + document.documentElement.scrollTop;
		
		var ofsElem = rootControl;
		while (ofsElem != null) {
		    mx -= ofsElem.offsetLeft;
		    my -= ofsElem.offsetTop;
		    ofsElem = ofsElem.offsetParent;
		}
	}  
	return {x: mx, y: my};
}


function getMouseButton(mouseEventArgs) {
	if (!mouseEventArgs) mouseEventArgs = window.event;
	return mouseEventArgs.button;
}


function getMouseWheelDelta(mouseEventArgs) {
	if (!mouseEventArgs) mouseEventArgs = window.event;
	if (mouseEventArgs.wheelDelta) { // IE/Opera.
		var delta = mouseEventArgs.wheelDelta / 120;
		if (window.opera) delta = -delta; // In Opera 9, delta differs in sign as compared to IE.
		return delta;
	} 
	else if (mouseEventArgs.detail) return -mouseEventArgs.detail / 3; // Mozilla case.
	return 0;
}
		

function getKeyPressed(keyEventArgs) {
	if (keyEventArgs) {
		if (keyEventArgs.keyCode) return keyEventArgs.keyCode;
		else if (keyEventArgs.which) return keyEventArgs.which;
	}
	else {
		keyEventArgs = window.event;
	}
	return 0;
}


function getCharPressed(keyEventArgs) {
	if (keyEventArgs) {
		if (keyEventArgs.charCode) return keyEventArgs.charCode;
	}
	else {
		keyEventArgs = window.event;
		if (keyEventArgs.keyCode) return keyEventArgs.keyCode;
	}
	return 0;
}


function preventDefaultEventAction(args) {
	if (!args) args = window.event;
	if (window.event) window.event.cancelBubble = true;
	if (window.event) window.event.returnValue = false;
	if (args.preventDefault) args.preventDefault();
}


function delegateEventAction(args) {
	if (!args) args = window.event;
	if (window.event) window.event.cancelBubble = false;
	if (window.event) window.event.returnValue = true;
}


/************************************************/
// XML functions


function parseXmlString(xmlString) {
	var xmlDoc = null;
	if (xmlDoc == null) {
		try {
			xmlDoc = new ActiveXObject("Microsoft.XMLDOM");
			xmlDoc.async = "false";
			xmlDoc.loadXML(xmlString);
		}
		catch (e) {}
	}
	if (xmlDoc == null) {
		try {
			var parser = new DOMParser();
			xmlDoc = parser.parseFromString(xmlString, "text/xml");
		}
		catch (e) {}
	}
	
	return xmlDoc;
}


function getXmlElem(xmlParent, tagName) {
	if (xmlParent == null) return null;
	var itemList = xmlParent.getElementsByTagName(tagName);
	if (itemList.length <= 0) return null;
	return itemList[0];
}


function getXmlElemValue(xmlParent, tagName) {
	var item = getXmlElem(xmlParent, tagName);
	if ((item == null) || (item.firstChild == null)) return null;
	return item.firstChild.nodeValue;
} 


/************************************************/
// system functions


function getAllURLParams() {
	var strHref = window.location.href;
	if (strHref == null) return null;
	var questionPos = strHref.indexOf("?");
	if (questionPos < 0) return null;
	return strHref.substr(questionPos + 1).toLowerCase();
}


function getURLParam(strParamName) {
	var strQueryString = getAllURLParams();
	if (strQueryString == null) return null;
	var aQueryString = strQueryString.split("&");
	for (var iParam = 0; iParam < aQueryString.length; iParam++){
		if (aQueryString[iParam].indexOf(strParamName + "=") > -1) {
			var aParam = aQueryString[iParam].split("=");
			return aParam[1];
		}
	}
	
	return null;
}


function createHttpRequester() {
	if (window.XMLHttpRequest) { // code for Mozilla, Safari, etc
		try {
			return new XMLHttpRequest();
		} 
		catch(e) {}
	} 
	else if (window.ActiveXObject) { // IE/Windows ActiveX version
		try {
			return new ActiveXObject("Msxml2.XMLHTTP");
		} 
		catch(e) {
			try {
				return new ActiveXObject("Microsoft.XMLHTTP");
			} 
			catch(e) {}
		}
	}
	return null;
}


function getRemoteFile(method, url, params, isCrossDomain, doReturnXml, callbackFunc, callbackData) {
	var xmlHttp = createHttpRequester();
	if (xmlHttp == null) return null;
	try {
	    method = method.toUpperCase();
		var isAsync = (callbackFunc != null);
		if (isCrossDomain) url = URL_READER + "?url=" + encodeURIComponent(url);
		xmlHttp.open(method, url + ((method == "GET") ? "?" + params : ""), isAsync);
		xmlHttp.setRequestHeader("If-Modified-Since", "Sat, 1 Jan 2000 00:00:00 GMT");
		if (method == "POST") {
		    xmlHttp.setRequestHeader("Content-type", "application/x-www-form-urlencoded");
            xmlHttp.setRequestHeader("Content-length", params.length);
            xmlHttp.setRequestHeader("Connection", "close");
		}
		
		if (isAsync) {
			xmlHttp.onreadystatechange = function() {
				if (xmlHttp.readyState == 4) {
					callbackFunc(doReturnXml ? xmlHttp.responseXML : xmlHttp.responseText, callbackData);
					delete xmlHttp.onreadystatechange;
				}
			};
		}
		
		xmlHttp.send((method == "POST") ? params : "");
		if (isAsync) return null; // later
		if (doReturnXml) return xmlHttp.responseXML;
		return xmlHttp.responseText;
	}
	catch (e) {}
	return null;
}


function getCurrentServer() {
	var url = window.location.href;
	if (url == null) return null;
	var ofs = 0;
	if (url.substring(0, 7) == "http://") ofs = 7;
	else if (url.substring(0, 8) == "https://") ofs = 8;
	else if (url.substring(0, 7) == "file://") ofs = 7;
	if (ofs == 0) return null;
	var slashPos = url.indexOf('/', ofs + 1);
	if (slashPos >= 0) url = url.substring(0, slashPos);
	return url;
}


function getIsAbsoluteLink(url) {
    if (url.substring(0, 6) == "abs://") return true; // internaly used
	if ((url.substring(0, 7) == "http://") || (url.substring(0, 7) == "file://")) return true;
	if (url.substring(0, 7) == "mailto:") return true;
	else return false;
}
	

function navigateToLink(url, isNewWindow) {
    if (url.substring(0, 6) == "abs://") {
        url = url.substring(6);
        isNewWindow = false;
    }
	else if (url.substring(0, 7) == "mailto:") isNewWindow = false;
	if (isNewWindow) window.open(url, "", "");
	else window.location.href = url;
}


function getWindowWidth() {
	if (typeof(window.innerWidth) == 'number') return window.innerWidth; // Non-IE
	if (document.documentElement && document.documentElement.clientWidth) return document.documentElement.clientWidth; // IE 6+ in 'standards compliant mode'
	if (document.body && document.body.clientWidth) return document.body.clientWidth; // IE 4 compatible
	return 0;
}


function getWindowHeight() {
	if (typeof(window.innerHeight) == 'number') return window.innerHeight; // Non-IE
	if (document.documentElement && document.documentElement.clientHeight) return document.documentElement.clientHeight; // IE 6+ in 'standards compliant mode'
	if (document.body && document.body.clientHeight) return document.body.clientHeight; // IE 4 compatible
	return 0;
}


function getWindowXScroll() {
	if (self.pageXOffset) return self.pageXOffset;
	if (document.documentElement && document.documentElement.scrollTop) return document.documentElement.scrollLeft; // Explorer 6 Strict
	if (document.body) return document.body.scrollLeft; // all other Explorers
	return 0;
}


function getWindowYScroll() {
	if (self.pageYOffset) return self.pageYOffset;
	if (document.documentElement && document.documentElement.scrollTop) return document.documentElement.scrollTop; // Explorer 6 Strict
	if (document.body) return document.body.scrollTop; // all other Explorers
	return 0;
}


function createCookie(name, value, days) {
	var expires = "";
	if (days) {
		var date = new Date();
		date.setTime(date.getTime() + (days * 24*60*60*1000));
		expires = "; expires=" + date.toGMTString();
	}
	document.cookie = name + "=" + value + expires + "; path=/";
}


function readCookie(name) {
	var nameEQ = name + "=";
	var cookies = document.cookie.split(';');
	for(var i = 0; i < cookies.length; i++) {
		var cok = cookies[i];
		while (cok.charAt(0) == ' ') cok = cok.substring(1, cok.length);
		if (cok.indexOf(nameEQ) == 0) return cok.substring(nameEQ.length, cok.length);
	}
	return null;
}


function eraseCookie(name) {
	createCookie(name, "", -1);
}


function getCurrentBrowserName() {
	var ua = navigator.userAgent;
	if (ua.indexOf("MSIE") >= 0) return "Internet Explorer";
	else if (ua.indexOf("Firefox") >= 0) return "Mozilla Firefox";
	return navigator.appName;
}


function getCurrentBrowserVersion() {
	var ua = navigator.userAgent;
	var iePos = ua.indexOf("MSIE");
	if (iePos >= 0) return parseFloat(ua.substring(iePos + 5)).toString();
	var ffPos = ua.indexOf("Firefox");
	if (ffPos >= 0) return parseFloat(ua.substring(ffPos + 8)).toString();
	var version = navigator.appVersion;
	return parseFloat(version).toString();
}
