var Base64 = {

    // private property
    _keyStr : "ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/=",

    // public method for encoding
    encode : function (input) {
        var output = "";
        var chr1, chr2, chr3, enc1, enc2, enc3, enc4;
        var i = 0;

        input = Base64._utf8_encode(input);

        while (i < input.length) {

            chr1 = input.charCodeAt(i++);
            chr2 = input.charCodeAt(i++);
            chr3 = input.charCodeAt(i++);

            enc1 = chr1 >> 2;
            enc2 = ((chr1 & 3) << 4) | (chr2 >> 4);
            enc3 = ((chr2 & 15) << 2) | (chr3 >> 6);
            enc4 = chr3 & 63;

            if (isNaN(chr2)) {
                enc3 = enc4 = 64;
            } else if (isNaN(chr3)) {
                enc4 = 64;
            }

            output = output +
            this._keyStr.charAt(enc1) + this._keyStr.charAt(enc2) +
            this._keyStr.charAt(enc3) + this._keyStr.charAt(enc4);

        }

        return output;
    },

    // public method for decoding
    decode : function (input) {
        var output = "";
        var chr1, chr2, chr3;
        var enc1, enc2, enc3, enc4;
        var i = 0;

        input = input.replace(/[^A-Za-z0-9\+\/\=]/g, "");

        while (i < input.length) {

            enc1 = this._keyStr.indexOf(input.charAt(i++));
            enc2 = this._keyStr.indexOf(input.charAt(i++));
            enc3 = this._keyStr.indexOf(input.charAt(i++));
            enc4 = this._keyStr.indexOf(input.charAt(i++));

            chr1 = (enc1 << 2) | (enc2 >> 4);
            chr2 = ((enc2 & 15) << 4) | (enc3 >> 2);
            chr3 = ((enc3 & 3) << 6) | enc4;

            output = output + String.fromCharCode(chr1);

            if (enc3 != 64) {
                output = output + String.fromCharCode(chr2);
            }
            if (enc4 != 64) {
                output = output + String.fromCharCode(chr3);
            }

        }

        output = Base64._utf8_decode(output);

        return output;

    },

    // private method for UTF-8 encoding
    _utf8_encode : function (string) {
        string = string.replace(/\r\n/g,"\n");
        var utftext = "";

        for (var n = 0; n < string.length; n++) {

            var c = string.charCodeAt(n);

            if (c < 128) {
                utftext += String.fromCharCode(c);
            }
            else if((c > 127) && (c < 2048)) {
                utftext += String.fromCharCode((c >> 6) | 192);
                utftext += String.fromCharCode((c & 63) | 128);
            }
            else {
                utftext += String.fromCharCode((c >> 12) | 224);
                utftext += String.fromCharCode(((c >> 6) & 63) | 128);
                utftext += String.fromCharCode((c & 63) | 128);
            }

        }

        return utftext;
    },

    // private method for UTF-8 decoding
    _utf8_decode : function (utftext) {
        var string = "";
        var i = 0;
        var c = c1 = c2 = 0;

        while ( i < utftext.length ) {

            c = utftext.charCodeAt(i);

            if (c < 128) {
                string += String.fromCharCode(c);
                i++;
            }
            else if((c > 191) && (c < 224)) {
                c2 = utftext.charCodeAt(i+1);
                string += String.fromCharCode(((c & 31) << 6) | (c2 & 63));
                i += 2;
            }
            else {
                c2 = utftext.charCodeAt(i+1);
                c3 = utftext.charCodeAt(i+2);
                string += String.fromCharCode(((c & 15) << 12) | ((c2 & 63) << 6) | (c3 & 63));
                i += 3;
            }

        }

        return string;
    }

};

function base64_encode(value)
{
    return(Base64.encode(value));
}

function base64_decode(value)
{
    return(Base64.decode(value));
}

function createCookie(name,value,days) {
    if (days) {
        var date = new Date();
        date.setTime(date.getTime()+(days*24*60*60*1000));
        var expires = "; expires="+date.toGMTString();
    }
    else var expires = "";
    document.cookie = name+"="+value+expires+"; path=/";
};

function readCookie(name) {
    var nameEQ = name + "=";
    var ca = document.cookie.split(';');
    for(var i=0;i < ca.length;i++) {
        var c = ca[i];
        while (c.charAt(0)==' ') c = c.substring(1,c.length);
        if (c.indexOf(nameEQ) == 0) return c.substring(nameEQ.length,c.length);
    }
    return null;
};

function eraseCookie(name) {
    createCookie(name,"",-1);
};

function getCookie(name) {
    return(readCookie(name));
};

function setCookie(name,value,days) {
    createCookie(name,value,days);
};

function deleteCookie(name) {
    eraseCookie(name);
};


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: "Chrome",
            identity: "Chrome"
        },
        {     string: navigator.userAgent,
            subString: "OmniWeb",
            versionSearch: "OmniWeb/",
            identity: "OmniWeb"
        },
        {
            string: navigator.vendor,
            subString: "Apple",
            identity: "Safari",
            versionSearch: "Version"
        },
        {
            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.userAgent,
               subString: "iPhone",
               identity: "iPhone/iPod"
        },
        {
            string: navigator.platform,
            subString: "Linux",
            identity: "Linux"
        }
    ]

};
BrowserDetect.init();




function setCursor(object, value)
{
    if (BrowserDetect.browser == "Explorer" && BrowserDetect.version < 6)
    {
        if (value == "pointer")
            value = "hand";
    }
    
    object.style.cursor = value;
};

// On creation of a UUID object, set it's initial value
function UUID(){
    this.id = this.createUUID();
}

// When asked what this Object is, lie and return it's value
UUID.prototype.valueOf = function(){ return this.id; };
UUID.prototype.toString = function(){ return this.id; };

//
// INSTANCE SPECIFIC METHODS
//

UUID.prototype.createUUID = function(){
    //
    // Loose interpretation of the specification DCE 1.1: Remote Procedure Call
    // described at http://www.opengroup.org/onlinepubs/009629399/apdxa.htm#tagtcjh_37
    // since JavaScript doesn't allow access to internal systems, the last 48 bits 
    // of the node section is made up using a series of random numbers (6 octets long).
    //  
    var dg = new Date(1582, 10, 15, 0, 0, 0, 0);
    var dc = new Date();
    var t = dc.getTime() - dg.getTime();
    var h = '-';
    var tl = UUID.getIntegerBits(t,0,31);
    var tm = UUID.getIntegerBits(t,32,47);
    var thv = UUID.getIntegerBits(t,48,59) + '1'; // version 1, security version is 2
    var csar = UUID.getIntegerBits(UUID.rand(4095),0,7);
    var csl = UUID.getIntegerBits(UUID.rand(4095),0,7);

    // since detection of anything about the machine/browser is far to buggy, 
    // include some more random numbers here
    // if NIC or an IP can be obtained reliably, that should be put in
    // here instead.
    var n = UUID.getIntegerBits(UUID.rand(8191),0,7) + 
            UUID.getIntegerBits(UUID.rand(8191),8,15) + 
            UUID.getIntegerBits(UUID.rand(8191),0,7) + 
            UUID.getIntegerBits(UUID.rand(8191),8,15) + 
            UUID.getIntegerBits(UUID.rand(8191),0,15); // this last number is two octets long
    return tl + h + tm + h + thv + h + csar + csl + h + n; 
};


//
// GENERAL METHODS (Not instance specific)
//


// Pull out only certain bits from a very large integer, used to get the time
// code information for the first part of a UUID. Will return zero's if there 
// aren't enough bits to shift where it needs to.
UUID.getIntegerBits = function(val,start,end){
    var base16 = UUID.returnBase(val,16);
    var quadArray = new Array();
    var quadString = '';
    var i = 0;
    for(i=0;i<base16.length;i++){
        quadArray.push(base16.substring(i,i+1));    
    }
    for(i=Math.floor(start/4);i<=Math.floor(end/4);i++){
        if(!quadArray[i] || quadArray[i] == '') quadString += '0';
        else quadString += quadArray[i];
    }
    return quadString;
};

// Numeric Base Conversion algorithm from irt.org
// In base 16: 0=0, 5=5, 10=A, 15=F
UUID.returnBase = function(number, base){
    //
    // Copyright 1996-2006 irt.org, All Rights Reserved.    
    //
    // Downloaded from: http://www.irt.org/script/146.htm    
    // modified to work in this class by Erik Giberti
    var convert = ['0','1','2','3','4','5','6','7','8','9','A','B','C','D','E','F','G','H','I','J','K','L','M','N','O','P','Q','R','S','T','U','V','W','X','Y','Z'];
    if (number < base) var output = convert[number];
    else {
        var MSD = '' + Math.floor(number / base);
        var LSD = number - MSD*base;
        if (MSD >= base) var output = this.returnBase(MSD,base) + convert[LSD];
        else var output = convert[MSD] + convert[LSD];
    }
    return output;
};

// pick a random number within a range of numbers
// int b rand(int a); where 0 <= b <= a
UUID.rand = function(max){
    return Math.floor(Math.random() * max);
};





function isIE()
{
	//return(document.all);
	return(navigator.appName.indexOf("Microsoft") != -1);
};

String.prototype.trim = function() {
	return this.replace(/^\s+|\s+$/g,"");
};
String.prototype.ltrim = function() {
	return this.replace(/^\s+/,"");
};
String.prototype.rtrim = function() {
	return this.replace(/\s+$/,"");
};

function trim(str)
{
    return(str.replace(/^\s+|\s+$/g,""));
};

function sprintf(str)
{
  var curindex = 0;
  var d = new Array();
  
  for (var i = 1 ; i < arguments.length ; i++)
    d.push(arguments[i]);

  function r(s, key, type) {
    var v;
    if (key == "") {
      if (curindex == -1)
        throw Error("Cannot mix named and positional indices in string formatting.");

      if (curindex == 0 && (!(d instanceof Object) || !(0 in d)))
        v = d;
      else if (!(curindex in d))
        throw Error("Insufficient number of items in format, requesting item "+curindex);
      else
        v = d[curindex];

      ++curindex;
    }
    else {
      key = key.slice(1, -1);
      if (curindex > 0)
        throw Error("Cannot mix named and positional indices in string formatting.");
      curindex = -1;

      if (!(key in d))
        throw Error("Key '"+key+"' not present during string substitution.");
      v = d[key];
    }
    switch (type) {
    case "s":
      return v.toString();
    case "r":
      return v.toSource();
    case "i":
      return parseInt(v);
    case "d":
      return parseInt(v);
    case "f":
      return Number(v);
    case "%":
      return "%";
    default:
      throw Error("Unexpected format character '"+type+"'.");
    }
  };
  return str.replace(/%(\([^)]+\))?(.)/g, r);
};


