

// ---------------------------------------------------------------------------------------------------------------------
// base  ----------------------------------------------------------------------------------



function attachEventUni(obj,evnt,func)
{
	if (typeof obj.attachEvent!='undefined')
    {
        obj.attachEvent(evnt,func);
    }
    else if(typeof obj.addEventListener!='undefined')
    {
        if(evnt.substr(0,2)=='on' )
            evnt=evnt.substring(2,evnt.length);
        obj.addEventListener(evnt,func,false);

    }
}


function dettachEventUni(obj,evnt,func)
{
	if (typeof obj.attachEvent!='undefined')
    {
        obj.dettachEvent(evnt,func);
    }
    else if(typeof obj.addEventListener!='undefined')
    {
        if(evnt.substr(0,2)=='on' )
            evnt=evnt.substring(2,evnt.length);
        obj.removeEventListener(evnt,func,false);

    }
}


function printpreview()
{
var OLECMDID = 7;
/* OLECMDID values:
* 6 - print
* 7 - print preview
* 1 - open window
* 4 - Save As
*/
var PROMPT = 1; // 2 DONTPROMPTUSER
var WebBrowser = '<OBJECT ID="WebBrowser1" WIDTH=0 HEIGHT=0 CLASSID="CLSID:8856F961-340A-11D0-A96B-00C04FD705A2"></OBJECT>';
document.body.insertAdjacentHTML('beforeEnd', WebBrowser);
WebBrowser1.ExecWB(OLECMDID, PROMPT);
WebBrowser1.outerHTML = "";
}

function confirmBeforeUnload(question)
{

    attachEventUni(window,"onbeforeunload",function(ev) { if(!ev)  ev=event; ev.returnValue='Ok pre zmazanie, Cancel pre navrat';(confirm('Nehnutelnost nebola ulozena. \nZmazat nehnutelnost?'));});

}
function openPopup(url,id,params)
{
	var handler=window.open(url,id,params);
    if(handler)
        handler.focus();

    return false;

}

function openUrl(url,newWindow)
{
	if(!newWindow)
        //location.replace(url);
        window.location.href=url;
    else
        openPopup(url,"_blank","toolbar=1,location=1,directories=1,status=1,menubar=1,scrollbars=1,resizable=1");
}


var GlobalMouseX=0;
var GlobalMouseY=0;

function getMouseCoords(ev,fromDocumentZero)
{

    // ak to budeme zistovat z globanych premennych
    // pouziva sa ked sa neda poslat event
    // pre pouzitim je potrebne spustit mouseCoordsStartChecking();

    if(ev == -1 )
       return {x:GlobalMouseX, y:GlobalMouseY};


    ev = ev || window.event;

    if(fromDocumentZero == undefined)
        fromDocumentZero=false;

    var x;
    var y;

    // od zaciatku dokumentu
    if(fromDocumentZero)
    {
    	if(ev.pageX || ev.pageY)
        {
            x=ev.pageX;
            y=ev.pageY;
        }
        else
        {
            x=ev.clientX + (document.documentElement.scrollLeft ? document.documentElement.scrollLeft : document.body.scrollLeft); //- document.body.clientLeft;
            y=ev.clientY + (document.documentElement.scrollTop ? document.documentElement.scrollTop  : document.body.scrollTop); // - document.body.clientTop;
        }
     }

    // od viewportu - viditelnej casti
    else
    {
        x=ev.clientX;
        y=ev.clientY;
    }



    return {x:x, y:y};
}

function GetScrollPositions()
{
	var x;
	var y;
    if(window.pageXOffset)
        x= window.pageXOffset;
    else
        x = (document.documentElement.scrollLeft ? document.documentElement.scrollLeft : document.body.scrollLeft);

    if(window.pageYOffset)
        y= window.pageYOffset;
    else
        y = (document.documentElement.scrollTop ? document.documentElement.scrollTop : document.body.scrollTop);
    return {x:x, y:y};
}

function GetViewPortSize()
{
	var x;
    var y;

    if(window.innerWidth)
        x= window.innerWidth;
    else
        x = (document.documentElement.clientWidth ? document.documentElement.clientWidth : document.body.clientWidth);
    if(window.innerHeight)
        y= window.innerHeight;
    else
        y = (document.documentElement.clientHeight ? document.documentElement.clientHeight : document.body.clientHeight);

    return {x:x, y:y};

}

function GetDocumentSize()
{
	var x;
    var y;
    var xScroll, yScroll;

    if (window.innerHeight && window.scrollMaxY) {
        xScroll = window.innerWidth + window.scrollMaxX;
        yScroll = window.innerHeight + window.scrollMaxY;
    } else if (document.body.scrollHeight > document.body.offsetHeight){ // all but Explorer Mac
        xScroll = document.body.scrollWidth;
        yScroll = document.body.scrollHeight;
    } else { // Explorer Mac...would also work in Explorer 6 Strict, Mozilla and Safari
        xScroll = document.body.offsetWidth;
        yScroll = document.body.offsetHeight;
    }

    var windowWidth, windowHeight;

//  console.log(self.innerWidth);
//  console.log(document.documentElement.clientWidth);

    if (self.innerHeight) { // all except Explorer
        if(document.documentElement.clientWidth){
            windowWidth = document.documentElement.clientWidth;
        } else {
            windowWidth = self.innerWidth;
        }
        windowHeight = self.innerHeight;
    } else if (document.documentElement && document.documentElement.clientHeight) { // Explorer 6 Strict Mode
        windowWidth = document.documentElement.clientWidth;
        windowHeight = document.documentElement.clientHeight;
    } else if (document.body) { // other Explorers
        windowWidth = document.body.clientWidth;
        windowHeight = document.body.clientHeight;
    }

    // for small pages with total height less then height of the viewport
    if(yScroll < windowHeight){
        pageHeight = windowHeight;
    } else {
        pageHeight = yScroll;
    }


    // for small pages with total width less then width of the viewport
    if(xScroll < windowWidth){
        pageWidth = xScroll;
    } else {
        pageWidth = windowWidth;
    }

    //arrayPageSize = new Array(pageWidth,pageHeight,windowWidth,windowHeight)
    //return arrayPageSize;
    return {x:pageWidth, y:pageHeight};

}

// ziskavanie suradnic mysi - stale - priebezne do gloablnych premennych
function mouseCoordsStartChecking()
{
	var IE = document.all?true:false;
    if (!IE) document.captureEvents(Event.MOUSEMOVE);
    document.onmousemove = getMouseXY;
}
// ziskavanie suradnic mysi - vypnutie
function mouseCoordsStopChecking()
{
    document.onmousemove = '';
}
function getMouseXY(e)
{
    var cor= getMouseCoords(e,true);
    GlobalMouseX=cor.x;
    GlobalMouseY=cor.y;
    return true;
}




// ---------------------------------------------------------------------------------------------------------------------
// browser  ----------------------------------------------------------------------------------

function getIeReadOnlyTags()
{
	return Array('TABLE','THEAD','TFOOT','TBODY','TR');
}

// vracia 'opera' | 'ie' | 'firefox'
function getBrowser()
{
	var browser='firefox';
    op=navigator.userAgent.toLowerCase().indexOf('opera')!=-1;
    ie=(d.all)?1:0;
    if(ie)
       browser='ie';
    if(op)
       browser='opera';
    return browser;
}



var pageLoaded=false;
function pageIsLoaded()
{
	return   pageLoaded;
}
function pageSetLoaded()
{
	pageLoaded=true;

}

attachEventUni(window,'onload',pageSetLoaded);



// ---------------------------------------------------------------------------------------------------------------------
// objects, arrays, strings  ----------------------------------------------------------------------------------



function inArray(arr,value)
// Returns true if the passed value is found in the
// array.  Returns false if it is not.
{
    for ( keyVar in arr ) {
        // Matches identical (===), not just similar (==).

        if (arr[keyVar] == value)
        {
            return true;
        }
        else ;

    }
    return false;
};



String.prototype.trim = function()
{
    return this.replace(/^\s+|\s+$/g, "");
};

function replaceAll(text,oldStr,newStr)
{

    // TODO  - nie je blbu vzdorna - preto obmedzenie na 100 cyklov
    var i=0;
    while (text.indexOf(oldStr)>0 && i<100)
    {

        text=text.replace(oldStr,newStr);
        i++;
    }

    return text;

}
function nl2br(text)
{
    text=escape(text);
    return unescape(text.replace(/(%5Cr%5Cn)|(%5Cn%5Cr)|%5Cr|%5Cn/g,'<br />'));
}

function round2(number,precise)
{
    var nasob=Math.pow(10,precise);
    return roundBase(number,nasob);
    return number;
}

function roundBase(number,nasob)
{
    number = number*nasob;
    number = Math.round(number);
    number = number/nasob;
    return number;
}




function substr_count(string,substring,start,length)
{
 if(substring==null)
 {

	 substring="\n";

 }
  var c = 0;
 if(start) { string = string.substr(start); }
 if(length) { string = string.substr(0,length); }
 for (var i=0;i<string.length;i++)
 {
  if(substring == string.substr(i,substring.length))
  c++;
 }
 return c;
}


function randStr(length)
{

    if(null==length)
        length=6;
    var chars='abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ';
    var r='';
    var i=0;
    for(i=0;i<length;i++)
       r=r+chars.substr(Math.round(Math.random()*chars.length),1);

    return r;
}




function getArrayFromString(str,sep1,sep2,delimiter)
{
	var tweensSeparated;
    var list=str.split(sep1);
    var data=new Object();
    for (var keyVal in list)
    {
        if(typeof list[keyVal] == 'string')
        {
            tweensSeparated=list[keyVal].split(sep2);
            data[tweensSeparated[0]]=tweensSeparated[1];
        }
    }

    return data;
}

function isNull(val){return(val==null);}

function objectLength(obj)
{
	if(typeof obj !='object')
        return false;
    var i=0;
    for(keyVal in obj)
        i++;
    return i;

}


/*
function URLEncode (clearString) {
  var output = '';
  var x = 0;
  clearString = clearString.toString();
  var regex = /(^[a-zA-Z0-9_.]*)/;
  while (x < clearString.length) {
    var match = regex.exec(clearString.substr(x));
    if (match != null && match.length > 1 && match[1] != '') {
        output += match[1];
      x += match[1].length;
    } else {
      if (clearString[x] == ' ')
        output += '+';
      else {
        var charCode = clearString.charCodeAt(x);
        var hexVal = charCode.toString(16);
        output += '%' + ( hexVal.length < 2 ? '0' : '' ) + hexVal.toUpperCase();
      }
      x++;
    }
  }
  return output;
}
*/
function POSTencode(plaintext)
{
	return URLEncode(plaintext,130,false );
}


function URLEncode(plaintext,charMax,useSpace )
{

    if(charMax == undefined)
        charMax=255;
    if(useSpace == undefined)
        useSpace=true;

    // 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 plaintext = document.URLForm.F1.value;
    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 > charMax) {
                /*
                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." );*/
                if(useSpace)
                    encoded += "+";
                else
                    encoded += ch;
            } else {
                encoded += "%";
                encoded += HEX.charAt((charCode >> 4) & 0xF);
                encoded += HEX.charAt(charCode & 0xF);
            }
        }
    } // for

    return encoded;
    //document.URLForm.F2.value = encoded;
//  document.URLForm.F2.select();
  //  return false;
};


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 URLDecode2(utftext) {
        var string = "";
        var i = 0;
        var c = c1 = c2 = 0;
        alert(utftext + utftext.length);
        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;
            }

        }
        alert(string);
        return string;
    }

    function URLEncode2(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;
    }

function ord( string ) {
    // http://kevin.vanzonneveld.net
    // +   original by: Kevin van Zonneveld (http://kevin.vanzonneveld.net)
    // *     example 1: ord('K');
    // *     returns 1: 75

    return string.charCodeAt(0);
}


// ---------------------------------------------------------------------------------------------------------------------
// cookies  ----------------------------------------------------------------------------------


function saveCookie(name,value,days) {
	if (days) {
		var date=new Date();
		date.setTime(date.getTime()+(days*24*60*60*1000))
		var expires="; expires="+date.toGMTString()
	} else 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
}





// ---------------------------------------------------------------------------------------------------------------------
// akoze ajax -spustanie php skriptov  ----------------------------------------------------------------------------------


function showClock(loadingElmId,opacity)
{

	if(opacity == undefined)
         opacity=0.7;

	if(loadingElmId==undefined)
		return false;
	if(!loadingElmId)
		return false;

    var animationElm=gE('loader-animation-'+loadingElmId);
    if(!animationElm)
    {
    	var animationElm=document.createElement('DIV');
    	document.body.appendChild(animationElm);
    	animationElm.setAttribute('id','loader-animation-'+loadingElmId);
    	animationElm.onmouseover= function () { eval("hideClock('"+loadingElmId+"');"); }
    }

    if(!animationElm)
    		return false;


   // animationElm.style.cssText= 'opacity: '+opacity+'; filter: alpha(opacity = '+(opacity*100)+'); -moz-opacity: '+opacity+'; -khtml-opacity: '+opacity+';position:absolute;background-color:#FFF;z-index:1000;overflow:hidden;';
    animationElm.style.cssText= 'position:absolute;z-index:1000;overflow:hidden;';

   var loadingElm = gE(loadingElmId);
    if(loadingElm)
    {

        var sizes=getElmSize(loadingElm);
        var position=getElmPosition(loadingElm);
        if(position)
        {
	        var iLeft=position.x;
	    	var iTop=position.y;
        }
    }
    else
    {
    	 //var sizes=GetViewPortSize();
    	var sizes=GetDocumentSize();
    	var iLeft=0;
    	var iTop=0;
    }
    if(sizes)
    {
    	animationElm.style.width=(sizes.x)+'px';
	    animationElm.style.height=(sizes.y)+'px';
	    var toHtml="";
	    toHtml+='<div style="width:100%;height:100%;position:relative;"><div style="width:100%;height:100%;opacity: '+opacity+'; filter: alpha(opacity = '+(opacity*100)+'); -moz-opacity: '+opacity+'; -khtml-opacity: '+opacity+';background-color:#FFF;" ></div>';
	    if(sizes.y>60)
	    	toHtml += '<img src="http://static.living.sk/icons/ajax-loader.gif" style="position:absolute;top:'+Math.round((sizes.y-100)/2)+'px;left:'+Math.round((sizes.x-100)/2)+'px;"  >';
	     else
	    	 toHtml += '<img src="http://static.living.sk/icons/progressbar.gif" style="position:absolute;top:'+Math.round((sizes.y-4)/2)+'px;left:'+Math.round((sizes.x-85)/2)+'px;"  >';
	    toHtml+='</div>';
	    animationElm.innerHTML=toHtml;
    }
    animationElm.style.left=(iLeft)+'px';
    animationElm.style.top=(iTop)+'px';



    sE(animationElm);




}
var AllHCTimers= new Array();
function hideClock(id)
{
    //alert('hideClock');

    if(id == undefined)
    	return false;
    var animationElm=gE('loader-animation-'+id);
    if(!animationElm)
    	return false

    if(AllHCTimers[id])
    	window.clearTimeout(AllHCTimers[id]);
    AllHCTimers[id]=window.setTimeout("hE(gE('loader-animation-"+id+"'))",200);


}




var allLitBoxes = new Array();
function LITBoxStart(url,arg2,boxId,checkBrowser)
{
    if(typeof (boxId) == undefined)
        boxId=0;
    if(typeof (checkBroser) == undefined)
        checkBroser=false;

    /*
    if(checkBrowser && inArray(Array('ie','opera'),getBrowser()))
    {
    	url=url.replace(/litbox/,'');
        location.replace(url);
        return false;
    }
    */

    //showClock();
    hideSelects();
    var query='';

   LITBoxClose(boxId);
    allLitBoxes[boxId]=new LITBox(url,arg2,1);
   /*
    if(typeof arg2=='object')
    {
    	for(var keyVal in arg2)
        {
            if(typeof arg2[keyVal] == 'string')
                query=query+keyVal+':\''+arg2[keyVal]+'\',';
            else
                query=query+keyVal+':'+arg2[keyVal]+',';

        }
    }

    query='{'+query.substr(0,query.length-1)+'}';
    window.setTimeout('LITBoxClose(\''+boxId+'\');allLitBoxes[\''+boxId+'\']=new LITBox(\''+url+'\','+query+',1)',1);
    */

    //addCls(document.body,'o-hidden');
    ///alert(document.body.className);


}

function LITBoxClose(boxId)
{
    if(boxId && allLitBoxes[boxId])
    {
        allLitBoxes[boxId].remove();
        showSelects();
    }


}

function LITBoxExists(boxId)
{
    return (boxId && allLitBoxes[boxId]!=undefined);
}

function LITBoxRefresh(boxId,post,afterScript,condEval)
{
    if(boxId && allLitBoxes[boxId])
        allLitBoxes[boxId].reload(post,afterScript,condEval);

}

function LITBoxChangeUrl(boxId,newurl,newOptions)
{
    if(boxId && allLitBoxes[boxId])
        allLitBoxes[boxId].change_url(newurl);
    if(boxId && allLitBoxes[boxId] && typeof(newOptions)!='undefined')
        allLitBoxes[boxId].changeOptions(newOptions);

}


function runPhpScript(url,postRequest,intoDivId,callBack,dontUseAnimation,condEval)
{

	if(!pageIsLoaded())
	{
		//attachEventUni(window,'onload', function () { runPhpScript(url,postRequest,intoDivId,callBack,dontUseAnimation,condEval)} ) ;
		window.setTimeout( "runPhpScript('" + url + "','"+postRequest+"','"+intoDivId+"','"+callBack+"','"+dontUseAnimation+"','"+condEval+"')",250);
		return false;
	}


		if(postRequest==undefined || postRequest==-1 || postRequest=='')
			postRequest=false;

	 	if(dontUseAnimation!=true && intoDivId && intoDivId!='document.title' && gE(intoDivId))
	 	{
            showClock(intoDivId);
		}
		
	 	questmark='?';
	 	if(url.indexOf('?')>0)
	 		questmark='';
	 	new Ajax.Request(url+ (postRequest?'': questmark + '&ajax=1'), {
			  onSuccess: function(response) {
			               if(      (intoDivId!='' )
			               				&& (elmdiv=gE(intoDivId)) && typeof(elmdiv.innerHTML) != undefined
			               	 )
                         {

          	                	//evalnut zaslane veci
                              	if(condEval!=undefined  && condEval && condEval[response.responseText])
				    			    {
				    					eval(condEval[response.responseText]);
				    			    }
				    			    else
				    			    {
				    			    	wE(elmdiv,response.responseText);
				    			    }

                         }
			             hideClock(intoDivId);
                         if(callBack!='')
                   				eval(callBack);

			  },
			  onFailure:function(response) {
				  elmdiv=gE(intoDivId);
				  wE(elmdiv, ''
				 	 		+' <span >loading error... </span><a href="#" onclick="runPhpScript(\''+url+'\',\''+ postRequest+'\',\''+intoDivId+'\',\''+callBack+'\',\''+condEval+'\')"> <small>try again</small></a>'
				 	 		);
				  hideClock(intoDivId);
			  },
			  parameters:(postRequest? '&ajax=1'+postRequest:null),
			  method:(postRequest? 'post':'get'),
			  evalScripts:true,
			  evalJS:true
			});

	 	/*

        var http_request = false;
        //var postRequest = "string="+string;
		var r='';
        if (window.XMLHttpRequest)
        {
            http_request = new XMLHttpRequest();
        }
        else if (window.ActiveXObject)
        {
            try {
              http_request = new ActiveXObject("Msxml2.XMLHTTP");
            } catch (eror) {
              http_request = new ActiveXObject("Microsoft.XMLHTTP");
            }
        }

    	http_request.onreadystatechange = function()
        {

            if(intoDivId!=''||otherFunction!='')
    	    if (http_request && http_request.readyState == 4)
            {
        	    if (http_request.status == 200)
        	    {
    			   if(condEval!=undefined  && condEval && condEval[http_request.responseText])
    			   {
    					eval(condEval[http_request.responseText]);
    			   }
                   else
                   {


                       if((intoDivId!='' )&& (elmdiv=gE(intoDivId)) )
                       {
        	               if(typeof(elmdiv.innerHTML) != undefined)
        	               {
                              var str=http_request.responseText;
                              //str=str.replace('%7E','~');
                              //str=str.replace('%7E','~');
                              //str=str.replace('%7E','~');
                              wE(elmdiv,str);
                           }
                       }

                       if(otherFunction!='')
                	       eval(otherFunction);

                   }


    			   if(dontUseAnimation!==true && intoDivId)
                   {
    				   hideClock(intoDivId);

                   }

        	    }
        	    else
        	    {
        	        //alert('Chyba pri ajax load php - '+http_request.responseText);
        	    	if(dontUseAnimation!==true && intoDivId)
        	    		hideClock(intoDivId);
        	    }
    	    }
    	    else
    	    	if(dontUseAnimation!==true && intoDivId)
                {
    	    		hideClock(intoDivId);
                }
    	};
		if(postRequest==undefined)
			postRequest='';
		if(postRequest==-1)
		{
        	http_request.open('GET', url+'&ajax=1', true);
        	http_request.send(null);
        }
        else
        {
        	http_request.open('POST', url, true);
	    	http_request.setRequestHeader('Content-Type', 'application/x-www-form-urlencoded');
	    	http_request.send(postRequest+'&ajax=1');
        }
        */

}
// ------------------------------------------------------------------------------------------------








// ---------------------------------------------------------------------------------------------------------------------
// pressed keys handling  ----------------------------------------------------------------------------------

/*
var pressedKeys=new Array();

function setKey(e)
{
    var code;
    if (!e) var e = window.event;
    if (e.keyCode)
        code = e.keyCode;
    else if (e.which)
        code = e.which;
    pressedKeys[code]=true;
    var character = String.fromCharCode(code);
    //alert('Character was ' +  code + ' ' + character);

}

function unsetKey(e)
{
    var code;
    if (!e) var e = window.event;
    if (e.keyCode)
        code = e.keyCode;
    else if (e.which)
        code = e.which;
    pressedKeys[code]=false;
    var character = String.fromCharCode(code);
    alert('Character was ' +  code + ' ' + character);

}

function isPressedKey(keyNo)
{
	//alert('pressedKeys length' + pressedKeys.length);
    //for ( i in pressedKeys )
    //    alert('pressed keys:'+ pressedKeys[i]);

    return (pressedKeys && pressedKeys[keyNo])
}


if (typeof document.attachEvent!='undefined')
    {
        document.attachEvent('onkeydown',setKey);
        document.body.attachEvent('onkeyup',unsetKey);
    }
else
    {
        document.addEventListener('onkeydown',setKey,true);
        document.addEventListener('onkeyup',unsetKey,true);
    }

*/

function allowOnlyInt(elm)
{

    var txt=elm.value;
    if(!txt)
        return true;
    var i=0;
    var txtN='';
    var ordNo=0;
    var ordNoZero= ord('0');
    var ordNoNine= ord('9');
	var ordNoMinus= ord('-');

    for(i=0;i<txt.length;i++)
    {
    	ordNo=ord(txt.substr(i,1));
        if((ordNo >= ordNoZero && ordNo <= ordNoNine) || (i==0 && (ordNo==ord('-'))))
            txtN=txtN+txt.substr(i,1);
    }

    elm.value=txtN;
}

function allowOnlyFloat(elm)
{

    var txt=elm.value;
    if(!txt)
        return true;
    var i=0;
    var txtN='';
    var ordNo=0;
    var ordNoZero= ord('0');
    var ordNoNine= ord('9');
    var ordNoPoint= ord('.');
    var ordNoComma= ord(',');
	var ordNoMinus= ord('-');
    var afterComma=false;
    for(i=0;i<txt.length;i++)
    {
    	ordNo=ord(txt.substr(i,1));
        if((ordNo >= ordNoZero && ordNo <= ordNoNine) || (i == 0 && (ordNo == ordNoMinus)))
            txtN=txtN+txt.substr(i,1);
        if((ordNo==ordNoPoint || ordNo==ordNoComma) && !afterComma)
        {
            txtN=txtN+'.';
            afterComma=true;
        }
    }
    elm.value=txtN;
}

function normalizeString(elm)
{
	var val = new String(elm.value);
	elm.value = val.normalize();
}

/*
function onlyInt(ev) {

    ev = ev || window.event;


    if (!ev || !ev.keyCode)
        return true;

    alert(ev.charCode + ' - ' + ev.keyCode + ' - ' + ev.which)



    return false;

    return ((  ev.keyCode >= ord('0')
            && ev.keyCode <= ord('9'))
            // esc
            || ev.keyCode == 27
            // backspace
            || ev.keyCode == 8
            // enter
            || ev.keyCode == 13
            // delete
            || ev.keyCode == 46
            // insert
            || ev.keyCode == 45
            // end
            || ev.keyCode == 35
            // home
            || ev.keyCode == 36
			// -
			|| ev.keyCode == ord('-')
            );
}
*/

function strReplace(s, r, w)
{
    return w.replace(s, r);
}





function gE(e,f)
{
    d=document;
    l=(d.layers)?1:0;
    if(l)
    {
        f=(f)?f:self;
        var V=f.document.layers;
        if(V[e])
            return V[e];
        for(var W=0;W<V.length;)
            t=gE(e,V[W++]);
        return t;
     }
     if(d.all)
        return d.all[e];
     return d.getElementById(e);
}



function disapearElm(elm,delay)
{
	if(delay==undefined || !delay)
		delay=3000;
	window.setTimeout(hE(elm), delay);
}
function sE(e,displayPropertie)
{
  if(displayPropertie == undefined)
    displayPropertie='block';

  if(l)
    e.visibility='show';
  else
    e.style.display=displayPropertie;
  return false;
}
function sEi(e){
	sE(e,'inline');
}
function hE(e)
{

    if(l)
        e.visibility='hide';
    else
        e.style.display='none';
    return false;

    }

d=document;l=(d.layers)?1:0;op=navigator.userAgent.toLowerCase().indexOf('opera')!=-1;ie=(d.all)?1:0;

function sX(e,x){if(l)e.left=x;else if(op)e.style.pixelLeft=x;else e.style.left=x+'px';}
function sY(e,y){if(l)e.top=y;else if(op)e.style.pixelTop=y;else e.style.top=y+'px';}
function sW(e,w){e.style.width=w+'px';}
function sH(e,h){e.style.height=h+'px';}

function mT(e,x,y){sX(e,x);sY(e,y);}
function mB(e,x,y){sX(e,gX(e)+x);sY(e,gY(e)+y);}


function sEv(e)
{
    e.style.visibility="visible";
}
function hEv(e)
{
    e.style.visibility="hidden";
}

function switchE(sel){
        shE(sel);
}



function shEv(e,firstHidden){

    if(firstHidden == undefined)
        firstHidden=false;

   // najprv je viditelny
   if(true != firstHidden)
   {
        if(e.style.visibility=="hidden"){
            e.style.visibility="visible";
        }
        else{
            e.style.visibility="hidden";
        }

    }
    // najprv je hidden
    else
    {
        if(e.style.visibility=="visible"){
            e.style.visibility="hidden";
        }
        else{
            e.style.visibility="visible";
        }
    }
    return false;
}

function shE(e,trigger){

    if(e==undefined)
        return false;
    if(e.style.display!="block"){
        e.style.display="block";
        if(trigger)
          trigger.innerHTML = '-';
    }
    else{
        e.style.display="none";
         if(trigger)
            trigger.innerHTML = '+';
    }
    return false;
}

function hsE(e,trigger){

     if(e==undefined)
        return false;

    if(e.style.display!="none"){
        e.style.display="none";
        if(trigger)
          trigger.innerHTML = '+';
    }
    else{
        e.style.display="block";
         if(trigger)
            trigger.innerHTML = '-';
    }
    return false;
}

function hsEDetermined(determinator,elmIdorIds,determinatorVals,displayProp,changeType)
{

    //if(determinatorVals == undefined || determinatorVals == null)
    //    determinatorVals=new Array(1,99999999);

    var displayPropOrig=displayProp;
    var elmIds=new Array();
    elmIds=elmIdorIds.split(",");

    var show=false;


    switch(determinator.tagName)
    {
        case 'INPUT':


            switch(determinator.getAttribute('type'))
            {
                case 'checkbox':
                case 'radio':
                    if(determinatorVals == undefined || determinatorVals == null)
                        determinatorValsTmp=new Array(1,99999999);
                    else
                        determinatorValsTmp=determinatorVals;
                    show=((determinator.checked && inArray(determinatorValsTmp,1)) || (!determinator.checked && !inArray(determinatorValsTmp,1)));
                    break;
                case 'text':
                    show=(determinator.value!='');
                    break;
            }
         break;
         case 'SELECT':
            //alert(inArray(determinatorVals,determinator.value));
            if(determinatorVals)
                show=inArray(determinatorVals,determinator.value);
            else
                show=(determinator.value>0);

         break;


         default:
            alert('hsEDetermined: element '+determinator.tagName+' not supported');
         break;
    }

    var visibilityProp;
    var enabledProp;
    var checkedProp;
    if(changeType == undefined)
        changeType=0;


    if(show)
    {
       switch(changeType)
       {
         case 1: //setVisibilityOnly
            visibilityProp='visible';
         break;
         case 2: //setDisabled
            enabledProp=1;
         break;
         case 3: //setChecked
            checkedProp=1;
         break;
         default:
           if(!displayProp)
            displayProp='block';
         break;
       }

    }
    else
    {
        switch(changeType)
        {

         case 1: //setVisibilityOnly
            visibilityProp='hidden';
         break;
         case 2: //setDisabled
            enabledProp=-1;
         break;
         case 3: //setChecked
            checkedProp=-1;
         break;
         default:
            displayProp='none';
         break;
        }
    }
    var i;
    var elm;
    for(i=0;i<elmIds.length;i++)
    {
        elm=gE(elmIds[i]);
        if(elm)
        {
            if(visibilityProp)
                elm.style.visibility=visibilityProp;
            else if(enabledProp)
                //elm.setAttribute('disabled',(enabledProp==1?'':'disabled'));
                elm.disabled= (enabledProp==1?false:true);
             else if(checkedProp)
                elm.checked= (checkedProp==1?false:true);
            else
            {

               //alert('display: '+elm.style.display);
               elm.style.cssText='display:' + new String(displayProp);
               if(displayPropOrig == 'table-row')
               {

                    //taky hack pre IE - skryt vsetky SEELCTy v tomto elemente

                    if(displayProp=='none')
                        hideSelects(elm);
                       else
                        showSelects(elm);
               }

               /*
               if(displayProp=='none')
                hE(elm);
               else
                sE(elm,displayProp);
               */
            }
        }
        else
        {
            //alert('no element found: '+elmIds[i]);
            if(i>10)
                break;//

        }
    }


}