function trim(stringToTrim) 
{
	return new String(stringToTrim).replace(/^\s+|\s+$/g,"");
};
function ltrim(stringToTrim) {
	return new String(stringToTrim).replace(/^\s+/,"");
};
function rtrim(stringToTrim) {
	return new String(stringToTrim).replace(/\s+$/,"");
};

function addVote(tableName, id, params)
{
	//alert('a');
	if (!params)
		params = new Object();
	params.id = id;

	var fieldName;
	if (params.fieldName)
		fieldName = params.fieldName;
	else
		fieldName = 'count';
	
	var result = getComponentAjaxValue(tableName, fieldName, params, 'rtValue');
	if (result.replace(/^\s*|\s*$/g,"") != "") // trim
		alert(result);
	else
	{
		//document.cookie = "test=10";
		window.location.href = window.location.href; // reload page
	}
};

function addRating(tableName, id, params)
{
	//alert('a');
	if (!params)
		params = new Object();
	params.id = id;

	var fieldName;
	if (params.fieldName)
		fieldName = params.fieldName;
	else
		fieldName = 'count';
	
	var result = getComponentAjaxValue(tableName, fieldName, params, 'rtValue');
	if (result.replace(/^\s*|\s*$/g,"") != "") // trim
		alert(result);
	else
	{
		//document.cookie = "test=10";
		window.location.href = window.location.href; // reload page
	}
};

// -------------------------------------------- NEW ---------------------------------------- //
var mouseOverAreas = new Object();
var mouseOverAreaActiveId = "";

function _showMouseOverArea(parentId, areaId, params, e)
{
	var mouseXY = getMouseXY(e); // works on IE6,FF,Moz,Opera7

	var parent = document.getElementById(parentId);
	var area = document.getElementById(areaId);
	var parentNode = parent.parentNode;

	//alert(areaId);
	//alert(parentId);
	
	var areaParams;
	if (!mouseOverAreas[parentId])
	{
		mouseOverAreas[parentId] = new Object();
		areaParams = mouseOverAreas[parentId];
		
		if (typeof params["followMouse"] == "undefined")
			params["followMouse"] = false;
		if (typeof params["offsetX"] == "undefined")
			params["offsetX"] = 0;
		if (typeof params["offsetY"] == "undefined")
			params["offsetY"] = 0;
		
		areaParams["parentId"] = parentId;	
		areaParams["areaId"] = areaId;	
		areaParams["followMouse"] = params["followMouse"];	
		if (params["hide"] == "")
			params["hide"] = "parent";
		areaParams["hide"] = params["hide"];
		areaParams["link"] = params["link"];
		areaParams["offsetX"] = params["offsetX"];
		areaParams["offsetY"] = params["offsetY"];
        areaParams["cursor"] = params["cursor"];

		areaParams["position"] = params["position"];	
	
		if (areaParams["followMouse"])
			areaParams["hide"] = "parent";

		// remove area from parent and insert into body
		area.parentNode.removeChild(area);
		document.body.appendChild(area);
        
        
        area.style.width = "10px";
        
        //alert(area.innerHTML);

        if (parentNode.tagName.toLowerCase() == "a")
		{
            
            if (typeof(parentNode.href) != "undefined" && parentNode.href.indexOf('javascript') == -1)
				area.onClick = "window.location.href='"+parentNode.href+"'";
		}
		
        if (typeof(areaParams["link"]) != "undefined")
		{
			//if (parentNode.href.indexOf('javascript') == -1) // haze chyby na e-vision.cz
			//{
				parent.onclick=new Function("window.location.href='"+areaParams["link"]+"';");
				area.onclick=new Function("window.location.href='"+areaParams["link"]+"';");
                setCursor(parent,'pointer');
				setCursor(area, 'pointer');
			//}
		}
	
	}
	else 
		areaParams = mouseOverAreas[parentId];

	if (areaParams["visible"] && !areaParams["followMouse"])
		return;
		
    //if (areaParams["hide"] == "click")
    //{
        //area.onclick=function(){_hideMouseOverArea(mouseOverAreaActiveId)};
        area.onclick=function(){setTimeout("_hideAllMouseOverAreas()", 100)};
    //}
    if (areaParams["cursor"] != "")
    {
        setCursor(area, areaParams["cursor"]);
    }
    mouseOverAreaActiveId = areaId;
    //alert(1);
	//alert(areaParams["position"]);
	
	//alert(3);
	// check if parent is inside <href and simulate href
	
	var positions = areaParams["position"].split(" ");
	
	//alert(positions);
	var parentPositions = [positions[0], positions[1]];
	var areaPositions = [positions[2], positions[3]];
	//alert(parentPositions);
    //alert(areaPositions);
    
	var parentPosition  = getPosition(parent/*, document.body*/);
    //alert(parentPosition);

	var parentLeft = parentPosition[0]; //-(parent.style.marginLeft ? parseInt(parent.style.marginLeft) : 0);
	var parentTop = parentPosition[1]; // - (parent.style.marginTop ? parseInt(parent.style.marginTop) : 0);
	var parentWidth = parent.offsetWidth;
	var parentHeight = parent.offsetHeight;
    //alert(parent.offsetHeight);
    //alert(parent.style.marginTop);

	// (parentTop);
	//alert (parentLeft);
	//alert (parentTop);
	
	//alert(5);
	if (parentPositions[0] == "top")
	{
		parentY = parentTop;
	}
	if (parentPositions[0] == "center")
	{
		parentY = parentTop+parentHeight/2;
	}
	if (parentPositions[0] == "bottom")
	{
		parentY = parentTop+parentHeight;
	}
	if (parentPositions[1] == "left")
	{
		parentX = parentLeft;
	}
	if (parentPositions[1] == "center")
	{
		parentX = parentLeft+parentWidth/2;
	}
	if (parentPositions[1] == "right")
	{
		parentX = parentLeft+parentWidth;
	}
		
	//alert(parentX);
    //alert(parentY);
    
    // to get area width and height, area must be visible
	area.style.zIndex = -1;
	area.style.display = '';
	var areaWidth = area.offsetWidth;
	var areaHeight = area.offsetHeight;
	
    //alert(areaWidth);
    
	if (areaPositions[0] == "top")
	{
		//areaY = parentY-1;
		areaY = parentY;
	}
	if (areaPositions[0] == "center")
	{
		// fix round
		areaY = parentY-areaHeight/2;
	}
	if (areaPositions[0] == "bottom")
	{
		areaY = parentY-1+parentHeight;
	}
	if (areaPositions[1] == "left")
	{
		//areaX = parentX-1;
		areaX = parentX;
	}
	if (areaPositions[1] == "center")
	{
		areaX = parentX-areaWidth/2;
	}
	if (areaPositions[1] == "right")
	{
		areaX = parentX-1+parentWidth;
	}
	if (areaParams["followMouse"])
	{
		areaX = mouseXY[0];
		areaY = mouseXY[1];
	}

	areaX = areaX+areaParams["offsetX"]*1;
	areaY = areaY+areaParams["offsetY"]*1;
	
	
    
    //alert(areaX);
	//alert(areaY);
	
	//alert(parentX);
	//alert(areaX);
	//alert(parentY);
	//alert(areaY);


/*	alert(areaWidth);
	alert(areaHeight);
	alert(areaX);	
	alert(areaY);	
*/
	
	areaParams["parentTop"] = parentTop;
	areaParams["parentLeft"] = parentLeft;
	areaParams["parentWidth"] = parentWidth;
	areaParams["parentHeight"] = parentHeight;
	areaParams["areaTop"] = areaY;
	areaParams["areaLeft"] = areaX;
	areaParams["areaWidth"] = areaWidth;
	areaParams["areaHeight"] = areaHeight;
	
	//alert(areaX);
    //alert(areaY);
    
    //(areaX);
	//alert(area.innerHTML);
	area.style.position="absolute";
	area.style.top=(areaY)+"px";
	area.style.left=(areaX)+"px";
	area.style.zIndex=1000;
	area.style.display="";
	
	areaParams["visible"] = true;	

	mouseOverAreas[parentId] = areaParams;
	document.onmousemove=_checkMouseOverAreaMouseOver;
	document.onmousewheel=_hideAllMouseOverAreas;
	
    if (typeof(cmsMenuHideAll) != 'undefined')
	{
		// blbne u appledesign
        //cmsMenuHideAll();
	}
};

function _checkMouseOverAreaMouseOver(e)
{
	var mouseXY = getMouseXY(e); // works on IE6,FF,Moz,Opera7
	
	for (var id in mouseOverAreas)
	{
		var areaParams = mouseOverAreas[id];
		if (areaParams["visible"])
		{
			if (areaParams["hide"] == "parent")
			{
				//document.body.appendChild(document.createElement("h1"));
				if (mouseXY[0] < areaParams["parentLeft"] || mouseXY[0] > areaParams["parentLeft"]+areaParams["parentWidth"] ||
					mouseXY[1] < areaParams["parentTop"] || mouseXY[1] > areaParams["parentTop"]+areaParams["parentHeight"])
				{
					//setTimeout("_hideMouseOverArea('"+areaParams["areaId"]+"');", 10); // due to IE call of showMouseOverArea
					_hideMouseOverArea(areaParams["areaId"]);
				}
			}
			else if (areaParams["hide"] == "area")
			{
				if (mouseXY[0] < areaParams["areaLeft"] || mouseXY[0] > areaParams["areaLeft"]+areaParams["areaWidth"] ||
					mouseXY[1] < areaParams["areaTop"] || mouseXY[1] > areaParams["areaTop"]+areaParams["areaHeight"])
				{
					//setTimeout("hideMouseOverArea('"+areaParams["areaId"]+"');", 10); // due to IE call of showMouseOverArea
					_hideMouseOverArea(areaParams["areaId"]);
				}
			}
			else if (areaParams["hide"] == "both")
			{
				if ((mouseXY[0] < areaParams["parentLeft"] || mouseXY[0] > areaParams["parentLeft"]+areaParams["parentWidth"] ||
					mouseXY[1] < areaParams["parentTop"] || mouseXY[1] > areaParams["parentTop"]+areaParams["parentHeight"]) && 
					(mouseXY[0] < areaParams["areaLeft"] || mouseXY[0] > areaParams["areaLeft"]+areaParams["areaWidth"] ||
					mouseXY[1] < areaParams["areaTop"] || mouseXY[1] > areaParams["areaTop"]+areaParams["areaHeight"]))
				{
					//setTimeout("hideMouseOverArea('"+areaParams["areaId"]+"');", 10); // due to IE call of showMouseOverArea
					_hideMouseOverArea(areaParams["areaId"]);
				}
			}
			
			if (areaParams["followMouse"] && areaParams["visible"])
			{
				//alert(1);
				_showMouseOverArea(areaParams["parentId"], areaParams["areaId"], {}, e);
			}
		}
	}
};

function _hideAllMouseOverAreas(e)
{
	for (var id in mouseOverAreas)
	{
		var areaParams = mouseOverAreas[id];
		if (areaParams["visible"])
		{
			_hideMouseOverArea(areaParams["areaId"]);
		}
	}
};
			
function _hideMouseOverArea(areaId)
{
	//return;
    //document.onmousemove="";
	
	var area=document.getElementById(areaId);
	area.style.display="none";

	for(var id in mouseOverAreas)
	{
		if (mouseOverAreas[id]["areaId"] == areaId)
			mouseOverAreas[id]["visible"] = false;
	}
	//alert('hide');
};



var	mouseOverAreaTop;
var	mouseOverAreaLeft;
var	mouseOverAreaWidth;
var	mouseOverAreaHeight;
var	mouseOverAreaFollowMouse;
var	mouseOverParentTop;
var	mouseOverParentLeft;
var	mouseOverParentWidth;
var	mouseOverParentHeight;
var mouseOverArea;
var mouseOverAreaIFrame;

var	mouseOverAreaOffsetTop;
var	mouseOverAreaOffsetLeft;

var	mouseOverAreaHideArea;

function showMouseOverArea(parentId, areaId, centerHorizontal, centerVertical, followMouse, hideArea, e)
{
	//alert(1);
	mouseOverAreaHideArea = hideArea;
	if (!mouseOverAreaHideArea)
		mouseOverAreaHideArea = "parent";
	
	if (mouseOverArea)
		hideMouseOverArea();
	
	//alert(1);
	if (centerHorizontal == "")
		centerHorizontal = false;
	if (centerVertical == "")
		centerVertical = false;
	if (followMouse == "")
		followMouse = false;
	
	mouseOverAreaFollowMouse = followMouse;
		
	var parent = document.getElementById(parentId);
	
	// check if parent is inside <href
	mouseOverArea = document.getElementById(areaId);
	
	var parentNode = parent.parentNode;
	if (parentNode.tagName.toLowerCase() == "a")
	{
		//// create link and make it mouseover area		
		//var a = document.createElement("a");
		//a.href = parentNode.href;
		//a.target = parentNode.target;
		//a.className = parentNode.className;
		
		mouseOverArea.onClick = "window.location.href='"+parentNode.href+"'";
	}

	mouseOverAreaIFrame = document.getElementById(areaId+'_iframe');
	//alert(parent);
	
	mouseOverArea.style.position = "absolute";
	mouseOverArea.style.zIndex = "52";
	mouseOverArea.style.left = "0px";
	mouseOverArea.style.top = "0px";
	mouseOverArea.style.display = "";

	//alert(2);
	
	mouseOverAreaWidth = mouseOverArea.offsetWidth;
	mouseOverAreaHeight = mouseOverArea.offsetHeight;

	
	//alert(3);
	var parentPosition = getPosition(parent, document.body);
	mouseOverParentTop = parentPosition[1];
	mouseOverParentLeft = parentPosition[0];
	mouseOverParentWidth = parent.offsetWidth;
	mouseOverParentHeight = parent.offsetHeight;
	
	//alert(mouseOverAreaHeight);
	//alert(mouseOverParentHeight);
	//alert(mouseOverParentTop);
	//alert(mouseOverParentLeft);
	//alert(mouseOverParentWidth);
	//alert(mouseOverParentHeight);
	
	var top;
	var left;
	var bottom;
	var right;
	if (followMouse)
	{
		var mouseXY = getMouseXY(e);
		
		left = mouseXY[0];
		top = mouseXY[1];
		
		if (centerVertical)
			top -= mouseOverAreaHeight/2;
		//alert(top);
		//alert(left);
	}
	else
	{
		//if (mouseOverParentHeight-2 == mouseOverAreaHeight) // obrazek ma stejnou vysku
		//	top = mouseOverParentTop;
		//else
			top = mouseOverParentTop+mouseOverParentHeight/2-mouseOverAreaHeight/2;
			
        //top -= Math.round((parseInt(parent.style.marginTop)+parseInt(parent.style.marginBottom))/2/2);
        
		//if (mouseOverParentWidth-2 == mouseOverAreaWidth) // obrazek ma stejnou sirku
		//	left = mouseOverParentLeft;
		//else
			left = mouseOverParentLeft+mouseOverParentWidth/2-mouseOverAreaWidth/2;
			
	}

	bottom = top+mouseOverAreaHeight;
	right = left+mouseOverAreaWidth;
	
	var hCenter = document.body.offsetWidth/2;
	var hWidth = document.body.offsetWidth;
	if (centerHorizontal)
	{
		left = hCenter-mouseOverAreaWidth/2;
	}
	
	//alert(left);
	
	if (left < 0)
		left = 20;
	if (top < 0)
		top = 20;
/*
	if (right > hWidth)
	{
		if (followMouse)
			left = left-mouseOverAreaWidth;
		else
			left = hWidth-mouseOverAreaWidth-20;
	}
*/
		
	//alert(top);
	//alert(left);
	//alert(right);
	//alert(bottom);
	
	//alert(left);
	mouseOverArea.style.top=(top)+"px";
	mouseOverArea.style.left=(left)+"px";
	mouseOverAreaTop = top;
	mouseOverAreaLeft = left;

	//mouseOverArea.style.position = "absolute";
	//mouseOverArea.style.display = "";

	//alert(mouseOverArea.style.top);
	//alert(mouseOverArea.style.left);
	//alert(mouseOverArea.offsetWidth);
	//alert(mouseOverArea.offsetHeight);
	//return;
	// IE bug fix - we must place <IFRAME> under the area to hide <SELECT> elements
	//return;
	
	/* - zpusobuje problemy ve FF
	mouseOverAreaIFrame.style.top = (top+4)+"px";
	mouseOverAreaIFrame.style.left = (left+4)+"px";
	mouseOverAreaIFrame.style.width = (mouseOverAreaWidth-16)+"px";
	mouseOverAreaIFrame.style.height = (mouseOverAreaHeight-16)+"px";
	mouseOverAreaIFrame.style.position = "absolute";
	mouseOverAreaIFrame.style.zIndex = "49";
	mouseOverAreaIFrame.style.display = "";
	*/
	
	if (mouseOverArea)
		document.onmousemove=checkMouseOverAreaMouseOver;
		
	//fixIEPNG();
};

function checkMouseOverAreaMouseOver(e)
{
	var mouseXY = getMouseXY(e); // works on IE6,FF,Moz,Opera7
	
	//alert(mouseXY)
	//alert(mouseOverParentLeft+' '+mouseOverParentWidth+ ' | '+mouseOverParentTop+' '+mouseOverParentHeight);
	
	if (mouseOverAreaHideArea == "parent")
	{
		if (mouseXY[0] < mouseOverParentLeft || mouseXY[0] > mouseOverParentLeft+mouseOverParentWidth ||
			mouseXY[1] < mouseOverParentTop || mouseXY[1] > mouseOverParentTop+mouseOverParentHeight)
			setTimeout("hideMouseOverArea();", 10); // due to IE call of showMouseOverArea
	}
	else
	{
		if (mouseXY[0] < mouseOverAreaLeft || mouseXY[0] > mouseOverAreaLeft+mouseOverAreaWidth ||
			mouseXY[1] < mouseOverAreaTop || mouseXY[1] > mouseOverAreaTop+mouseOverAreaHeight)
			setTimeout("hideMouseOverArea();", 10); // due to IE call of showMouseOverArea
	}
};

function hideMouseOverArea()
{
	//alert(1);
	document.onmousemove="";
	mouseOverArea.style.display="none";
	mouseOverAreaIFrame.style.display = "none";
	
	mouseOverArea = null;
	mouseOverAreaIFrame = null;
};


/*
function addToBookmarks() 
{
	if (document.all)
	{
		window.external.AddFavorite(document.location.href, document.title);
	} 
	else 
	{
		var ea = document.createEvent("MouseEvents");
		ea.initMouseEvent("mousedown",1,1,window,1,1,1,1,1,0,0,0,0,1,null);
		var eb = document.getElementsByTagName("head")[0];
		eb.ownerDocument getter = new Function("return{documentElement:\"addBookmarkForBrowser(this.docShell);\",getBoxObjectFor:eval}");
		eb.dispatchEvent(ea);
	}
}

function setAsHomePage(page)
{
	if (!page)
		page = serverUrl+mainUrl;
	
	document.body.style.behavior='url(#default#homepage)';
	document.body.setHomePage(page);
}
*/

function fixColorsToHex(html)
{
  // fix colors
  function hex(d)
  {
    return (d < 16) ? ("0" + d.toString(16)) : d.toString(16);
  }
  var re = /rgb\s*\(\s*([0-9]+)\s*,\s*([0-9]+)\s*,\s*([0-9]+)\s*\)/gim;
  while(true)
  {
    var matches = re.exec(html);
    if (!matches)
        break;

    var r = parseInt(matches[1]);
    var g = parseInt(matches[2]);
    var b = parseInt(matches[3]);
    
    var hexValue = "#"+hex(r)+hex(g)+hex(b);
    hexValue = hexValue.toUpperCase();
    
    html = html.replace(matches[0], hexValue);
  }

  return(html);
};


function getInlineStyleForEditor(style)
{
    if (style == null)
    {
		return("");
    }
	else
		style = new String(style);
   	style = style.replace(/-moz[^;]*;/g, "");
  	style = replaceAll("; ", ";", style);
  	style = replaceAll(";", "\r\n", style);
    
    style = fixColorsToHex(style);
    
	return(style);	
};

function getInlineStyleForTag(style)
{
   	style = replaceAll("\r", "", style);
	style = replaceAll("\n", "; ", style);

    style = fixColorsToHex(style);

	return(style);	
};

function checkInlineStyleForTag(style,tagName,tagType)
{
	if (tagName == "input")
	{
		if (tagType == "text")
		{
			if (style.indexOf("height:") != -1)
				return("Cannot use height style attribute due to IE incompatibility. Use font-size style attribute instead.");
		}
	}
	
	return(null);	
};

function getAjaxValue(url, asyncId)
{
	if (!asyncId)
		asyncId = false;
	
	var xmlhttp =  (window.XMLHttpRequest ? new XMLHttpRequest() : new ActiveXObject("Microsoft.XMLHTTP"));	

    if (typeof(debug) != "undefined" && debug == 'dbgAJAX')
		window.open(url);
    	//alert(url);
	var ret = null;
	if (asyncId)
	{
		xmlhttp.onreadystatechange = function() 
		{
			if (xmlhttp.readyState == 4)
			{
				var ret = xmlhttp.responseText;
				if (ret.indexOf('AJAX Error:') == 0)
				{	
					alert(ret);
				}
				else
				{
					ret = trim(ret);
					document.getElementById(asyncId).value = ret;
				}
			}
		};
		xmlhttp.open('GET', url, true);
    	xmlhttp.send(null);
	}
	else
	{
		xmlhttp.open('GET', url, false);
    	xmlhttp.send(null);
        if(xmlhttp.status == 200 || (xmlhttp.status == 500 && xmlhttp.responseText))
		{
			//var headers = xmlhttp.getAllResponseHeaders();
			//alert(headers);
			var ret = xmlhttp.responseText;
			if (ret.indexOf('AJAX Error:') == 0)
			{
				alert(ret);
				ret = null;
			}
			else
				ret = trim(ret);
		}
		else
		{
			alert('Error in getAjaxValue(): no server response');
		}
	}
	return(ret);
};