function wEa(e,txt,onbegin,appending)
{

    if(!e)
        return false;

    if((typeof onbegin) == undefined)
        onbegin=false;

    if((typeof appending) == undefined)
        appending=false;


    // ak treba appendovat alebo ak to je tabulka v IE .. addRow, addCell atd ..
    if(appending || (getBrowser()=='ie' && inArray(getIeReadOnlyTags(),e.tagName)))
    {
        //alert('appending in '+e.tagName);
        var i;
        var j;
        var count;
        var childTagName='';


        if(e.tagName=='TR')
        {
            /*
            if(e.cells && (count=e.cells.length))
                for(i=1;i<=count;i++)
                    e.deleteCell(0);
            */
            childTagName='td';

        }
        else
        {
            /*
            if(e.rows && (count=e.rows.length))
                for(i=1;i<=count;i++)
                    e.deleteRow(0);
            */
            childTagName='tr';
        }


        var childs=txt.split('<'+childTagName);

        for (i=0;i<childs.length;i++)
        {
            if(childs[i].indexOf('>')<0)
                continue;
            //odstranit '</td>' | </tr>
            childs[i]=childs[i].replace('</'+childTagName+'>','');

            // odrezat znaky na zaciatku az po '>', tieto znaky rozparsovat ako vlastnosti
            var childProperties=childs[i].substr(0,childs[i].indexOf('>'));
            childs[i]=childs[i].substring(childs[i].indexOf('>')+1,childs[i].length);


            //pridat cell alebo row ako child, do childu vpisat obsah bunky
            if(getBrowser()=='ie')
            {
                if(childTagName=='td')
                    var added=e.insertCell();
                else if(childTagName=='tr')
                    var added=e.insertRow();
            }
            else
            {
                if(childTagName=='td')
                    var added=e.appendChild(document.createElement('TD'));
                else if(childTagName=='tr')
                    var added=e.appendChild(document.createElement('TR'));
            }
            if(added != null)
            {
                // pridat vlastnosti
                elmAddProperties(added,childProperties);
                // pridat obsah do bunky alebo do riadku?
                wEa(added,childs[i]);
                //alert('child content: '+childs[i]);
            }

        }


    }
    else
    {
        // klasika

        if(e.innerHTML)
            txt=(onbegin?txt+e.innerHTML:e.innerHTML+txt);

        if(typeof(e.value) != undefined && e.value!=null)
            e.value=txt;
        else if(typeof(e.innerHTML) != undefined)
            e.innerHTML=txt;
        else
            alert('nie je innerHTML ani value');
    }
}

function wE(e,txt)
{
    if(txt == undefined)
            txt='';
    if(!e)
        return false;
    clearE(e);
    /*
    if(!txt)
        txt='';*/
    wEa(e,txt);
}

function clearE(e)
{
    if((e.innerHTML) && (getBrowser()!='ie' || !inArray(getIeReadOnlyTags(),e.tagName)))
        e.innerHTML='';
    else
        if ( e.hasChildNodes() )
            while ( e.childNodes.length >= 1 )
                e.removeChild( e.firstChild );

}


// Gets the absolute position on the page of the element passed in
function getAbsolutePosition(obj) {
    var result = {x:0, y:0};
    while (obj != null) {
        result['x'] += obj.offsetTop;
        result['y'] += obj.offsetLeft;
        obj = obj.offsetParent;
    }
    return result;
}


function getElmPosition(e){
    var left = 0;
    var top  = 0;



    while (e.offsetParent){
        left += e.offsetLeft;
        top  += e.offsetTop;
        e     = e.offsetParent;
    }

    left += e.offsetLeft;
    top  += e.offsetTop;

    return {x:left, y:top};
}


function getElmSize(e){
    var width = 0;
    var height  = 0;


    width = e.offsetWidth;
    height  = e.offsetHeight;

    return {x:width, y:height};
}


var ElmVarForEval=null;

function elmAddProperties(elm,strProperties)
{

    var propertiesArrIndexed=new Object();
    propertiesArr=(strProperties+" ").split('" ');
    if(propertiesArr.length && elm)
    {
        for(j=0;j<propertiesArr.length;j++)
        {


            var pom=propertiesArr[j].split('="');
            propertiesArrIndexed[pom[0].trim()]=pom[1];

        }
        if(objectLength(propertiesArrIndexed))
        for (keyVal in propertiesArrIndexed)
        {

            //alert(propertiesArrIndexed[keyVal]);

            if(!propertiesArrIndexed[keyVal])
                continue;



             //wEa(gE('pre_dump'),keyVal+': '+propertiesArrIndexed[keyVal]+'<br>');

            switch(keyVal)
            {
                case "class":
                    elm.className=propertiesArrIndexed[keyVal];
                break;
                case "onclick":  case "onmouseover":  case "onmouseout":  case "onmousemove":
                    ElmVarForEval=elm;
                    eval('attachEventUni(ElmVarForEval,\''+keyVal+'\',function(event){'+propertiesArrIndexed[keyVal]+';})');
                break;
                case "id":
                    //elm.id=propertiesArrIndexed[keyVal];
                    elm.setAttribute('id',propertiesArrIndexed[keyVal]);
                break;
                case "colspan":
                    elm.colSpan=propertiesArrIndexed[keyVal];
                    elm.setAttribute('id',propertiesArrIndexed[keyVal]);
                break;
                default:
                    ;//elm.keyVal=rowPropertiesArrIndexed[keyVal];
                    //alert('row Properties-'+keyVal+': '+rowPropertiesArrIndexed[keyVal]);
                break;

            }
        }

    }

}


function addCls(elm,cls)
{

    if(elm)
    {
        if(!haveCls(elm,cls))
          elm.className+=" "+cls;

        return true;
    }
    else
        return 0;
}

function haveCls(elm,cls)
{
    var pos;
    if(elm)
    {

        var clsValues='# '+elm.className+' ';
        var toSearch=' '+cls+' ';
        //alert(clsValues + toSearch);
        // ak ma okolo medzery
        pos=clsValues.indexOf(toSearch);
    }
    return (pos>0 ? pos : false );
}

function remCls(elm,cls)
{

    if(elm)
    {
        //alert('rem1:'+elm.className);
        var position;
        position=haveCls(elm,cls);
        //alert(position);
        if(position)
            elm.className=elm.className.substring(0,position-1) + elm.className.substring(position+cls.length-1);

        //alert('rem2:'+elm.className);
    }

}



function setButtonEnabled(elm,value)
{
    if(!elm)
        return false;
    elm.disabled=(value?false:true);
}


function setReadonly(elm,value)
{
    if(!elm)
    {
        alert('no elm');
        return false;

    }
    if(value)
        elm.setAttribute('readonly','readonly');
    else
        elm.removeAttribute('readonly');
}


var defaultValuesToClear= new Array();
function clearDefaultVal(elm,defaultValue,addClas)
{

     if(elm.value == defaultValue)
        elm.value='';

     if (addClas)
        addCls(elm,addClas);
     /*
     if(elm.value==elm.getAttribute('value'))
     {
          if()
          // tieto tri riadky su tu len pre IE7 bug ---
          if(!defaultValuesToClear[elm.getAttribute('name')])
            defaultValuesToClear[elm.getAttribute('name')]=elm.value;
          if(elm.value==defaultValuesToClear[elm.getAttribute('name')])
          // --------------
            elm.value='';
     }*/

}


function elmGetValue(elmId)
{
    var elm=gE(elmId);
    if(!elm)
        return false;

    switch(elm.tagName)
    {
        case 'INPUT': case 'SELECT':
        return elm.value;
        break;

        default:
        return elm.innerHTML;
        break;
    }
}




function fillElement(elmId,value)
{
	var elm;
    if(!elmId || !(elm=gE(elmId)))
        return false;



    switch (elm.tagName)
    {

        case 'INPUT': case 'TEXTAREA':
          if (typeof (elm.value) != undefined)
                elm.value=value;
        break;
        case 'IMG':
           if (typeof (elm.src) != undefined)
                elm.src=value;
        break;
        default:
            wE(elm,value);
        break;

    }
}

function fillElements(query)
{
    var tweensSeparated=new Object();
    var data=new Object();
    var elm;

    var data=getArrayFromString(query,'&','=');


    for (var keyVal in data)
    {
         if(data[keyVal] != undefined)
            fillElement(keyVal,replaceAll(data[keyVal],'##','&'));
    }


}

function submitFormToLitbox(formElm,litBoxName,litboxOptions,otherUrl)
{
	 LITBoxStart(otherUrl,litboxOptions, litBoxName, false);
	 submitForm(formElm, litBoxName,'',otherUrl);
}
function submitForm(formElm,outputElmId,afterScript,otherUrl,method,dontUseClock,condEval)
{

     if(isNull(formElm))
     {
        alert(formElm + 'no form element');
        return false;
     }
    var post='';
    var name='';
    var value='';
    var type='';
    var i;
    var action;
    if(otherUrl==undefined)
    	otherUrl=false;
    if(otherUrl)
        action=otherUrl;
    else
    	action=formElm.getAttribute('action');
    if(method==undefined)
    	method=formElm.getAttribute('action');


    //alert(getBrowser());

    //alert('ina' + inArray(Array('ie','opera'),getBrowser()));

    /*
    if(checkBrowser && inArray(Array('ie','opera'),getBrowser()))
    {
        action=action.replace(/litbox/,'');
        formElm.setAttribute('action',action);
        alert(formElm.getAttribute('action'));
        //return true;
        return false;
    }
    */




    var allchilds=formElm.getElementsByTagName('*');
     post=ElementsToQuery(allchilds);



    //alert('action:'+action+' post: '+post);
    if(LITBoxExists(outputElmId))
    {
        //alert('litbox exists');
        if(action)
            LITBoxChangeUrl(outputElmId,action);
        LITBoxRefresh(outputElmId,post,afterScript,condEval);
    }
    else
    {

        if(isNull(action) || action == '')
        {
            alert('no action in form element');
            return false;
        }
        //alert('litbox NOT exists');
        if(method==undefined)
        	method=false;
        if(method=='GET')
        	runPhpScript(action+post,-1,outputElmId,afterScript,dontUseClock,condEval);
        else
        	runPhpScript(action,post,outputElmId,afterScript,dontUseClock,condEval);
    }

    return false;

}


function CheckAll(value,form,runOnclick)
{

    if(typeof(form)!="object")
        form=gE(form);
    if(typeof(form)!="object")
    {
        alert('no form');
        return false;
    }
    var allchilds=form.getElementsByTagName('INPUT');
    for(i=0;i< allchilds.length;i++ )
    {
        type=allchilds[i].getAttribute('type');
        //name=allchilds[i].getAttribute('name');
        if(type=='checkbox')
        {
            allchilds[i].checked=value;
            if(runOnclick)
                allchilds[i].onclick();
        }
    }
}


function showSelects(parentElm,ieonly){

   if(ieonly == undefined)
    ieonly=true;

   if(ieonly && 'ie' != getBrowser())
     return false;

   if(!parentElm)
        parentElm=document;
   var elements = parentElm.getElementsByTagName("select");
   for (i=0;i< elements.length;i++){
      elements[i].style.visibility='visible';
   }
}

function hideSelects(parentElm,ieonly)
{
   if(ieonly == undefined)
    ieonly=true;

   if(ieonly && 'ie' != getBrowser())
     return false;

   if(!parentElm)
        parentElm=document;
   var elements = parentElm.getElementsByTagName("select");
   for (i=0;i< elements.length;i++){
   elements[i].style.visibility='hidden';
   }
}

function ElementsToQuery(allchilds)
{
    var post='';
    for(i=0;i< allchilds.length;i++ )
    {
        switch(allchilds[i].tagName)
        {

            case 'INPUT':
                type=allchilds[i].getAttribute('type');
                name=allchilds[i].getAttribute('name');
                var value=allchilds[i].value;
                var checked=allchilds[i].checked;

                if(name && (value != null) && (type!='checkbox' || (checked!=false &&  checked!=null)  ) && (type!='radio' || (checked!=false &&  checked!=null)  ))
                    post=post+'&'+name+'='+POSTencode(value);
                //alert(value + ' vs '+POSTencode(value));
            break;

            case 'SELECT':

                name=allchilds[i].getAttribute('name');
                var multi=allchilds[i].getAttribute('multiple');

                if(null != multi)
                {
                    selected = new Array();
                    for (var c = 0; c < allchilds[i].length; c++)
                        if(allchilds[i][c].selected)
                            selected.push(allchilds[i][c].value);


                    post=post+'&'+name+'='+POSTencode(selected.join(','));
                }
                else
                {
                    value=allchilds[i].value;

                    if(name && value != null)
                        post=post+'&'+name+'='+POSTencode(value);
                 }
            break;

            case 'TEXTAREA':
                name=allchilds[i].getAttribute('name');
                value=allchilds[i].value;
                if(name && value != null)
                    post=post+'&'+name+'='+POSTencode(value);
            break;

            default:

               continue;
            break;
        }



    }
    return post;
}


var BottomElm;
function putElmToBottom(elm,dontuseRecurs)
{

    // ziskat vysku viewportu a vysky scrollu
    var viewport = GetViewPortSize();
    var scrolls = GetScrollPositions();
    // zisakt vysku elementu
    var sizes=getElmSize(elm);
    // nastavit top elementu
    elm.style.top = (scrolls.y + viewport.y - sizes.y -1)+ 'px';


    //alert(scrolls.y +' '+ viewport.y +' '+ sizes.y +' ' );


    if(dontuseRecurs)
        return true;
    BottomElm=elm;
    attachEventUni(window,'onscroll',
        function() {
        	putElmToBottom(BottomElm,true);
        }
        )



}


function JBoxOpen(divId,opacity)
{

    if(opacity == undefined)
        opacity=0.8;

    var elm;
    var divElm;

    if(elm=gE('jbox1'))
    {

    }
    else
    {
        elm=document.createElement('DIV');
        elm.setAttribute('jb',divId);
        elm.setAttribute('id','jbox1');
        elm.onclick= JBoxClose;

        document.body.appendChild(elm);
    }



    elm.style.cssText= 'opacity: '+opacity+'; filter: alpha(opacity = '+(opacity*100)+'); -moz-opacity: '+opacity+'; -khtml-opacity: '+opacity+';position:absolute;top:0px;left:0px;background-color:#000;z-index:1000;';
    //var sizes=GetViewPortSize();
    var sizes=GetDocumentSize();
    elm.style.width=(sizes.x-21)+'px';
    elm.style.height=sizes.y+'px';
    sE(elm);
    if(divElm=gE(divId)){
        sE(divElm);
        divElm.style.zIndex="1001";
        }




}


function JBoxClose()
{
    var elm;
    if(elm=gE('jbox1'))
    {
        var divElmId=elm.getAttribute('jb');
        hE(elm);
        if(divElm=gE(divElmId))
            hE(divElm);
    }

}



function removeAllOptions(selectbox)
{
 var i;
 for(i=selectbox.options.length-1; i>=0; i--)
 {
    selectbox.remove(i);
 }
}

function addOption(selectbox, text, value)
{
    var optn = document.createElement("option");
    optn.text = text;
    optn.value = value;
    selectbox.options.add(optn);
}

function addOptions(selectbox, group)
{
    for ( var i in group){
    addOption(selectbox, group[i], i);
    }
}


function changeOptions(selectbox, group)
{
    var val=selectbox.value;
    removeAllOptions(selectbox);
    addOptions(selectbox, group);
    selectbox.value=val;
}



var allMoves=new Array();
function moveLeft(id,idParent,continualy)
{

    if(!allMoves[id])
        moveInit(id,idParent);
    allMoves[id]['posun']=5;
    moveMove(id,1);
     if(continualy !=undefined  && continualy)
      allMoves[id]['timer']=window.setInterval('moveMove(\''+id+'\',1)',15);

}
function moveRight(id,idParent,continualy)
{
	if(!allMoves[id])
        moveInit(id,idParent);
    allMoves[id]['posun']=5;
    moveMove(id,-1);
    if(continualy !=undefined  && continualy)
      allMoves[id]['timer']=window.setInterval('moveMove(\''+id+'\',-1)',15);
}

function moveMove(id,posun)
{
	if(!allMoves[id])
        moveInit(id,idParent);

    allMoves[id]['actualLeft']=allMoves[id]['actualLeft']+Math.round(posun*allMoves[id]['posun']);

    allMoves[id]['posun'] += 0.8;

    allMoves[id]['actualLeft']=Math.max(allMoves[id]['actualLeft'],allMoves[id]['minLeft']);
    allMoves[id]['actualLeft']=Math.min(allMoves[id]['actualLeft'],allMoves[id]['maxLeft']);

    allMoves[id]['elm'].style.left= allMoves[id]['actualLeft']+'px';

}

function moveInit(id,idParent)
{
	allMoves[id]=new Object();
    allMoves[id]['elm']=gE(id);
    allMoves[id]['parentId']=idParent;
    allMoves[id]['btn_left']=gE(id+'-left');
    allMoves[id]['btn_right']=gE(id+'-right');
    allMoves[id]['parent']=gE(idParent);
    allMoves[id]['actualLeft']=0;
    allMoves[id]['maxLeft']=0;
    allMoves[id]['posun']=5;

     var sizeElm=getElmSize(allMoves[id]['elm']);
     var sizeParent=getElmSize(allMoves[id]['parent']);

    allMoves[id]['minLeft']=-(sizeElm.x-sizeParent.x);
    //alert(allMoves[id]['minLeft']);
}

function moveStop(id)
{
	if(allMoves[id]['timer'])
        window.clearInterval(allMoves[id]['timer']);
    if(allMoves[id]['actualLeft'] <= allMoves[id]['minLeft'] && allMoves[id]['btn_right']!=null)
        hE(allMoves[id]['btn_right']);
    else
        sE(allMoves[id]['btn_right']);

    if(allMoves[id]['actualLeft']>=allMoves[id]['maxLeft'] && allMoves[id]['btn_left']!=null)
        hE(allMoves[id]['btn_left']);
    else
        sE(allMoves[id]['btn_left']);
}


/*  Prototype JavaScript framework, version 1.5.0_rc0
 *  (c) 2005 Sam Stephenson <sam@conio.net>
 *
 *  Prototype is freely distributable under the terms of an MIT-style license.
 *  For details, see the Prototype web site: http://prototype.conio.net/
 *
/*--------------------------------------------------------------------------*/

var Prototype = {
  Version: '1.5.0_rc0',
  ScriptFragment: '(?:<script.*?>)((\n|\r|.)*?)(?:<\/script>)',

  emptyFunction: function() {},
  K: function(x) {return x}
}

var Class = {
  create: function() {
    return function() {
      this.initialize.apply(this, arguments);
    }
  }
}

var Abstract = new Object();

Object.extend = function(destination, source) {
  for (var property in source) {
    destination[property] = source[property];
  }
  return destination;
}

Object.inspect = function(object) {
  try {
    if (object == undefined) return 'undefined';
    if (object == null) return 'null';
    return object.inspect ? object.inspect() : object.toString();
  } catch (e) {
    if (e instanceof RangeError) return '...';
    throw e;
  }
}

Function.prototype.bind = function() {
  var __method = this, args = $A(arguments), object = args.shift();
  return function() {
    return __method.apply(object, args.concat($A(arguments)));
  }
}

Function.prototype.bindAsEventListener = function(object) {
  var __method = this;
  return function(event) {
    return __method.call(object, event || window.event);
  }
}

Object.extend(Number.prototype, {
  toColorPart: function() {
    var digits = this.toString(16);
    if (this < 16) return '0' + digits;
    return digits;
  },

  succ: function() {
    return this + 1;
  },

  times: function(iterator) {
    $R(0, this, true).each(iterator);
    return this;
  }
});

var Try = {
  these: function() {
    var returnValue;

    for (var i = 0; i < arguments.length; i++) {
      var lambda = arguments[i];
      try {
        returnValue = lambda();
        break;
      } catch (e) {}
    }

    return returnValue;
  }
}

/*--------------------------------------------------------------------------*/

var PeriodicalExecuter = Class.create();
PeriodicalExecuter.prototype = {
  initialize: function(callback, frequency) {
    this.callback = callback;
    this.frequency = frequency;
    this.currentlyExecuting = false;

    this.registerCallback();
  },

  registerCallback: function() {
    setInterval(this.onTimerEvent.bind(this), this.frequency * 1000);
  },

  onTimerEvent: function() {
    if (!this.currentlyExecuting) {
      try {
        this.currentlyExecuting = true;
        this.callback();
      } finally {
        this.currentlyExecuting = false;
      }
    }
  }
}
Object.extend(String.prototype, {
  gsub: function(pattern, replacement) {
    var result = '', source = this, match;
    replacement = arguments.callee.prepareReplacement(replacement);

    while (source.length > 0) {
      if (match = source.match(pattern)) {
        result += source.slice(0, match.index);
        result += (replacement(match) || '').toString();
        source  = source.slice(match.index + match[0].length);
      } else {
        result += source, source = '';
      }
    }
    return result;
  },

  sub: function(pattern, replacement, count) {
    replacement = this.gsub.prepareReplacement(replacement);
    count = count === undefined ? 1 : count;

    return this.gsub(pattern, function(match) {
      if (--count < 0) return match[0];
      return replacement(match);
    });
  },

  scan: function(pattern, iterator) {
    this.gsub(pattern, iterator);
    return this;
  },

  truncate: function(length, truncation) {
    length = length || 30;
    truncation = truncation === undefined ? '...' : truncation;
    return this.length > length ?
      this.slice(0, length - truncation.length) + truncation : this;
  },

  strip: function() {
    return this.replace(/^\s+/, '').replace(/\s+$/, '');
  },

  stripTags: function() {
    return this.replace(/<\/?[^>]+>/gi, '');
  },

  stripScripts: function() {
    return this.replace(new RegExp(Prototype.ScriptFragment, 'img'), '');
  },

  extractScripts: function() {
    var matchAll = new RegExp(Prototype.ScriptFragment, 'img');
    var matchOne = new RegExp(Prototype.ScriptFragment, 'im');
    return (this.match(matchAll) || []).map(function(scriptTag) {
      return (scriptTag.match(matchOne) || ['', ''])[1];
    });
  },

  evalScripts: function() {
    return this.extractScripts().map(function(script) { return eval(script) });
  },

  escapeHTML: function() {
    var div = document.createElement('div');
    var text = document.createTextNode(this);
    div.appendChild(text);
    return div.innerHTML;
  },

  unescapeHTML: function() {
    var div = document.createElement('div');
    div.innerHTML = this.stripTags();
    return div.childNodes[0] ? div.childNodes[0].nodeValue : '';
  },

  toQueryParams: function() {
    var pairs = this.match(/^\??(.*)$/)[1].split('&');
    return pairs.inject({}, function(params, pairString) {
      var pair = pairString.split('=');
      params[pair[0]] = pair[1];
      return params;
    });
  },

  toArray: function() {
    return this.split('');
  },

  camelize: function() {
    var oStringList = this.split('-');
    if (oStringList.length == 1) return oStringList[0];

    var camelizedString = this.indexOf('-') == 0
      ? oStringList[0].charAt(0).toUpperCase() + oStringList[0].substring(1)
      : oStringList[0];

    for (var i = 1, len = oStringList.length; i < len; i++) {
      var s = oStringList[i];
      camelizedString += s.charAt(0).toUpperCase() + s.substring(1);
    }

    return camelizedString;
  },

  inspect: function() {
    return "'" + this.replace(/\\/g, '\\\\').replace(/'/g, '\\\'') + "'";
  }
});

String.prototype.gsub.prepareReplacement = function(replacement) {
  if (typeof replacement == 'function') return replacement;
  var template = new Template(replacement);
  return function(match) { return template.evaluate(match) };
}

String.prototype.parseQuery = String.prototype.toQueryParams;