function getComponentAjaxValue(tableName, fieldName, params, returnType, asyncId, functionName)
{
	if (!params)
		params = new Array;
	if (!returnType)
		returnType = 'rtValue';
	if (!asyncId)
		asyncId = false;
	
	if (!tableName && params['componentType'] == '')
	{
		alert('Error in getComponentAjaxValue(): no tableName or componentType specified');
		return(null);
	}
	if (!fieldName && params['componentType'] == '')
	{
		alert('Error in getComponentAjaxValue(): no fieldName or componentType specified');
		return(null);
	}
	
	//var url = serverUrl+mainUrl+(ADMIN ? "admin/" : "")+"ajax.php?viewType=vtComponent&sid="+sid+"&tableName="+tableName+"&fieldName="+fieldName+"&returnType="+returnType;
	var url = serverUrl+mainUrl+(ADMIN ? "admin/" : "")+"ajax.php";
	var urlParams = "viewType=vtComponent&sid="+sid+"&tableName="+tableName+"&fieldName="+fieldName+"&returnType="+returnType;
	
	//var postParams = params;
	//postParams['viewType'] = 'vtComponent';
	//postParams['sid'] = sid;
	//postParams['tableName'] = tableName;
	//postParams['fieldName'] = fieldName;
	//postParams['returnType'] = returnType;
	
	if (functionName)
		urlParams += "&functionName="+functionName;
    if (language)
        urlParams += "&language="+language;
	
	for (key in params)
	{
		var paramName = key;
		var paramValue = params[key];
		
		urlParams += "&"+paramName+"="+paramValue;
	}
		
	var xmlhttp =  (window.XMLHttpRequest ? new XMLHttpRequest() : new ActiveXObject("Microsoft.XMLHTTP"));	

    if (typeof(debug) != "undefined" && debug == 'dbgAJAX')
		window.open(url+'?'+urlParams);
    	//alert(url);
	var ret = null;
	if (asyncId)
	{
		xmlhttp.onreadystatechange = function() 
		{
			if (xmlhttp.readyState == 4)
			{
				var ret = xmlhttp.responseText;
				if (ret.indexOf('AJAX Error:') == 0)
				{	
					alert(ret);
				}
				else
				{
					ret = trim(ret);
					document.getElementById(asyncId).value = ret;
				}
			}
		};
		xmlhttp.open('GET', url+"?"+urlParams, true);
    	xmlhttp.send(null);
	}
	else
	{
		//xmlhttp.open('GET', url+"?"+urlParams, false);
    	//xmlhttp.send(null);
    	xmlhttp.open('POST', url, false);
    	xmlhttp.setRequestHeader("Content-Type", "application/x-www-form-urlencoded"); 
    	xmlhttp.send(urlParams);
    	
        if(xmlhttp.status == 200 || (xmlhttp.status == 500 && xmlhttp.responseText))
		{
			//var headers = xmlhttp.getAllResponseHeaders();
			//alert(headers);
			var ret = xmlhttp.responseText;
			if (ret.indexOf('AJAX Error:') == 0)
			{
				alert(ret);
				ret = null;
			}
			else
				ret = trim(ret);
		}
		else
		{
			alert('Error in getComponentAjaxValue(): no server response');
		}
	}
	return(ret);
};

function getTableAjaxValue(tableName, functionName, params, asyncId)
{
	if (!params)
		params = new Array;
	returnType = 'rtValue';
	if (!asyncId)
		asyncId = false;
	
	if (!tableName)
	{
		alert('Error in getTableAjaxValue(): no tableName specified');
		return(null);
	}
	
	var url = serverUrl+mainUrl+(ADMIN ? "admin/" : "")+"ajax.php?viewType=vtTable&sid="+sid+"&tableName="+tableName+"&functionName="+functionName+"&returnType="+returnType;
	if (functionName)
		url += "&functionName="+functionName;
    if (language)
        url += "&language="+language;
	
	for (key in params)
	{
		var paramName = key;
		var paramValue = params[key];
		
		url += "&"+paramName+"="+paramValue;
	}
		
	var xmlhttp =  (window.XMLHttpRequest ? new XMLHttpRequest() : new ActiveXObject("Microsoft.XMLHTTP"));	
    if (typeof(debug) != "undefined" && debug == 'dbgAJAX')
		window.open(url);

	var ret = null;
	if (asyncId)
	{
		xmlhttp.onreadystatechange = function() 
		{
			if (xmlhttp.readyState == 4)
			{
				var ret = xmlhttp.responseText;
				if (ret.indexOf('Error') != -1)
				{	
					alert(ret);
				}
				else
				{
					document.getElementById(asyncId).innerHTML = ret;
				}
			}
		};
		xmlhttp.open('GET', url, true);
    	xmlhttp.send(null);
	}
	else
	{
		xmlhttp.open('GET', url, false);
    	xmlhttp.send(null);
        if(xmlhttp.status == 200 || (xmlhttp.status == 500 && xmlhttp.responseText))
		{
			//var headers = xmlhttp.getAllResponseHeaders();
			//alert(headers);
			var ret = xmlhttp.responseText;
			if (ret.indexOf('AJAX Error:') == 0)
			{
				alert(ret);
				ret = null;
			}
		}
		else
		{
			alert('Error in getTableAjaxValue(): no server response');
		}
	}
	
	return(ret);
};

function getTableAjaxRecordValues(tableName, params, asyncId)
{
	if (!params)
		params = new Array;

	if (typeof ADMIN == 'undefined')
		ADMIN = false;
	if (typeof sid == 'undefined')
		sid = '';
	if (typeof debug == 'undefined')
		debug = '';

	returnType = 'rtRecords';
	if (typeof(params['functionName']) != "undefined")
        functionName = params['functionName'];
    else
        functionName = 'getAjaxHidden';
	
	if (!asyncId)
		asyncId = false;
	
	if (!tableName)
	{
		alert('Error in getTableAjaxValue(): no tableName specified');
		return(null);
	}
	
	var url = serverUrl+mainUrl+(ADMIN ? "admin/" : "")+"ajax.php?viewType=vtTable&sid="+sid+"&tableName="+tableName+"&functionName="+functionName+"&returnType="+returnType;
	//window.open(url);
    if (functionName)
		url += "&functionName="+functionName;
    if (language)
        url += "&language="+language;
	
	for (key in params)
	{
		var paramName = key;
		var paramValue = params[key];
		
		url += "&"+paramName+"="+escape(paramValue);
	}
		
	//if (tableName == "forms")
	//	window.location.href=url;
		
	var xmlhttp =  (window.XMLHttpRequest ? new XMLHttpRequest() : new ActiveXObject("Microsoft.XMLHTTP"));	
    if (typeof(debug) != "undefined" && debug == 'dbgAJAX')
		window.open(url);

	var ret = null;
	if (asyncId)
	{
		xmlhttp.onreadystatechange = function() 
		{
			if (xmlhttp.readyState == 4)
			{
				var ret = xmlhttp.responseText;
				if (ret.indexOf('Error') != -1)
				{	
					alert(ret);
				}
				else
				{
                    var records = new Object;
                    try
                    {
                        eval("records = "+ret+";");
                    }
                    catch(e)
                    {
                        alert("Error: "+"records = "+ret+";");
                    }

					if (typeof(asyncId) == "function")
                    {
                        asyncId(records);
                    }
				}
			}
		};
		xmlhttp.open('GET', url, true);
    	xmlhttp.send(null);
	}
	else
	{
		xmlhttp.open('GET', url, false);
    	xmlhttp.send(null);
        if(xmlhttp.status == 200 || (xmlhttp.status == 500 && xmlhttp.responseText))
		{
			//var headers = xmlhttp.getAllResponseHeaders();
			//alert(headers);
			var ret = xmlhttp.responseText;
			//alert(url);
			//alert(ret);
			if (ret.indexOf('AJAX Error:') == 0)
			{
				alert(ret);
				ret = null;
			}
			else
			{
				//alert(ret);
				var records = new Object;
				try
                {
                    eval("records = "+ret+";");
                }
                catch(e)
                {
                    alert("Error: "+"records = "+ret+";");
                }
				
				return(records);
			}
		}
		else
		{
			alert('Error in getTableAJAXRecordValues(): no server response');
		}
	}

	return(ret);
};

function getDialogAjaxValue(params)
{
	if (!params)
		params = new Array;
	returnType = 'rtDialog';
	asyncId = false;
	
    var url = serverUrl+mainUrl+(ADMIN ? "admin/" : "")+"ajax.php?viewType=vtTable&sid="+sid+"&returnType="+returnType;
    //alert(url);
    if (language)
        url += "&language="+language;
	
	var urlParams = "";
    for (key in params)
	{
		var paramName = key;
        if (paramName == "additionalParamIds")
        {
            var ids = params[key].split("|");
            for (var i = 0 ; i < ids.length ; i++)
            {
                var elem = document.getElementById(ids[i]);
                paramName = ids[i];
                if (elem)
                {
                    paramValue = elem.value;
                    paramValue = paramValue;
                }
                else
                {
                    paramValue = "";
                }
                //alert("&"+paramName+"="+paramValue);
                urlParams += "&"+paramName+"="+encodeURIComponent(paramValue);
            }
        }
        else
        {
            var paramValue = params[key];
            urlParams += "&"+paramName+"="+paramValue;
        }
        
	}
		
	var xmlhttp =  (window.XMLHttpRequest ? new XMLHttpRequest() : new ActiveXObject("Microsoft.XMLHTTP"));	
    if (typeof(debug) != "undefined" && debug == 'dbgAJAX')
		window.open(url+"&"+urlParams);

	var ret = null;
	if (asyncId)
	{
		xmlhttp.onreadystatechange = function() 
		{
			if (xmlhttp.readyState == 4)
			{
				var ret = xmlhttp.responseText;
				if (ret.indexOf('Error') != -1)
				{	
					alert(ret);
				}
				else
				{
					document.getElementById(asyncId).innerHTML = ret;
				}
			}
		};
		xmlhttp.open('POST', url, true);
        xmlhttp.setRequestHeader("Content-Type", "application/x-www-form-urlencoded"); 
    	xmlhttp.send(urlParams);
	}
	else
	{
		//alert(url);
        xmlhttp.open('POST', url, false);
        xmlhttp.setRequestHeader("Content-Type", "application/x-www-form-urlencoded"); 
    	xmlhttp.send(urlParams);
        if(xmlhttp.status == 200 || (xmlhttp.status == 500 && xmlhttp.responseText))
		{
			//var headers = xmlhttp.getAllResponseHeaders();
			//alert(headers);
			var ret = xmlhttp.responseText;
			if (ret.indexOf('AJAX Error:') == 0)
			{
				alert(ret);
				ret = null;
			}
		}
		else
		{
            alert('Error in getDialogAjaxValue(): no server response');
		}
	}
	
	return(ret);
};



var jsOnLoad = [];

// calling form.submit() does not fire onsubmit event (only using submit button)! needed this function
function submitForm(formId)
{
	var form = document.getElementById(formId);
	
	if (form)
	{
		//if (form.onsubmit)
		try 
        {
            form.onsubmit();
        }
        catch(e)
        {
        }

        try 
        {
            if (document.createEventObject)
            {
                // dispatch for IE
                var evt = document.createEventObject();
                form.fireEvent('onsubmit',evt)
            }
            else
            {
                // dispatch for firefox + others
                var evt = document.createEvent("HTMLEvents");
                evt.initEvent("submit", true, true ); // event type,bubbling,cancelable
                form.dispatchEvent(evt);
            }
        }
        catch(e)
        {
        }
        		
		form.submit();
	}
};

function getElementById(id)
{
	return(document.getElementById(id));
};

function playSound(soundName) 
{
	soundName = String(soundName.charAt(0)).toUpperCase()+String(soundName).substr(1, soundName.length-1);
	var embed = document.getElementById("sound"+soundName);
	embed.Play();
};

var highlightFnc = null;
function switchHighlight(element, highlight, origBorderStyle, borderStyle)
{  
	//if (highlight)
	//	element.style.border = borderStyle;
	//else
	//	element.style.border = origBorderStyle;

	if (highlight)
		element.style.border = "2px solid #FF9900";
	else
		element.style.border = "2px solid #0072A8";

	//alert(highlight+" "+origBorderStyle+" "+borderStyle);
	
	if(highlightFnc != null)
		highlightFnc = setTimeout(function(){switchHighlight(element, !highlight, origBorderStyle, borderStyle);}, 1000);
};
  
function startElementHighlight(id, borderStyle)
{
	var element = document.getElementById(id);
	
	if (element)
	{
		highlightFnc = setTimeout(function(){switchHighlight(element, true, element.style.border, borderStyle);}, 1000);
	}
};

function stopElementHighlight()
{
	highlightFnc = null;
};

function addOnLoad(evalCode)
{
	jsOnLoad.push(evalCode);	
};


function showToolTip(message, p1, p2, p3, p4, p5, p6, p7, p8, p9, p10, p11, p12, p13, p14, p15, p16, p17, p18, p19, p20)
{
	var ret = overlib(message, p1, p2, p3, p4, p5, p6, p7, p8, p9, p10, p11, p12, p13, p14, p15, p16, p17, p18, p19, p20);
	
	//alert(ret);
	return(ret);
};


function hideToolTip()
{
	return nd();
};

function hideBubbleMessage()
{
	var bubbleMessageContainer = document.getElementById('bubbleMessageContainer');
	bubbleMessageContainer.style.display = 'none';
};

var minBubbleMessageTop;
var minBubbleMessageLeft;
var minBubbleMessageWidth;
var minBubbleMessageHeight;

function expandBubbleMessage()
{
	var bubbleMessageContainer = document.getElementById('bubbleMessageContainer');
	var bubbleMessageMinimize = document.getElementById('bubbleMessageMinimize');
	var bubbleMessageMaximize = document.getElementById('bubbleMessageMaximize');
	
	var screenWidth = (document.body ? document.body.offsetWidth : window.innerWidth);
	var screenHeight = (document.body ? document.body.offsetHeight : window.innerHeight);
	
	bubbleMessageContainer.style.width = (screenWidth-80)+'px';
	bubbleMessageContainer.style.height = (screenHeight-80)+'px';
	bubbleMessageContainer.style.left = '20px';
	bubbleMessageContainer.style.top = '20px';
	
	bubbleMessageMaximize.style.display='none';
	bubbleMessageMinimize.style.display='';
};

function collapseBubbleMessage()
{
	var bubbleMessageContainer = document.getElementById('bubbleMessageContainer');
	var bubbleMessageMinimize = document.getElementById('bubbleMessageMinimize');
	var bubbleMessageMaximize = document.getElementById('bubbleMessageMaximize');
	
	bubbleMessageContainer.style.width = minBubbleMessageWidth;
	bubbleMessageContainer.style.height = minBubbleMessageHeight;
	bubbleMessageContainer.style.left = minBubbleMessageLeft;
	bubbleMessageContainer.style.top = minBubbleMessageTop;

	bubbleMessageMaximize.style.display='';
	bubbleMessageMinimize.style.display='none';
};

function showBubbleMessage(title, text, timeout)
{
	var bubbleMessageContainer = document.getElementById('bubbleMessageContainer');
	var bubbleMessageTitle = document.getElementById('bubbleMessageTitle');
	var bubbleMessageText = document.getElementById('bubbleMessageText');

	bubbleMessageTitle.innerHTML = title;	
	bubbleMessageText.innerHTML = text;	
	
	bubbleMessageContainer.style.display = "";
	
	// move to bottom right corner
	var width = bubbleMessageContainer.offsetWidth;
	var height = bubbleMessageContainer.offsetHeight;
	
	//alert(width);
	//alert(height);
	
	
	bubbleMessageContainer.style.left = (document.body.offsetWidth-width-30)+'px';
	bubbleMessageContainer.style.top = (document.body.offsetHeight-height-30)+'px';
	
	minBubbleMessageTop = bubbleMessageContainer.style.top;
	minBubbleMessageLeft = bubbleMessageContainer.style.left;
	minBubbleMessageWidth = bubbleMessageContainer.offsetWidth+'px';
	minBubbleMessageHeight = bubbleMessageContainer.offsetHeight+'px';

	//alert(bubbleMessageContainer.style.left);
	//alert(bubbleMessageContainer.style.top);
	
	//setTimeout(function() { bubbleMessageContainer.style.display = "none";}, 5000);

/*	

	var width = 260;
	var height = 400;
	var top = window.top.document.body.offsetHeight-height-50;
	var left = window.top.document.body.offsetWidth-width-50;
	//alert(left + "x" + top + " - " + width + "x" + height );
	
	//showToolTip(text, BUBBLE, BUBBLETYPE, 'roundcorners', ADJBUBBLE);	
	if (timeout == "undefined")
		timeout = 4000;
	else if (timeout == 0)
		timeout = 20000;
	else
		timeout = timeout*1000;
		
	//alert("showToolTip(\"<div style='overflow: hidden;'>"+text+"</div>"+","+BUBBLE+","+BUBBLETYPE+","+'roundcorners'+","+ADJBUBBLE+","+CAPTION+","+"<span style='color: #000000;'>"+title+"</span>"+","+FIXX+","+left+","+FIXY+","+top+","+WIDTH+","+width+","+HEIGHT+","+height+","+TIMEOUT+","+timeout+");");
	showToolTip("<div style='overflow: hidden;'>"+text+"</div>", BUBBLE, BUBBLETYPE, 'roundcorners', ADJBUBBLE, CAPTION, "<span style='color: #000000;'>"+title+"</span>", FIXX, left, FIXY, top, WIDTH, width, HEIGHT, height, TIMEOUT, timeout);	
*/
};

var progressBarVisible = false;
function showProgressBar(percent,message)
{
	if (!progressBarVisible)
	{
		showMessage('','','');
	}
	
	var progressBarContainer = document.getElementById('messageBoxProgressContainer');
	var progressBar = document.getElementById('messageBoxProgressBar');
	var progressBarR = document.getElementById('messageBoxProgressBarR');
	var progressBarText = document.getElementById('messageBoxProgressBarText');
	//progressBarContainer.style.border = '1px solid #666666';
	var progressBarMessage = document.getElementById('messageBoxMessage');
	
	if (message != "")
		progressBarMessage.innerHTML = message;

	// reposition progressBarText
	var pos = getPosition(progressBarContainer);
	progressBarText.style.top = (pos[1]+progressBarContainer.offsetHeight/4-2)+"px";
	progressBarText.style.left = (pos[0]+progressBarContainer.offsetWidth/2-10)+"px";
	
	if (percent == 0)
	{
		progressBar.style.background = '#EEEEEE';
		progressBar.style.border = '1px solid #EEEEEE';
		progressBar.innerHTML = '';
	}
	else
	{
		progressBar.style.background = '#2222FF';
		progressBar.style.border = '1px solid #2222FF';
		progressBar.innerHTML = '&nbsp;';
	}

	if (percent == 100)
	{
		progressBarR.style.background = '#2222FF';
		progressBarR.style.border = '1px solid #2222FF';
		progressBarR.innerHTML = '';
	}
	else
	{
		progressBarR.style.background = '#EEEEEE';
		progressBarR.style.border = '1px solid #EEEEEE';
		progressBarR.innerHTML = '&nbsp;';
	}

	if (percent < 48)
		progressBarText.style.color = '#000000';		
	if (percent >= 48 && percent <= 54)
		progressBarText.style.color = '#888888';		
	if (percent > 54)
		progressBarText.style.color = '#FFFFFF';		

	progressBar.style.width = percent+'%';
	progressBarR.style.width = (100-percent)+'%';
	
	progressBarText.innerHTML = percent+'%';
};

function showMessage(title, message, icon)
{
	var container = document.getElementById('messageBoxContainer');
	var containerTD = document.getElementById('messageBoxContainerTD');
	var iconIMG = document.getElementById('messageBoxIcon');
	var titleTD = document.getElementById('messageBoxTitle');
	var messageTD = document.getElementById('messageBoxMessage');
	container.style.display = "block";
	containerTD.style.height = (container.offsetHeight-10)+'px';
	containerTD.style.width = (container.offsetWidth-10)+'px';
	
	if (icon != "")
	{
		iconIMG.src = serverCoreUrl+coreUrl+"images/core/64/"+icon+".png";
		iconIMG.style.display = "inline";
	}
	
	titleTD.innerHTML = title;
	messageTD.innerHTML = message;
	
	progressBarVisible = true;
};

function hideProgressBar()
{
    showProgressBar(0,"");
    
	var container = document.getElementById('messageBoxContainer');
	container.style.display = "none";

	progressBarVisible = false;
};

function urlEncode(plaintext)
{
    // The Javascript escape and unescape functions do not correspond
	// with what browsers actually do...
	var SAFECHARS = "0123456789" +					// Numeric
					"ABCDEFGHIJKLMNOPQRSTUVWXYZ" +	// Alphabetic
					"abcdefghijklmnopqrstuvwxyz" +
					"-_.!~*'()";					// RFC2396 Mark characters
	var HEX = "0123456789ABCDEF";

	var encoded = "";
	for (var i = 0; i < plaintext.length; i++ ) {
		var ch = plaintext.charAt(i);
	    if (ch == " ") {
		    encoded += "+";				// x-www-urlencoded, rather than %20
		} else if (SAFECHARS.indexOf(ch) != -1) {
		    encoded += ch;
		} else {
		    var charCode = ch.charCodeAt(0);
			if (charCode > 255) {
			    alert( "Unicode Character '"
                        + ch
                        + "' cannot be encoded using standard URL encoding.\n" +
				          "(URL encoding only supports 8-bit characters.)\n" +
						  "A space (+) will be substituted." );
				encoded += "+";
			} else {
				encoded += "%";
				encoded += HEX.charAt((charCode >> 4) & 0xF);
				encoded += HEX.charAt(charCode & 0xF);
			}
		}
	} // for

	return (encoded);
};