var Template = Class.create();
Template.Pattern = /(^|.|\r|\n)(#\{(.*?)\})/;
Template.prototype = {
  initialize: function(template, pattern) {
    this.template = template.toString();
    this.pattern  = pattern || Template.Pattern;
  },

  evaluate: function(object) {
    return this.template.gsub(this.pattern, function(match) {
      var before = match[1];
      if (before == '\\') return match[2];
      return before + (object[match[3]] || '').toString();
    });
  }
}

var $break    = new Object();
var $continue = new Object();

var Enumerable = {
  each: function(iterator) {
    var index = 0;
    try {
      this._each(function(value) {
        try {
          iterator(value, index++);
        } catch (e) {
          if (e != $continue) throw e;
        }
      });
    } catch (e) {
      if (e != $break) throw e;
    }
  },

  all: function(iterator) {
    var result = true;
    this.each(function(value, index) {
      result = result && !!(iterator || Prototype.K)(value, index);
      if (!result) throw $break;
    });
    return result;
  },

  any: function(iterator) {
    var result = true;
    this.each(function(value, index) {
      if (result = !!(iterator || Prototype.K)(value, index))
        throw $break;
    });
    return result;
  },

  collect: function(iterator) {
    var results = [];
    this.each(function(value, index) {
      results.push(iterator(value, index));
    });
    return results;
  },

  detect: function (iterator) {
    var result;
    this.each(function(value, index) {
      if (iterator(value, index)) {
        result = value;
        throw $break;
      }
    });
    return result;
  },

  findAll: function(iterator) {
    var results = [];
    this.each(function(value, index) {
      if (iterator(value, index))
        results.push(value);
    });
    return results;
  },

  grep: function(pattern, iterator) {
    var results = [];
    this.each(function(value, index) {
      var stringValue = value.toString();
      if (stringValue.match(pattern))
        results.push((iterator || Prototype.K)(value, index));
    })
    return results;
  },

  include: function(object) {
    var found = false;
    this.each(function(value) {
      if (value == object) {
        found = true;
        throw $break;
      }
    });
    return found;
  },

  inject: function(memo, iterator) {
    this.each(function(value, index) {
      memo = iterator(memo, value, index);
    });
    return memo;
  },

  invoke: function(method) {
    var args = $A(arguments).slice(1);
    return this.collect(function(value) {
      return value[method].apply(value, args);
    });
  },

  max: function(iterator) {
    var result;
    this.each(function(value, index) {
      value = (iterator || Prototype.K)(value, index);
      if (result == undefined || value >= result)
        result = value;
    });
    return result;
  },

  min: function(iterator) {
    var result;
    this.each(function(value, index) {
      value = (iterator || Prototype.K)(value, index);
      if (result == undefined || value < result)
        result = value;
    });
    return result;
  },

  partition: function(iterator) {
    var trues = [], falses = [];
    this.each(function(value, index) {
      ((iterator || Prototype.K)(value, index) ?
        trues : falses).push(value);
    });
    return [trues, falses];
  },

  pluck: function(property) {
    var results = [];
    this.each(function(value, index) {
      results.push(value[property]);
    });
    return results;
  },

  reject: function(iterator) {
    var results = [];
    this.each(function(value, index) {
      if (!iterator(value, index))
        results.push(value);
    });
    return results;
  },

  sortBy: function(iterator) {
    return this.collect(function(value, index) {
      return {value: value, criteria: iterator(value, index)};
    }).sort(function(left, right) {
      var a = left.criteria, b = right.criteria;
      return a < b ? -1 : a > b ? 1 : 0;
    }).pluck('value');
  },

  toArray: function() {
    return this.collect(Prototype.K);
  },

  zip: function() {
    var iterator = Prototype.K, args = $A(arguments);
    if (typeof args.last() == 'function')
      iterator = args.pop();

    var collections = [this].concat(args).map($A);
    return this.map(function(value, index) {
      return iterator(collections.pluck(index));
    });
  },

  inspect: function() {
    return '#<Enumerable:' + this.toArray().inspect() + '>';
  }
}

Object.extend(Enumerable, {
  map:     Enumerable.collect,
  find:    Enumerable.detect,
  select:  Enumerable.findAll,
  member:  Enumerable.include,
  entries: Enumerable.toArray
});
var $A = Array.from = function(iterable) {
  if (!iterable) return [];
  if (iterable.toArray) {
    return iterable.toArray();
  } else {
    var results = [];
    for (var i = 0; i < iterable.length; i++)
      results.push(iterable[i]);
    return results;
  }
}

Object.extend(Array.prototype, Enumerable);

if (!Array.prototype._reverse)
  Array.prototype._reverse = Array.prototype.reverse;

Object.extend(Array.prototype, {
  _each: function(iterator) {
    for (var i = 0; i < this.length; i++)
      iterator(this[i]);
  },

  clear: function() {
    this.length = 0;
    return this;
  },

  first: function() {
    return this[0];
  },

  last: function() {
    return this[this.length - 1];
  },

  compact: function() {
    return this.select(function(value) {
      return value != undefined || value != null;
    });
  },

  flatten: function() {
    return this.inject([], function(array, value) {
      return array.concat(value && value.constructor == Array ?
        value.flatten() : [value]);
    });
  },

  without: function() {
    var values = $A(arguments);
    return this.select(function(value) {
      return !values.include(value);
    });
  },

  indexOf: function(object) {
    for (var i = 0; i < this.length; i++)
      if (this[i] == object) return i;
    return -1;
  },

  reverse: function(inline) {
    return (inline !== false ? this : this.toArray())._reverse();
  },

  inspect: function() {
    return '[' + this.map(Object.inspect).join(', ') + ']';
  }
});
var Hash = {
  _each: function(iterator) {
    for (var key in this) {
      var value = this[key];
      if (typeof value == 'function') continue;

      var pair = [key, value];
      pair.key = key;
      pair.value = value;
      iterator(pair);
    }
  },

  keys: function() {
    return this.pluck('key');
  },

  values: function() {
    return this.pluck('value');
  },

  merge: function(hash) {
    return $H(hash).inject($H(this), function(mergedHash, pair) {
      mergedHash[pair.key] = pair.value;
      return mergedHash;
    });
  },

  toQueryString: function() {
    return this.map(function(pair) {
      return pair.map(encodeURIComponent).join('=');
    }).join('&');
  },

  inspect: function() {
    return '#<Hash:{' + this.map(function(pair) {
      return pair.map(Object.inspect).join(': ');
    }).join(', ') + '}>';
  }
}

function $H(object) {
  var hash = Object.extend({}, object || {});
  Object.extend(hash, Enumerable);
  Object.extend(hash, Hash);
  return hash;
}
ObjectRange = Class.create();
Object.extend(ObjectRange.prototype, Enumerable);
Object.extend(ObjectRange.prototype, {
  initialize: function(start, end, exclusive) {
    this.start = start;
    this.end = end;
    this.exclusive = exclusive;
  },

  _each: function(iterator) {
    var value = this.start;
    do {
      iterator(value);
      value = value.succ();
    } while (this.include(value));
  },

  include: function(value) {
    if (value < this.start)
      return false;
    if (this.exclusive)
      return value < this.end;
    return value <= this.end;
  }
});

var $R = function(start, end, exclusive) {
  return new ObjectRange(start, end, exclusive);
}

var Ajax = {
  getTransport: function() {
    return Try.these(
      function() {return new XMLHttpRequest()},
      function() {return new ActiveXObject('Msxml2.XMLHTTP')},
      function() {return new ActiveXObject('Microsoft.XMLHTTP')}
    ) || false;
  },

  activeRequestCount: 0
}

Ajax.Responders = {
  responders: [],

  _each: function(iterator) {
    this.responders._each(iterator);
  },

  register: function(responderToAdd) {
    if (!this.include(responderToAdd))
      this.responders.push(responderToAdd);
  },

  unregister: function(responderToRemove) {
    this.responders = this.responders.without(responderToRemove);
  },

  dispatch: function(callback, request, transport, json) {
    this.each(function(responder) {
      if (responder[callback] && typeof responder[callback] == 'function') {
        try {
          responder[callback].apply(responder, [request, transport, json]);
        } catch (e) {}
      }
    });
  }
};

Object.extend(Ajax.Responders, Enumerable);

Ajax.Responders.register({
  onCreate: function() {
    Ajax.activeRequestCount++;
  },

  onComplete: function() {
    Ajax.activeRequestCount--;
  }
});

Ajax.Base = function() {};
Ajax.Base.prototype = {
  setOptions: function(options) {
    this.options = {
      method:       'post',
      asynchronous: true,
      contentType:  'application/x-www-form-urlencoded',
      parameters:   ''
    }
    Object.extend(this.options, options || {});
  },

  responseIsSuccess: function() {
    return this.transport.status == undefined
        || this.transport.status == 0
        || (this.transport.status >= 200 && this.transport.status < 300);
  },

  responseIsFailure: function() {
    return !this.responseIsSuccess();
  }
}

Ajax.Request = Class.create();
Ajax.Request.Events =
  ['Uninitialized', 'Loading', 'Loaded', 'Interactive', 'Complete'];

Ajax.Request.prototype = Object.extend(new Ajax.Base(), {
  initialize: function(url, options) {
    this.transport = Ajax.getTransport();
    this.setOptions(options);
    this.request(url);
  },

  request: function(url) {
    var parameters = this.options.parameters || '';
    if (parameters.length > 0) parameters += '&_=';

    try {
      this.url = url;
      if (this.options.method == 'get' && parameters.length > 0)
        this.url += (this.url.match(/\?/) ? '&' : '?') + parameters;

      Ajax.Responders.dispatch('onCreate', this, this.transport);

      this.transport.open(this.options.method, this.url,
        this.options.asynchronous);

      if (this.options.asynchronous) {
        this.transport.onreadystatechange = this.onStateChange.bind(this);
        setTimeout((function() {this.respondToReadyState(1)}).bind(this), 10);
      }

      this.setRequestHeaders();

      var body = this.options.postBody ? this.options.postBody : parameters;
      this.transport.send(this.options.method == 'post' ? body : null);

    } catch (e) {
      this.dispatchException(e);
    }
  },

  setRequestHeaders: function() {
    var requestHeaders =
      ['X-Requested-With', 'XMLHttpRequest',
       'X-Prototype-Version', Prototype.Version,
       'Accept', 'text/javascript, text/html, application/xml, text/xml, */*'];

    if (this.options.method == 'post') {
      requestHeaders.push('Content-type', this.options.contentType);

      /* Force "Connection: close" for Mozilla browsers to work around
       * a bug where XMLHttpReqeuest sends an incorrect Content-length
       * header. See Mozilla Bugzilla #246651.
       */
      if (this.transport.overrideMimeType)
        requestHeaders.push('Connection', 'close');
    }

    if (this.options.requestHeaders)
      requestHeaders.push.apply(requestHeaders, this.options.requestHeaders);

    for (var i = 0; i < requestHeaders.length; i += 2)
      this.transport.setRequestHeader(requestHeaders[i], requestHeaders[i+1]);
  },

  onStateChange: function() {
    var readyState = this.transport.readyState;
    if (readyState != 1)
      this.respondToReadyState(this.transport.readyState);
  },

  header: function(name) {
    try {
      return this.transport.getResponseHeader(name);
    } catch (e) {}
  },

  evalJSON: function() {
    try {
      return eval('(' + this.header('X-JSON') + ')');
    } catch (e) {}
  },

  evalResponse: function() {
    try {
      return eval(this.transport.responseText);
    } catch (e) {
      this.dispatchException(e);
    }
  },

  respondToReadyState: function(readyState) {
    var event = Ajax.Request.Events[readyState];
    var transport = this.transport, json = this.evalJSON();

    if (event == 'Complete') {
      try {
        (this.options['on' + this.transport.status]
         || this.options['on' + (this.responseIsSuccess() ? 'Success' : 'Failure')]
         || Prototype.emptyFunction)(transport, json);
      } catch (e) {
        this.dispatchException(e);
      }

      if ((this.header('Content-type') || '').match(/^text\/javascript/i))
        this.evalResponse();
    }

    try {
      (this.options['on' + event] || Prototype.emptyFunction)(transport, json);
      Ajax.Responders.dispatch('on' + event, this, transport, json);
    } catch (e) {
      this.dispatchException(e);
    }

    /* Avoid memory leak in MSIE: clean up the oncomplete event handler */
    if (event == 'Complete')
      this.transport.onreadystatechange = Prototype.emptyFunction;
  },

  dispatchException: function(exception) {
    (this.options.onException || Prototype.emptyFunction)(this, exception);
    Ajax.Responders.dispatch('onException', this, exception);
  }
});

Ajax.Updater = Class.create();

Object.extend(Object.extend(Ajax.Updater.prototype, Ajax.Request.prototype), {
  initialize: function(container, url, options) {
    this.containers = {
      success: container.success ? $(container.success) : $(container),
      failure: container.failure ? $(container.failure) :
        (container.success ? null : $(container))
    }

    this.transport = Ajax.getTransport();
    this.setOptions(options);

    var onComplete = this.options.onComplete || Prototype.emptyFunction;
    this.options.onComplete = (function(transport, object) {
      this.updateContent();
      onComplete(transport, object);
    }).bind(this);

    this.request(url);
  },

  updateContent: function() {
    var receiver = this.responseIsSuccess() ?
      this.containers.success : this.containers.failure;
    var response = this.transport.responseText;

    if (!this.options.evalScripts)
      response = response.stripScripts();

    if (receiver) {
      if (this.options.insertion) {
        new this.options.insertion(receiver, response);
      } else {
        Element.update(receiver, response);
      }
    }

    if (this.responseIsSuccess()) {
      if (this.onComplete)
        setTimeout(this.onComplete.bind(this), 10);
    }
  }
});

Ajax.PeriodicalUpdater = Class.create();
Ajax.PeriodicalUpdater.prototype = Object.extend(new Ajax.Base(), {
  initialize: function(container, url, options) {
    this.setOptions(options);
    this.onComplete = this.options.onComplete;

    this.frequency = (this.options.frequency || 2);
    this.decay = (this.options.decay || 1);

    this.updater = {};
    this.container = container;
    this.url = url;

    this.start();
  },

  start: function() {
    this.options.onComplete = this.updateComplete.bind(this);
    this.onTimerEvent();
  },

  stop: function() {
    this.updater.onComplete = undefined;
    clearTimeout(this.timer);
    (this.onComplete || Prototype.emptyFunction).apply(this, arguments);
  },

  updateComplete: function(request) {
    if (this.options.decay) {
      this.decay = (request.responseText == this.lastText ?
        this.decay * this.options.decay : 1);

      this.lastText = request.responseText;
    }
    this.timer = setTimeout(this.onTimerEvent.bind(this),
      this.decay * this.frequency * 1000);
  },

  onTimerEvent: function() {
    this.updater = new Ajax.Updater(this.container, this.url, this.options);
  }
});
function $() {
  var results = [], element;
  for (var i = 0; i < arguments.length; i++) {
    element = arguments[i];
    if (typeof element == 'string')
      element = document.getElementById(element);
    results.push(Element.extend(element));
  }
  return results.length < 2 ? results[0] : results;
}

document.getElementsByClassName = function(className, parentElement) {
  var children = ($(parentElement) || document.body).getElementsByTagName('*');
  return $A(children).inject([], function(elements, child) {
    if (child.className.match(new RegExp("(^|\\s)" + className + "(\\s|$)")))
      elements.push(Element.extend(child));
    return elements;
  });
}

/*--------------------------------------------------------------------------*/

if (!window.Element)
  var Element = new Object();

Element.extend = function(element) {
  if (!element) return;
  if (_nativeExtensions) return element;

  if (!element._extended && element.tagName && element != window) {
    var methods = Element.Methods, cache = Element.extend.cache;
    for (property in methods) {
      var value = methods[property];
      if (typeof value == 'function')
        element[property] = cache.findOrStore(value);
    }
  }

  element._extended = true;
  return element;
}

Element.extend.cache = {
  findOrStore: function(value) {
    return this[value] = this[value] || function() {
      return value.apply(null, [this].concat($A(arguments)));
    }
  }
}

Element.Methods = {
  visible: function(element) {
    return $(element).style.display != 'none';
  },

  toggle: function() {
    for (var i = 0; i < arguments.length; i++) {
      var element = $(arguments[i]);
      Element[Element.visible(element) ? 'hide' : 'show'](element);
    }
  },

  hide: function() {
    for (var i = 0; i < arguments.length; i++) {
      var element = $(arguments[i]);
      element.style.display = 'none';
    }
  },

  show: function() {
    for (var i = 0; i < arguments.length; i++) {
      var element = $(arguments[i]);
      element.style.display = '';
    }
  },

  remove: function(element) {
    element = $(element);
    if(element.parentNode)
	    element.parentNode.removeChild(element);
  },

  update: function(element, html) {
    $(element).innerHTML = html.stripScripts();
    setTimeout(function() {html.evalScripts()}, 10);
  },

  replace: function(element, html) {
    element = $(element);
    if (element.outerHTML) {
      element.outerHTML = html.stripScripts();
    } else {
      var range = element.ownerDocument.createRange();
      range.selectNodeContents(element);
      element.parentNode.replaceChild(
        range.createContextualFragment(html.stripScripts()), element);
    }
    setTimeout(function() {html.evalScripts()}, 10);
  },

  getHeight: function(element) {
    element = $(element);
    return element.offsetHeight;
  },

  classNames: function(element) {
    return new Element.ClassNames(element);
  },

  hasClassName: function(element, className) {
    if (!(element = $(element))) return;
    return Element.classNames(element).include(className);
  },

  addClassName: function(element, className) {
    if (!(element = $(element))) return;
    return Element.classNames(element).add(className);
  },

  removeClassName: function(element, className) {
    if (!(element = $(element))) return;
    return Element.classNames(element).remove(className);
  },

  // removes whitespace-only text node children
  cleanWhitespace: function(element) {
    element = $(element);
    for (var i = 0; i < element.childNodes.length; i++) {
      var node = element.childNodes[i];
      if (node.nodeType == 3 && !/\S/.test(node.nodeValue))
        Element.remove(node);
    }
  },

  empty: function(element) {
    return $(element).innerHTML.match(/^\s*$/);
  },

  childOf: function(element, ancestor) {
    element = $(element), ancestor = $(ancestor);
    while (element = element.parentNode)
      if (element == ancestor) return true;
    return false;
  },

  scrollTo: function(element) {
    element = $(element);
    var x = element.x ? element.x : element.offsetLeft,
        y = element.y ? element.y : element.offsetTop;
    window.scrollTo(x, y);
  },

  getStyle: function(element, style) {
    element = $(element);
    var value = element.style[style.camelize()];
    if (!value) {
      if (document.defaultView && document.defaultView.getComputedStyle) {
        var css = document.defaultView.getComputedStyle(element, null);
        value = css ? css.getPropertyValue(style) : null;
      } else if (element.currentStyle) {
        value = element.currentStyle[style.camelize()];
      }
    }

    if (window.opera && ['left', 'top', 'right', 'bottom'].include(style))
      if (Element.getStyle(element, 'position') == 'static') value = 'auto';

    return value == 'auto' ? null : value;
  },

  setStyle: function(element, style) {
    element = $(element);
    for (var name in style)
      element.style[name.camelize()] = style[name];
  },

  getDimensions: function(element) {
    element = $(element);
    if (Element.getStyle(element, 'display') != 'none')
      return {width: element.offsetWidth, height: element.offsetHeight};

    // All *Width and *Height properties give 0 on elements with display none,
    // so enable the element temporarily
    var els = element.style;
    var originalVisibility = els.visibility;
    var originalPosition = els.position;
    els.visibility = 'hidden';
    els.position = 'absolute';
    els.display = '';
    var originalWidth = element.clientWidth;
    var originalHeight = element.clientHeight;
    els.display = 'none';
    els.position = originalPosition;
    els.visibility = originalVisibility;
    return {width: originalWidth, height: originalHeight};
  },

  makePositioned: function(element) {
    element = $(element);
    var pos = Element.getStyle(element, 'position');
    if (pos == 'static' || !pos) {
      element._madePositioned = true;
      element.style.position = 'relative';
      // Opera returns the offset relative to the positioning context, when an
      // element is position relative but top and left have not been defined
      if (window.opera) {
        element.style.top = 0;
        element.style.left = 0;
      }
    }
  },

  undoPositioned: function(element) {
    element = $(element);
    if (element._madePositioned) {
      element._madePositioned = undefined;
      element.style.position =
        element.style.top =
        element.style.left =
        element.style.bottom =
        element.style.right = '';
    }
  },

  makeClipping: function(element) {
    element = $(element);
    if (element._overflow) return;
    element._overflow = element.style.overflow;
    if ((Element.getStyle(element, 'overflow') || 'visible') != 'hidden')
      element.style.overflow = 'hidden';
  },

  undoClipping: function(element) {
    element = $(element);
    if (element._overflow) return;
    element.style.overflow = element._overflow;
    element._overflow = undefined;
  }
}

Object.extend(Element, Element.Methods);

var _nativeExtensions = false;

if(!HTMLElement && /Konqueror|Safari|KHTML/.test(navigator.userAgent)) {
  var HTMLElement = {}
  HTMLElement.prototype = document.createElement('div').__proto__;
}

Element.addMethods = function(methods) {
  Object.extend(Element.Methods, methods || {});

  if(typeof HTMLElement != 'undefined') {
    var methods = Element.Methods, cache = Element.extend.cache;
    for (property in methods) {
      var value = methods[property];
      if (typeof value == 'function')
        HTMLElement.prototype[property] = cache.findOrStore(value);
    }
    _nativeExtensions = true;
  }
}

Element.addMethods();

var Toggle = new Object();
Toggle.display = Element.toggle;

/*--------------------------------------------------------------------------*/

Abstract.Insertion = function(adjacency) {
  this.adjacency = adjacency;
}

Abstract.Insertion.prototype = {
  initialize: function(element, content) {
    this.element = $(element);
    this.content = content.stripScripts();

    if (this.adjacency && this.element.insertAdjacentHTML) {
      try {
        this.element.insertAdjacentHTML(this.adjacency, this.content);
      } catch (e) {
        var tagName = this.element.tagName.toLowerCase();
        if (tagName == 'tbody' || tagName == 'tr') {
          this.insertContent(this.contentFromAnonymousTable());
        } else {
          throw e;
        }
      }
    } else {
      this.range = this.element.ownerDocument.createRange();
      if (this.initializeRange) this.initializeRange();
      this.insertContent([this.range.createContextualFragment(this.content)]);
    }

    setTimeout(function() {content.evalScripts()}, 10);
  },

  contentFromAnonymousTable: function() {
    var div = document.createElement('div');
    div.innerHTML = '<table><tbody>' + this.content + '</tbody></table>';
    return $A(div.childNodes[0].childNodes[0].childNodes);
  }
}

var Insertion = new Object();

Insertion.Before = Class.create();
Insertion.Before.prototype = Object.extend(new Abstract.Insertion('beforeBegin'), {
  initializeRange: function() {
    this.range.setStartBefore(this.element);
  },

  insertContent: function(fragments) {
    fragments.each((function(fragment) {
      this.element.parentNode.insertBefore(fragment, this.element);
    }).bind(this));
  }
});

Insertion.Top = Class.create();
Insertion.Top.prototype = Object.extend(new Abstract.Insertion('afterBegin'), {
  initializeRange: function() {
    this.range.selectNodeContents(this.element);
    this.range.collapse(true);
  },

  insertContent: function(fragments) {
    fragments.reverse(false).each((function(fragment) {
      this.element.insertBefore(fragment, this.element.firstChild);
    }).bind(this));
  }
});

Insertion.Bottom = Class.create();
Insertion.Bottom.prototype = Object.extend(new Abstract.Insertion('beforeEnd'), {
  initializeRange: function() {
    this.range.selectNodeContents(this.element);
    this.range.collapse(this.element);
  },

  insertContent: function(fragments) {
    fragments.each((function(fragment) {
      this.element.appendChild(fragment);
    }).bind(this));
  }
});

Insertion.After = Class.create();
Insertion.After.prototype = Object.extend(new Abstract.Insertion('afterEnd'), {
  initializeRange: function() {
    this.range.setStartAfter(this.element);
  },

  insertContent: function(fragments) {
    fragments.each((function(fragment) {
      this.element.parentNode.insertBefore(fragment,
        this.element.nextSibling);
    }).bind(this));
  }
});

/*--------------------------------------------------------------------------*/

Element.ClassNames = Class.create();
Element.ClassNames.prototype = {
  initialize: function(element) {
    this.element = $(element);
  },

  _each: function(iterator) {
    this.element.className.split(/\s+/).select(function(name) {
      return name.length > 0;
    })._each(iterator);
  },

  set: function(className) {
    this.element.className = className;
  },

  add: function(classNameToAdd) {
    if (this.include(classNameToAdd)) return;
    this.set(this.toArray().concat(classNameToAdd).join(' '));
  },

  remove: function(classNameToRemove) {
    if (!this.include(classNameToRemove)) return;
    this.set(this.select(function(className) {
      return className != classNameToRemove;
    }).join(' '));
  },

  toString: function() {
    return this.toArray().join(' ');
  }
}

Object.extend(Element.ClassNames.prototype, Enumerable);
var Selector = Class.create();
Selector.prototype = {
  initialize: function(expression) {
    this.params = {classNames: []};
    this.expression = expression.toString().strip();
    this.parseExpression();
    this.compileMatcher();
  },

  parseExpression: function() {
    function abort(message) { throw 'Parse error in selector: ' + message; }

    if (this.expression == '')  abort('empty expression');

    var params = this.params, expr = this.expression, match, modifier, clause, rest;
    while (match = expr.match(/^(.*)\[([a-z0-9_:-]+?)(?:([~\|!]?=)(?:"([^"]*)"|([^\]\s]*)))?\]$/i)) {
      params.attributes = params.attributes || [];
      params.attributes.push({name: match[2], operator: match[3], value: match[4] || match[5] || ''});
      expr = match[1];
    }

    if (expr == '*') return this.params.wildcard = true;

    while (match = expr.match(/^([^a-z0-9_-])?([a-z0-9_-]+)(.*)/i)) {
      modifier = match[1], clause = match[2], rest = match[3];
      switch (modifier) {
        case '#':       params.id = clause; break;
        case '.':       params.classNames.push(clause); break;
        case '':
        case undefined: params.tagName = clause.toUpperCase(); break;
        default:        abort(expr.inspect());
      }
      expr = rest;
    }

    if (expr.length > 0) abort(expr.inspect());
  },

  buildMatchExpression: function() {
    var params = this.params, conditions = [], clause;

    if (params.wildcard)
      conditions.push('true');
    if (clause = params.id)
      conditions.push('element.id == ' + clause.inspect());
    if (clause = params.tagName)
      conditions.push('element.tagName.toUpperCase() == ' + clause.inspect());
    if ((clause = params.classNames).length > 0)
      for (var i = 0; i < clause.length; i++)
        conditions.push('Element.hasClassName(element, ' + clause[i].inspect() + ')');
    if (clause = params.attributes) {
      clause.each(function(attribute) {
        var value = 'element.getAttribute(' + attribute.name.inspect() + ')';
        var splitValueBy = function(delimiter) {
          return value + ' && ' + value + '.split(' + delimiter.inspect() + ')';
        }

        switch (attribute.operator) {
          case '=':       conditions.push(value + ' == ' + attribute.value.inspect()); break;
          case '~=':      conditions.push(splitValueBy(' ') + '.include(' + attribute.value.inspect() + ')'); break;
          case '|=':      conditions.push(
                            splitValueBy('-') + '.first().toUpperCase() == ' + attribute.value.toUpperCase().inspect()
                          ); break;
          case '!=':      conditions.push(value + ' != ' + attribute.value.inspect()); break;
          case '':
          case undefined: conditions.push(value + ' != null'); break;
          default:        throw 'Unknown operator ' + attribute.operator + ' in selector';
        }
      });
    }

    return conditions.join(' && ');
  },

  compileMatcher: function() {
    this.match = new Function('element', 'if (!element.tagName) return false; \
      return ' + this.buildMatchExpression());
  },

  findElements: function(scope) {
    var element;

    if (element = $(this.params.id))
      if (this.match(element))
        if (!scope || Element.childOf(element, scope))
          return [element];

    scope = (scope || document).getElementsByTagName(this.params.tagName || '*');

    var results = [];
    for (var i = 0; i < scope.length; i++)
      if (this.match(element = scope[i]))
        results.push(Element.extend(element));

    return results;
  },

  toString: function() {
    return this.expression;
  }
}

function $$() {
  return $A(arguments).map(function(expression) {
    return expression.strip().split(/\s+/).inject([null], function(results, expr) {
      var selector = new Selector(expr);
      return results.map(selector.findElements.bind(selector)).flatten();
    });
  }).flatten();
}
var Field = {
  clear: function() {
    for (var i = 0; i < arguments.length; i++)
      $(arguments[i]).value = '';
  },

  focus: function(element) {
    $(element).focus();
  },

  present: function() {
    for (var i = 0; i < arguments.length; i++)
      if ($(arguments[i]).value == '') return false;
    return true;
  },

  select: function(element) {
    $(element).select();
  },

  activate: function(element) {
    element = $(element);
    element.focus();
    if (element.select)
      element.select();
  }
}

/*--------------------------------------------------------------------------*/

var Form = {
  serialize: function(form) {
    var elements = Form.getElements($(form));
    var queryComponents = new Array();

    for (var i = 0; i < elements.length; i++) {
      var queryComponent = Form.Element.serialize(elements[i]);
      if (queryComponent)
        queryComponents.push(queryComponent);
    }

    return queryComponents.join('&');
  },

  getElements: function(form) {
    form = $(form);
    var elements = new Array();

    for (var tagName in Form.Element.Serializers) {
      var tagElements = form.getElementsByTagName(tagName);
      for (var j = 0; j < tagElements.length; j++)
        elements.push(tagElements[j]);
    }
    return elements;
  },

  getInputs: function(form, typeName, name) {
    form = $(form);
    var inputs = form.getElementsByTagName('input');

    if (!typeName && !name)
      return inputs;

    var matchingInputs = new Array();
    for (var i = 0; i < inputs.length; i++) {
      var input = inputs[i];
      if ((typeName && input.type != typeName) ||
          (name && input.name != name))
        continue;
      matchingInputs.push(input);
    }

    return matchingInputs;
  },

  disable: function(form) {
    var elements = Form.getElements(form);
    for (var i = 0; i < elements.length; i++) {
      var element = elements[i];
      element.blur();
      element.disabled = 'true';
    }
  },

  enable: function(form) {
    var elements = Form.getElements(form);
    for (var i = 0; i < elements.length; i++) {
      var element = elements[i];
      element.disabled = '';
    }
  },

  findFirstElement: function(form) {
    return Form.getElements(form).find(function(element) {
      return element.type != 'hidden' && !element.disabled &&
        ['input', 'select', 'textarea'].include(element.tagName.toLowerCase());
    });
  },

  focusFirstElement: function(form) {
    Field.activate(Form.findFirstElement(form));
  },

  reset: function(form) {
    $(form).reset();
  }
}

Form.Element = {
  serialize: function(element) {
    element = $(element);
    var method = element.tagName.toLowerCase();
    var parameter = Form.Element.Serializers[method](element);

    if (parameter) {
      var key = encodeURIComponent(parameter[0]);
      if (key.length == 0) return;

      if (parameter[1].constructor != Array)
        parameter[1] = [parameter[1]];

      return parameter[1].map(function(value) {
        return key + '=' + encodeURIComponent(value);
      }).join('&');
    }
  },

  getValue: function(element) {
    element = $(element);
    var method = element.tagName.toLowerCase();
    var parameter = Form.Element.Serializers[method](element);

    if (parameter)
      return parameter[1];
  }
}

Form.Element.Serializers = {
  input: function(element) {
    switch (element.type.toLowerCase()) {
      case 'submit':
      case 'hidden':
      case 'password':
      case 'text':
        return Form.Element.Serializers.textarea(element);
      case 'checkbox':
      case 'radio':
        return Form.Element.Serializers.inputSelector(element);
    }
    return false;
  },

  inputSelector: function(element) {
    if (element.checked)
      return [element.name, element.value];
  },

  textarea: function(element) {
    return [element.name, element.value];
  },

  select: function(element) {
    return Form.Element.Serializers[element.type == 'select-one' ?
      'selectOne' : 'selectMany'](element);
  },

  selectOne: function(element) {
    var value = '', opt, index = element.selectedIndex;
    if (index >= 0) {
      opt = element.options[index];
      value = opt.value || opt.text;
    }
    return [element.name, value];
  },

  selectMany: function(element) {
    var value = [];
    for (var i = 0; i < element.length; i++) {
      var opt = element.options[i];
      if (opt.selected)
        value.push(opt.value || opt.text);
    }
    return [element.name, value];
  }
}

/*--------------------------------------------------------------------------*/

var $F = Form.Element.getValue;

/*--------------------------------------------------------------------------*/

Abstract.TimedObserver = function() {}
Abstract.TimedObserver.prototype = {
  initialize: function(element, frequency, callback) {
    this.frequency = frequency;
    this.element   = $(element);
    this.callback  = callback;

    this.lastValue = this.getValue();
    this.registerCallback();
  },

  registerCallback: function() {
    setInterval(this.onTimerEvent.bind(this), this.frequency * 1000);
  },

  onTimerEvent: function() {
    var value = this.getValue();
    if (this.lastValue != value) {
      this.callback(this.element, value);
      this.lastValue = value;
    }
  }
}

Form.Element.Observer = Class.create();
Form.Element.Observer.prototype = Object.extend(new Abstract.TimedObserver(), {
  getValue: function() {
    return Form.Element.getValue(this.element);
  }
});

Form.Observer = Class.create();
Form.Observer.prototype = Object.extend(new Abstract.TimedObserver(), {
  getValue: function() {
    return Form.serialize(this.element);
  }
});

/*--------------------------------------------------------------------------*/

Abstract.EventObserver = function() {}
Abstract.EventObserver.prototype = {
  initialize: function(element, callback) {
    this.element  = $(element);
    this.callback = callback;

    this.lastValue = this.getValue();
    if (this.element.tagName.toLowerCase() == 'form')
      this.registerFormCallbacks();
    else
      this.registerCallback(this.element);
  },

  onElementEvent: function() {
    var value = this.getValue();
    if (this.lastValue != value) {
      this.callback(this.element, value);
      this.lastValue = value;
    }
  },

  registerFormCallbacks: function() {
    var elements = Form.getElements(this.element);
    for (var i = 0; i < elements.length; i++)
      this.registerCallback(elements[i]);
  },

  registerCallback: function(element) {
    if (element.type) {
      switch (element.type.toLowerCase()) {
        case 'checkbox':
        case 'radio':
          Event.observe(element, 'click', this.onElementEvent.bind(this));
          break;
        case 'password':
        case 'text':
        case 'textarea':
        case 'select-one':
        case 'select-multiple':
          Event.observe(element, 'change', this.onElementEvent.bind(this));
          break;
      }
    }
  }
}

Form.Element.EventObserver = Class.create();
Form.Element.EventObserver.prototype = Object.extend(new Abstract.EventObserver(), {
  getValue: function() {
    return Form.Element.getValue(this.element);
  }
});

Form.EventObserver = Class.create();
Form.EventObserver.prototype = Object.extend(new Abstract.EventObserver(), {
  getValue: function() {
    return Form.serialize(this.element);
  }
});
if (!window.Event) {
  var Event = new Object();
}

Object.extend(Event, {
  KEY_BACKSPACE: 8,
  KEY_TAB:       9,
  KEY_RETURN:   13,
  KEY_ESC:      27,
  KEY_LEFT:     37,
  KEY_UP:       38,
  KEY_RIGHT:    39,
  KEY_DOWN:     40,
  KEY_DELETE:   46,

  element: function(event) {
    return event.target || event.srcElement;
  },

  isLeftClick: function(event) {
    return (((event.which) && (event.which == 1)) ||
            ((event.button) && (event.button == 1)));
  },

  pointerX: function(event) {
    return event.pageX || (event.clientX +
      (document.documentElement.scrollLeft || document.body.scrollLeft));
  },

  pointerY: function(event) {
    return event.pageY || (event.clientY +
      (document.documentElement.scrollTop || document.body.scrollTop));
  },

  stop: function(event) {
    if (event.preventDefault) {
      event.preventDefault();
      event.stopPropagation();
    } else {
      event.returnValue = false;
      event.cancelBubble = true;
    }
  },

  // find the first node with the given tagName, starting from the
  // node the event was triggered on; traverses the DOM upwards
  findElement: function(event, tagName) {
    var element = Event.element(event);
    while (element.parentNode && (!element.tagName ||
        (element.tagName.toUpperCase() != tagName.toUpperCase())))
      element = element.parentNode;
    return element;
  },

  observers: false,

  _observeAndCache: function(element, name, observer, useCapture) {
    if (!this.observers) this.observers = [];
    if (element.addEventListener) {
      this.observers.push([element, name, observer, useCapture]);
      element.addEventListener(name, observer, useCapture);
    } else if (element.attachEvent) {
      this.observers.push([element, name, observer, useCapture]);
      element.attachEvent('on' + name, observer);
    }
  },

  unloadCache: function() {
    if (!Event.observers) return;
    for (var i = 0; i < Event.observers.length; i++) {
      Event.stopObserving.apply(this, Event.observers[i]);
      Event.observers[i][0] = null;
    }
    Event.observers = false;
  },

  observe: function(element, name, observer, useCapture) {
    var element = $(element);
    useCapture = useCapture || false;

    if (name == 'keypress' &&
        (navigator.appVersion.match(/Konqueror|Safari|KHTML/)
        || element.attachEvent))
      name = 'keydown';

    this._observeAndCache(element, name, observer, useCapture);
  },

  stopObserving: function(element, name, observer, useCapture) {
    var element = $(element);
    useCapture = useCapture || false;

    if (name == 'keypress' &&
        (navigator.appVersion.match(/Konqueror|Safari|KHTML/)
        || element.detachEvent))
      name = 'keydown';

    if (element.removeEventListener) {
      element.removeEventListener(name, observer, useCapture);
    } else if (element.detachEvent) {
      element.detachEvent('on' + name, observer);
    }
  }
});

/* prevent memory leaks in IE */
if (navigator.appVersion.match(/\bMSIE\b/))
  Event.observe(window, 'unload', Event.unloadCache, false);
var Position = {
  // set to true if needed, warning: firefox performance problems
  // NOT neeeded for page scrolling, only if draggable contained in
  // scrollable elements
  includeScrollOffsets: false,

  // must be called before calling withinIncludingScrolloffset, every time the
  // page is scrolled
  prepare: function() {
    this.deltaX =  window.pageXOffset
                || document.documentElement.scrollLeft
                || document.body.scrollLeft
                || 0;
    this.deltaY =  window.pageYOffset
                || document.documentElement.scrollTop
                || document.body.scrollTop
                || 0;
  },

  realOffset: function(element) {
    var valueT = 0, valueL = 0;
    do {
      valueT += element.scrollTop  || 0;
      valueL += element.scrollLeft || 0;
      element = element.parentNode;
    } while (element);
    return [valueL, valueT];
  },

  cumulativeOffset: function(element) {
    var valueT = 0, valueL = 0;
    do {
      valueT += element.offsetTop  || 0;
      valueL += element.offsetLeft || 0;
      element = element.offsetParent;
    } while (element);
    return [valueL, valueT];
  },

  positionedOffset: function(element) {
    var valueT = 0, valueL = 0;
    do {
      valueT += element.offsetTop  || 0;
      valueL += element.offsetLeft || 0;
      element = element.offsetParent;
      if (element) {
        p = Element.getStyle(element, 'position');
        if (p == 'relative' || p == 'absolute') break;
      }
    } while (element);
    return [valueL, valueT];
  },

  offsetParent: function(element) {
    if (element.offsetParent) return element.offsetParent;
    if (element == document.body) return element;

    while ((element = element.parentNode) && element != document.body)
      if (Element.getStyle(element, 'position') != 'static')
        return element;

    return document.body;
  },

  // caches x/y coordinate pair to use with overlap
  within: function(element, x, y) {
    if (this.includeScrollOffsets)
      return this.withinIncludingScrolloffsets(element, x, y);
    this.xcomp = x;
    this.ycomp = y;
    this.offset = this.cumulativeOffset(element);

    return (y >= this.offset[1] &&
            y <  this.offset[1] + element.offsetHeight &&
            x >= this.offset[0] &&
            x <  this.offset[0] + element.offsetWidth);
  },

  withinIncludingScrolloffsets: function(element, x, y) {
    var offsetcache = this.realOffset(element);

    this.xcomp = x + offsetcache[0] - this.deltaX;
    this.ycomp = y + offsetcache[1] - this.deltaY;
    this.offset = this.cumulativeOffset(element);

    return (this.ycomp >= this.offset[1] &&
            this.ycomp <  this.offset[1] + element.offsetHeight &&
            this.xcomp >= this.offset[0] &&
            this.xcomp <  this.offset[0] + element.offsetWidth);
  },

  // within must be called directly before
  overlap: function(mode, element) {
    if (!mode) return 0;
    if (mode == 'vertical')
      return ((this.offset[1] + element.offsetHeight) - this.ycomp) /
        element.offsetHeight;
    if (mode == 'horizontal')
      return ((this.offset[0] + element.offsetWidth) - this.xcomp) /
        element.offsetWidth;
  },

  clone: function(source, target) {
    source = $(source);
    target = $(target);
    target.style.position = 'absolute';
    var offsets = this.cumulativeOffset(source);
    target.style.top    = offsets[1] + 'px';
    target.style.left   = offsets[0] + 'px';
    target.style.width  = source.offsetWidth + 'px';
    target.style.height = source.offsetHeight + 'px';
  },

  page: function(forElement) {
    var valueT = 0, valueL = 0;

    var element = forElement;
    do {
      valueT += element.offsetTop  || 0;
      valueL += element.offsetLeft || 0;

      // Safari fix
      if (element.offsetParent==document.body)
        if (Element.getStyle(element,'position')=='absolute') break;

    } while (element = element.offsetParent);

    element = forElement;
    do {
      valueT -= element.scrollTop  || 0;
      valueL -= element.scrollLeft || 0;
    } while (element = element.parentNode);

    return [valueL, valueT];
  },

  clone: function(source, target) {
    var options = Object.extend({
      setLeft:    true,
      setTop:     true,
      setWidth:   true,
      setHeight:  true,
      offsetTop:  0,
      offsetLeft: 0
    }, arguments[2] || {})

    // find page position of source
    source = $(source);
    var p = Position.page(source);

    // find coordinate system to use
    target = $(target);
    var delta = [0, 0];
    var parent = null;
    // delta [0,0] will do fine with position: fixed elements,
    // position:absolute needs offsetParent deltas
    if (Element.getStyle(target,'position') == 'absolute') {
      parent = Position.offsetParent(target);
      delta = Position.page(parent);
    }

    // correct by body offsets (fixes Safari)
    if (parent == document.body) {
      delta[0] -= document.body.offsetLeft;
      delta[1] -= document.body.offsetTop;
    }

    // set position
    if(options.setLeft)   target.style.left  = (p[0] - delta[0] + options.offsetLeft) + 'px';
    if(options.setTop)    target.style.top   = (p[1] - delta[1] + options.offsetTop) + 'px';
    if(options.setWidth)  target.style.width = source.offsetWidth + 'px';
    if(options.setHeight) target.style.height = source.offsetHeight + 'px';
  },

  absolutize: function(element) {
    element = $(element);
    if (element.style.position == 'absolute') return;
    Position.prepare();

    var offsets = Position.positionedOffset(element);
    var top     = offsets[1];
    var left    = offsets[0];
    var width   = element.clientWidth;
    var height  = element.clientHeight;

    element._originalLeft   = left - parseFloat(element.style.left  || 0);
    element._originalTop    = top  - parseFloat(element.style.top || 0);
    element._originalWidth  = element.style.width;
    element._originalHeight = element.style.height;

    element.style.position = 'absolute';
    element.style.top    = top + 'px';;
    element.style.left   = left + 'px';;
    element.style.width  = width + 'px';;
    element.style.height = height + 'px';;
  },

  relativize: function(element) {
    element = $(element);
    if (element.style.position == 'relative') return;
    Position.prepare();

    element.style.position = 'relative';
    var top  = parseFloat(element.style.top  || 0) - (element._originalTop || 0);
    var left = parseFloat(element.style.left || 0) - (element._originalLeft || 0);

    element.style.top    = top + 'px';
    element.style.left   = left + 'px';
    element.style.height = element._originalHeight;
    element.style.width  = element._originalWidth;
  }
}

// Safari returns margins on body which is incorrect if the child is absolutely
// positioned.  For performance reasons, redefine Position.cumulativeOffset for
// KHTML/WebKit only.
if (/Konqueror|Safari|KHTML/.test(navigator.userAgent)) {
  Position.cumulativeOffset = function(element) {
    var valueT = 0, valueL = 0;
    do {
      valueT += element.offsetTop  || 0;
      valueL += element.offsetLeft || 0;
      if (element.offsetParent == document.body)
        if (Element.getStyle(element, 'position') == 'absolute') break;

      element = element.offsetParent;
    } while (element);

    return [valueL, valueT];
  }
}
// Copyright (c) 2005 Thomas Fuchs (http://script.aculo.us, http://mir.aculo.us)
// Contributors:
//  Justin Palmer (http://encytemedia.com/)
//  Mark Pilgrim (http://diveintomark.org/)
//  Martin Bialasinki
// 
// See scriptaculous.js for full license.  

/* ------------- element ext -------------- */  
 
// converts rgb() and #xxx to #xxxxxx format,  
// returns self (or first argument) if not convertable  
String.prototype.parseColor = function() {  
  var color = '#';  
  if(this.slice(0,4) == 'rgb(') {  
    var cols = this.slice(4,this.length-1).split(',');  
    var i=0; do { color += parseInt(cols[i]).toColorPart() } while (++i<3);  
  } else {  
    if(this.slice(0,1) == '#') {  
      if(this.length==4) for(var i=1;i<4;i++) color += (this.charAt(i) + this.charAt(i)).toLowerCase();  
      if(this.length==7) color = this.toLowerCase();  
    }  
  }  
  return(color.length==7 ? color : (arguments[0] || this));  
}  

Element.collectTextNodesIgnoreClass = function(element, ignoreclass) {  
  var children = $(element).childNodes;  
  var text     = '';  
  var classtest = new RegExp('^([^ ]+ )*' + ignoreclass+ '( [^ ]+)*$','i');  
 
  for (var i = 0; i < children.length; i++) {  
    if(children[i].nodeType==3) {  
      text+=children[i].nodeValue;  
    } else {  
      if((!children[i].className.match(classtest)) && children[i].hasChildNodes())  
        text += Element.collectTextNodesIgnoreClass(children[i], ignoreclass);  
    }  
  }  
 
  return text;
}

Element.setStyle = function(element, style) {
   element = $(element);
  for(k in style) element.style[k.camelize()] = style[k];
}

Element.setContentZoom = function(element, percent) {  
  Element.setStyle(element, {fontSize: (percent/100) + 'em'});   
  if(navigator.appVersion.indexOf('AppleWebKit')>0) window.scrollBy(0,0);  
}

Element.getOpacity = function(element){  
  var opacity;
  if (opacity = Element.getStyle(element, 'opacity'))  
    return parseFloat(opacity);  
  if (opacity = (Element.getStyle(element, 'filter') || '').match(/alpha\(opacity=(.*)\)/))  
    if(opacity[1]) return parseFloat(opacity[1]) / 100;  
  return 1.0;  
}

Element.setOpacity = function(element, value){  
  element= $(element);  
  if (value == 1){
    Element.setStyle(element, { opacity: 
      (/Gecko/.test(navigator.userAgent) && !/Konqueror|Safari|KHTML/.test(navigator.userAgent)) ? 
      0.999999 : null });
    if(/MSIE/.test(navigator.userAgent))  
      Element.setStyle(element, {filter: Element.getStyle(element,'filter').replace(/alpha\([^\)]*\)/gi,'')});  
  } else {  
    if(value < 0.00001) value = 0;  
    Element.setStyle(element, {opacity: value});
    if(/MSIE/.test(navigator.userAgent))  
     Element.setStyle(element, 
       { filter: Element.getStyle(element,'filter').replace(/alpha\([^\)]*\)/gi,'') +
                 'alpha(opacity='+value*100+')' });  
  }   
}  
 
Element.getInlineOpacity = function(element){  
  return $(element).style.opacity || '';
}  

Element.childrenWithClassName = function(element, className) {  
  return $A($(element).getElementsByTagName('*')).select(
    function(c) { return Element.hasClassName(c, className) });
}

Array.prototype.call = function() {
  var args = arguments;
  this.each(function(f){ f.apply(this, args) });
}

/*--------------------------------------------------------------------------*/

var Effect = {
  tagifyText: function(element) {
    var tagifyStyle = 'position:relative';
    if(/MSIE/.test(navigator.userAgent)) tagifyStyle += ';zoom:1';
    element = $(element);
    $A(element.childNodes).each( function(child) {
      if(child.nodeType==3) {
        child.nodeValue.toArray().each( function(character) {
          element.insertBefore(
            Builder.node('span',{style: tagifyStyle},
              character == ' ' ? String.fromCharCode(160) : character), 
              child);
        });
        Element.remove(child);
      }
    });
  },
  multiple: function(element, effect) {
    var elements;
    if(((typeof element == 'object') || 
        (typeof element == 'function')) && 
       (element.length))
      elements = element;
    else
      elements = $(element).childNodes;
      
    var options = Object.extend({
      speed: 0.1,
      delay: 0.0
    }, arguments[2] || {});
    var masterDelay = options.delay;

    $A(elements).each( function(element, index) {
      new effect(element, Object.extend(options, { delay: index * options.speed + masterDelay }));
    });
  },
  PAIRS: {
    'slide':  ['SlideDown','SlideUp'],
    'blind':  ['BlindDown','BlindUp'],
    'appear': ['Appear','Fade']
  },
  toggle: function(element, effect) {
    element = $(element);
    effect = (effect || 'appear').toLowerCase();
    var options = Object.extend({
      queue: { position:'end', scope:(element.id || 'global') }
    }, arguments[2] || {});
    Effect[Element.visible(element) ? 
      Effect.PAIRS[effect][1] : Effect.PAIRS[effect][0]](element, options);
  }
};

var Effect2 = Effect; // deprecated

/* ------------- transitions ------------- */

Effect.Transitions = {}

Effect.Transitions.linear = function(pos) {
  return pos;
}
Effect.Transitions.cosinoidal = function(pos) {
  return (-Math.cos(pos*Math.PI)/2) + 0.5;
}
Effect.Transitions.sinoidal = function(pos) {
  return (-Math.sin(pos*Math.PI)/2) + 0.5;
}
Effect.Transitions.reverse  = function(pos) {
  return 1-pos;
}
Effect.Transitions.flicker = function(pos) {
  return ((-Math.cos(pos*Math.PI)/2) + 0.75) + Math.random()/4;
}
Effect.Transitions.wobble = function(pos) {
  return (-Math.cos(pos*Math.PI*(9*pos))/2) + 0.5;
}
Effect.Transitions.pulse = function(pos) {
  return (Math.floor(pos*10) % 2 == 0 ? 
    (pos*10-Math.floor(pos*10)) : 1-(pos*10-Math.floor(pos*10)));
}
Effect.Transitions.none = function(pos) {
  return 0;
}
Effect.Transitions.full = function(pos) {
  return 1;
}

/* ------------- core effects ------------- */

Effect.ScopedQueue = Class.create();
Object.extend(Object.extend(Effect.ScopedQueue.prototype, Enumerable), {
  initialize: function() {
    this.effects  = [];
    this.interval = null;
  },
  _each: function(iterator) {
    this.effects._each(iterator);
  },
  add: function(effect) {
    var timestamp = new Date().getTime();
    
    var position = (typeof effect.options.queue == 'string') ? 
      effect.options.queue : effect.options.queue.position;
    
    switch(position) {
      case 'front':
        // move unstarted effects after this effect  
        this.effects.findAll(function(e){ return e.state=='idle' }).each( function(e) {
            e.startOn  += effect.finishOn;
            e.finishOn += effect.finishOn;
          });
        break;
      case 'end':
        // start effect after last queued effect has finished
        timestamp = this.effects.pluck('finishOn').max() || timestamp;
        break;
    }
    
    effect.startOn  += timestamp;
    effect.finishOn += timestamp;
    this.effects.push(effect);
    if(!this.interval) 
      this.interval = setInterval(this.loop.bind(this), 40);
  },
  remove: function(effect) {
    this.effects = this.effects.reject(function(e) { return e==effect });
    if(this.effects.length == 0) {
      clearInterval(this.interval);
      this.interval = null;
    }
  },
  loop: function() {
    var timePos = new Date().getTime();
    this.effects.invoke('loop', timePos);
  }
});

Effect.Queues = {
  instances: $H(),
  get: function(queueName) {
    if(typeof queueName != 'string') return queueName;
    
    if(!this.instances[queueName])
      this.instances[queueName] = new Effect.ScopedQueue();
      
    return this.instances[queueName];
  }
}
Effect.Queue = Effect.Queues.get('global');

Effect.DefaultOptions = {
  transition: Effect.Transitions.cosinoidal,
  duration:   1.0,   // seconds
  fps:        25.0,  // max. 25fps due to Effect.Queue implementation
  sync:       false, // true for combining
  from:       0.0,
  to:         1.0,
  delay:      0.0,
  queue:      'parallel'
}

Effect.Base = function() {};
Effect.Base.prototype = {
  position: null,
  start: function(options) {
    this.options      = Object.extend(Object.extend({},Effect.DefaultOptions), options || {});
    this.currentFrame = 0;
    this.state        = 'idle';
    this.startOn      = this.options.delay*1000;
    this.finishOn     = this.startOn + (this.options.duration*1000);
    this.event('beforeStart');
    if(!this.options.sync)
      Effect.Queues.get(typeof this.options.queue == 'string' ? 
        'global' : this.options.queue.scope).add(this);
  },
  loop: function(timePos) {
    if(timePos >= this.startOn) {
      if(timePos >= this.finishOn) {
        this.render(1.0);
        this.cancel();
        this.event('beforeFinish');
        if(this.finish) this.finish(); 
        this.event('afterFinish');
        return;  
      }
      var pos   = (timePos - this.startOn) / (this.finishOn - this.startOn);
      var frame = Math.round(pos * this.options.fps * this.options.duration);
      if(frame > this.currentFrame) {
        this.render(pos);
        this.currentFrame = frame;
      }
    }
  },
  render: function(pos) {
    if(this.state == 'idle') {
      this.state = 'running';
      this.event('beforeSetup');
      if(this.setup) this.setup();
      this.event('afterSetup');
    }
    if(this.state == 'running') {
      if(this.options.transition) pos = this.options.transition(pos);
      pos *= (this.options.to-this.options.from);
      pos += this.options.from;
      this.position = pos;
      this.event('beforeUpdate');
      if(this.update) this.update(pos);
      this.event('afterUpdate');
    }
  },
  cancel: function() {
    if(!this.options.sync)
      Effect.Queues.get(typeof this.options.queue == 'string' ? 
        'global' : this.options.queue.scope).remove(this);
    this.state = 'finished';
  },
  event: function(eventName) {
    if(this.options[eventName + 'Internal']) this.options[eventName + 'Internal'](this);
    if(this.options[eventName]) this.options[eventName](this);
  },
  inspect: function() {
    return '#<Effect:' + $H(this).inspect() + ',options:' + $H(this.options).inspect() + '>';
  }
}

Effect.Parallel = Class.create();
Object.extend(Object.extend(Effect.Parallel.prototype, Effect.Base.prototype), {
  initialize: function(effects) {
    this.effects = effects || [];
    this.start(arguments[1]);
  },
  update: function(position) {
    this.effects.invoke('render', position);
  },
  finish: function(position) {
    this.effects.each( function(effect) {
      effect.render(1.0);
      effect.cancel();
      effect.event('beforeFinish');
      if(effect.finish) effect.finish(position);
      effect.event('afterFinish');
    });
  }
});

Effect.Opacity = Class.create();
Object.extend(Object.extend(Effect.Opacity.prototype, Effect.Base.prototype), {
  initialize: function(element) {
    this.element = $(element);
    // make this work on IE on elements without 'layout'
    if(/MSIE/.test(navigator.userAgent) && (!this.element.hasLayout))
      Element.setStyle(this.element, {zoom: 1});
    var options = Object.extend({
      from: Element.getOpacity(this.element) || 0.0,
      to:   1.0
    }, arguments[1] || {});
    this.start(options);
  },
  update: function(position) {
    Element.setOpacity(this.element, position);
  }
});

Effect.Move = Class.create();
Object.extend(Object.extend(Effect.Move.prototype, Effect.Base.prototype), {
  initialize: function(element) {
    this.element = $(element);
    var options = Object.extend({
      x:    0,
      y:    0,
      mode: 'relative'
    }, arguments[1] || {});
    this.start(options);
  },
  setup: function() {
    // Bug in Opera: Opera returns the "real" position of a static element or
    // relative element that does not have top/left explicitly set.
    // ==> Always set top and left for position relative elements in your stylesheets 
    // (to 0 if you do not need them) 
    Element.makePositioned(this.element);
    this.originalLeft = parseFloat(Element.getStyle(this.element,'left') || '0');
    this.originalTop  = parseFloat(Element.getStyle(this.element,'top')  || '0');
    if(this.options.mode == 'absolute') {
      // absolute movement, so we need to calc deltaX and deltaY
      this.options.x = this.options.x - this.originalLeft;
      this.options.y = this.options.y - this.originalTop;
    }
  },
  update: function(position) {
    Element.setStyle(this.element, {
      left: this.options.x  * position + this.originalLeft + 'px',
      top:  this.options.y  * position + this.originalTop  + 'px'
    });
  }
});

// for backwards compatibility
Effect.MoveBy = function(element, toTop, toLeft) {
  return new Effect.Move(element, 
    Object.extend({ x: toLeft, y: toTop }, arguments[3] || {}));
};

Effect.Scale = Class.create();
Object.extend(Object.extend(Effect.Scale.prototype, Effect.Base.prototype), {
  initialize: function(element, percent) {
    this.element = $(element)
    var options = Object.extend({
      scaleX: true,
      scaleY: true,
      scaleContent: true,
      scaleFromCenter: false,
      scaleMode: 'box',        // 'box' or 'contents' or {} with provided values
      scaleFrom: 100.0,
      scaleTo:   percent
    }, arguments[2] || {});
    this.start(options);
  },
  setup: function() {
    this.restoreAfterFinish = this.options.restoreAfterFinish || false;
    this.elementPositioning = Element.getStyle(this.element,'position');
    
    this.originalStyle = {};
    ['top','left','width','height','fontSize'].each( function(k) {
      this.originalStyle[k] = this.element.style[k];
    }.bind(this));
      
    this.originalTop  = this.element.offsetTop;
    this.originalLeft = this.element.offsetLeft;
    
    var fontSize = Element.getStyle(this.element,'font-size') || '100%';
    ['em','px','%'].each( function(fontSizeType) {
      if(fontSize.indexOf(fontSizeType)>0) {
        this.fontSize     = parseFloat(fontSize);
        this.fontSizeType = fontSizeType;
      }
    }.bind(this));
    
    this.factor = (this.options.scaleTo - this.options.scaleFrom)/100;
    
    this.dims = null;
    if(this.options.scaleMode=='box')
      this.dims = [this.element.offsetHeight, this.element.offsetWidth];
    if(/^content/.test(this.options.scaleMode))
      this.dims = [this.element.scrollHeight, this.element.scrollWidth];
    if(!this.dims)
      this.dims = [this.options.scaleMode.originalHeight,
                   this.options.scaleMode.originalWidth];
  },
  update: function(position) {
    var currentScale = (this.options.scaleFrom/100.0) + (this.factor * position);
    if(this.options.scaleContent && this.fontSize)
      Element.setStyle(this.element, {fontSize: this.fontSize * currentScale + this.fontSizeType });
    this.setDimensions(this.dims[0] * currentScale, this.dims[1] * currentScale);
  },
  finish: function(position) {
    if (this.restoreAfterFinish) Element.setStyle(this.element, this.originalStyle);
  },
  setDimensions: function(height, width) {
    var d = {};
    if(this.options.scaleX) d.width = width + 'px';
    if(this.options.scaleY) d.height = height + 'px';
    if(this.options.scaleFromCenter) {
      var topd  = (height - this.dims[0])/2;
      var leftd = (width  - this.dims[1])/2;
      if(this.elementPositioning == 'absolute') {
        if(this.options.scaleY) d.top = this.originalTop-topd + 'px';
        if(this.options.scaleX) d.left = this.originalLeft-leftd + 'px';
      } else {
        if(this.options.scaleY) d.top = -topd + 'px';
        if(this.options.scaleX) d.left = -leftd + 'px';
      }
    }
    Element.setStyle(this.element, d);
  }
});

Effect.Highlight = Class.create();
Object.extend(Object.extend(Effect.Highlight.prototype, Effect.Base.prototype), {
  initialize: function(element) {
    this.element = $(element);
    var options = Object.extend({ startcolor: '#ffff99' }, arguments[1] || {});
    this.start(options);
  },
  setup: function() {
    // Prevent executing on elements not in the layout flow
    if(Element.getStyle(this.element, 'display')=='none') { this.cancel(); return; }
    // Disable background image during the effect
    this.oldStyle = {
      backgroundImage: Element.getStyle(this.element, 'background-image') };
    Element.setStyle(this.element, {backgroundImage: 'none'});
    if(!this.options.endcolor)
      this.options.endcolor = Element.getStyle(this.element, 'background-color').parseColor('#ffffff');
    if(!this.options.restorecolor)
      this.options.restorecolor = Element.getStyle(this.element, 'background-color');
    // init color calculations
    this._base  = $R(0,2).map(function(i){ return parseInt(this.options.startcolor.slice(i*2+1,i*2+3),16) }.bind(this));
    this._delta = $R(0,2).map(function(i){ return parseInt(this.options.endcolor.slice(i*2+1,i*2+3),16)-this._base[i] }.bind(this));
  },
  update: function(position) {
    Element.setStyle(this.element,{backgroundColor: $R(0,2).inject('#',function(m,v,i){
      return m+(Math.round(this._base[i]+(this._delta[i]*position)).toColorPart()); }.bind(this)) });
  },
  finish: function() {
    Element.setStyle(this.element, Object.extend(this.oldStyle, {
      backgroundColor: this.options.restorecolor
    }));
  }
});

Effect.ScrollTo = Class.create();
Object.extend(Object.extend(Effect.ScrollTo.prototype, Effect.Base.prototype), {
  initialize: function(element) {
    this.element = $(element);
    this.start(arguments[1] || {});
  },
  setup: function() {
    Position.prepare();
    var offsets = Position.cumulativeOffset(this.element);
    if(this.options.offset) offsets[1] += this.options.offset;
    var max = window.innerHeight ? 
      window.height - window.innerHeight :
      document.body.scrollHeight - 
        (document.documentElement.clientHeight ? 
          document.documentElement.clientHeight : document.body.clientHeight);
    this.scrollStart = Position.deltaY;
    this.delta = (offsets[1] > max ? max : offsets[1]) - this.scrollStart;
  },
  update: function(position) {
    Position.prepare();
    window.scrollTo(Position.deltaX, 
      this.scrollStart + (position*this.delta));
  }
});

/* ------------- combination effects ------------- */

Effect.Fade = function(element) {
  var oldOpacity = Element.getInlineOpacity(element);
  var options = Object.extend({
  from: Element.getOpacity(element) || 1.0,
  to:   0.0,
  afterFinishInternal: function(effect) { with(Element) { 
    if(effect.options.to!=0) return;
    hide(effect.element);
    setStyle(effect.element, {opacity: oldOpacity}); }}
  }, arguments[1] || {});
  return new Effect.Opacity(element,options);
}

Effect.Appear = function(element) {
  var options = Object.extend({
  from: (Element.getStyle(element, 'display') == 'none' ? 0.0 : Element.getOpacity(element) || 0.0),
  to:   1.0,
  beforeSetup: function(effect) { with(Element) {
    setOpacity(effect.element, effect.options.from);
    show(effect.element); }}
  }, arguments[1] || {});
  return new Effect.Opacity(element,options);
}

Effect.Puff = function(element) {
  element = $(element);
  var oldStyle = { opacity: Element.getInlineOpacity(element), position: Element.getStyle(element, 'position') };
  return new Effect.Parallel(
   [ new Effect.Scale(element, 200, 
      { sync: true, scaleFromCenter: true, scaleContent: true, restoreAfterFinish: true }), 
     new Effect.Opacity(element, { sync: true, to: 0.0 } ) ], 
     Object.extend({ duration: 1.0, 
      beforeSetupInternal: function(effect) { with(Element) {
        setStyle(effect.effects[0].element, {position: 'absolute'}); }},
      afterFinishInternal: function(effect) { with(Element) {
         hide(effect.effects[0].element);
         setStyle(effect.effects[0].element, oldStyle); }}
     }, arguments[1] || {})
   );
}

Effect.BlindUp = function(element) {
  element = $(element);
  Element.makeClipping(element);
  return new Effect.Scale(element, 0, 
    Object.extend({ scaleContent: false, 
      scaleX: false, 
      restoreAfterFinish: true,
      afterFinishInternal: function(effect) { with(Element) {
        [hide, undoClipping].call(effect.element); }} 
    }, arguments[1] || {})
  );
}

Effect.BlindDown = function(element) {
  element = $(element);
  var oldHeight = Element.getStyle(element, 'height');
  var elementDimensions = Element.getDimensions(element);
  return new Effect.Scale(element, 100, 
    Object.extend({ scaleContent: false, 
      scaleX: false,
      scaleFrom: 0,
      scaleMode: {originalHeight: elementDimensions.height, originalWidth: elementDimensions.width},
      restoreAfterFinish: true,
      afterSetup: function(effect) { with(Element) {
        makeClipping(effect.element);
        setStyle(effect.element, {height: '0px'});
        show(effect.element); 
      }},  
      afterFinishInternal: function(effect) { with(Element) {
        undoClipping(effect.element);
        setStyle(effect.element, {height: oldHeight});
      }}
    }, arguments[1] || {})
  );
}

Effect.SwitchOff = function(element) {
  element = $(element);
  var oldOpacity = Element.getInlineOpacity(element);
  return new Effect.Appear(element, { 
    duration: 0.4,
    from: 0,
    transition: Effect.Transitions.flicker,
    afterFinishInternal: function(effect) {
      new Effect.Scale(effect.element, 1, { 
        duration: 0.3, scaleFromCenter: true,
        scaleX: false, scaleContent: false, restoreAfterFinish: true,
        beforeSetup: function(effect) { with(Element) {
          [makePositioned,makeClipping].call(effect.element);
        }},
        afterFinishInternal: function(effect) { with(Element) {
          [hide,undoClipping,undoPositioned].call(effect.element);
          setStyle(effect.element, {opacity: oldOpacity});
        }}
      })
    }
  });
}

Effect.DropOut = function(element) {
  element = $(element);
  var oldStyle = {
    top: Element.getStyle(element, 'top'),
    left: Element.getStyle(element, 'left'),
    opacity: Element.getInlineOpacity(element) };
  return new Effect.Parallel(
    [ new Effect.Move(element, {x: 0, y: 100, sync: true }), 
      new Effect.Opacity(element, { sync: true, to: 0.0 }) ],
    Object.extend(
      { duration: 0.5,
        beforeSetup: function(effect) { with(Element) {
          makePositioned(effect.effects[0].element); }},
        afterFinishInternal: function(effect) { with(Element) {
          [hide, undoPositioned].call(effect.effects[0].element);
          setStyle(effect.effects[0].element, oldStyle); }} 
      }, arguments[1] || {}));
}

Effect.Shake = function(element) {
  element = $(element);
  var oldStyle = {
    top: Element.getStyle(element, 'top'),
    left: Element.getStyle(element, 'left') };
	  return new Effect.Move(element, 
	    { x:  20, y: 0, duration: 0.05, afterFinishInternal: function(effect) {
	  new Effect.Move(effect.element,
	    { x: -40, y: 0, duration: 0.1,  afterFinishInternal: function(effect) {
	  new Effect.Move(effect.element,
	    { x:  40, y: 0, duration: 0.1,  afterFinishInternal: function(effect) {
	  new Effect.Move(effect.element,
	    { x: -40, y: 0, duration: 0.1,  afterFinishInternal: function(effect) {
	  new Effect.Move(effect.element,
	    { x:  40, y: 0, duration: 0.1,  afterFinishInternal: function(effect) {
	  new Effect.Move(effect.element,
	    { x: -20, y: 0, duration: 0.05, afterFinishInternal: function(effect) { with(Element) {
        undoPositioned(effect.element);
        setStyle(effect.element, oldStyle);
  }}}) }}) }}) }}) }}) }});
}

Effect.SlideDown = function(element) {
  element = $(element);
  Element.cleanWhitespace(element);
  // SlideDown need to have the content of the element wrapped in a container element with fixed height!
  var oldInnerBottom = Element.getStyle(element.firstChild, 'bottom');
  var elementDimensions = Element.getDimensions(element);
  return new Effect.Scale(element, 100, Object.extend({ 
    scaleContent: false, 
    scaleX: false, 
    scaleFrom: 0,
    scaleMode: {originalHeight: elementDimensions.height, originalWidth: elementDimensions.width},
    restoreAfterFinish: true,
    afterSetup: function(effect) { with(Element) {
      makePositioned(effect.element);
      makePositioned(effect.element.firstChild);
      if(window.opera) setStyle(effect.element, {top: ''});
      makeClipping(effect.element);
      setStyle(effect.element, {height: '0px'});
      show(element); }},
    afterUpdateInternal: function(effect) { with(Element) {
      setStyle(effect.element.firstChild, {bottom:
        (effect.dims[0] - effect.element.clientHeight) + 'px' }); }},
    afterFinishInternal: function(effect) { with(Element) {
      undoClipping(effect.element); 
      undoPositioned(effect.element.firstChild);
      undoPositioned(effect.element);
      setStyle(effect.element.firstChild, {bottom: oldInnerBottom}); }}
    }, arguments[1] || {})
  );
}
  
Effect.SlideUp = function(element) {
  element = $(element);
  Element.cleanWhitespace(element);
  var oldInnerBottom = Element.getStyle(element.firstChild, 'bottom');
  return new Effect.Scale(element, 0, 
   Object.extend({ scaleContent: false, 
    scaleX: false, 
    scaleMode: 'box',
    scaleFrom: 100,
    restoreAfterFinish: true,
    beforeStartInternal: function(effect) { with(Element) {
      makePositioned(effect.element);
      makePositioned(effect.element.firstChild);
      if(window.opera) setStyle(effect.element, {top: ''});
      makeClipping(effect.element);
      show(element); }},  
    afterUpdateInternal: function(effect) { with(Element) {
      setStyle(effect.element.firstChild, {bottom:
        (effect.dims[0] - effect.element.clientHeight) + 'px' }); }},
    afterFinishInternal: function(effect) { with(Element) {
        [hide, undoClipping].call(effect.element); 
        undoPositioned(effect.element.firstChild);
        undoPositioned(effect.element);
        setStyle(effect.element.firstChild, {bottom: oldInnerBottom}); }}
   }, arguments[1] || {})
  );
}

// Bug in opera makes the TD containing this element expand for a instance after finish 
Effect.Squish = function(element) {
  return new Effect.Scale(element, window.opera ? 1 : 0, 
    { restoreAfterFinish: true,
      beforeSetup: function(effect) { with(Element) {
        makeClipping(effect.element); }},  
      afterFinishInternal: function(effect) { with(Element) {
        hide(effect.element); 
        undoClipping(effect.element); }}
  });
}

Effect.Grow = function(element) {
  element = $(element);
  var options = Object.extend({
    direction: 'center',
    moveTransistion: Effect.Transitions.sinoidal,
    scaleTransition: Effect.Transitions.sinoidal,
    opacityTransition: Effect.Transitions.full
  }, arguments[1] || {});
  var oldStyle = {
    top: element.style.top,
    left: element.style.left,
    height: element.style.height,
    width: element.style.width,
    opacity: Element.getInlineOpacity(element) };

  var dims = Element.getDimensions(element);    
  var initialMoveX, initialMoveY;
  var moveX, moveY;
  
  switch (options.direction) {
    case 'top-left':
      initialMoveX = initialMoveY = moveX = moveY = 0; 
      break;
    case 'top-right':
      initialMoveX = dims.width;
      initialMoveY = moveY = 0;
      moveX = -dims.width;
      break;
    case 'bottom-left':
      initialMoveX = moveX = 0;
      initialMoveY = dims.height;
      moveY = -dims.height;
      break;
    case 'bottom-right':
      initialMoveX = dims.width;
      initialMoveY = dims.height;
      moveX = -dims.width;
      moveY = -dims.height;
      break;
    case 'center':
      initialMoveX = dims.width / 2;
      initialMoveY = dims.height / 2;
      moveX = -dims.width / 2;
      moveY = -dims.height / 2;
      break;
  }
  
  return new Effect.Move(element, {
    x: initialMoveX,
    y: initialMoveY,
    duration: 0.01, 
    beforeSetup: function(effect) { with(Element) {
      hide(effect.element);
      makeClipping(effect.element);
      makePositioned(effect.element);
    }},
    afterFinishInternal: function(effect) {
      new Effect.Parallel(
        [ new Effect.Opacity(effect.element, { sync: true, to: 1.0, from: 0.0, transition: options.opacityTransition }),
          new Effect.Move(effect.element, { x: moveX, y: moveY, sync: true, transition: options.moveTransition }),
          new Effect.Scale(effect.element, 100, {
            scaleMode: { originalHeight: dims.height, originalWidth: dims.width }, 
            sync: true, scaleFrom: window.opera ? 1 : 0, transition: options.scaleTransition, restoreAfterFinish: true})
        ], Object.extend({
             beforeSetup: function(effect) { with(Element) {
               setStyle(effect.effects[0].element, {height: '0px'});
               show(effect.effects[0].element); }},
             afterFinishInternal: function(effect) { with(Element) {
               [undoClipping, undoPositioned].call(effect.effects[0].element); 
               setStyle(effect.effects[0].element, oldStyle); }}
           }, options)
      )
    }
  });
}

Effect.Shrink = function(element) {
  element = $(element);
  var options = Object.extend({
    direction: 'center',
    moveTransistion: Effect.Transitions.sinoidal,
    scaleTransition: Effect.Transitions.sinoidal,
    opacityTransition: Effect.Transitions.none
  }, arguments[1] || {});
  var oldStyle = {
    top: element.style.top,
    left: element.style.left,
    height: element.style.height,
    width: element.style.width,
    opacity: Element.getInlineOpacity(element) };

  var dims = Element.getDimensions(element);
  var moveX, moveY;
  
  switch (options.direction) {
    case 'top-left':
      moveX = moveY = 0;
      break;
    case 'top-right':
      moveX = dims.width;
      moveY = 0;
      break;
    case 'bottom-left':
      moveX = 0;
      moveY = dims.height;
      break;
    case 'bottom-right':
      moveX = dims.width;
      moveY = dims.height;
      break;
    case 'center':  
      moveX = dims.width / 2;
      moveY = dims.height / 2;
      break;
  }
  
  return new Effect.Parallel(
    [ new Effect.Opacity(element, { sync: true, to: 0.0, from: 1.0, transition: options.opacityTransition }),
      new Effect.Scale(element, window.opera ? 1 : 0, { sync: true, transition: options.scaleTransition, restoreAfterFinish: true}),
      new Effect.Move(element, { x: moveX, y: moveY, sync: true, transition: options.moveTransition })
    ], Object.extend({            
         beforeStartInternal: function(effect) { with(Element) {
           [makePositioned, makeClipping].call(effect.effects[0].element) }},
         afterFinishInternal: function(effect) { with(Element) {
           [hide, undoClipping, undoPositioned].call(effect.effects[0].element);
           setStyle(effect.effects[0].element, oldStyle); }}
       }, options)
  );
}

Effect.Pulsate = function(element) {
  element = $(element);
  var options    = arguments[1] || {};
  var oldOpacity = Element.getInlineOpacity(element);
  var transition = options.transition || Effect.Transitions.sinoidal;
  var reverser   = function(pos){ return transition(1-Effect.Transitions.pulse(pos)) };
  reverser.bind(transition);
  return new Effect.Opacity(element, 
    Object.extend(Object.extend({  duration: 3.0, from: 0,
      afterFinishInternal: function(effect) { Element.setStyle(effect.element, {opacity: oldOpacity}); }
    }, options), {transition: reverser}));
}

Effect.Fold = function(element) {
  element = $(element);
  var oldStyle = {
    top: element.style.top,
    left: element.style.left,
    width: element.style.width,
    height: element.style.height };
  Element.makeClipping(element);
  return new Effect.Scale(element, 5, Object.extend({   
    scaleContent: false,
    scaleX: false,
    afterFinishInternal: function(effect) {
    new Effect.Scale(element, 1, { 
      scaleContent: false, 
      scaleY: false,
      afterFinishInternal: function(effect) { with(Element) {
        [hide, undoClipping].call(effect.element); 
        setStyle(effect.element, oldStyle);
      }} });
  }}, arguments[1] || {}));
}
// Copyright (c) 2005 Thomas Fuchs (http://script.aculo.us, http://mir.aculo.us)
//           (c) 2005 Sammi Williams (http://www.oriontransfer.co.nz, sammi@oriontransfer.co.nz)
// 
// See scriptaculous.js for full license.

/*--------------------------------------------------------------------------*/

var Droppables = {
  drops: [],

  remove: function(element) {
    this.drops = this.drops.reject(function(d) { return d.element==$(element) });
  },

  add: function(element) {
    element = $(element);
    var options = Object.extend({
      greedy:     true,
      hoverclass: null,
      tree:       false
    }, arguments[1] || {});

    // cache containers
    if(options.containment) {
      options._containers = [];
      var containment = options.containment;
      if((typeof containment == 'object') && 
        (containment.constructor == Array)) {
        containment.each( function(c) { options._containers.push($(c)) });
      } else {
        options._containers.push($(containment));
      }
    }
    
    if(options.accept) options.accept = [options.accept].flatten();

    Element.makePositioned(element); // fix IE
    options.element = element;

    this.drops.push(options);
  },
  
  findDeepestChild: function(drops) {
    deepest = drops[0];
      
    for (i = 1; i < drops.length; ++i)
      if (Element.isParent(drops[i].element, deepest.element))
        deepest = drops[i];
    
    return deepest;
  },

  isContained: function(element, drop) {
    var containmentNode;
    if(drop.tree) {
      containmentNode = element.treeNode; 
    } else {
      containmentNode = element.parentNode;
    }
    return drop._containers.detect(function(c) { return containmentNode == c });
  },
  
  isAffected: function(point, element, drop) {
    return (
      (drop.element!=element) &&
      ((!drop._containers) ||
        this.isContained(element, drop)) &&
      ((!drop.accept) ||
        (Element.classNames(element).detect( 
          function(v) { return drop.accept.include(v) } ) )) &&
      Position.within(drop.element, point[0], point[1]) );
  },

  deactivate: function(drop) {
    if(drop.hoverclass)
      Element.removeClassName(drop.element, drop.hoverclass);
    this.last_active = null;
  },

  activate: function(drop) {
    if(drop.hoverclass)
      Element.addClassName(drop.element, drop.hoverclass);
    this.last_active = drop;
  },

  show: function(point, element) {
    if(!this.drops.length) return;
    var affected = [];
    
    if(this.last_active) this.deactivate(this.last_active);
    this.drops.each( function(drop) {
      if(Droppables.isAffected(point, element, drop))
        affected.push(drop);
    });
        
    if(affected.length>0) {
      drop = Droppables.findDeepestChild(affected);
      Position.within(drop.element, point[0], point[1]);
      if(drop.onHover)
        drop.onHover(element, drop.element, Position.overlap(drop.overlap, drop.element));
      
      Droppables.activate(drop);
    }
  },

  fire: function(event, element) {
    if(!this.last_active) return;
    Position.prepare();

    if (this.isAffected([Event.pointerX(event), Event.pointerY(event)], element, this.last_active))
      if (this.last_active.onDrop) 
        this.last_active.onDrop(element, this.last_active.element, event);
  },

  reset: function() {
    if(this.last_active)
      this.deactivate(this.last_active);
  }
}

var Draggables = {
  drags: [],
  observers: [],
  
  register: function(draggable) {
    if(this.drags.length == 0) {
      this.eventMouseUp   = this.endDrag.bindAsEventListener(this);
      this.eventMouseMove = this.updateDrag.bindAsEventListener(this);
      this.eventKeypress  = this.keyPress.bindAsEventListener(this);
      
      Event.observe(document, "mouseup", this.eventMouseUp);
      Event.observe(document, "mousemove", this.eventMouseMove);
      Event.observe(document, "keypress", this.eventKeypress);
    }
    this.drags.push(draggable);
  },
  
  unregister: function(draggable) {
    this.drags = this.drags.reject(function(d) { return d==draggable });
    if(this.drags.length == 0) {
      Event.stopObserving(document, "mouseup", this.eventMouseUp);
      Event.stopObserving(document, "mousemove", this.eventMouseMove);
      Event.stopObserving(document, "keypress", this.eventKeypress);
    }
  },
  
  activate: function(draggable) {
    window.focus(); // allows keypress events if window isn't currently focused, fails for Safari
    this.activeDraggable = draggable;
  },
  
  deactivate: function() {
    this.activeDraggable = null;
  },
  
  updateDrag: function(event) {
    if(!this.activeDraggable) return;
    var pointer = [Event.pointerX(event), Event.pointerY(event)];
    // Mozilla-based browsers fire successive mousemove events with
    // the same coordinates, prevent needless redrawing (moz bug?)
    if(this._lastPointer && (this._lastPointer.inspect() == pointer.inspect())) return;
    this._lastPointer = pointer;
    this.activeDraggable.updateDrag(event, pointer);
  },
  
  endDrag: function(event) {
    if(!this.activeDraggable) return;
    this._lastPointer = null;
    this.activeDraggable.endDrag(event);
    this.activeDraggable = null;
  },
  
  keyPress: function(event) {
    if(this.activeDraggable)
      this.activeDraggable.keyPress(event);
  },
  
  addObserver: function(observer) {
    this.observers.push(observer);
    this._cacheObserverCallbacks();
  },
  
  removeObserver: function(element) {  // element instead of observer fixes mem leaks
    this.observers = this.observers.reject( function(o) { return o.element==element });
    this._cacheObserverCallbacks();
  },
  
  notify: function(eventName, draggable, event) {  // 'onStart', 'onEnd', 'onDrag'
    if(this[eventName+'Count'] > 0)
      this.observers.each( function(o) {
        if(o[eventName]) o[eventName](eventName, draggable, event);
      });
  },
  
  _cacheObserverCallbacks: function() {
    ['onStart','onEnd','onDrag'].each( function(eventName) {
      Draggables[eventName+'Count'] = Draggables.observers.select(
        function(o) { return o[eventName]; }
      ).length;
    });
  }
}

/*--------------------------------------------------------------------------*/

var Draggable = Class.create();
Draggable.prototype = {
  initialize: function(element) {
  	this.offset = Array();
    var options = Object.extend({
      handle: false,
      starteffect: function(element) {
        element._opacity = Element.getOpacity(element); 
        new Effect.Opacity(element, {duration:0.2, from:element._opacity, to:0.7}); 
      },
      reverteffect: function(element, top_offset, left_offset) {
        var dur = Math.sqrt(Math.abs(top_offset^2)+Math.abs(left_offset^2))*0.02;
        element._revert = new Effect.Move(element, { x: -left_offset, y: -top_offset, duration: dur});
      },
      endeffect: function(element) {
        var toOpacity = typeof element._opacity == 'number' ? element._opacity : 1.0
        new Effect.Opacity(element, {duration:0.2, from:0.7, to:toOpacity}); 
      },
      zindex: 1000,
      revert: false,
      scroll: false,
      scrollSensitivity: 20,
      scrollSpeed: 15,
      snap: false   // false, or xy or [x,y] or function(x,y){ return [x,y] }
    }, arguments[1] || {});

    this.element = $(element);
    
    if(options.handle && (typeof options.handle == 'string')) {
      var h = Element.childrenWithClassName(this.element, options.handle, true);
      if(h.length>0) this.handle = h[0];
    }
    if(!this.handle) this.handle = $(options.handle);
    if(!this.handle) this.handle = this.element;
    
    if(options.scroll && !options.scroll.scrollTo && !options.scroll.outerHTML)
      options.scroll = $(options.scroll);

    Element.makePositioned(this.element); // fix IE    

    this.delta    = this.currentDelta();
    this.options  = options;
    this.dragging = false;   

    this.eventMouseDown = this.initDrag.bindAsEventListener(this);
    Event.observe(this.handle, "mousedown", this.eventMouseDown);
    
    Draggables.register(this);
  },
  
  destroy: function() {
    Event.stopObserving(this.handle, "mousedown", this.eventMouseDown);
    Draggables.unregister(this);
  },
  
  currentDelta: function() {
    return([
      parseInt(Element.getStyle(this.element,'left') || '0'),
      parseInt(Element.getStyle(this.element,'top') || '0')]);
  },
  
  initDrag: function(event) {
    if(Event.isLeftClick(event)) {    
      // abort on form elements, fixes a Firefox issue
      var src = Event.element(event);
      if(src.tagName && (
        src.tagName=='INPUT' ||
        src.tagName=='SELECT' ||
        src.tagName=='OPTION' ||
        src.tagName=='BUTTON' ||
        src.tagName=='TEXTAREA')) return;
        
      if(this.element._revert) {
        this.element._revert.cancel();
        this.element._revert = null;
      }
      
      var pointer = [Event.pointerX(event), Event.pointerY(event)];
      var pos     = Position.cumulativeOffset(this.element);
//      this.offset = [0,1].map( function(i) { return (pointer[i] - pos[i]) });

      this.offset[0] = pointer[0] - pos[0];
      this.offset[1] = pointer[1] - pos[1];
      
      Draggables.activate(this);
      Event.stop(event);
    }
  },
  
  startDrag: function(event) {
    this.dragging = true;
    
    if(this.options.zindex) {
      this.originalZ = parseInt(Element.getStyle(this.element,'z-index') || 0);
      this.element.style.zIndex = this.options.zindex;
    }
    
    if(this.options.ghosting) {
      this._clone = this.element.cloneNode(true);
      Position.absolutize(this.element);
      this.element.parentNode.insertBefore(this._clone, this.element);
    }
    
    if(this.options.scroll) {
      if (this.options.scroll == window) {
        var where = this._getWindowScroll(this.options.scroll);
        this.originalScrollLeft = where.left;
        this.originalScrollTop = where.top;
      } else {
        this.originalScrollLeft = this.options.scroll.scrollLeft;
        this.originalScrollTop = this.options.scroll.scrollTop;
      }
    }
    
    Draggables.notify('onStart', this, event);
    if(this.options.starteffect) this.options.starteffect(this.element);
  },
  
  updateDrag: function(event, pointer) {
    if(!this.dragging) this.startDrag(event);
    Position.prepare();
    Droppables.show(pointer, this.element);
    Draggables.notify('onDrag', this, event);
    this.draw(pointer);
    if(this.options.change) this.options.change(this);
    
    if(this.options.scroll) {
      this.stopScrolling();
      
      var p;
      if (this.options.scroll == window) {
        with(this._getWindowScroll(this.options.scroll)) { p = [ left, top, left+width, top+height ]; }
      } else {
        p = Position.page(this.options.scroll);
        p[0] += this.options.scroll.scrollLeft;
        p[1] += this.options.scroll.scrollTop;
        p.push(p[0]+this.options.scroll.offsetWidth);
        p.push(p[1]+this.options.scroll.offsetHeight);
      }
      var speed = [0,0];
      if(pointer[0] < (p[0]+this.options.scrollSensitivity)) speed[0] = pointer[0]-(p[0]+this.options.scrollSensitivity);
      if(pointer[1] < (p[1]+this.options.scrollSensitivity)) speed[1] = pointer[1]-(p[1]+this.options.scrollSensitivity);
      if(pointer[0] > (p[2]-this.options.scrollSensitivity)) speed[0] = pointer[0]-(p[2]-this.options.scrollSensitivity);
      if(pointer[1] > (p[3]-this.options.scrollSensitivity)) speed[1] = pointer[1]-(p[3]-this.options.scrollSensitivity);
      this.startScrolling(speed);
    }
    
    // fix AppleWebKit rendering
    if(navigator.appVersion.indexOf('AppleWebKit')>0) window.scrollBy(0,0);
    
    Event.stop(event);
  },
  
  finishDrag: function(event, success) {
    this.dragging = false;

    if(this.options.ghosting) {
      Position.relativize(this.element);
      Element.remove(this._clone);
      this._clone = null;
    }

    if(success) Droppables.fire(event, this.element);
    Draggables.notify('onEnd', this, event);

    var revert = this.options.revert;
    if(revert && typeof revert == 'function') revert = revert(this.element);
    
    var d = this.currentDelta();
    if(revert && this.options.reverteffect) {
      this.options.reverteffect(this.element, 
        d[1]-this.delta[1], d[0]-this.delta[0]);
    } else {
      this.delta = d;
    }

    //if(this.options.zindex)
      this.element.style.zIndex = this.originalZ;

    if(this.options.endeffect) 
      this.options.endeffect(this.element);

    Draggables.deactivate(this);
    Droppables.reset();
  },
  
  keyPress: function(event) {
    if(event.keyCode!=Event.KEY_ESC) return;
    this.finishDrag(event, false);
    Event.stop(event);
  },
  
  endDrag: function(event) {
    if(!this.dragging) return;
    this.stopScrolling();
    this.finishDrag(event, true);
    Event.stop(event);
  },
  
  draw: function(point) {
    var pos = Position.cumulativeOffset(this.element);
    var d = this.currentDelta();
    pos[0] -= d[0]; pos[1] -= d[1];
    
    if(this.options.scroll && (this.options.scroll != window)) {
      pos[0] -= this.options.scroll.scrollLeft-this.originalScrollLeft;
      pos[1] -= this.options.scroll.scrollTop-this.originalScrollTop;
    }
    var p = [0,1].map(function(i){ 
      return (point[i]-pos[i]-this.offset[i]) 
    }.bind(this));
    p[0] = point[0] - pos[0] - this.offset[0];
	  p[1] = point[1] - pos[1] - this.offset[1];


    if(this.options.snap) {
      if(typeof this.options.snap == 'function') {
        p = this.options.snap(p[0],p[1],this);
      } else {
      if(this.options.snap instanceof Array) {
        p = p.map( function(v, i) {
          return Math.round(v/this.options.snap[i])*this.options.snap[i] }.bind(this))
      } else {
        p = p.map( function(v) {
          return Math.round(v/this.options.snap)*this.options.snap }.bind(this))
      }
    }}
    
    var style = this.element.style;
    if((!this.options.constraint) || (this.options.constraint=='horizontal'))
      style.left = p[0] + "px";
    if((!this.options.constraint) || (this.options.constraint=='vertical'))
      style.top  = p[1] + "px";
    if(style.visibility=="hidden") style.visibility = ""; // fix gecko rendering
  },
  
  stopScrolling: function() {
    if(this.scrollInterval) {
      clearInterval(this.scrollInterval);
      this.scrollInterval = null;
      Draggables._lastScrollPointer = null;
    }
  },
  
  startScrolling: function(speed) {
    this.scrollSpeed = [speed[0]*this.options.scrollSpeed,speed[1]*this.options.scrollSpeed];
    this.lastScrolled = new Date();
    this.scrollInterval = setInterval(this.scroll.bind(this), 10);
  },
  
  scroll: function() {
    var current = new Date();
    var delta = current - this.lastScrolled;
    this.lastScrolled = current;
    if(this.options.scroll == window) {
      with (this._getWindowScroll(this.options.scroll)) {
        if (this.scrollSpeed[0] || this.scrollSpeed[1]) {
          var d = delta / 1000;
          this.options.scroll.scrollTo( left + d*this.scrollSpeed[0], top + d*this.scrollSpeed[1] );
        }
      }
    } else {
      this.options.scroll.scrollLeft += this.scrollSpeed[0] * delta / 1000;
      this.options.scroll.scrollTop  += this.scrollSpeed[1] * delta / 1000;
    }
    
    Position.prepare();
    Droppables.show(Draggables._lastPointer, this.element);
    Draggables.notify('onDrag', this);
    Draggables._lastScrollPointer = Draggables._lastScrollPointer || $A(Draggables._lastPointer);
    Draggables._lastScrollPointer[0] += this.scrollSpeed[0] * delta / 1000;
    Draggables._lastScrollPointer[1] += this.scrollSpeed[1] * delta / 1000;
    if (Draggables._lastScrollPointer[0] < 0)
      Draggables._lastScrollPointer[0] = 0;
    if (Draggables._lastScrollPointer[1] < 0)
      Draggables._lastScrollPointer[1] = 0;
    this.draw(Draggables._lastScrollPointer);
    
    if(this.options.change) this.options.change(this);
  },
  
  _getWindowScroll: function(w) {
    var T, L, W, H;
    with (w.document) {
      if (w.document.documentElement && documentElement.scrollTop) {
        T = documentElement.scrollTop;
        L = documentElement.scrollLeft;
      } else if (w.document.body) {
        T = body.scrollTop;
        L = body.scrollLeft;
      }
      if (w.innerWidth) {
        W = w.innerWidth;
        H = w.innerHeight;
      } else if (w.document.documentElement && documentElement.clientWidth) {
        W = documentElement.clientWidth;
        H = documentElement.clientHeight;
      } else {
        W = body.offsetWidth;
        H = body.offsetHeight
      }
    }
    return { top: T, left: L, width: W, height: H };
  }
}

/*--------------------------------------------------------------------------*/

var SortableObserver = Class.create();
SortableObserver.prototype = {
  initialize: function(element, observer) {
    this.element   = $(element);
    this.observer  = observer;
    this.lastValue = Sortable.serialize(this.element);
  },
  
  onStart: function() {
    this.lastValue = Sortable.serialize(this.element);
  },
  
  onEnd: function() {
    Sortable.unmark();
    if(this.lastValue != Sortable.serialize(this.element))
      this.observer(this.element)
  }
}

var Sortable = {
  sortables: {},
  
  _findRootElement: function(element) {
    while (element.tagName != "BODY") {  
      if(element.id && Sortable.sortables[element.id]) return element;
      element = element.parentNode;
    }
  },

  options: function(element) {
    element = Sortable._findRootElement($(element));
    if(!element) return;
    return Sortable.sortables[element.id];
  },
  
  destroy: function(element){
    var s = Sortable.options(element);
    
    if(s) {
      Draggables.removeObserver(s.element);
      s.droppables.each(function(d){ Droppables.remove(d) });
      s.draggables.invoke('destroy');
      
      delete Sortable.sortables[s.element.id];
    }
  },

  create: function(element) {
    element = $(element);
    var options = Object.extend({ 
      element:     element,
      tag:         'li',       // assumes li children, override with tag: 'tagname'
      dropOnEmpty: false,
      tree:        false,
      treeTag:     'ul',
      overlap:     'vertical', // one of 'vertical', 'horizontal'
      constraint:  'vertical', // one of 'vertical', 'horizontal', false
      containment: element,    // also takes array of elements (or id's); or false
      handle:      false,      // or a CSS class
      only:        false,
      hoverclass:  null,
      ghosting:    false,
      scroll:      false,
      scrollSensitivity: 20,
      scrollSpeed: 15,
      format:      /^[^_]*_(.*)$/,
      onChange:    Prototype.emptyFunction,
      onUpdate:    Prototype.emptyFunction
    }, arguments[1] || {});

    // clear any old sortable with same element
    this.destroy(element);

    // build options for the draggables
    var options_for_draggable = {
      revert:      true,
      scroll:      options.scroll,
      scrollSpeed: options.scrollSpeed,
      scrollSensitivity: options.scrollSensitivity,
      ghosting:    options.ghosting,
      constraint:  options.constraint,
      handle:      options.handle };

    if(options.starteffect)
      options_for_draggable.starteffect = options.starteffect;

    if(options.reverteffect)
      options_for_draggable.reverteffect = options.reverteffect;
    else
      if(options.ghosting) options_for_draggable.reverteffect = function(element) {
        element.style.top  = 0;
        element.style.left = 0;
      };

    if(options.endeffect)
      options_for_draggable.endeffect = options.endeffect;

    if(options.zindex)
      options_for_draggable.zindex = options.zindex;

    // build options for the droppables  
    var options_for_droppable = {
      overlap:     options.overlap,
      containment: options.containment,
      tree:        options.tree,
      hoverclass:  options.hoverclass,
      onHover:     Sortable.onHover
      //greedy:      !options.dropOnEmpty
    }
    
    var options_for_tree = {
      onHover:      Sortable.onEmptyHover,
      overlap:      options.overlap,
      containment:  options.containment,
      hoverclass:   options.hoverclass
    }

    // fix for gecko engine
    Element.cleanWhitespace(element); 

    options.draggables = [];
    options.droppables = [];

    // drop on empty handling
    if(options.dropOnEmpty || options.tree) {
      Droppables.add(element, options_for_tree);
      options.droppables.push(element);
    }

    (this.findElements(element, options) || []).each( function(e) {
      // handles are per-draggable
      var handle = options.handle ? 
        Element.childrenWithClassName(e, options.handle)[0] : e;    
      options.draggables.push(
        new Draggable(e, Object.extend(options_for_draggable, { handle: handle })));
      Droppables.add(e, options_for_droppable);
      if(options.tree) e.treeNode = element;
      options.droppables.push(e);      
    });
    
    if(options.tree) {
      (Sortable.findTreeElements(element, options) || []).each( function(e) {
        Droppables.add(e, options_for_tree);
        e.treeNode = element;
        options.droppables.push(e);
      });
    }

    // keep reference
    this.sortables[element.id] = options;

    // for onupdate
    Draggables.addObserver(new SortableObserver(element, options.onUpdate));

  },

  // return all suitable-for-sortable elements in a guaranteed order
  findElements: function(element, options) {
    return Element.findChildren(
      element, options.only, options.tree ? true : false, options.tag);
  },
  
  findTreeElements: function(element, options) {
    return Element.findChildren(
      element, options.only, options.tree ? true : false, options.treeTag);
  },

  onHover: function(element, dropon, overlap) {
    if(Element.isParent(dropon, element)) return;

    if(overlap > .33 && overlap < .66 && Sortable.options(dropon).tree) {
      return;
    } else if(overlap>0.5) {
      Sortable.mark(dropon, 'before');
      if(dropon.previousSibling != element) {
        var oldParentNode = element.parentNode;
        element.style.visibility = "hidden"; // fix gecko rendering
        dropon.parentNode.insertBefore(element, dropon);
        if(dropon.parentNode!=oldParentNode) 
          Sortable.options(oldParentNode).onChange(element);
        Sortable.options(dropon.parentNode).onChange(element);
      }
    } else {
      Sortable.mark(dropon, 'after');
      var nextElement = dropon.nextSibling || null;
      if(nextElement != element) {
        var oldParentNode = element.parentNode;
        element.style.visibility = "hidden"; // fix gecko rendering
        dropon.parentNode.insertBefore(element, nextElement);
        if(dropon.parentNode!=oldParentNode) 
          Sortable.options(oldParentNode).onChange(element);
        Sortable.options(dropon.parentNode).onChange(element);
      }
    }
  },
  
  onEmptyHover: function(element, dropon, overlap) {
    var oldParentNode = element.parentNode;
    var droponOptions = Sortable.options(dropon);
        
    if(!Element.isParent(dropon, element)) {
      var index;
      
      var children = Sortable.findElements(dropon, {tag: droponOptions.tag});
      var child = null;
            
      if(children) {
        var offset = Element.offsetSize(dropon, droponOptions.overlap) * (1.0 - overlap);
        
        for (index = 0; index < children.length; index += 1) {
          if (offset - Element.offsetSize (children[index], droponOptions.overlap) >= 0) {
            offset -= Element.offsetSize (children[index], droponOptions.overlap);
          } else if (offset - (Element.offsetSize (children[index], droponOptions.overlap) / 2) >= 0) {
            child = index + 1 < children.length ? children[index + 1] : null;
            break;
          } else {
            child = children[index];
            break;
          }
        }
      }
      
      dropon.insertBefore(element, child);
      
      Sortable.options(oldParentNode).onChange(element);
      droponOptions.onChange(element);
    }
  },

  unmark: function() {
    if(Sortable._marker) Element.hide(Sortable._marker);
  },

  mark: function(dropon, position) {
    // mark on ghosting only
    var sortable = Sortable.options(dropon.parentNode);
    if(sortable && !sortable.ghosting) return; 

    if(!Sortable._marker) {
      Sortable._marker = $('dropmarker') || document.createElement('DIV');
      Element.hide(Sortable._marker);
      Element.addClassName(Sortable._marker, 'dropmarker');
      Sortable._marker.style.position = 'absolute';
      document.getElementsByTagName("body").item(0).appendChild(Sortable._marker);
    }    
    var offsets = Position.cumulativeOffset(dropon);
    Sortable._marker.style.left = offsets[0] + 'px';
    Sortable._marker.style.top = offsets[1] + 'px';
    
    if(position=='after')
      if(sortable.overlap == 'horizontal') 
        Sortable._marker.style.left = (offsets[0]+dropon.clientWidth) + 'px';
      else
        Sortable._marker.style.top = (offsets[1]+dropon.clientHeight) + 'px';
    
    Element.show(Sortable._marker);
  },
  
  _tree: function(element, options, parent) {
    var children = Sortable.findElements(element, options) || [];
  
    for (var i = 0; i < children.length; ++i) {
      var match = children[i].id.match(options.format);

      if (!match) continue;
      
      var child = {
        id: encodeURIComponent(match ? match[1] : null),
        element: element,
        parent: parent,
        children: new Array,
        position: parent.children.length,
        container: Sortable._findChildrenElement(children[i], options.treeTag.toUpperCase())
      }
      
      /* Get the element containing the children and recurse over it */
      if (child.container)
        this._tree(child.container, options, child)
      
      parent.children.push (child);
    }

    return parent; 
  },

  /* Finds the first element of the given tag type within a parent element.
    Used for finding the first LI[ST] within a L[IST]I[TEM].*/
  _findChildrenElement: function (element, containerTag) {
    if (element && element.hasChildNodes)
      for (var i = 0; i < element.childNodes.length; ++i)
        if (element.childNodes[i].tagName == containerTag)
          return element.childNodes[i];
  
    return null;
  },

  tree: function(element) {
    element = $(element);
    var sortableOptions = this.options(element);
    var options = Object.extend({
      tag: sortableOptions.tag,
      treeTag: sortableOptions.treeTag,
      only: sortableOptions.only,
      name: element.id,
      format: sortableOptions.format
    }, arguments[1] || {});
    
    var root = {
      id: null,
      parent: null,
      children: new Array,
      container: element,
      position: 0
    }
    
    return Sortable._tree (element, options, root);
  },

  /* Construct a [i] index for a particular node */
  _constructIndex: function(node) {
    var index = '';
    do {
      if (node.id) index = '[' + node.position + ']' + index;
    } while ((node = node.parent) != null);
    return index;
  },

  sequence: function(element) {
    element = $(element);
    var options = Object.extend(this.options(element), arguments[1] || {});
    
    return $(this.findElements(element, options) || []).map( function(item) {
      return item.id.match(options.format) ? item.id.match(options.format)[1] : '';
    });
  },

  setSequence: function(element, new_sequence) {
    element = $(element);
    var options = Object.extend(this.options(element), arguments[2] || {});
    
    var nodeMap = {};
    this.findElements(element, options).each( function(n) {
        if (n.id.match(options.format))
            nodeMap[n.id.match(options.format)[1]] = [n, n.parentNode];
        n.parentNode.removeChild(n);
    });
   
    new_sequence.each(function(ident) {
      var n = nodeMap[ident];
      if (n) {
        n[1].appendChild(n[0]);
        delete nodeMap[ident];
      }
    });
  },
  
  serialize: function(element) {
    element = $(element);
    var options = Object.extend(Sortable.options(element), arguments[1] || {});
    var name = encodeURIComponent(
      (arguments[1] && arguments[1].name) ? arguments[1].name : element.id);
    
    if (options.tree) {
      return Sortable.tree(element, arguments[1]).children.map( function (item) {
        return [name + Sortable._constructIndex(item) + "=" + 
                encodeURIComponent(item.id)].concat(item.children.map(arguments.callee));
      }).flatten().join('&');
    } else {
      return Sortable.sequence(element, arguments[1]).map( function(item) {
        return name + "[]=" + encodeURIComponent(item);
      }).join('&');
    }
  }
}

/* Returns true if child is contained within element */
Element.isParent = function(child, element) {
  if (!child.parentNode || child == element) return false;

  if (child.parentNode == element) return true;

  return Element.isParent(child.parentNode, element);
}

Element.findChildren = function(element, only, recursive, tagName) {    
  if(!element.hasChildNodes()) return null;
  tagName = tagName.toUpperCase();
  if(only) only = [only].flatten();
  var elements = [];
  $A(element.childNodes).each( function(e) {
    if(e.tagName && e.tagName.toUpperCase()==tagName &&
      (!only || (Element.classNames(e).detect(function(v) { return only.include(v) }))))
        elements.push(e);
    if(recursive) {
      var grandchildren = Element.findChildren(e, only, recursive, tagName);
      if(grandchildren) elements.push(grandchildren);
    }
  });

  return (elements.length>0 ? elements.flatten() : []);
}

Element.offsetSize = function (element, type) {
  if (type == 'vertical' || type == 'height')
    return element.offsetHeight;
  else
    return element.offsetWidth;
}
// Copyright (c) 2005 Thomas Fuchs (http://script.aculo.us, http://mir.aculo.us)
// 
// Permission is hereby granted, free of charge, to any person obtaining
// a copy of this software and associated documentation files (the
// "Software"), to deal in the Software without restriction, including
// without limitation the rights to use, copy, modify, merge, publish,
// distribute, sublicense, and/or sell copies of the Software, and to
// permit persons to whom the Software is furnished to do so, subject to
// the following conditions:
// 
// The above copyright notice and this permission notice shall be
// included in all copies or substantial portions of the Software.
//
// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND,
// EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF
// MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND
// NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE
// LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION
// OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION
// WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.

var Scriptaculous = {
  Version: '1.6.1',
  require: function(libraryName) {
    // inserting via DOM fails in Safari 2.0, so brute force approach
    document.write('<script type="text/javascript" src="'+libraryName+'"></script>');
  },
  load: function() {
    if((typeof Prototype=='undefined') || 
       (typeof Element == 'undefined') || 
       (typeof Element.Methods=='undefined') ||
       parseFloat(Prototype.Version.split(".")[0] + "." +
                  Prototype.Version.split(".")[1]) < 1.5)
       throw("script.aculo.us requires the Prototype JavaScript framework >= 1.5.0");
    
    $A(document.getElementsByTagName("script")).findAll( function(s) {
      return (s.src && s.src.match(/scriptaculous\.js(\?.*)?$/))
    }).each( function(s) {
      var path = s.src.replace(/scriptaculous\.js(\?.*)?$/,'');
      var includes = s.src.match(/\?.*load=([a-z,]*)/);
      (includes ? includes[1] : 'builder,effects,dragdrop,controls,slider').split(',').each(
       function(include) { Scriptaculous.require(path+include+'.js') });
    });
  }
}

Scriptaculous.load();
/*
 * A Javascript date chooser.
 * Copyright (C) 2004 Baron Schwartz <baron at sequent dot org>
 *
 * This program is free software; you can redistribute it and/or modify it under
 * the terms of the GNU General Public License as published by the Free Software
 * Foundation; either version 2 of the License, or (at your option) any later
 * version.
 *
 * This program is distributed in the hope that it will be useful, but WITHOUT
 * ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS
 * FOR A PARTICULAR PURPOSE.  See the GNU General Public License for more
 * details.
 *
 * You should have received a copy of the GNU General Public License along with
 * this program; if not, write to the Free Software Foundation, Inc., 59 Temple
 * Place, Suite 330, Boston, MA 02111-1307  USA
 */

// Shows or hides the date chooser on the page
function showDateChooser(inputId, start, end, format, isTimeChooser,runOnChange,ev) {
    ev =  ev || window.event;
    coords=getMouseCoords(ev,true);
    //alert(coords['x'] + ' - '+coords['y']);    
    if (document.getElementById) {
        var input = document.getElementById(inputId);        
        if (input !== undefined) 
        {
            if (input.DateChooser === undefined || input.DateChooser==null) 
            {
                input.DateChooser = new DateChooser(input, start, end, format, isTimeChooser,runOnChange,coords );
                input.DateChooser.initializeDate(); //setDate(Date.parseDate(input.value, format));
                input.DateChooser.refresh();
            }
            else
            {
            	input.DateChooser.close();
            }            
        }

    }
}

// Sets a date on the object attached to 'inputId'
function dateChooserDateToInput(inputId, value) 
{

	var input = document.getElementById(inputId);	
    if (input !== undefined && input.DateChooser !== undefined) 
    {
        if (value!='')
    	{
    	    input.DateChooser.setDate(Date.parseDate(value, input.DateChooser._format));
        	if (input.DateChooser.isTimeChooser()) 
            {
               var hourElm=document.getElementById(input.DateChooser._hourId);
                var minElm=document.getElementById(input.DateChooser._minId);
                var ampmElm=document.getElementById(input.DateChooser._ampmId);
            
               var newHour=parseInt(hourElm.value)+ parseInt(ampmElm.value);
               var newMin=parseInt(minElm.value);
               input.DateChooser.setTime(newHour,newMin);
            }

        	input.value = input.DateChooser.getValue();
        	if (input.DateChooser._runOnchange>0 && input.onchange)
            {
        		
                input.onchange();
                //input.form.submit();
            }

    	}
        input.DateChooser.close();

    }

}

function dateChooserClose(inputId)
{
	var input = document.getElementById(inputId);  
    if (input !== undefined && input.DateChooser !== undefined) 
        input.DateChooser.close();
}


// The callback function for when someone changes the pulldown menus on the date
// chooser
function dateChooserDateChange(inputId,monthDiff) {
    
    var input = document.getElementById(inputId);
        
    var yearElm=document.getElementById(input.DateChooser._yearId);
    var monthElm=document.getElementById(input.DateChooser._monthId);
    
    
    
    // monthDiff = -1,0,1 - posun mesiaca o 1 dozadu alebo dopredu
    if(monthDiff==1)
    {               
                   
        if(monthElm.selectedIndex=='11')
        {
            monthElm.selectedIndex=0;
            if(yearElm.selectedIndex==(input.DateChooser._end - input.DateChooser._start))
                yearElm.selectedIndex= 0;
             else
                yearElm.selectedIndex=yearElm.selectedIndex+1;
        }    
        else
            monthElm.selectedIndex=monthElm.selectedIndex+1;                
        
    }
    if(monthDiff==-1)
    {        
        
        if(monthElm.selectedIndex==0)
        {
            monthElm.selectedIndex=11;
            if(yearElm.selectedIndex==0)
                yearElm.selectedIndex= input.DateChooser._end - input.DateChooser._start;
             else
                yearElm.selectedIndex=yearElm.selectedIndex-1;
        }
        else
            monthElm.selectedIndex=monthElm.selectedIndex-1; 
        
    }
    
    
    
    var newDate = new Date(yearElm.value,monthElm.value,1);    
    
                            
    // Try to preserve the day of month (watch out for months with 31 days)
    newDate.setDate(Math.max(1, Math.min(newDate.getDaysInMonth(),
                    input.DateChooser._date.getDate())));
    input.DateChooser.setDate(newDate);
    if (input.DateChooser.isTimeChooser()) 
    {
       var hourElm=document.getElementById(input.DateChooser._hourId);
        var minElm=document.getElementById(input.DateChooser._minId);
        var ampmElm=document.getElementById(input.DateChooser._ampmId);
    
       var newHour=parseInt(hourElm.value)+ parseInt(ampmElm.value);
       var newMin=parseInt(minElm.value);
       input.DateChooser.setTime(newHour,newMin);
    }
    input.DateChooser.refresh();
}



// DateChooser constructor --- OOP --------------------------------------------------
function DateChooser(input, start, end, format, isTimeChooser, runOnChange,mouse) {
    var div  = document.createElement('DIV');   
    div.className='date-chooser';
    document.body.appendChild(div);
    this._input = input;
    this._div = div;
    this._mouseCoords = mouse;
    this._start = start;
    this._end = end;
    this._format = format;
    this._date = new Date();
    this._isTimeChooser = isTimeChooser;    
    this._runOnchange=runOnChange;
    // Choose a random prefix for all pulldown menus
    this._prefix = "";
    var letters = ["a", "b", "c", "d", "e", "f", "h", "i", "j", "k", "l",
        "m", "n", "o", "p", "q", "r", "s", "t", "u", "v", "w", "x", "y", "z"];
    for (var i = 0; i < 10; ++i) {
        this._prefix += letters[Math.floor(Math.random() * letters.length)];
    }
    this._monthId = this._prefix+'month';
    this._yearId =this._prefix+'year';
    this._hourId =this._prefix+'hour';
    this._minId =this._prefix+'min';
    this._ampmId =this._prefix+'ampm';
    this._inputId =  this._input.getAttribute('id');
}




// 
DateChooser.prototype.isTimeChooser = function() {
    return this._isTimeChooser;
}


// Gets the value, as a formatted string, of the date attached to the chooser
DateChooser.prototype.getValue = function() {
    return this._date.dateFormat(this._format);
}

// Hides the chooser
DateChooser.prototype.close = function() {
    
    /*
    this._div.style.visibility = "hidden";
    this._div.style.display = "none";
    this._div.innerHTML = "";
    
    */
    document.body.removeChild(this._div);
    this._input.DateChooser=null;
    
}



// Shows the chooser on the page
DateChooser.prototype.refresh = function() {
    this._div.style.display = "block";
    this._div.style.visibility = "visible";
    this._div.style.position = "absolute";
    //var inputPos = getAbsolutePosition(this._input);    
    var mousePos = this._mouseCoords;          
    this._div.style.top = mousePos['y'] + "px";//(inputPos[0] + this._input.offsetHeight)-70 + "px";
    this._div.style.left = mousePos['x'] + "px"; //(inputPos[1] + this._input.offsetWidth) + "px";
    this._div.innerHTML = this.createChooserHtml();
    
}

// Sets the date to what is in the input box
DateChooser.prototype.initializeDate = function() {
    if (this._input.value != null && this._input.value != "" ) {
        this._date = Date.parseDate(this._input.value, this._format);
    }
    if(!this._date)
    {
        this._date = new Date();
    }
}

// Sets the date attached to the chooser
DateChooser.prototype.setDate = function(date) {
    this._date = date ? date : new Date();
    //this._date = date ? date : '';
}

// Sets the time portion of the date attached to the chooser
DateChooser.prototype.setTime = function(hour, minute) {
    this._date.setHours(hour);
    this._date.setMinutes(minute);
}

// Creates the HTML for the whole chooser
DateChooser.prototype.createChooserHtml = function() 
{
    var formHtml = ""
        + "\r\n  <span class=\"dc-previous\" onclick=\"dateChooserDateChange('"+this._inputId+"',-1);\"><span>|<<|</span></span>"
        + "\r\n  <span class=\"dc-close\" onclick=\"dateChooserClose('"+this._inputId+"');\"><span>|X|</span></span>"
        + "\r\n  <span class=\"dc-next\" onclick=\"dateChooserDateChange('"+this._inputId+"',1);\"><span>|>>|</span></span>"
        + "<select id=\""+this._monthId+"\" class=\"dc-month\"  onChange=\"dateChooserDateChange('"+this._inputId+"');\">";
    for (var mon in Date.monthNames) {
        if(typeof(Date.monthNames[mon])!='string')
            continue;
        formHtml += "\r\n    <option value=\"" + mon + "\""
            + (mon == this._date.getMonth() ? " selected=\"1\"" : "")
            + ">" + Date.monthNames[mon] + "</option>";
    }
    formHtml += "\r\n  </select>\r\n  <select id=\""+this._yearId+"\"  class=\"dc-year\"  onChange=\"dateChooserDateChange('"+this._inputId+"');\">";
    for (var i = this._start; i <= this._end; ++i) {
        formHtml += "\r\n    <option value=\"" + i + "\""
            + (i == this._date.getFullYear() ? " selected=\"1\"" : "")
            + ">" + i + "</option>";
    }
    formHtml += "\r\n  </select>";
    formHtml += this.createCalendarHtml();
    if (this._isTimeChooser) {
        formHtml += this.createTimeChooserHtml();
    }
    return formHtml;
}


// Creates the extra HTML needed for choosing the time
DateChooser.prototype.createTimeChooserHtml = function() 
{
    // Add hours
    var result = "\r\n  <select id=\"" + this._hourId + "\">";
    for (var i = 0; i < 12; ++i) {
        result += "\r\n    <option value=\"" + i + "\""
            + (((this._date.getHours() % 12) == i) ? " selected=\"1\">" : ">")
            + i + "</option>";
    }
    // Add extra entry for 12:00
    result += "\r\n    <option value=\"0\">12</option>";
    result += "\r\n  </select>";
    // Add minutes
    result += "\r\n  <select id=\"" + this._hourId + "\">";
    for (var i = 0; i < 60; i += 15) {
        result += "\r\n    <option value=\"" + i + "\""
            + ((this._date.getMinutes() == i) ? " selected=\"1\">" : ">")
            + String.leftPad(i, 2, '0') + "</option>";
    }
    result += "\r\n  </select>";
    // Add AM/PM
    result += "\r\n  <select id=\"" + this._hourId + "\">";
    result += "\r\n    <option value=\"0\""
        + (this._date.getHours() < 12 ? " selected=\"1\">" : ">")
        + "AM</option>";
    result += "\r\n    <option value=\"12\""
        + (this._date.getHours() >= 12 ? " selected=\"1\">" : ">")
        + "PM</option>";
    result += "\r\n  </select>";
    return result;
}

// Creates the HTML for the actual calendar part of the chooser
DateChooser.prototype.createCalendarHtml = function() 
{
    var result = "\r\n<table cellspacing=\"0\" class=\"dateChooser\">"
        + "\r\n  <tr><th>"+Date.dayNames[0].substr(0,1)+"</th>"
        +"<th>"+Date.dayNames[1].substr(0,1)+"</th>"
        + "<th>"+Date.dayNames[2].substr(0,1)+"</th>"
        +"<th>"+Date.dayNames[3].substr(0,1)+"</th>"
        +"<th>"+Date.dayNames[4].substr(0,1)+"</th>"
        +"<th>"+Date.dayNames[5].substr(0,1)+"</th>"
        +"<th>"+Date.dayNames[6].substr(0,1)+"</th>"
        +"</tr>\r\n  <tr>";
    // Fill up the days of the week until we get to the first day of the month
    var firstDay = this._date.getFirstDayOfMonth();
    var lastDay = this._date.getLastDayOfMonth();
    if (firstDay != 0) {
        result += "<td colspan=\"" + firstDay + "\">&nbsp;</td>";
    }
    // Fill in the days of the month
    var i = 0;
    while (i < this._date.getDaysInMonth()) {
        if (((i++ + firstDay) % 7) == 0) {
            result += "</tr>\r\n  <tr>";
        }
        var thisDay = new Date(
            this._date.getFullYear(),
            this._date.getMonth(), i);
        var js = '"dateChooserDateToInput(\''
            + this._inputId + "', '"
            + thisDay.dateFormat(this._format) + '\');"'
        result += "\r\n    <td class=\"dateChooserActive"
            // If the date is the currently chosen date, highlight it
            + (i == this._date.getDate() ? " dateChooserActiveToday" : "")
            + "\" onClick=" + js + ">" + i + "</td>";
    }
    // Fill in any days after the end of the month
    if (lastDay != 6) {
        result += "<td colspan=\"" + (6 - lastDay) + "\">&nbsp;</td>";
    }
    return result + "\r\n  </tr>\r\n</table>";
}



/*
 * Javascript functions for date-parsing and date-formatting.
 * Copyright (C) 2004 Baron Schwartz <baron at sequent dot org>
 *
 * This program is free software; you can redistribute it and/or modify it under
 * the terms of the GNU General Public License as published by the Free Software
 * Foundation; either version 2 of the License, or (at your option) any later
 * version.
 *
 * This program is distributed in the hope that it will be useful, but WITHOUT
 * ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS
 * FOR A PARTICULAR PURPOSE.  See the GNU General Public License for more
 * details.
 *
 * You should have received a copy of the GNU General Public License along with
 * this program; if not, write to the Free Software Foundation, Inc., 59 Temple
 * Place, Suite 330, Boston, MA 02111-1307  USA
 */

Date.parseFunctions = {count:0};
Date.parseRegexes = [];
Date.formatFunctions = {count:0};

Date.prototype.dateFormat = function(format) {
    if (Date.formatFunctions[format] == null) {
        Date.createNewFormat(format);
    }
    var func = Date.formatFunctions[format];
    return eval("this." + func + "();");
}

Date.createNewFormat = function(format) {
    var funcName = "format" + Date.formatFunctions.count++;
    Date.formatFunctions[format] = funcName;
    var code = "Date.prototype." + funcName + " = function(){return ";
    var special = false;
    var ch = '';
    for (var i = 0; i < format.length; ++i) {
        ch = format.charAt(i);
        if (!special && ch == "\\") {
            special = true;
        }
        else if (special) {
            special = false;
            code += "'" + String.escape(ch) + "' + ";
        }
        else {
            code += Date.getFormatCode(ch);
        }
    }
    eval(code.substring(0, code.length - 3) + ";}");
}

Date.getFormatCode = function(character) {
    switch (character) {
    case "d":
        return "String.leftPad(this.getDate(), 2, '0') + ";
    case "D":
        return "Date.dayNames[this.getDay()].substring(0, 3) + ";       
    case "j":
        return "this.getDate() + ";
    case "l":
        return "Date.dayNames[this.getDay()] + ";
    case "S":
        return "this.getSuffix() + ";
    case "w":
        return "this.getDay() + ";
    case "z":
        return "this.getDayOfYear() + ";
    case "W":
        return "this.getWeekOfYear() + ";
    case "F":
        return "Date.monthNames[this.getMonth()] + ";
    case "m":
        return "String.leftPad(this.getMonth() + 1, 2, '0') + ";
    case "M":
        return "Date.monthNames[this.getMonth()].substring(0, 3) + ";
    case "n":
        return "(this.getMonth() + 1) + ";
    case "t":
        return "this.getDaysInMonth() + ";
    case "L":
        return "(this.isLeapYear() ? 1 : 0) + ";
    case "Y":
        return "this.getFullYear() + ";
    case "y":
        return "('' + this.getFullYear()).substring(2, 4) + ";
    case "a":
        return "(this.getHours() < 12 ? 'am' : 'pm') + ";
    case "A":
        return "(this.getHours() < 12 ? 'AM' : 'PM') + ";
    case "g":
        return "((this.getHours() %12) ? this.getHours() % 12 : 12) + ";
    case "G":
        return "this.getHours() + ";
    case "h":
        return "String.leftPad((this.getHours() %12) ? this.getHours() % 12 : 12, 2, '0') + ";
    case "H":
        return "String.leftPad(this.getHours(), 2, '0') + ";
    case "i":
        return "String.leftPad(this.getMinutes(), 2, '0') + ";
    case "s":
        return "String.leftPad(this.getSeconds(), 2, '0') + ";
    case "O":
        return "this.getGMTOffset() + ";
    case "T":
        return "this.getTimezone() + ";
    case "Z":
        return "(this.getTimezoneOffset() * -60) + ";
    default:
        return "'" + String.escape(character) + "' + ";
    }
}

Date.parseDate = function(input, format) {
    if (Date.parseFunctions[format] == null) {
        Date.createParser(format);
    }
    var func = Date.parseFunctions[format];
    return Date[func](input);
}


Date.createParser = function(format) {
    var funcName = "parse" + Date.parseFunctions.count++;
    var regexNum = Date.parseRegexes.length;
    var currentGroup = 1;
    Date.parseFunctions[format] = funcName;

    var code = "Date." + funcName + " = function(input){\n"
        + "var y = -1, m = -1, d = -1, h = -1, i = -1, s = -1;\n"
        + "var d = new Date();\n"
        + "y = d.getFullYear();\n"
        + "m = d.getMonth();\n"
        + "d = d.getDate();\n"
        + "var results = input.match(Date.parseRegexes[" + regexNum + "]);\n"
        + "if (results && results.length > 0) {"
    var regex = "";

    var special = false;
    var ch = '';
    for (var i = 0; i < format.length; ++i) {
        ch = format.charAt(i);
        if (!special && ch == "\\") {
            special = true;
        }
        else if (special) {
            special = false;
            regex += String.escape(ch);
        }
        else {
            obj = Date.formatCodeToRegex(ch, currentGroup);
            currentGroup += obj.g;
            regex += obj.s;
            if (obj.g && obj.c) {
                code += obj.c;
            }
        }
    }

    code += "if (y > 0 && m >= 0 && d > 0 && h >= 0 && i >= 0 && s >= 0)\n"
        + "{return new Date(y, m, d, h, i, s);}\n"
        + "else if (y > 0 && m >= 0 && d > 0 && h >= 0 && i >= 0)\n"
        + "{return new Date(y, m, d, h, i);}\n"
        + "else if (y > 0 && m >= 0 && d > 0 && h >= 0)\n"
        + "{return new Date(y, m, d, h);}\n"
        + "else if (y > 0 && m >= 0 && d > 0)\n"
        + "{return new Date(y, m, d);}\n"
        + "else if (y > 0 && m >= 0)\n"
        + "{return new Date(y, m);}\n"
        + "else if (y > 0)\n"
        + "{return new Date(y);}\n"
        + "}return null;}";

    Date.parseRegexes[regexNum] = new RegExp("^" + regex + "$");
    eval(code);
}

Date.formatCodeToRegex = function(character, currentGroup) {
    switch (character) {
    case "D":
        return {g:0,
        c:null,
        s:"(?:Sun|Mon|Tue|Wed|Thu|Fri|Sat)"};
    case "j":
    case "d":
        return {g:1,
            c:"d = parseInt(results[" + currentGroup + "], 10);\n",
            s:"(\\d{1,2})"};
    case "l":
        return {g:0,
            c:null,
            s:"(?:" + Date.dayNames.join("|") + ")"};
    case "S":
        return {g:0,
            c:null,
            s:"(?:st|nd|rd|th)"};
    case "w":
        return {g:0,
            c:null,
            s:"\\d"};
    case "z":
        return {g:0,
            c:null,
            s:"(?:\\d{1,3})"};
    case "W":
        return {g:0,
            c:null,
            s:"(?:\\d{2})"};
    case "F":
        return {g:1,
            c:"m = parseInt(Date.monthNumbers[results[" + currentGroup + "].substring(0, 3)], 10);\n",
            s:"(" + Date.monthNames.join("|") + ")"};
    case "M":
        return {g:1,
            c:"m = parseInt(Date.monthNumbers[results[" + currentGroup + "]], 10);\n",
            s:"(Jan|Feb|Mar|Apr|May|Jun|Jul|Aug|Sep|Oct|Nov|Dec)"};
    case "n":
    case "m":
        return {g:1,
            c:"m = parseInt(results[" + currentGroup + "], 10) - 1;\n",
            s:"(\\d{1,2})"};
    case "t":
        return {g:0,
            c:null,
            s:"\\d{1,2}"};
    case "L":
        return {g:0,
            c:null,
            s:"(?:1|0)"};
    case "Y":
        return {g:1,
            c:"y = parseInt(results[" + currentGroup + "], 10);\n",
            s:"(\\d{4})"};
    case "y":
        return {g:1,
            c:"var ty = parseInt(results[" + currentGroup + "], 10);\n"
                + "y = ty > Date.y2kYear ? 1900 + ty : 2000 + ty;\n",
            s:"(\\d{1,2})"};
    case "a":
        return {g:1,
            c:"if (results[" + currentGroup + "] == 'am') {\n"
                + "if (h == 12) { h = 0; }\n"
                + "} else { if (h < 12) { h += 12; }}",
            s:"(am|pm)"};
    case "A":
        return {g:1,
            c:"if (results[" + currentGroup + "] == 'AM') {\n"
                + "if (h == 12) { h = 0; }\n"
                + "} else { if (h < 12) { h += 12; }}",
            s:"(AM|PM)"};
    case "g":
    case "G":
    case "h":
    case "H":
        return {g:1,
            c:"h = parseInt(results[" + currentGroup + "], 10);\n",
            s:"(\\d{1,2})"};
    case "i":
        return {g:1,
            c:"i = parseInt(results[" + currentGroup + "], 10);\n",
            s:"(\\d{2})"};
    case "s":
        return {g:1,
            c:"s = parseInt(results[" + currentGroup + "], 10);\n",
            s:"(\\d{2})"};
    case "O":
        return {g:0,
            c:null,
            s:"[+-]\\d{4}"};
    case "T":
        return {g:0,
            c:null,
            s:"[A-Z]{3}"};
    case "Z":
        return {g:0,
            c:null,
            s:"[+-]\\d{1,5}"};
    default:
        return {g:0,
            c:null,
            s:String.escape(character)};
    }
}

Date.prototype.getTimezone = function() {
    return this.toString().replace(
        /^.*? ([A-Z]{3}) [0-9]{4}.*$/, "$1").replace(
        /^.*?\(([A-Z])[a-z]+ ([A-Z])[a-z]+ ([A-Z])[a-z]+\)$/, "$1$2$3");
}

Date.prototype.getGMTOffset = function() {
    return (this.getTimezoneOffset() > 0 ? "-" : "+")
        + String.leftPad(Math.floor(this.getTimezoneOffset() / 60), 2, "0")
        + String.leftPad(this.getTimezoneOffset() % 60, 2, "0");
}

Date.prototype.getDayOfYear = function() {
    var num = 0;
    Date.daysInMonth[1] = this.isLeapYear() ? 29 : 28;
    for (var i = 0; i < this.getMonth(); ++i) {
        num += Date.daysInMonth[i];
    }
    return num + this.getDate() - 1;
}

Date.prototype.getWeekOfYear = function() {
    // Skip to Thursday of this week
    var now = this.getDayOfYear() + (4 - this.getDay());
    // Find the first Thursday of the year
    var jan1 = new Date(this.getFullYear(), 0, 1);
    var then = (7 - jan1.getDay() + 4);
    document.write(then);
    return String.leftPad(((now - then) / 7) + 1, 2, "0");
}

Date.prototype.isLeapYear = function() {
    var year = this.getFullYear();
    return ((year & 3) == 0 && (year % 100 || (year % 400 == 0 && year)));
}

Date.prototype.getFirstDayOfMonth = function() {
    var day = (this.getDay() - (this.getDate() - 0)) % 7;
    return (day < 0) ? (day + 7) : day;
}

Date.prototype.getLastDayOfMonth = function() {
    var day = (this.getDay() + (Date.daysInMonth[this.getMonth()] - (this.getDate()+1))) % 7;
    return (day < 0) ? (day + 7) : day;
}

Date.prototype.getDaysInMonth = function() {
    Date.daysInMonth[1] = this.isLeapYear() ? 29 : 28;
    return Date.daysInMonth[this.getMonth()];
}

Date.prototype.getSuffix = function() {
    switch (this.getDate()) {
        case 1:
        case 21:
        case 31:
            return "st";
        case 2:
        case 22:
            return "nd";
        case 3:
        case 23:
            return "rd";
        default:
            return "th";
    }
}

String.escape = function(string) {
    return string.replace(/('|\\)/g, "\\$1");
}

String.leftPad = function (val, size, ch) {
    var result = new String(val);
    if (ch == null) {
        ch = " ";
    }
    while (result.length < size) {
        result = ch + result;
    }
    return result;
}

Date.daysInMonth = [31,28,31,30,31,30,31,31,30,31,30,31];
//Date.monthNames = new Object();
Date.monthNames = 
  ["Január","Február","Marec","Apríl","Máj","Jún","Júl","August","September","Október","November","December"];Date.dayNames =
  ["Pondelok","Utorok","Streda","Štvrtok","Piatok","Sobota","Nedeľa"];Date.y2kYear = 50;
Date.monthNumbers = {
    Jan:0,
    Feb:1,
    Mar:2,
    Apr:3,
    May:4,
    Jun:5,
    Jul:6,
    Aug:7,
    Sep:8,
    Oct:9,
    Nov:10,
    Dec:11};
Date.patterns = {
    ISO8601LongPattern:"Y-m-d H:i:s",
    ISO8601ShortPattern:"Y-m-d",
    ShortDatePattern: "n/j/Y",
    LongDatePattern: "l, F d, Y",
    FullDateTimePattern: "l, F d, Y g:i:s A",
    MonthDayPattern: "F d",
    ShortTimePattern: "g:i A",
    LongTimePattern: "g:i:s A",
    SortableDateTimePattern: "Y-m-d\\TH:i:s",
    UniversalSortableDateTimePattern: "Y-m-d H:i:sO",
    YearMonthPattern: "F, Y"};




 // --------------------------------------------------------------------------------
 /// funkcie volane z html kodu -------------- -------------------------------------
 

var allIntelisearchs = new Array();


function IsInputKeyUp(elm,ev)
{        
     
     if(!pageIsLoaded())
        return false;
    
    ev = ev || window.event;
    var id=IntelisearchInitialize(elm);
    
        
    if(allIntelisearchs[id])
    {
        // pockat chvilu ci nenapise dalsie pismeno
        if(allIntelisearchs[id]._waitTimer)
            window.clearTimeout(allIntelisearchs[id]._waitTimer);
       if(1 && !inArray(new Array(13,37,38,39,40),ev.keyCode)) // (waitForKeyup == true)
       {        
        allIntelisearchs[id]._waitTimer=window.setTimeout("allIntelisearchs['"+id+"'].sepkaj('"+ev.keyCode+"');",550);
        return false;
       }
       else
         return allIntelisearchs[id].sepkaj(ev.keyCode);
    }                   
}

function IsInputKeyDown(elm,ev)
{    
     if(!pageIsLoaded())
        return false;
    ev = ev || window.event;    
    var id=IntelisearchInitialize(elm);
    
    
    
    if(allIntelisearchs[id])
        return allIntelisearchs[id].quickMoving(ev.keyCode);
        
        
}

function IsInputBlur(elm)
{    
    var id=IntelisearchInitialize(elm);
    if(allIntelisearchs[id])
        return allIntelisearchs[id].tryHideOutput();    
}

function IsInputFocus(elm,event)
{
   IsInputKeyUp(elm,event);
}

function IsDivMouseMove(ISid)
{       
    if(allIntelisearchs[ISid])
        allIntelisearchs[ISid]._allowHide=false;   
}

function IsDivMouseOut(ISid)
{   
    if(allIntelisearchs[ISid])
        allIntelisearchs[ISid]._allowHide=true;   
}

function IsDivClick(ISid)
{       
    if(allIntelisearchs[ISid])
        allIntelisearchs[ISid]._allowHide=true; 
    allIntelisearchs[ISid].tryHideOutput();            
}


function IsSimiwordMouseOver(ISid,wordNo)
{
	
    if(!allIntelisearchs[ISid])
        return false;           
    allIntelisearchs[ISid].selectSimiword(wordNo);       
}

function IsSimiwordClick(ISid)
{
    if(!allIntelisearchs[ISid])
        return false;	
    allIntelisearchs[ISid].fillSimiword(false);    
}




function IntelisearchInitialize(elm)
{
   
   
   var id=elm.getAttribute('id');
   var propertiesStr=elm.getAttribute('is');
   var val=elm.getAttribute('value');
   var properties=getArrayFromString(propertiesStr,';','::');
   
   if(allIntelisearchs[id])
     return id;
     
     
   
     
   allIntelisearchs[id]=new intelisearch(id);     
   
   var simiwordsDiv = document.createElement('DIV');
    
    allIntelisearchs[id]._inputValue= val;
    allIntelisearchs[id]._inputId= id;
    allIntelisearchs[id]._inputElm= elm;    
    allIntelisearchs[id]._simiwordsId= simiwordsDiv.getAttribute('id');
    allIntelisearchs[id]._simiwordsElm= simiwordsDiv;
    allIntelisearchs[id]._simiwordsId_span_prefix= 'simiwords-span'+id;
    allIntelisearchs[id]._simiwordsId_p_prefix= 'simiwords-p'+id;
    
           
    allIntelisearchs[id]._aditionalPost= '&simiwordsId_span_prefix='+allIntelisearchs[id]._simiwordsId_span_prefix
                +'&simiwordsId_p_prefix='+allIntelisearchs[id]._simiwordsId_p_prefix;                  
    
   
   
      
   if(properties)
   for (var keyVal in properties)
   {
       	
        
        switch (keyVal)
        {
        	case "maxSimiwords":
                allIntelisearchs[id]._maxSimiwords= properties[keyVal];
            break;
        	case "quickMovingDelay":
                allIntelisearchs[id]._quickMovingDelay= properties[keyVal];
            break;        	
        	case "postAddress":
                allIntelisearchs[id]._postAddress= properties[keyVal];
            break;
        	case "sqlShowField": case"sqlSearchField": case"sqlCountField": case"sqlHiddenField":  case"sqlonlyBegin": case"maxChars":
                allIntelisearchs[id]._aditionalPost= allIntelisearchs[id]._aditionalPost +  '&'+keyVal+'='+properties[keyVal];
            break;
        	case"sqlAditional": 
                allIntelisearchs[id]._sqlAditional= properties[keyVal];
            break;
        	case "hiddenId":
                allIntelisearchs[id]._hiddenId= properties[keyVal];
            break;
        	case "replaceUrl":
                allIntelisearchs[id]._replaceUrl= properties[keyVal];
        	  break;        
        	case "submitForm":
                allIntelisearchs[id]._submitForm= properties[keyVal];
            break;        
        	case "simiwordsId":
                allIntelisearchs[id]._simiwordsId= properties[keyVal];
            break;        
        	case "simiwordsClass":
                simiwordsDiv.className= properties[keyVal];
            break;
            case "sqlCoordinatesFieldx":  //case "coordinatesId":         
                allIntelisearchs[id]._otherHiddens[properties[keyVal]]=new Object();
                allIntelisearchs[id]._otherHiddens[properties[keyVal]]['elmId']=properties['coordinatesId'];
                allIntelisearchs[id]._otherHiddens[properties[keyVal]]['elm']=gE(properties['coordinatesId']);

                allIntelisearchs[id]._aditionalPost= allIntelisearchs[id]._aditionalPost +  '&'+keyVal+'='+properties[keyVal];
            break;                 
            case "sqlCoordinatesFieldy":  //case "coordinatesId":                         
                allIntelisearchs[id]._aditionalPost= allIntelisearchs[id]._aditionalPost +  '&'+keyVal+'='+properties[keyVal];
            break;                 
             
            case "sqlMap_zoomField": //case "map_zoomId": 
            
                allIntelisearchs[id]._otherHiddens[properties[keyVal]]=new Object();
                allIntelisearchs[id]._otherHiddens[properties[keyVal]]['elmId']=properties['map_zoomId'];                                                                  
                allIntelisearchs[id]._otherHiddens[properties[keyVal]]['elm']=gE(properties['map_zoomId']);                
                allIntelisearchs[id]._aditionalPost= allIntelisearchs[id]._aditionalPost +  '&'+keyVal+'='+properties[keyVal];   
                                                                             
            break;        
        }    
        
        
        
   }
    
    if(allIntelisearchs[id]._hiddenId)
        allIntelisearchs[id]._hiddenElm= gE(allIntelisearchs[id]._hiddenId);
    
    if(!simiwordsDiv.className)
        simiwordsDiv.className='simiwords';    
    if(!allIntelisearchs[id]._simiwordsId)
    {
        allIntelisearchs[id]._simiwordsId='simiwords-'+id;
        simiwordsDiv.setAttribute('id',allIntelisearchs[id]._simiwordsId);        
    }
    
    var pos=getElmPosition(elm);
    var size=getElmSize(elm);
    
    simiwordsDiv.style.cssText = 'position:absolute;display:block;top:'+(pos.y+size.y)+'px;left:'+(pos.x-1)+'px;z-index:1500;width:'+(size.x)+'px;';
    
   
        
   document.body.appendChild(simiwordsDiv); 
    
    eval('allIntelisearchs[\''+id+'\']._simiwordsElm.onclick = function(){IsDivClick(\''+id+'\');};');
    eval('allIntelisearchs[\''+id+'\']._simiwordsElm.onmousemove = function(){IsDivMouseMove(\''+id+'\');};');
    eval('allIntelisearchs[\''+id+'\']._simiwordsElm.onmouseout = function(){IsDivMouseOut(\''+id+'\');};');
            
    return id; 
}




//-------------------------------------------------------------------------------------------------- 
// TRIEDY - OOP 
//-------------------------------------------------------------------------------------------------- 
/*  OOP volane len z funkcii z hora ------------------------------------------------------- **/
 


// class intelisearch - zobrazuje ako suggestions od googlu
/*
 * vyzuziva dalsie js funkcie:
 *  element gE(string elmId);
 *  element hE(string elmId);
 *  element sE(string elmId);
 *  runPhpScript(string phpScript,string post,string divId, string runFunctionAfter)
 * 
 */
function intelisearch(id) {
	
    this._id=id;   

}

intelisearch.prototype._id= '';
intelisearch.prototype._maxSimiwords= 20;
intelisearch.prototype._quickMovingDelay= 3;
intelisearch.prototype._quickMovingDelayTemp= 0;
intelisearch.prototype._inputValue= '';
intelisearch.prototype._inputId= '';
intelisearch.prototype._inputElm= 0;
intelisearch.prototype._simiwordsId= '';
intelisearch.prototype._simiwordsElm= 0;
intelisearch.prototype._simiwordsId_span_prefix= '';
intelisearch.prototype._simiwordsId_p_prefix= '';
intelisearch.prototype._waitTimer= null;
intelisearch.prototype._allowHide= true;
intelisearch.prototype._activeSimiwordNo= 0;
intelisearch.prototype._maxSimiwordNo= 0;
intelisearch.prototype._postAddress= '';
intelisearch.prototype._hiddenId= '';
intelisearch.prototype._replaceUrl= '';

intelisearch.prototype._submitForm= '';
intelisearch.prototype._hiddenValues= new Array();
intelisearch.prototype._otherHiddens= new Array();


intelisearch.prototype.tryHideOutput = function ()
{
	if(this._allowHide)
	{
	 //if(this.getElements())
		if(this._simiwordsElm)		
		{
	        hE(this._simiwordsElm);	        
	    }
    }
}



intelisearch.prototype.markText = function (begin,end)
{
	 // netreba lebo sa vola len z metod
	 //this.getElements();
	 
	 //MOZILLA/NETSCAPE support
      if (this._inputElm.selectionStart || this._inputElm.selectionStart == "0") {
           this._inputElm.selectionStart=begin;
           this._inputElm.selectionEnd=end;
      }
      //IE support
      else if (document.selection) {
          var t = this._inputElm.value.substring(begin,end);
          var r = this._inputElm.createTextRange();
          if(t)
	      {
	          r.findText(t);
              r.select();
          }
         else
         	document.selection.empty();     
      }
}


intelisearch.prototype.replaceUrl = function (val)
      {         
            
            var url=this._replaceUrl;
            url=url.replace('%value%',val);
            location.replace(url);                                  
      }

intelisearch.prototype.submitForm = function ()
      {         
          if(this._inputElm)
           this._inputElm.form.submit();
          else if(this._hiddenElm)
           this._hiddenElm.form.submit();
      }


intelisearch.prototype.fillSimiword = function (mark)
      {
         if(mark == undefined)
            mark=false;
         //this.getElements();
         
         if(row=gE(this._simiwordsId_span_prefix+this._activeSimiwordNo))
         {
             //alert(row.title);
             this._inputElm.value=row.title;
             //alert(row.title);
             
             if(mark)
                  this.markText(this._inputValue.length,this._inputElm.value.length);
             else
             	 this.markText(0,0);	       
                        
             if(this._hiddenElm)
             {
                      
                      var hiddenValues = new Array();
                      var data=row.attributes.getNamedItem("rel").value;                                           
                      var dataA=data.split('|');
                        if(dataA.length>0)
                        {
                            this._hiddenElm.value=dataA[0];
                            
                            //var alrt='';
                            for(j=1;j<dataA.length;j++)
                            {
                                if(dataA[j])
                                    arr=dataA[j].split(":");
                                else
                                    arr=null;    
                                if(arr)
                                    hiddenValues[arr[0]]=arr[1];
                                //alrt+=arr[1];    
                            }
                         }   
                //this._hiddenElm.value=row.attributes.getNamedItem("rel").value;
                this._hiddenValues=hiddenValues;   
             }   
             if(!mark && this._hiddenElm && this._hiddenElm.onchange)
                 this._hiddenElm.onchange();	 
             if(!mark && this._replaceUrl!='' && this._hiddenElm)
                 this.replaceUrl(this._hiddenElm.value);	 
             if(!mark && this._submitForm!='' && (this._inputElm || this._hiddenElm))
                 this.submitForm();
                 
             var onchanges=new Object();
                 
         if(this._hiddenValues)   
         for (id in this._otherHiddens)
         {          
            if(!this._otherHiddens[id]['elm'])
                continue;
            var nVal=this._hiddenValues[id];                                
            var oVal=this._otherHiddens[id]['elm'].value;                                                
            this._otherHiddens[id]['elm'].value=nVal;            
            if(oVal!=nVal && this._otherHiddens[id]['elm'].onchange)
               onchanges[id]=this._otherHiddens[id]['elm'].onchange;                                             
         } 
         if(!mark)
            for (keyVal in onchanges)
                onchanges[keyVal]();    	 
         }		             
                  
                  
      }
 
intelisearch.prototype.selectSimiword = function (no)
      {         
         var elmRow;
         var i;
         if(no)
         	this._activeSimiwordNo=no;

         for(i=1;i<=this._maxSimiwords;i++)
            if(elmRow=gE(this._simiwordsId_p_prefix+i))
             {
                 this._maxSimiwordNo=i;
                 if(this._activeSimiwordNo!=i)
                     remCls(elmRow,'active');
             }
         
         this._activeSimiwordNo=Math.min(this._maxSimiwordNo,this._activeSimiwordNo);
         this._activeSimiwordNo=Math.max(0,this._activeSimiwordNo);
         
         if((this._activeSimiwordNo) && (elmRow=gE(this._simiwordsId_p_prefix+this._activeSimiwordNo)))
         {
             addCls(elmRow,'active');
         }                
      }

intelisearch.prototype.quickMoving = function (keyCode)
      {         
	     
          var markit=0;
	     
	     // zabranenie odoslaniu na enter		
	     if( keyCode==13 && !this._submitForm)
	     {           	
           	return false;
         }
         
         // pokym sa to nedrzi dost dlho tak nerob nic  	      
         if(this._quickMovingDelayTemp++<this._quickMovingDelay)
             return true;
             
         // v zavislosti na stlacenej klavese    
         switch(keyCode)
         {
             case 38:
                 this.selectSimiword(this._activeSimiwordNo-1);                 
                  break;
             case 40:
                 this.selectSimiword(this._activeSimiwordNo+1);                        
                 break;
         }
         if((keyCode>=37)&&(keyCode<=40))
             markit=1;             
         this.fillSimiword(markit);
         return true;
      }             




intelisearch.prototype.sepkaj = function (keyCode)
      {
         
         
       
         var markit=0;
         
         //this.getElements();
         this._quickMovingDelayTemp=0;
         switch(keyCode)
         {
           //enter
           case 13:
              	//this.fillSimiword(markit);
              	hE(this._simiwordsElm);	                
             break;
           case 38:
             this._activeSimiwordNo=this._activeSimiwordNo-1;
             
             break;
           case 37:
             //break;
           case 39:
             this._activeSimiwordNo=0;
             break;
           case 40:
             this._activeSimiwordNo=this._activeSimiwordNo+1;
             
             break;
           default:
             this._activeSimiwordNo=0;
             if(this._inputElm.value=='')
                 hE(this._simiwordsElm);
             else
                 sE(this._simiwordsElm);
             
             if(this._inputValue!=this._inputElm.value)
             {
    	           //dorobena podpora pre moznost doplnania parametrov z hodnot objektov
                    var newval=URLDecode(this._sqlAditional);
                   
                    var pos1=newval.indexOf('[');
                    var pos2=newval.indexOf(']');
                    if(pos1!=-1 && pos2!=-1)
                    {
                        
                        var elmFromId=newval.substring(pos1+1,pos2);
                                  
                        elmFrom=gE(elmFromId);
                        if(elmFrom)
                        {
                            
                            newval=newval.substring(0,pos1)
                             + new String(elmFrom.value)
                             + newval.substring(pos2+1,newval.length);
                            
                           var sqlAditional=URLEncode(newval);                                                       
                        }
                        
                            
                        
                    }
                    if(!sqlAditional)
                       var sqlAditional= this._sqlAditional;
                    
                    var postStr='&identif='+this._inputId+'&'+this._inputId+'='+this._inputElm.value+'&maxWords='+this._maxSimiwords+this._aditionalPost;
                    if(sqlAditional)
                         postStr += '&sqlAditional='+sqlAditional;
                    
                                    
                     runPhpScript(this._postAddress,postStr,this._simiwordsId);
               }                          
                 
               this._inputValue=this._inputElm.value;             
               break;
         }
         
         
         this.selectSimiword();         
         if((keyCode>=37)&&(keyCode<=40))
             markit=1;
         this.fillSimiword(markit);
      }

             

             
             
             
             
             
             
             
 // --------------------------------------------------------------------------------
 /// funkcie volane z html kodu -------------- -------------------------------------



var allIntelitrees = new Array();

var IntelitreesPreopened = new Array();

function ItInputClick(elm,ev)
{

    if(!pageIsLoaded())
        return false;

    ev = ev || window.event;
    var id=IntelitreeInitialize(elm);
    if(allIntelitrees[id])
    {
        // to je zatvaranie ostatnych serach parts - pri vyhladavani s viacerymi stromami
        if(typeof(SearchOnOpenPart) != "undefined")
            SearchOnOpenPart(id,'ItDivClose(\''+id+'\')');

        if(!allIntelitrees[id]._nodes[1] || !allIntelitrees[id]._nodes[1]._isOpen )
           allIntelitrees[id].sepkaj(ev.keyCode);
        else
             allIntelitrees[id].hide(true);

    }
}

function ItInputKeyDown(elm,ev)
{
    ev = ev || window.event;
    var id=IntelitreeInitialize(elm);
    if(allIntelitrees[id])
        return allIntelitrees[id].quickMoving(ev.keyCode);
}

function ItInputKeyUp(elm,ev)
{
    ev = ev || window.event;
    var id=IntelitreeInitialize(elm);
    if(allIntelitrees[id])
        return allIntelitrees[id].quickMoving(ev.keyCode);
}

function ItInputBlur(elm)
{
    var id=IntelitreeInitialize(elm);
    if(allIntelitrees[id])
        return allIntelitrees[id].hide();
}

function ItInputFocus(elm,ev)
{
    return true;
    /*
    ev = ev || window.event;
    var id=IntelitreeInitialize(elm);

    if(allIntelitrees[id])
        return allIntelitrees[id].sepkaj(ev.keyCode);
        */
}

function ItDivMouseMove(ITid)
{
    if(allIntelitrees[ITid])
        allIntelitrees[ITid].hiding(false);
}

function ItDivMouseOut(ITid)
{
    if(allIntelitrees[ITid])
        allIntelitrees[ITid].hiding(true);
}

function ItDivClose(ITid)
{
    if(allIntelitrees[ITid])
        allIntelitrees[ITid].hide(true);
}




function ItOutputRowMouseOver(ITid,rowId)
{
    if(!allIntelitrees[ITid])
        return false;
    allIntelitrees[ITid].setActiveNode(rowId);
}

function ItOutputWordClick(ITid)
{
    if(!allIntelitrees[ITid])
        return false;
    allIntelitrees[ITid].wordClick();

}


function ItCheckAllClick(ITid,parentId)
{
    if(!allIntelitrees[ITid])
        return false;
    allIntelitrees[ITid].selectMulti(parentId);
    //alert(parentId);

}






function IntelitreeInitialize(elm)
{

   var id=elm.getAttribute('id');
   var propertiesStr=elm.getAttribute('it');

   var position_type;

   var properties=getArrayFromString(propertiesStr,';','::');

   if(allIntelitrees[id])
     return id;



   allIntelitrees[id]=new intelitree(id);

   var outputDiv = document.createElement('DIV');


    allIntelitrees[id]._inputId= id;
    allIntelitrees[id]._inputElm= elm;

    allIntelitrees[id]._outputElm= outputDiv;
    allIntelitrees[id]._outputId_word_prefix= 'output-word'+id;
    allIntelitrees[id]._outputId_row_prefix= 'output-row'+id;
    allIntelitrees[id]._outputId_div_prefix= 'output-div'+id;
    allIntelitrees[id]._checkAll_prefix= 'output-checkall'+id;


    allIntelitrees[id]._aditionalPost= '&outputId_word_prefix='+allIntelitrees[id]._outputId_word_prefix
                +'&outputId_row_prefix='+allIntelitrees[id]._outputId_row_prefix
                +'&outputId_div_prefix='+allIntelitrees[id]._outputId_div_prefix
                +'&checkAll_prefix='+allIntelitrees[id]._checkAll_prefix;


   allIntelitrees[id]._otherHiddens= new Object();
   allIntelitrees[id]._nodes= new Object();

   if(properties)
   for (var keyVal in properties)
   {
        switch (keyVal)
        {
            case "position":
                position_type =properties[keyVal];
            break;
            case "purposeInputId":
                allIntelitrees[id]._purposeInput= gE(properties[keyVal]);
            break;


            case "categoryInputId":
                allIntelitrees[id]._categoryInput= gE(properties[keyVal]);
            break;


            case "quickMovingDelay":
                allIntelitrees[id]._quickMovingDelay= properties[keyVal];
            break;
            case "postAddress":
                allIntelitrees[id]._postAddress= properties[keyVal];
            break;
            case "replaceUrl":
                allIntelitrees[id]._replaceUrl= properties[keyVal];
                break;
            case "sqlShowField": case"sqlSearchField": case"sqlCountField": case"sqlHiddenField": case"sqlAditional":  case "advertiserId":
                allIntelitrees[id]._aditionalPost= allIntelitrees[id]._aditionalPost +  '&'+keyVal+'='+properties[keyVal];
            break;
            case "hiddenId":
                allIntelitrees[id]._hiddenId= properties[keyVal];
            break;
            case "titleId":
                allIntelitrees[id]._titleId= properties[keyVal];
            break;
            case "outputId":
                allIntelitrees[id]._outputId= properties[keyVal];
            break;
            case "outputClass":
                outputDiv.className= properties[keyVal];
            break;
            case "allowed_treepaths_code":
                allIntelitrees[id]._aditionalPost= allIntelitrees[id]._aditionalPost +  '&'+keyVal+'='+properties[keyVal];
            break;
            case "sqlCountsTable":
                allIntelitrees[id]._aditionalPost= allIntelitrees[id]._aditionalPost +  '&'+keyVal+'='+properties[keyVal];
                allIntelitrees[id]._sqlCountsTable= properties[keyVal];
            break;
            case "useMultiple":
                allIntelitrees[id]._aditionalPost= allIntelitrees[id]._aditionalPost +  '&'+keyVal+'='+properties[keyVal];
                allIntelitrees[id]._useMultiple= properties[keyVal];
            break;
            case "sqlCoordinatesField":  //case "coordinatesId":
                allIntelitrees[id]._otherHiddens[properties[keyVal]]=new Object();
                allIntelitrees[id]._otherHiddens[properties[keyVal]]['elmId']=properties['coordinatesId'];
                allIntelitrees[id]._otherHiddens[properties[keyVal]]['elm']=gE(properties['coordinatesId']);

                allIntelitrees[id]._aditionalPost= allIntelitrees[id]._aditionalPost +  '&'+keyVal+'='+properties[keyVal];
            break;
            case "sqlMap_zoomField": //case "map_zoomId":
                allIntelitrees[id]._otherHiddens[properties[keyVal]]=new Object();
                allIntelitrees[id]._otherHiddens[properties[keyVal]]['elmId']=properties['map_zoomId'];
                allIntelitrees[id]._otherHiddens[properties[keyVal]]['elm']=gE(properties['map_zoomId']);

                allIntelitrees[id]._aditionalPost= allIntelitrees[id]._aditionalPost +  '&'+keyVal+'='+properties[keyVal];
            break;

        }
   }

    if(allIntelitrees[id]._titleId)
        allIntelitrees[id]._titleElm= gE(allIntelitrees[id]._titleId);

    if(allIntelitrees[id]._useMultiple)
    {
        if(allIntelitrees[id]._titleElm)
            allIntelitrees[id]._inputValue= allIntelitrees[id]._titleElm.innerHTML;
    }
    else
        allIntelitrees[id]._inputValue= elm.getAttribute('value');

    allIntelitrees[id]._hiddenElm= gE(allIntelitrees[id]._hiddenId);

    allIntelitrees[id]._selectedNodesNos= new Object();


    if(!outputDiv.className)
        outputDiv.className='rollout';
    if(!allIntelitrees[id]._outputId)
    {
        allIntelitrees[id]._outputId='itoutput-'+id;
    }

    outputDiv.setAttribute('id',allIntelitrees[id]._outputId);


    var pos=getElmPosition(elm);
    var size=getElmSize(elm);
    var cssProps='';
    cssProps = 'position:absolute;display:block;z-index:500;width:'+size.width+'px;';
    switch(position_type)
        {
            case "right":
                cssProps  = cssProps +  'top:'+(pos.y)+'px;left:'+(pos.x+size.x)+'px;';
            break;
            case "bottom":
            default:

                cssProps = cssProps + 'top:'+(pos.y+size.y)+'px;left:'+(pos.x)+'px;';
            break;
        }
    outputDiv.style.cssText =   cssProps ;
    outputDiv.innerHTML = '<i></i>'
                           +'     <i class="cor tr"></i>'
                           +'     <i class="cor bl"></i>'
                           +'     <a class="close" title="close"  href="#" onclick="ItDivClose(\''+id+'\');return false;"><span>X</span></a>'
                           +'     <div class="content" id="'+allIntelitrees[id]._outputId_div_prefix+'"></div>';


   document.body.appendChild(outputDiv);

    eval('allIntelitrees[\''+id+'\']._outputElm.onmousemove = function(){ItDivMouseMove(\''+id+'\');};');
    eval('allIntelitrees[\''+id+'\']._outputElm.onmouseout = function(){ItDivMouseOut(\''+id+'\');};');

    return id;
}





//--------------------------------------------------------------------------------------------------
// TRIEDY - OOP
//--------------------------------------------------------------------------------------------------




// class Intelitree - zobrazuje ako suggestions od googlu
/*
 * vyzuziva dalsie js funkcie:
 *  element gE(string elmId);
 *  element hE(string elmId);
 *  element sE(string elmId);
 *  runPhpScript(string phpScript,string post,string divId, string runFunctionAfter)
 *
 */
function intelitree() {
	this._activeNodeNo=0;

}

intelitree.prototype._hideAfterOutTimer= 0;
intelitree.prototype._hideAfterOutDelay= 2000;
intelitree.prototype._quickMovingDelay= 0;
intelitree.prototype._quickMovingDelayTemp= 0;
intelitree.prototype._inputValue= '';
intelitree.prototype._inputId= '';
intelitree.prototype._inputElm= 0;
intelitree.prototype._outputId= '';
intelitree.prototype._outputElm= 0;
intelitree.prototype._outputId_row_prefix= '';
intelitree.prototype._outputId_word_prefix= '';
intelitree.prototype._outputId_div_prefix= '';
intelitree.prototype._checkAll_prefix= '';
intelitree.prototype._allowHide= true;
intelitree.prototype._postAddress= '';
intelitree.prototype._replaceUrl= '';

intelitree.prototype._hiddenId= '';
intelitree.prototype._otherHiddens= null;
intelitree.prototype._useMultiple= false;
intelitree.prototype._sqlCountsTable= 'liv_counts';

intelitree.prototype._nodes= null;
intelitree.prototype._activeNodeNo= 0;
intelitree.prototype._selectedNodesNos= null;


intelitree.prototype._aditionalPost = '';

// to je na prenasanie udajov pre strom - zobrazit len tie vetcy v ktorych je aspn jeden inzerat
intelitree.prototype._purposeInput= null;
intelitree.prototype._categoryInput= null;
intelitree.prototype._purposeLastValue= '';
intelitree.prototype._categoryLastValue= '';




// otvaranie / skryvanie ---------------------------------------------

// pociatocny bod
intelitree.prototype.sepkaj = function (keyCode)
      {
           // ak sa nieco zmenilo v zavislych fieldoch - purpose a category tak to treba resetnut

           if(this._purposeInput || this._categoryInput)
           {
                if((this._purposeInput && this._purposeLastValue!=this._purposeInput.value)
                        || (this._categoryInput && this._categoryLastValue!=this._categoryInput.value))
                this.clearData();
                if(this._categoryInput)
                    this._categoryLastValue=this._categoryInput.value;
                if(this._purposeInput)
                    this._purposeLastValue=this._purposeInput.value;
           }
           // prvotne otvorenie
           // ak uz nebolo otvorene
           //if(!this._nodes[this._activeNodeNo])
           // ak uz nebolo otvorene alebo ak bola chyba pri Ajax loade
           if(!this._nodes[this._activeNodeNo] || this._nodes[this._activeNodeNo]._error)
           {

               this._quickMovingDelayTemp=0;
               this._activeNodeNo=1;
               if(!this._nodes[this._activeNodeNo])
               {
                   this._nodes[this._activeNodeNo]=new Object();
                   // nastavit tie co su poslane ako oznacene
                   this.preselectRecursive();
               }
               //zobrazit deti
               this.showChilds();
           }
           // taka VYNIMKA pre ie - skryt selecty
           hideSelects(document);



           sE(this._outputElm);
           this._nodes[1]._isOpen=true;
      }


// skryt intelitree
intelitree.prototype.hide = function (forced)
{
	if(forced == undefined)
        forced=false;
    if(this._allowHide || forced)
	{
		if(this._outputElm)
		{
	        hE(this._outputElm);
            this._nodes[1]._isOpen=false;
	    }

        // taka VYNIMKA pre ie
        showSelects(document);

    }



}

// skryt za nejaky cas
intelitree.prototype.hiding = function (set)
{
   if(set)
   {
   	this._allowHide=true;
   	this._hideAfterOutTimer=window.setTimeout('allIntelitrees[\''+this._inputId+'\'].hide()',this._hideAfterOutDelay);
   }
   else
   {
   	this._allowHide=false;
   	window.clearTimeout(this._hideAfterOutTimer);
   }
}



// nastavenie a zistenie vlastnosti nodov ---------------------------------------------


intelitree.prototype.clearData = function ()
{

    delete this._nodes;
    this._nodes= new Object();
    delete this._selectedNodesNos;
    this._selectedNodesNos= new Object();
    this._activeNodeNo= 0;
    if(gE(this._outputId_div_prefix))
        gE(this._outputId_div_prefix).innerHTML='';
}


intelitree.prototype.isSelected = function (id)
{
    if(this._selectedNodesNos[id] > 0)
        return this._selectedNodesNos[id];
    else
        return 0;
}

intelitree.prototype.preselectRecursive = function ()
{
        if(!this._hiddenElm.value)
            return false;

        var treepaths=new Object();
        treepaths=this._hiddenElm.value.split(',');
        if(!treepaths)
            return false;

        var openIds=new Array();

        for(keyVal in treepaths)
        {
            var onepath=new String(treepaths[keyVal]);
            //alert(keyVal +' '+ onepath+": "+typeof(onepath));
            if(onepath == undefined)
                continue;
            var i=0;
            for(i=0;i<onepath.length;i+=6)
            {
                idTemp_str=onepath.substr(i,6);
                idTemp=Number(idTemp_str);
                IntelitreesPreopened[idTemp]=(  i+6 == onepath.length   ? 1:2);
            }
        }
}


intelitree.prototype.selectMulti = function (parentId,forced)
{


     // alert('f:'+forced);

    // nies u selectnute ziadne, alebo len niektore, alebo je to ziadane forced
    if(0 == this.isSelected(parentId) || 2 == this.isSelected(parentId) || forced)
    {

        if(parentId!=1)
            this.selectNode(parentId);
        for(keyVal in this._nodes)
        {
            if(this._nodes[keyVal]._parentId == parentId)
                this.selectNode(keyVal,false);
        }
        this._nodes[parentId]._childsFullSelectedCount=this._nodes[parentId]._childsCount;
        this._nodes[parentId]._childsPartSelectedCount=0;//this._nodes[parentId]._childsCount;

    }
    else
    {
        if(parentId != 1)
            this.unselectNode(parentId);

        for(keyVal in this._nodes)
        {
            if(this._nodes[keyVal]._parentId == parentId)
                this.unselectNode(keyVal,false);
        }
        this._nodes[parentId]._childsFullSelectedCount=0;
        this._nodes[parentId]._childsPartSelectedCount=0;

    }

    this.fill();
    this.setParentClass(parentId);

    return 1;



}



intelitree.prototype.selectNode = function (id,parentControl,setValue)
{
    //alert(id + ': '+ setValue);
    if(parentControl == undefined)
        parentControl=true;
    if(setValue == undefined)
        setValue=1;

    var oldValue=this._selectedNodesNos[id];
    if(setValue == 0)
        delete this._selectedNodesNos[id]; //=false;
    else
        this._selectedNodesNos[id]=setValue;



    //zmena aj rodica ak treba
    var parentId=this._nodes[id]._parentId;
    if(parentControl && id>1 && parentId)
    {
        if(oldValue == 1)
           this._nodes[parentId]._childsFullSelectedCount--;
        if(oldValue == 2)
           this._nodes[parentId]._childsPartSelectedCount--;

        if(setValue == 1)
           this._nodes[parentId]._childsFullSelectedCount++;
        if(setValue == 2)
           this._nodes[parentId]._childsPartSelectedCount++;



        var parentValue=0;

       if(this._nodes[parentId]._childsFullSelectedCount >= this._nodes[parentId]._childsCount)
          parentValue=1;
       else if (this._nodes[parentId]._childsPartSelectedCount + this._nodes[parentId]._childsFullSelectedCount > 0)
         parentValue=2;
       else if (this._nodes[parentId]._childsPartSelectedCount == 0 && this._nodes[parentId]._childsFullSelectedCount == 0)
         parentValue=0;


       //  alert('pocet deti:' + this._nodes[parentId]._childsCount + ', pocet d.sel-full:' + this._nodes[parentId]._childsFullSelectedCount +', pocet d.sel-part:' + this._nodes[parentId]._childsPartSelectedCount +', selected-val: ' +parentValue);

       this.selectNode(parentId,true,parentValue);
        if(parentId!=1)
           this.setParentClass(parentId);

     }




     var elmWord=this._nodes[id]._elmWord;
     var elmImg=gE(this._checkAll_prefix+id);

      if(elmWord)
      {
          if(setValue == 0)
            remCls(elmWord,'select');
          else
            addCls(elmWord,'select');
      }

      if(elmImg)
      {
          if(setValue == 1)
          {
            elmImg.src='http://static.living.sk/roll_check_region_active.png';
            addCls(elmImg,'select');
          }
          else
          {
          	elmImg.src='http://static.living.sk/roll_check_region.png';
            remCls(elmImg,'select');
          }
      }




}

intelitree.prototype.unselectNode = function (id,parentControl)
{
     if(parentControl == undefined)
        parentControl=true;


     return this.selectNode(id,parentControl,0)

}


intelitree.prototype.setActiveNode = function (id,dontRemoveOthers)
  {
     var elmRow;
     var i;

     // nastavit aktivny riadok/node na tento
     if(id)
        this._activeNodeNo=id;

   if((this._activeNodeNo) && (elmWord=this._nodes[this._activeNodeNo]._elmWord))
    {
         this._nodes[this._activeNodeNo]._isActive=true;
         addCls(elmWord,'hover');
    }

    if(true != dontRemoveOthers)
        for(var idTemp in this._nodes)
        {
           if(idTemp!=id && this._nodes[idTemp]._isActive)
           {
             elmWord=this._nodes[idTemp]._elmWord;
             remCls(elmWord,'hover');
             this._nodes[idTemp]._isActive=false;
           }
        }
  }


// otvaranie a zobrazovanie deti ---------------------------------------------

intelitree.prototype.hideChilds = function(forced)
{
    if(forced == undefined)
        forced=false;
    if(this._activeNodeNo==1)
         var elmId=this._outputId_div_prefix;
     else
         var elmId=this._outputId_div_prefix+this._activeNodeNo;
    var elm=gE(elmId);

    //if(this._nodes[this._activeNodeNo]._isOpen)
    {
        // skryt deti
        hE(elm);
        // odstranit deti naozaj
        if(!this._useMultiple || forced)
        {
            elm.innerHTML='';
            this.removeChilds(this._activeNodeNo);
        }
        // nastavit ako zatvorene
        this._nodes[this._activeNodeNo]._isOpen=false;
        remCls(this._nodes[this._activeNodeNo]._elmWord,'act');
    }
}
intelitree.prototype.showChilds = function(setactiveFirst,selectAll,afterScript)
{

    if(setactiveFirst == undefined)
        setactiveFirst=true;
    if(selectAll == undefined)
        selectAll=false;

    if(afterScript == undefined)
        afterScript='';


    if(this._activeNodeNo==1)
         var elmId=this._outputId_div_prefix;
     else
         var elmId=this._outputId_div_prefix+this._activeNodeNo;

    //alert(elmId);
    var elm=gE(elmId);
    //if(!this._nodes[this._activeNodeNo]._isOpen)
    {
        if(!elm)
        {
          elm=document.createElement('DIV');
          elm.setAttribute('id',elmId);
          this._nodes[this._activeNodeNo]._elmRow.appendChild(elm);
        }

        // nacitat obsah nazivo
        //if(!this._useMultiple || !elm.innerHTML)
        if(!this._useMultiple || !elm.innerHTML )
        {
            var postquery='&identif='+this._inputId+'&parentId='+this._activeNodeNo+''+this._aditionalPost;
            if(this._useMultiple)
            {
               if(this._purposeInput)
                postquery+= '&purpose='+this._purposeInput.value;
               if(this._categoryInput)
                postquery+= '&category='+this._categoryInput.value;
               // else 	alert(this._categoryInput);
            }
            runPhpScript(this._postAddress+postquery,
                -1,
                elmId,
                'allIntelitrees[\''+this._inputId+'\'].getChilds('+this._activeNodeNo+','+setactiveFirst+','+selectAll+');'
                    +afterScript);
        }
        // zobrazit
        sE(elm);
        this._nodes[this._activeNodeNo]._isOpen=true;
        addCls(this._nodes[this._activeNodeNo]._elmWord,'act');
    }



}


intelitree.prototype.getChilds = function (parentId,setactiveFirst,selectAll)
{
    var data,dataA,lastId,id,pathTree,childsCount,generation,title,hiddenValue,beforeId,afterId;
    if(parentId==1)
        var parentElm=gE(this._outputId_div_prefix);
    else
        var parentElm=gE(this._outputId_div_prefix+parentId);




    if(!parentElm)
    {
        alert(parentId+' not-exists:'+this._outputId_div_prefix+parentId);
        return 0;
    }
    var childsElms=parentElm.getElementsByTagName('li');

    if(this._nodes[parentId])
    {
        this._nodes[parentId]._elmCheckall=gE(this._checkAll_prefix+parentId);

        if(this._nodes[parentId]._childsCount > 0 && childsElms.length==0)
            this._nodes[parentId]._error=1;
        else
            this._nodes[parentId]._error=0;
        this._nodes[parentId]._childsCount=childsElms.length;
    }

    lastId=0;
    var arr;
    var hiddenValues=new Array();
    for (var i=0; i<childsElms.length; i++)
    {
        data=childsElms[i].attributes.getNamedItem("rel").value;
        dataA=data.split('|');
        if(dataA.length>0)
        {
            id=dataA[0];
            parentIdtemp=dataA[1];
            pathTree=dataA[2];
            childsCount=dataA[3];
            generation=dataA[4];
            title=dataA[5];
            hiddenValue=dataA[6];

            var alrt='';
            for(j=7;j<dataA.length;j++)
            {
                if(dataA[j])
                    arr=dataA[j].split(":");
                else
                    arr=null;
                if(arr)
                    hiddenValues[arr[0]]=arr[1];
                //alrt+=arr[1];
            }
            //alert(title+alrt);
            beforeId=lastId;
            afterId=0;
            wordElm=gE(this._outputId_word_prefix+id).parentNode;
            this.addNode(id,parentIdtemp,pathTree,childsCount,generation,title,hiddenValue,childsElms[i],wordElm,beforeId,afterId,hiddenValues);
            if(beforeId)
                this._nodes[beforeId]._afterId=id;
            lastId=id;
            if(setactiveFirst && i==0)
                this.setActiveNode(id);
        }
        //
        // zobrazenie dalsich generacii ak su preopened
        if(IntelitreesPreopened && IntelitreesPreopened[id] > 0)
        {
            //alert('opening '+id);
            this.setActiveNode(id,true);
            this.selectNode(this._activeNodeNo,true,IntelitreesPreopened[id]);
            if(IntelitreesPreopened[id] == 2)
                this.showChilds(false);
            delete IntelitreesPreopened[id];
        }



    }


    // ak su deti a useMultiple a  je o to poziadane tak checkni vsetky
    if(this._nodes[parentId]._childsCount && this._useMultiple && selectAll )
    {

            this.selectMulti(parentId,true);
    }

}



intelitree.prototype.removeChilds = function (parentId)
{
    for(var idTemp in this._nodes)
        {
           if(this._nodes[idTemp]._parentId==parentId)
             delete this._nodes[idTemp];
           if(this._useMultiple)
                this.unselectNode(idTemp);
        }
}




intelitree.prototype.addNode = function (id,parentId,pathTree,childsCount,generation,title,hiddenValue,elmRow,elmWord,beforeId,afterId,hiddenValues)
	{
		this._nodes[id]=new intelitreeNode();
		this._nodes[id]._parentId=parentId;
		this._nodes[id]._pathTree=pathTree;
		this._nodes[id]._childsCount=childsCount;
		this._nodes[id]._generation=generation;
		this._nodes[id]._title=title;
		this._nodes[id]._hiddenValue=hiddenValue;
		this._nodes[id]._beforeId=beforeId;
		this._nodes[id]._afterId=afterId;
		this._nodes[id]._isOpen=false;
		this._nodes[id]._isActive=false;
		this._nodes[id]._elmRow=elmRow;
		this._nodes[id]._elmWord=elmWord;
        this._nodes[id]._hiddenValues=new Object();
        for (keyVal in hiddenValues)
            this._nodes[id]._hiddenValues[keyVal]=hiddenValues[keyVal];
	}






intelitree.prototype.setParentClass = function (parentId)
{

    if(  0 < this.isSelected(parentId) )
        addCls(this._nodes[parentId]._elmWord,'select');
    else
        remCls(this._nodes[parentId]._elmWord,'select');

}

// ovladanie klavesnicou --------
intelitree.prototype.quickMoving = function (keyCode)
      {


	     // zabranenie odoslaniu na enter
	     if( keyCode==13)
	     {
           	this.fill();
           	this.hide(true);
           	return false;
         }

         this.hiding(false);

         if(!this._nodes[1]._isOpen)
            {
                this.sepkaj();
            }

         // pokym sa to nedrzi dost dlho tak nerob nic
         if(this._quickMovingDelayTemp++<this._quickMovingDelay)
             return true;

         this._quickMovingDelayTemp=0;
         switch(keyCode)
         {

          // hore
           case 38:
             if(this._nodes[this._activeNodeNo]._beforeId)
                this.setActiveNode(this._nodes[this._activeNodeNo]._beforeId);

             break;
             // dolava - zavriet
           case 37:
             if(this._nodes[this._activeNodeNo]._parentId)
             {
                this.setActiveNode(this._nodes[this._activeNodeNo]._parentId);
                this.hideChilds();
             }
             break;

           // doprava - otvorit
           case 39:
             this.showChilds();
             break;

           // dole
           case 40:
             if(this._nodes[this._activeNodeNo]._afterId)
                  this.setActiveNode(this._nodes[this._activeNodeNo]._afterId);
             break;
           //medzera
           case 32:
             this.fill();
             this.hide(true);
             break;


            default:
                ;//alert(keyCode);
            break;
         }

         return true;

      }


intelitree.prototype.wordClick = function ()
{
	//to je node na ktorom sa nachadz amis alebo kurzor
    //alert(this._activeNodeNo);
    //return true;



    // ak ma deti
    if(this._nodes[this._activeNodeNo] && this._nodes[this._activeNodeNo]._childsCount>0 )
    {
        if(this._nodes[this._activeNodeNo]._isOpen)
            this.hideChilds();
        else
        {

           var selectAll = ( 1 == this.isSelected(this._activeNodeNo) && !this._nodes[this._activeNodeNo]._isOpen );
           this.showChilds(false,selectAll);
        }
    }
    // ak nema deti
    else
    {
        // ak nie je MODE multiple tak rovno vyber
        if(!this._useMultiple)
           this.hide(true);

        // inak selectni
        else
        {
            if(0 == this.isSelected(this._activeNodeNo))
                this.selectNode(this._activeNodeNo);
            else
                this.unselectNode(this._activeNodeNo);
         }
         this.fill();
    }

}



intelitree.prototype.fill = function ()
      {
         // vyplni hidden field hodnotami na spracovanie

         if(this._useMultiple)
         {

            var req='';
            var title='';
            for(keyVal in this._selectedNodesNos)
            {

                // tie co su uplne oznacene a zaroven nemaju upne oznacenych rodicov
                if(1 == this._selectedNodesNos[keyVal]  &&  1 !== this._selectedNodesNos[this._nodes[keyVal]._parentId]  )
                    if(this._nodes[keyVal])
                            {
                                req+=this._nodes[keyVal]._hiddenValue+',';
                                title+=this._nodes[keyVal]._title+',';
                            }


            }


            if(!title)
            {
                title=this._inputValue;
                if(this._categoryInput)
                    title='Vyber lokalitu...';//this._inputValue;
                else
                    title='Vyber kategóriu...';//this._inputValue;
            }
            else
                title=title.substr(0,title.length-1);
            this._titleElm.innerHTML=title;
            this._titleElm.title=title;


            this._hiddenElm.value=req;
            if(this._hiddenElm.onchange)
                this._hiddenElm.onchange();
         }
         else
         {
             if(this._nodes[this._activeNodeNo]._hiddenValue)
                this._hiddenElm.value=this._nodes[this._activeNodeNo]._hiddenValue;
             if(this._nodes[this._activeNodeNo]._title)
                this._inputElm.value=this._nodes[this._activeNodeNo]._title;
             this._allowHide=true;
             if(this._hiddenElm.onchange)
                this._hiddenElm.onchange();
             else if(this._replaceUrl!='' && this._hiddenElm)
                 this.replaceUrl(this._hiddenElm.value);

         }

         var onchanges=new Object();

         if(this._nodes[this._activeNodeNo]._hiddenValues)
         for (id in this._otherHiddens)
         {
            if(!this._otherHiddens[id]['elm'])
                continue;
            var nVal=this._nodes[this._activeNodeNo]._hiddenValues[id];
            var oVal=this._otherHiddens[id]['elm'].value;
            this._otherHiddens[id]['elm'].value=nVal;
            if(oVal!=nVal && this._otherHiddens[id]['elm'].onchange)
               onchanges[id]=this._otherHiddens[id]['elm'].onchange;
         }

         for (keyVal in onchanges)
            onchanges[keyVal]();
      }



intelitree.prototype.replaceUrl = function (val)
      {

            var url=this._replaceUrl;
            url=url.replace('%value%',val);
            location.replace(url);
      }



/* class intelitreeNode ---------
 *
*/

function intelitreeNode() {


}
intelitreeNode.prototype._parentId=0;
intelitreeNode.prototype._childsCount=0;
intelitreeNode.prototype._childsPartSelectedCount=0;
intelitreeNode.prototype._childsFullSelectedCount=0;
intelitreeNode.prototype._childsOpenedCount=0;
intelitreeNode.prototype._generation=0;
intelitreeNode.prototype._treePath='';
intelitreeNode.prototype._title='';
intelitreeNode.prototype._beforeId='';
intelitreeNode.prototype._afterId='';
intelitreeNode.prototype._isOpen='';
intelitreeNode.prototype._isActive='';
intelitreeNode.prototype._elmRow=0;
intelitreeNode.prototype._elmWord=0;
intelitreeNode.prototype._elmCheckall=0;
intelitreeNode.prototype._error=0;
intelitreeNode.prototype._hiddenValues=new Array();






var QuickTitleActive=new Array();
var allQuickTitlesDivs= new Array();

// toto sa musi volat v onmouseover pre element
function QuickTitleShow(elm,type)
{

    if(!pageIsLoaded())
        return false;


    if(!elm)
        return false;
    if(type==undefined)
        type=1;

    if(!allQuickTitlesDivs[type])
    {
        QuickTitleInitialize(type);
        attachEventUni(document,'onmousemove',getMouseXY);
        attachEventUni(document,'onmousemove',QuickTitleMove);
    }



    QuickTitleSetElm(elm,type);



}

function QuickTitleSetElm(elm,type)
{



    if('1' == elm.getAttribute('qtact'))
        return false;


    // vratit title staremu objektu
     if(QuickTitleActive['title'] && (!QuickTitleActive['object'].getAttribute('title')) )
    {
        QuickTitleActive['object'].setAttribute('title',QuickTitleActive['title']);
        // nastavit ze uz nie je aktivny
        QuickTitleActive['object'].setAttribute('qtact','');
    }

    elm.setAttribute('qtact','1');
     // nastavit objekt do globalnej premennej
    QuickTitleActive['object']=elm;
    // nastavit title do premennej
    QuickTitleActive['title']=elm.getAttribute('title');
    // nastavit hranicne body pre objekt
    var pos=getElmPosition(elm);
    var size=getElmSize(elm);
    QuickTitleActive['minX']=pos.x;
    QuickTitleActive['maxX']=pos.x+size.x;
    QuickTitleActive['minY']=pos.y;
    QuickTitleActive['maxY']=pos.y+size.y;
    // odobrat title
    elm.setAttribute('title','');

    if(QuickTitleActive && QuickTitleActive['type']!=type && QuickTitleActive['div'])
    	hE(QuickTitleActive['div']);
    // nastavit divko
    QuickTitleActive['div']=allQuickTitlesDivs[type]['outer_elm'];
    QuickTitleActive['type']=type;

    // zobrazit divko s titlom
    wE(allQuickTitlesDivs[type]['inner_elm'],replaceAll(QuickTitleActive['title'],'|','<br>'));
    sE(QuickTitleActive['div']);
}


// toto sa musi volat v onmousemove pre document
function QuickTitleMove()
{

    // skontrolovat ci je pozicia mysi v objekte
    var pos=getMouseCoords(-1);

    // ak ano
    if((pos.x>=QuickTitleActive['minX'] && pos.x<=QuickTitleActive['maxX']) && (pos.y>=QuickTitleActive['minY'] && pos.y<=QuickTitleActive['maxY']))
    {

        // nastavit divku suradnice
        if(QuickTitleActive['div'])
        {
        QuickTitleActive['div'].style.left=(pos.x+8)+'px';
        QuickTitleActive['div'].style.top=(pos.y+8)+'px';
        }
    }
    // ak nie
    else
    {
        //wE(gE('category-sel'),QuickTitleActive['title']+pos.x+'-no');
        // skryt divko
        if(QuickTitleActive['div'])
        	hE(QuickTitleActive['div']);
        // vratit title objektu ak je prazdne
        if(!QuickTitleActive['object'].getAttribute('title'))
            QuickTitleActive['object'].setAttribute('title',QuickTitleActive['title']);
        // nastavit ze uz nie je aktivny
        QuickTitleActive['object'].setAttribute('qtact','');
    }


}

function QuickTitleInitialize(type)
{
    allQuickTitlesDivs[type] = new Array();



    switch (type)
    {
        default:
        case '1':
             var outerdiv = document.createElement('DIV');
             outerdiv.setAttribute('id','quicktitle-type'+type);
             outerdiv.style.cssText = 'position:absolute;display:block;';
             outerdiv.className = type;
             outerdiv.innerHTML = '';
             var innerelm=outerdiv;
             document.body.appendChild(outerdiv);

        break;
    }

    allQuickTitlesDivs[type]['inner_elm']=innerelm;
    allQuickTitlesDivs[type]['outer_elm']=outerdiv;


    return true;
}


     var perline = 9;
     var divSet = false;
     var curId;
     var myfield;
     var colorLevels = Array('0', '3', '6', '9', 'C', 'F');
     var colorArray = Array();
     var ie = false;
     var nocolor = 'none';
	 if (document.all) { ie = true; nocolor = ''; }
	 function getObj(id) {
		if (ie) { return document.all[id]; } 
		else {	return document.getElementById(id);	}
	 }

     function addColor(r, g, b) {
     	var red = colorLevels[r];
     	var green = colorLevels[g];
     	var blue = colorLevels[b];
     	addColorValue(red, green, blue);
     }

     function addColorValue(r, g, b) {
     	colorArray[colorArray.length] = '#' + r + r + g + g + b + b;
     	//colorArray[colorArray.length] = '' + r + r + g + g + b + b;
     }
     
     function setColor(color) {
     	var link = getObj(curId);
     	var field = getObj(myfield);
     	var picker = getObj('colorpicker');
     	
     	field.value = color.substring(1,color.length);
     	//field.value.substring(1,field.value.length);
     	if (color == '') {
	     	link.style.background = nocolor;
	     	link.style.color = nocolor;
	     	color = nocolor;
     	} else {
	     	link.style.background = color;
	     	link.style.color = color;
	    }
     	picker.style.display = 'none';
	    //alert(curId + myfield);
	    //eval(getObj(curId + myfield).title);
     }
        
     function setDiv(id) {     
     	if (!document.createElement) { return; }
        var elemDiv = document.createElement('div');
        if (typeof(elemDiv.innerHTML) != 'string') { return; }
        genColors();
        elemDiv.id = 'colorpicker';
	    elemDiv.style.position = 'absolute';
        elemDiv.style.display = 'none';
        elemDiv.style.border = '#000000 1px solid';
        elemDiv.style.background = '#FFFFFF';
        elemDiv.innerHTML = '<span style="font-family:Verdana; font-size:11px;">' 
          	+ '[<a href="javascript:setColor(\'\');">X Zrus</a>]<br>' 
        	+ getColorTable() 
        	+ '<center></center></span>';
;
        
        var t_name =  id+"holder";
        document.getElementById(t_name).appendChild(elemDiv);
        divSet = true;
     }
     
     function pickColor(id,field) {
     	if (!divSet) { setDiv(id); }
     	var picker = getObj('colorpicker');     	
		if (id == curId && picker.style.display == 'block') {
			picker.style.display = 'none';
			return;
		}
     	curId = id;
     	var thelink = getObj(id);
     	myfield = field;
     	
     	picker.style.top = getElementPosition(id).top;
     	picker.style.left = getElementPosition(id).left;
     	//alert(getElementPosition(id).top+' '+getElementPosition(id).left);
		picker.style.display = 'block';
     }
     
     function genColors() {
        addColorValue('0','0','0');
        addColorValue('3','3','3');
        addColorValue('6','6','6');
        addColorValue('8','8','8');
        addColorValue('9','9','9');                
        addColorValue('A','A','A');
        addColorValue('C','C','C');
        addColorValue('E','E','E');
        addColorValue('F','F','F');                                
			
        for (a = 1; a < colorLevels.length; a++)
			addColor(0,0,a);
        for (a = 1; a < colorLevels.length - 1; a++)
			addColor(a,a,5);

        for (a = 1; a < colorLevels.length; a++)
			addColor(0,a,0);
        for (a = 1; a < colorLevels.length - 1; a++)
			addColor(a,5,a);
			
        for (a = 1; a < colorLevels.length; a++)
			addColor(a,0,0);
        for (a = 1; a < colorLevels.length - 1; a++)
			addColor(5,a,a);
			
			
        for (a = 1; a < colorLevels.length; a++)
			addColor(a,a,0);
        for (a = 1; a < colorLevels.length - 1; a++)
			addColor(5,5,a);
			
        for (a = 1; a < colorLevels.length; a++)
			addColor(0,a,a);
        for (a = 1; a < colorLevels.length - 1; a++)
			addColor(a,5,5);

        for (a = 1; a < colorLevels.length; a++)
			addColor(a,0,a);			
        for (a = 1; a < colorLevels.length - 1; a++)
			addColor(5,a,5);
			
       	return colorArray;
     }
     function getColorTable() {
         var colors = colorArray;
      	 var tableCode = '';
         tableCode += '<table border="0" cellspacing="1" cellpadding="1">';
         for (i = 0; i < colors.length; i++) {
              if (i % perline == 0) { tableCode += '<tr>'; }
              tableCode += '<td bgcolor="#000000"><a style="width:13px; display:block; outline: 1px solid #000000; color: ' 
              	  + colors[i] + '; background: ' + colors[i] + ';font-size: 10px;" title="' 
              	  + colors[i] + '" href="javascript:setColor(\'' + colors[i] + '\');">&nbsp;&nbsp;&nbsp;</a></td>';
              if (i % perline == perline - 1) { tableCode += '</tr>'; }
         }
         if (i % perline != 0) { tableCode += '</tr>'; }
         tableCode += '</table>';
      	 return tableCode;
     }
     function relateColor(id, color) {
     	var link = getObj(id);
     	if (color == '') {
	     	link.style.background = nocolor;
	     	link.style.color = nocolor;
	     	color = nocolor;
     	} else {
	     	link.style.background = color;
	     	link.style.color = color;
	    }
	    eval(getObj(id + 'field').title);
     }

     
     function getElementPosition(elemID){
		var offsetTrail = document.getElementById(elemID);
		var offsetLeft = 0;
		var offsetTop = 0;
		while (offsetTrail){
			offsetLeft += offsetTrail.offsetLeft;
			offsetTop += offsetTrail.offsetTop;
			offsetTrail = offsetTrail.offsetParent;
		}
		if (navigator.userAgent.indexOf('Mac') != -1 && typeof document.body.leftMargin != 'undefined'){
			offsetLeft += document.body.leftMargin;
			offsetTop += document.body.topMargin;
		}
		return {left:offsetLeft,top:offsetTop};
	}
     