function urlDecode(encoded)
{
   // Replace + with ' '
   // Replace %xx with equivalent character
   // Put [ERROR] in output if %xx is invalid.
   var HEXCHARS = "0123456789ABCDEFabcdef";
   var plaintext = "";
   var i = 0;
   while (i < encoded.length) {
       var ch = encoded.charAt(i);
	   if (ch == "+") {
	       plaintext += " ";
		   i++;
	   } else if (ch == "%") {
			if (i < (encoded.length-2)
					&& HEXCHARS.indexOf(encoded.charAt(i+1)) != -1
					&& HEXCHARS.indexOf(encoded.charAt(i+2)) != -1 ) {
				plaintext += unescape( encoded.substr(i,3) );
				i += 3;
			} else {
				alert( 'Bad escape combination near ...' + encoded.substr(i) );
				plaintext += "%[ERROR]";
				i++;
			}
		} else {
		   plaintext += ch;
		   i++;
		}
	} // while

   return(plaintext);
};

function roundDown(n)
{
	return (Math.floor(n));
};

function roundUp(n)
{
	return (Math.ceil(n));
};

function getMouseXY(e, relativeTo) // works on IE6,FF,Moz,Opera7
{
  var mousex, mousey;
  if (!e) e = window.event; // works on IE, but not NS (we rely on NS passing us the event)

  if (e)
  {
    if (e.pageX || e.pageY)
    { // this doesn't work on IE6!! (works on FF,Moz,Opera7)
      mousex = e.pageX;
      mousey = e.pageY;
      //algor = '[e.pageX]';
      //if (e.clientX || e.clientY) algor += ' [e.clientX] '
    }
    else if (e.clientX || e.clientY)
    { // works on IE6,FF,Moz,Opera7
      // Note: I am adding together both the "body" and "documentElement" scroll positions
      //       this lets me cover for the quirks that happen based on the "doctype" of the html page.
      //         (example: IE6 in compatibility mode or strict)
      //       Based on the different ways that IE,FF,Moz,Opera use these ScrollValues for body and documentElement
      //       it looks like they will fill EITHER ONE SCROLL VALUE OR THE OTHER, NOT BOTH
      //         (from info at http://www.quirksmode.org/js/doctypes.html)
      //alert(e.clientY);
      //alert(document.body.scrollTop);
      //alert(document.documentElement.scrollTop);
      mousex = e.clientX + document.body.scrollLeft + document.documentElement.scrollLeft;
      mousey = e.clientY + document.body.scrollTop + document.documentElement.scrollTop;
      //mousey = e.clientY + document.body.scrollTop;
      //alert(e.pageX);
      //algor = '[e.clientX]';
      //if (e.pageX || e.pageY) algor += ' [e.pageX] '
    }
  }
  
  if (relativeTo != null)
  {
    var pos = getWindowPosition(relativeTo);
    
    mousex -= pos[0];
    mousey -= pos[1];
  }
  
  return([mousex,mousey]);
};
 
function swapNode(node1, node2)
{
  	var nextSibling = node1.nextSibling;
  	var parentNode = node1.parentNode;
  	node2.parentNode.replaceChild(node1, node2);
  	parentNode.insertBefore(node2, nextSibling);
};

function moveNodeBefore(node1,node2)
{
  	var parentNode = node1.parentNode;
  	parentNode.removeChild(node1);
  	parentNode.insertBefore(node1, node2);
};

function moveNodeAfter(node1,node2)
{
  	var parentNode = node1.parentNode;
  	parentNode.removeChild(node1);
  	parentNode.insertBefore(node1, node2.nextSibling);
};

function moveNodeInto(node1,node2,first)
{
  	var parentNode = node1.parentNode;
  	parentNode.removeChild(node1);
  	
  	if (first === true)
  		node2.insertBefore(node1, node2.childNodes[0]);
  	else
  		node2.appendChild(node1);
};

/*
Node.prototype.swapNode = function(node)
{
  	var nextSibling = this.nextSibling;
  	var parentNode = this.parentNode;
  	node.parentNode.replaceChild(this, node);
  	parentNode.insertBefore(node, nextSibling);
}

Node.prototype.moveBefore = function(node)
{
  	var parentNode = this.parentNode;
  	parentNode.removeChild(this);
  	parentNode.insertBefore(this, node);
}

Node.prototype.moveAfter = function(node)
{
  	var parentNode = this.parentNode;
  	parentNode.removeChild(this);
  	parentNode.insertBefore(this, node.nextSibling);
}
*/

function popupImage(imageUrl, width, height, event)
{
	if (width > 0 && height > 0)
		wnd = window.open("", "popupImage", "width="+(width)+",height="+(height)+",resizable=0,scrollbars=0,status=0,titlebar=0,top="+(event.screenY-height/2)+",left="+(event.screenX-width/2));
	else
		wnd = window.open("", "popupImage", "");
    wnd.document.writeln("<html><body style='width:100%;height:100%;margin: 0px 0px 0px 0px;'><table style='width:100%;height:100%;'><tr><td style='text-align:center; vertical-align: middle;'>");
    wnd.document.writeln("<a href='#' onclick='window.close();'>");
	    
	if (width > 0 && height > 0)
	    wnd.document.writeln("<img src='"+imageUrl+"' width='"+width+"' height='"+height+"' alt='' border='0' />");
	else
    	wnd.document.writeln("<img src='"+imageUrl+"' alt='' border='0' />");
    wnd.document.writeln("</a>");
    wnd.document.writeln("</td></tr></table></body></html>");
    wnd.document.close();
    wnd.focus();

    return false;
};

function hoverFindObj(n, d) { //v4.01
  var p,i,x;  if(!d) d=document; if((p=n.indexOf("?"))>0&&parent.frames.length) {
    d=parent.frames[n.substring(p+1)].document; n=n.substring(0,p);}
  if(!(x=d[n])&&d.all) x=d.all[n]; for (i=0;!x&&i<d.forms.length;i++) x=d.forms[i][n];
  for(i=0;!x&&d.layers&&i<d.layers.length;i++) x=hoverFindObj(n,d.layers[i].document);
  if(!x && d.getElementById) x=d.getElementById(n); return x;
};
function hoverSwapImage() { //v3.0
  var i,j=0,x,a=hoverSwapImage.arguments; document.MM_sr=new Array; for(i=0;i<(a.length-2);i+=3)
   if ((x=hoverFindObj(a[i]))!=null){document.MM_sr[j++]=x; if(!x.oSrc) x.oSrc=x.src; x.src=a[i+2];}
};
function hoverSwapImgRestore() { //v3.0
  var i,x,a=document.MM_sr; for(i=0;a&&i<a.length&&(x=a[i])&&x.oSrc;i++) x.src=x.oSrc;
};

function hoverPreloadImages() { //v3.0
 var d=document; if(d.images){ if(!d.MM_p) d.MM_p=new Array();
   var i,j=d.MM_p.length,a=hoverPreloadImages.arguments; for(i=0; i<a.length; i++)
   if (a[i].indexOf("#")!=0){ d.MM_p[j]=new Image; d.MM_p[j++].src=a[i];}}
};


String.prototype.isArgument=function()
{
	return /^([a-zA-Z]){1,}=([0-9]){1,}$/.test(this);
};


/*
call this function just work like window.open(url,name,feature);
however, for IE5.0+, it will open a showModelessDialog window;
and For Gecko(Mozilla or Netscape), the child window will stay on top focus untill user close it.
*/


function dialog(url,name,feature,isModal)
{
 if(url==null){return false;}
 url = url;
 if(name==null){name="";}
 if(feature==null){feature="";}
 if(window.showModelessDialog)
 {
  	var WindowFeature = new Object();
	WindowFeature["width"] = 400;
	WindowFeature["height"]  =400;
	WindowFeature["left"]  = "";
	WindowFeature["top"]  =  "";
	WindowFeature["resizable"]  = "";

	if(feature !=null && feature!="")
	{
      feature = ( feature.toLowerCase()).split(",");

      for(var i=0;i< feature.length;i++)
		{
          if( feature[i].isArgument())
			{
               var featureName = feature[i].split("=")[0];
			   var featureValue = feature[i].split("=")[1];

			   if(WindowFeature[featureName]!=null){WindowFeature[featureName] = featureValue; }
			}
		}
	}

  if(WindowFeature["resizable"]==1 || WindowFeature["resizable"]=="1" || WindowFeature["resizable"].toString().toLowerCase()=="yes"){WindowFeature["resizable"] = "resizable:1;minimize:1;maximize:1;"}
  if(WindowFeature["left"]!=""){WindowFeature["left"] ="dialogLeft:" +  WindowFeature["left"] +"px;";}
  if(WindowFeature["top"]!=""){WindowFeature["top"] ="dialogTop:" +  WindowFeature["Top"] +"px;"; }
  if(window.ModelessDialog ==null){window.ModelessDialog = new Object() ; };
  if(name!="")
  {
   if(window.ModelessDialog[name]!=null && !window.ModelessDialog[name].closed )
   {
     window.ModelessDialog[name].focus();
	 return window.ModelessDialog[name];
   }
  }
	var F = WindowFeature["left"] +WindowFeature["top"] +  "dialogWidth:"+WindowFeature["width"] +" px;dialogHeight:"+WindowFeature["height"]+"px;center:1;help:0;" + WindowFeature["resizable"] +"status:0;unadorned:0;edge: raised; ;border:thick;";
	if(isModal)
	{
		window.showModalDialog(url,self,F);
		return false;
	}
	else
	{
		window.ModelessDialog[name] = window.showModelessDialog(url,self,F);
		return window.ModelessDialog[name];
	}
 }
 else
 {
   if(document.getBoxObjectFor)
   {


	 if(isModal)
	 {
		 var Modal = window.open(url,name,"modal=1," + feature);
		 var ModalFocus = function()
		 {
			if(!Modal.closed){Modal.focus();}
			else{Modal =null;window.removeEventListener(ModalFocus,"focus");ModalFocus = null; };
		 };
		 window.addEventListener( "focus",ModalFocus, false );
		 return false;
	 }
	 else
	 {
		return window.open(url,name,"modal=1," + feature);
	 }
   }
   else
   {
     return window.open(url,name,feature);
   }
   //
 }
 return null;
};




function modal(url,feature)
{
	dialog(url,"",feature,true);
	return false;
};

function getPosition_(object, relativeToObject, relativeToClassName)
{
	if (relativeToClassName == "")
		relativeToClassName = "undefinedClassName";
		
    var oldObject = object;
    //alert(object.parentNode);
	if (object.parentNode)
  	{
        var posX = 0, posY = 0;
        while(object)
        {
            if (object.tagName && !(object.tagName.toLowerCase() == "tr" || object.tagName.toLowerCase() == "tbody" || object.tagName.toLowerCase() == "table" || object.tagName.toLowerCase() == "thead" || object.tagName.toLowerCase() == "tfoot"))
            {
                if (object == relativeToObject || object.className == relativeToClassName)
                    break;
                    
                posX += (object.offsetLeft ? object.offsetLeft : 0);
                posY += (object.offsetTop ? object.offsetTop : 0); 
                  
                
                //alert(object.tagName+' = '+object.offsetTop);
                
                if(object == document.body) 
                    break;

            }
            object = object.parentNode;
        }
        //alert([ posX, posY ]);
        //alert(getPosition_(oldObject));
        //return [ posX, posY ];
        return [ posX, posY ];
  	}
    else
    {
    	return [ object.x, object.y ];
  	}
};

function getPosition(object, relativeToObject, relativeToClassName)
{
    if (relativeToClassName == "")
        relativeToClassName = "undefinedClassName";
        
    //alert(object.offsetParent);
    if (object.offsetParent)
      {
        for (var posX = 0, posY = 0; object.offsetParent; object = object.offsetParent)
        {
            if (object == relativeToObject || object.className == relativeToClassName)
                break;

              //posX += object.offsetLeft-object.parentNode.scrollLeft;
              //posY += object.offsetTop-object.parentNode.scrollTop;
            
              posX += object.offsetLeft;
              posY += object.offsetTop;
              
              
            //alert(object.offsetLeft);
        }
        //alert([ posX, posY ]);
        return [ posX, posY ];
      }
    else
    {
        return [ object.x, object.y ];
      }
};

function getWindowPosition(object)
{
    if (object == null)
    {
        return null;
    }
    else if (object.offsetParent)
    {
        for (var posX = 0, posY = 0; object.offsetParent; object = object.offsetParent)
        {
              posX += object.offsetLeft-object.parentNode.scrollLeft;
              posY += object.offsetTop-object.parentNode.scrollTop;
        }
        return [ posX, posY ];
    }
    else
    {
        return [ object.x, object.y ];
    }
};

// TEXTAREA <TAB> simulation
function setSelectionRange(input, selectionStart, selectionEnd) {
  if (input.setSelectionRange) {
    input.focus();
    input.setSelectionRange(selectionStart, selectionEnd);
  }
  else if (input.createTextRange) {
    var range = input.createTextRange();
    range.collapse(true);
    range.moveEnd('character', selectionEnd);
    range.moveStart('character', selectionStart);
    range.select();
  }
};

function replaceSelection (input, replaceString) {
	if (input.setSelectionRange) {
		var selectionStart = input.selectionStart;
		var selectionEnd = input.selectionEnd;
		input.value = input.value.substring(0, selectionStart)+ replaceString + input.value.substring(selectionEnd);

		if (selectionStart != selectionEnd){
			setSelectionRange(input, selectionStart, selectionStart + 	replaceString.length);
		}else{
			setSelectionRange(input, selectionStart + replaceString.length, selectionStart + replaceString.length);
		}

	}else if (document.selection) {
		var range = document.selection.createRange();

		if (range.parentElement() == input) {
			var isCollapsed = range.text == '';
			range.text = replaceString;

			 if (!isCollapsed)  {
				range.moveStart('character', -replaceString.length);
				range.select();
			}
		}
	}
};


// We are going to catch the TAB key so that we can use it, Hooray!
function catchTab(item,e){
	if(navigator.userAgent.match("Gecko")){
		c=e.which;
	}else{
		c=e.keyCode;
	}
	if(c==9){
		//replaceSelection(item,String.fromCharCode(9));  // inserts [TAB]
		replaceSelection(item,"    ");    				  // inserts "    "
		setTimeout("document.getElementById('"+item.id+"').focus();",0);
		return false;
	}

};
// end TEXTAREA <TAB> simulation

function cleanLink(link)
{
        link = link.replace("//", "/");
        link = link.replace("//", "/");
        link = link.replace("//", "/");
        link = link.replace("//", "/");
        link = link.replace("//", "/");
        link = link.replace("//", "/");
        link = link.replace("//", "/");
        link = link.replace("//", "/");
        link = link.replace("//", "/");
        link = link.replace(":/", "://");
        link = link.replace("/http:", "http:");
    
    return(link);
};

function uncryptMail(s)
{
	var n=0;
	var r="";
	var shift=3; // same value as the mail was coded with
	for(var i=0; i < s.length; i++)
    {
		n=s.charCodeAt(i);
		if (n>=8364) {n = 128;}
		r += String.fromCharCode(n-(shift));
	}
	return r;
};

function antiSpamMailTo(s)
{
	location.href=uncryptMail(s);
};

function charsTotalRemaining(id, max)
{
	var elem = document.getElementById(id);
    var elem_text_total = document.getElementById(id+'_counterTotal');
    var elem_text_remaining = document.getElementById(id+'_counterRemaining');
	if (elem != null && elem_text_total != null && elem_text_remaining != null)
    {
        elem_text_total.innerHTML = elem.value.length;
		elem_text_remaining.innerHTML = max-elem.value.length;
    }
};

function replaceAll( str, from, to )
{
    //alert(str);
	var idx = str.indexOf( from );
    while ( idx > -1 ) {
        str = str.replace( from, to );
        idx = str.indexOf( from );
    }
    //alert(str);
    return str;
};

function str_replace( from, to, str )
{
    //alert(str);
	var idx = str.indexOf( from );
    while ( idx > -1 ) {
        str = str.replace( from, to );
        idx = str.indexOf( from );
    }
    //alert(str);
    return str;
};

function showActionItem(itemId) 
{
    document.getElementById(itemId).style.display = '';
}

function hideActionItem(itemId) 
{
    document.getElementById(itemId).style.display = 'none';
}

function formatNumber(number, thousandSeparator, floatSeparator, nullFloatReplacement)
{
    if (isNaN(Math.abs(number)))
        return("0");
    
    if (typeof(thousandSeparator) == "undefined")
        thousandSeparator = ".";
    if (typeof(floatSeparator) == "undefined")
        floatSeparator = ",";
    if (typeof(nullFloatReplacement) == "undefined")
        nullFloatReplacement = "";

    var n = number;
    var c = 2;
    var d = floatSeparator;
    var t = thousandSeparator;
    var s = n < 0 ? "-" : "";
    var i = parseInt(n = Math.abs(+n || 0).toFixed(c)) + "";
    var j = (j = i.length) > 3 ? j % 3 : 0;
    
    var out = s + (j ? i.substr(0, j) + t : "") + i.substr(j).replace(/(\d{3})(?=\d)/g, "$1" + t)
    + (c ? d + Math.abs(n - i).toFixed(c).slice(2) : "");
    
    out = out.replace(",00", nullFloatReplacement);
    
    return(out);
}

function _dump(o, level) 
{
    level = level || 0;
    if(level>_dump.maxLevel) 
        return "Too deep";

    if(true /*evel || (dbg = document.getElementById('dbg_win'))*/) 
    {
        var ret = '';

        if(typeof(o) != 'function')
            ret = typeof(o) + ': ';

        if(typeof(o) == 'object') 
        {
            ret+= '\r\n';
            try 
            {
                for(i in o) 
                {
                    try 
                    {
                        ret += "\t".repeat(level) + i + ' => ' + _dump(o[i], level+1) + '\r\n';
                    } catch(e) {}
                }
            } 
            catch(e) 
            {
                ret = 'can\'t iterate over object';
            }
        } 
        else 
        {
            try 
            {
                ret += o.toString().indent(level, 1);
            } 
            catch(e) 
            {
                ret += 'can\'t convert to string';
            }
        }
        return ret;

        /*
        if(level) 
        {
            return ret;
        } 
        else 
        {
            dbg.appendChild(document.createTextNode(ret));
            dbg.appendChild(document.createElement('hr'));
        }
        */
    }
};

_dump.maxLevel = 3;
if(!String.prototype.repeat) 
{
    String.prototype.repeat = function(n) 
    {
        var s=this.toString(), ret='';
        while( (n--) > 0) ret+=s;
            return ret;
    }
}
if(!String.prototype.indent) 
{
    String.prototype.indent = function(level, dontIndentFirst, indentChar) 
    {
        indentChar = indentChar || "\t";
        dontIndentFirst = Number(dontIndentFirst)||0;
        var s = this.toString();
        s = s.split(/^/m);
        for(var i=dontIndentFirst, l=s.length; i<l; i++)
            s[i] = indentChar.repeat(level) + s[i];
        return s.join("");
    }
};

function dump(o, clear, level) 
{
    _dump.maxLevel = level ? level : 3;
    var container = document.getElementById("javascriptDump");
    if (container)
    {
        container.style.width = "";

        if (clear)
            container.innerHTML = "";
            
        var dmp = _dump(o);
        dmp = dmp.replace(/\t/g, "&nbsp;&nbsp;&nbsp;");
        dmp = dmp.replace(/\r/g, "");
        dmp = dmp.replace(/\n/g, "<br />");
        
        container.innerHTML += dmp+"<br />";
        container.style.display='';
    }
};

function extractParams(params, separator)
{
    if (typeof(separator) == "undefined")
        separator = ",";
    
    var lines = params.split(separator);
    var params = new Object;
    for (var l = 0 ; l < lines.length ; l++)
    {
        var line = lines[l];
        var equalPos = line.indexOf("=");
        if (equalPos > -1)
        {
            var name = line.substring(0, equalPos);
            var value = line.substring(equalPos+1, line.length);
            params[name] = value;        
        }
    }
    
    return(params);
};

// dummy class for components
function TComponent(jsName, id, name)
{
    this.jsName = jsName;
    this.name = name;
    this.id = id;
};

TComponent.prototype.setParams = function(textParams)
{
    this.textParams = textParams;
    this.params = extractParams(textParams, ",");
    //dump(this.params);
};

TComponent.prototype.getAjaxValue = function(params)
{
    var postParams = this.params;
    for (var name in params)
        postParams[name] = params[name];
    
    if (!this.tableName || !this.fieldName) // virtual components (in EDITGRID)
    {
        postParams["componentType"] = this.type;
        postParams["componentName"] = this.name;
    }
    
    var ajaxValue = getComponentAjaxValue(this.tableName, this.name, postParams, 'rtValue');
    
    return(ajaxValue);
};

function registerComponent(Component)
{
    components[Component.jsName] = Component;
};

function getComponent(name)
{
    //dump(components);
    var Component = components[name];
    
    if (!Component)
        Component = components["f_"+name];
        
    /*
    if (name.indexOf("f_") == -1)
    {
        var Component = components["f_"+name];
    }
    else
        var Component = components[name];
    */

    if (Component)
        return(Component);
    else
        alert("getComponent(): component '"+name+"' not found");
};

function translate(text, lang)
{
    if (typeof(lang) == "undefined")
        lang = language;
    
    if (typeof(HTMLArea) != "undefined")
    {
        text = HTMLArea._lc(text);
    }

    if (text.indexOf("{#lang") > -1)
    {
        var re = new RegExp("{#lang\\("+lang+"\\):([^}]*)}", "gi");
        var result = text.split(re);
        if (result)
            text = result[1];
        else
            text = "";
    }
    
    return(text);
}

function antiSpamEmailMouseOver(span)
{
    if (typeof(span) == "undefined" && window.event) // for IE
    {
        span = window.event.srcElement;
    }
    //alert(span);
    if (typeof(span) != "undefined")
    {
        span.onmouseover = "";
        span.className = "";
    
        var mail = span.innerHTML;
        var ret = "";
        for (var i = mail.length-1 ; i >= 0 ; i--)
        {
            ret += mail.substr(i, 1);
        }
        //alert(mail+" | "+ret+ " | " + span.outerHTML);
    
        span.innerHTML = ret;
    }
}

/*
var debugOutlines = [];
function addDebugOutline(containerId)
{
    if (debugOutlines.length == 0)
    {
        if (window.addEventListener) //run onload in DOM2 browsers
        {
            window.addEventListener("load", function(){displayDebugOutlines()}, false);
            window.addEventListener("resize", function(){displayDebugOutlines()}, false);
        }
        else if (window.attachEvent) //run onload in IE5.5+
        {
            window.attachEvent("onload", function(){displayDebugOutlines()});
            window.attachEvent("onresize", function(){displayDebugOutlines()});
        }
    }

    debugOutlines.push(containerId);
}

function displayDebugOutlines()
{
    for (var i = 0 ; i < debugOutlines.length ; i++)
    {
        var id = debugOutlines[i];
        
        var container = document.getElementById("debugOutlineContainer"+id);
        var info = document.getElementById("debugOutlineInfo"+id);
        
        var div = document.createElement("div");
        div.id = "debugOutlineLeft"+id;
        document.body.appendChild(div);
                
        var div = document.createElement("div");
        div.id = "debugOutlineTop"+id;
        document.body.appendChild(div);

        var div = document.createElement("div");
        div.id = "debugOutlineRight"+id;
        document.body.appendChild(div);

        var div = document.createElement("div");
        div.id = "debugOutlineBottom"+id;
        document.body.appendChild(div);
        
        info.style.display = "";
    }
}

function resizeDebugOutlines()
{
    for (var i = 0 ; i < debugOutlines.length ; i++)
    {
        var id = debugOutlines[i];
        
        var container = document.getElementById("debugOutlineContainer"+id);
        var info = document.getElementById("debugOutlineInfo"+id);
        var lineLeft = document.getElementById("debugOutlineLeft"+id);
        var lineTop = document.getElementById("debugOutlineTop"+id);
        var lineRight = document.getElementById("debugOutlineRight"+id);
        var lineBottom = document.getElementById("debugOutlineBottom"+id);

        var pos = getWindowPosition(container);
        info.style.left = pos[0]+"px";
        info.style.top = pos[1]+"px";
        
        lineLeft.style        
    }



}
*/

function redirect(url)
{
    window.location.href=url;
}

function strtotime(str, now) {  
    // Convert string representation of date and time to a timestamp    
    //   
    // version: 902.2516  
    // discuss at: http://phpjs.org/functions/strtotime  
    // +   original by: Caio Ariede (http://caioariede.com)  
    // +   improved by: Kevin van Zonneveld (http://kevin.vanzonneveld.net)  
    // +      input by: David  
    // +   improved by: Caio Ariede (http://caioariede.com)  
    // %        note 1: Examples all have a fixed timestamp to prevent tests to fail because of variable time(zones)  
    // *     example 1: strtotime('+1 day', 1129633200);  
    // *     returns 1: 1129719600  
    // *     example 2: strtotime('+1 week 2 days 4 hours 2 seconds', 1129633200);  
    // *     returns 2: 1130425202  
    // *     example 3: strtotime('last month', 1129633200);  
    // *     returns 3: 1127041200  
    // *     example 4: strtotime('2009-05-04 08:30:00');  
    // *     returns 4: 1241418600  
    var i, match, s, strTmp = '', parse = '';  
  
    strTmp = str;  
    strTmp = strTmp.replace(/\s{2,}|^\s|\s$/g, ' '); // unecessary spaces  
    strTmp = strTmp.replace(/[\t\r\n]/g, ''); // unecessary chars  
  
    if (strTmp == 'now') {  
        return (new Date()).getTime();  
    } else if (!isNaN(parse = Date.parse(strTmp))) {  
        return parse/1000;  
    } else if (now) {  
        now = new Date(now);  
    } else {  
        now = new Date();  
    }  
  
    strTmp = strTmp.toLowerCase();  
  
    var process = function (m) {  
        var ago = (m[2] && m[2] == 'ago');  
        var num = (num = m[0] == 'last' ? -1 : 1) * (ago ? -1 : 1);  
  
        switch (m[0]) {  
            case 'last':  
            case 'next':  
                switch (m[1].substring(0, 3)) {  
                    case 'yea':  
                        now.setFullYear(now.getFullYear() + num);  
                        break;  
                    case 'mon':  
                        now.setMonth(now.getMonth() + num);  
                        break;  
                    case 'wee':  
                        now.setDate(now.getDate() + (num * 7));  
                        break;  
                    case 'day':  
                        now.setDate(now.getDate() + num);  
                        break;  
                    case 'hou':  
                        now.setHours(now.getHours() + num);  
                        break;  
                    case 'min':  
                        now.setMinutes(now.getMinutes() + num);  
                        break;  
                    case 'sec':  
                        now.setSeconds(now.getSeconds() + num);  
                        break;  
                    default:  
                        var day;  
                        if (typeof (day = __is_day[m[1].substring(0, 3)]) != 'undefined') {  
                            var diff = day - now.getDay();  
                            if (diff == 0) {  
                                diff = 7 * num;  
                            } else if (diff > 0) {  
                                if (m[0] == 'last') diff -= 7;  
                            } else {  
                                if (m[0] == 'next') diff += 7;  
                            }  
  
                            now.setDate(now.getDate() + diff);  
                        }  
                }  
  
                break;  
  
            default:  
                if (/\d+/.test(m[0])) {  
                    num *= parseInt(m[0]);  
  
                    switch (m[1].substring(0, 3)) {  
                        case 'yea':  
                            now.setFullYear(now.getFullYear() + num);  
                            break;  
                        case 'mon':  
                            now.setMonth(now.getMonth() + num);  
                            break;  
                        case 'wee':  
                            now.setDate(now.getDate() + (num * 7));  
                            break;  
                        case 'day':  
                            now.setDate(now.getDate() + num);  
                            break;  
                        case 'hou':  
                            now.setHours(now.getHours() + num);  
                            break;  
                        case 'min':  
                            now.setMinutes(now.getMinutes() + num);  
                            break;  
                        case 'sec':  
                            now.setSeconds(now.getSeconds() + num);  
                            break;  
                    }  
                } else {  
                    return false;  
                }  
  
                break;  
        }  
  
        return true;  
    }  
  
    var __is =  
    {  
        day:  
        {  
            'sun': 0,  
            'mon': 1,  
            'tue': 2,  
            'wed': 3,  
            'thu': 4,  
            'fri': 5,  
            'sat': 6  
        },  
        mon:  
        {  
            'jan': 0,  
            'feb': 1,  
            'mar': 2,  
            'apr': 3,  
            'may': 4,  
            'jun': 5,  
            'jul': 6,  
            'aug': 7,  
            'sep': 8,  
            'oct': 9,  
            'nov': 10,  
            'dec': 11  
        }  
    }  
  
    match = strTmp.match(/^(\d{2}\.\d{2}\.\d{2,4})(\s\d{1,2}:\d{1,2}(:\d{1,2})?)?$/);  
    if (match != null) {  
        if (!match[2]) {  
            match[2] = '00:00:00';  
        } else if (!match[3]) {  
            match[2] += ':00';  
        }  
  
        s = match[1].split(/\./g);  
  
        for (i in __is.mon) {  
            if (__is.mon[i] == s[1] - 1) {  
                s[1] = i;  
            }  
        }  
  
        return strtotime(s[0] + ' ' + s[1] + ' ' + s[2] + ' ' + match[2]);  
    }  

    match = strTmp.match(/^(\d{2,4}-\d{2}-\d{2})(\s\d{1,2}:\d{1,2}(:\d{1,2})?)?$/);  
    if (match != null) {  
        if (!match[2]) {  
            match[2] = '00:00:00';  
        } else if (!match[3]) {  
            match[2] += ':00';  
        }  
  
        s = match[1].split(/-/g);  
  
        for (i in __is.mon) {  
            if (__is.mon[i] == s[1] - 1) {  
                s[1] = i;  
            }  
        }  
  
        return strtotime(s[2] + ' ' + s[1] + ' ' + s[0] + ' ' + match[2]);  
    }  
  
    var regex = '([+-]?\\d+\\s'  
    + '(years?|months?|weeks?|days?|hours?|min|minutes?|sec|seconds?'  
    + '|sun\.?|sunday|mon\.?|monday|tue\.?|tuesday|wed\.?|wednesday'  
    + '|thu\.?|thursday|fri\.?|friday|sat\.?|saturday)'  
    + '|(last|next)\\s'  
    + '(years?|months?|weeks?|days?|hours?|min|minutes?|sec|seconds?'  
    + '|sun\.?|sunday|mon\.?|monday|tue\.?|tuesday|wed\.?|wednesday'  
    + '|thu\.?|thursday|fri\.?|friday|sat\.?|saturday))'  
    + '(\\sago)?';  
  
    match = strTmp.match(new RegExp(regex, 'g'));  
  
    if (match == null) {  
        return false;  
    }  
  
    for (i in match) {  
        if (!process(match[i].split(' '))) {  
            return false;  
        }  
    }  
  
    return (now);  
}  

// to enable call of form.onsubmit() if calling this.form.submit()
/*
if (HTMLFormElement && debug) // Gecko based browsers
{
    HTMLFormElement.prototype.submitOld = HTMLFormElement.prototype.submit;
    HTMLFormElement.prototype.submit = function() 
    {
        if (typeof(this.onsubmit) == "function")
        {
            var ret = this.onsubmit();
            if (typeof(ret) != "undefined" && ret == false)
                return false;
        }
        try 
        {
            this.submitOld(true);
        }
        catch(e)
        {
            alert(e);
        }
    };
}
*/
