function popup(href,name,width,height,r)
{
        popupWindow=window.open(href, name, 'toolbar=no,location=no,directories=no,status=no,menubar=no,scrollbars=no,resizable=no,width='+width+',height='+height);
        popupWindow.opener=window;

        if( r!=null )
	        return popupWindow;
}

function popupScroll(href,name,width,height,r)
{
        popupWindow=window.open(href, name, 'toolbar=no,location=no,directories=no,status=no,menubar=no,scrollbars=yes,resizable=no,width='+width+',height='+height);
        popupWindow.opener=window;

        if( r!=null )
        	return popupWindow;
}

function closeAndRedirect() {
	obj=window;
	var loop=true;

	var quit=false;

	while(!quit) {
		loop=true;
		while(loop) {
			if(obj.parent && obj.parent!=obj)
				obj=obj.parent;
			else {
				loop=false;
				quit=true;
			}
		}

		loop=true;
		while(loop) {
			if( obj.opener ) {
				obj.opener.location='SessionExpired.jsp';
				obj.close();

				obj=obj.opener;
				quit=false;
			}
			else
				loop=false;
		}
	}

	obj.location='SessionExpired.jsp';
	return obj;
}

function redirectToLogin() {
	obj=window;
	loop=5;
	while(loop) {
		loop=loop-1;
		if(obj.parent)
			obj=obj.parent;
		else {
			loop=0;
		}
	}

	if( obj.opener!=null ) {
		obj.opener='.p?nLogin.jsp';
		obj.close();

	}
	else
		obj.location='.p?nLogin.jsp';
}


function popupHelp(id) {
}




function getXPos(obj) {
    var v = obj.offsetLeft;
    while(obj.offsetParent!=null) {
      v += obj.offsetParent.offsetLeft;
      obj = obj.offsetParent;
	}

    return v;
}

function getYPos(obj) {
    var v = obj.offsetTop;
    while(obj.offsetParent!=null) {
      v += obj.offsetParent.offsetTop;
      obj = obj.offsetParent;
	}

    return v;
}



function fitObject(obj)
{

    oTop = getYPos(obj)
    oLeft = getXPos(obj)


    if( (oTop+ 10 + obj.clientHeight)>document.body.clientHeight )
	    obj.style.top=document.body.clientHeight - obj.clientHeight -5;
    else
	    obj.style.top=oTop+10;


    if( (oLeft+10 + obj.clientWidth)>document.body.clientWidth )
	    obj.style.left=document.body.clientWidth - obj.clientWidth -5;
    else
	    obj.style.left=oLeft+10;

}


function invert(tab,prefix,set)
{
	for(i=0;i<tab.length;i++)
	{
		if( tab[i].name.substr(0, prefix.length) == prefix) {


			if( set==null ) {
	   			if( tab[i].checked )
	   				tab[i].checked=false;
	   			else
	   				tab[i].checked=true;
   			}
   			else {
   				if( set )
	   				tab[i].checked=true;
	   			else
	   				tab[i].checked=false;


   			}

		}
	}
}


function showCenterDiv(obj)
{
	obj.style.top=-2000;
	obj.style.left=-2000;

	obj.style.display='block';

    obj.style.top=(document.body.clientHeight - obj.clientHeight)/2;
    obj.style.left=(document.body.clientWidth - obj.clientWidth)/2;
}

function changeMultiLang(variable,lang)
{
	// Fields
	document.getElementById('me_'+variable+'_lang0').style.display='none';
	document.getElementById('me_'+variable+'_lang1').style.display='none';
	document.getElementById('me_'+variable+'_'+lang).style.display='block';

	// Flags
	document.getElementById('me_flag_'+variable+'_lang0').selected=false; document.getElementById('me_flag_'+variable+'_lang0').src='pages/gfx/lang-pl-inactive.png';
	document.getElementById('me_flag_'+variable+'_lang1').selected=false; document.getElementById('me_flag_'+variable+'_lang1').src='pages/gfx/lang-en-inactive.png';

	document.getElementById('me_flag_'+variable+'_'+lang).selected=true;
	if( lang=='lang0' )
		document.getElementById('me_flag_'+variable+'_'+lang).src='pages/gfx/lang-pl-active.png';
	if( lang=='lang1' )
		document.getElementById('me_flag_'+variable+'_'+lang).src='pages/gfx/lang-en-active.png';
}



function gotoWithWait(url)
{

	if( document.getElementById('reloadPanel') )
	{
		document.getElementById('realPanel').style.display='none';
		document.getElementById('reloadPanel').style.display='block';
	}

	window.setTimeout("window.location='"+url+"'", 100);
}
function postWithWait(form)
{


	if( document.getElementById('reloadPanel') )
	{
		document.getElementById('realPanel').style.display='none';
		document.getElementById('reloadPanel').style.display='block';
	}


	form.submit();
}

function urlEncode(s)
{
	var url=s;
	url=url.replace('?','%3f');
	url=url.replace('&','%26');
	url=url.replace('=','%0d');
	return url;
}



function passwordStrength(passwd,factor)
{
		var intScore   = 0
		var strVerdict = "weak"
		var strLog     = ""

		// PASSWORD LENGTH
		if (passwd.length<5)                         // length 4 or less
		{
			intScore = (intScore+3)
			strLog   = strLog + "3 points for length (" + passwd.length + ")\n"
		}
		else if (passwd.length>4 && passwd.length<8) // length between 5 and 7
		{
			intScore = (intScore+6)
			strLog   = strLog + "6 points for length (" + passwd.length + ")\n"
		}
		else if (passwd.length>7 && passwd.length<16)// length between 8 and 15
		{
			intScore = (intScore+12)
			strLog   = strLog + "12 points for length (" + passwd.length + ")\n"
		}
		else if (passwd.length>15)                    // length 16 or more
		{
			intScore = (intScore+18)
			strLog   = strLog + "18 point for length (" + passwd.length + ")\n"
		}


		// LETTERS (Not exactly implemented as dictacted above because of my limited understanding of Regex)
		if (passwd.match(/[a-z]/))                              // [verified] at least one lower case letter
		{
			intScore = (intScore+1)
			strLog   = strLog + "1 point for at least one lower case char\n"
		}

		if (passwd.match(/[A-Z]/))                              // [verified] at least one upper case letter
		{
			intScore = (intScore+5)
			strLog   = strLog + "5 points for at least one upper case char\n"
		}

		// NUMBERS
		if (passwd.match(/\d+/))                                 // [verified] at least one number
		{
			intScore = (intScore+5)
			strLog   = strLog + "5 points for at least one number\n"
		}

		if (passwd.match(/(.*[0-9].*[0-9].*[0-9])/))             // [verified] at least three numbers
		{
			intScore = (intScore+5)
			strLog   = strLog + "5 points for at least three numbers\n"
		}


		// SPECIAL CHAR
		if (passwd.match(/.[!,@,#,$,%,^,&,*,?,_,~]/))            // [verified] at least one special character
		{
			intScore = (intScore+5)
			strLog   = strLog + "5 points for at least one special char\n"
		}

									 // [verified] at least two special characters
		if (passwd.match(/(.*[!,@,#,$,%,^,&,*,?,_,~].*[!,@,#,$,%,^,&,*,?,_,~])/))
		{
			intScore = (intScore+5)
			strLog   = strLog + "5 points for at least two special chars\n"
		}


		// COMBOS
		if (passwd.match(/([a-z].*[A-Z])|([A-Z].*[a-z])/))        // [verified] both upper and lower case
		{
			intScore = (intScore+2)
			strLog   = strLog + "2 combo points for upper and lower letters\n"
		}

		if (passwd.match(/([a-zA-Z])/) && passwd.match(/([0-9])/)) // [verified] both letters and numbers
		{
			intScore = (intScore+2)
			strLog   = strLog + "2 combo points for letters and numbers\n"
		}

									// [verified] letters, numbers, and special characters
		if (passwd.match(/([a-zA-Z0-9].*[!,@,#,$,%,^,&,*,?,_,~])|([!,@,#,$,%,^,&,*,?,_,~].*[a-zA-Z0-9])/))
		{
			intScore = (intScore+2)
			strLog   = strLog + "2 combo points for letters, numbers and special chars\n"
		}

		if( factor==null )
			factor=1;

		intScore = intScore * factor;

		if(intScore < 8)
		{
			return 0;
		}
		else if (intScore > 7 && intScore < 20)
		{
			return 1;
		}
		else if (intScore > 19 && intScore < 40)
		{
			return 2;
		}
		else if (intScore > 39 && intScore < 60)
		{
			return 3;
		}
		else
		{
			return 4;
		}
}

function PasswordStrengthMeter(divElement)
{
	var thisObj=this;

	var myDiv=Element.extend(divElement);
	myDiv.hide();

	this.register=function(obj) {
		var objExt=Element.extend(obj);
		objExt.observe('blur',this.blurAction);
		objExt.observe('keyup',this.updateAction);
		objExt.observe('focus',this.focusAction);
	}

	this.blurAction=function() {
		myDiv.hide();
	}

	this.focusAction=function(e) {
		updateScore(Event.element(e));
		showAbove(Event.element(e));
	}

	var showAbove=function(aboveWhat) {
		myDiv.setStyle({left: aboveWhat.cumulativeOffset()[0]});
		myDiv.setStyle({top: (aboveWhat.cumulativeOffset()[1] -  myDiv.getHeight() - 1 ) });
		myDiv.show();
	}

	this.updateAction=function(e) {
		updateScore(Event.element(e));
	}

	var updateScore=function(input) {
		var s=passwordStrength(input.value,2);

		var ar=myDiv.descendants();
		var n=0;
		for(var i=0;i<ar.length;i++)
		{
			if( ar[i].readAttribute('meter') ) {
				if( s>n)
					ar[i].setStyle({backgroundColor: colorActive(n)});
				else
					ar[i].setStyle({backgroundColor: colorInactive()});
				n++;
			}
			if( ar[i].readAttribute('metertext') ) {
				if( s==4 ) {
					ar[i].setStyle({color: colorActive(3)});
					ar[i].update('bardzo mocne');
				}
				else if( s==3 ) {
					ar[i].setStyle({color: colorActive(2)});
					ar[i].update('mocne');
				}
				else if( s==2 ) {
					ar[i].setStyle({color: colorActive(1)});
					ar[i].update('średnie');
				}
				else if( s==1 ) {
					ar[i].setStyle({color: colorActive(0)});
					ar[i].update('słabe');
				}
				else {
					ar[i].setStyle({color: colorInactive()});
					ar[i].update('bardzo słabe');
				}
			}
		}
	}

	var colorInactive=function() {
		return 'lightgrey';
	}
	var colorActive=function(n) {

		var c;
		if( n==0 ) c='#7dbae1';
		else if( n==1 ) c='#52ed33';
		else if( n==2 ) c='#fca61c';
		else c='#f12b2b';

		return c;
	}
}

function encodeUrlParameter(p)
{
	p=p.replace(/%/g,'%25');

	p=p.replace(/,/g,'%2C');

	p=p.replace(/ą/g,'%c4%85');
	p=p.replace(/Ą/g,'%c4%84');

	p=p.replace(/ć/g,'%c4%87');
	p=p.replace(/Ć/g,'%c4%86');

	p=p.replace(/ę/g,'%c4%99');
	p=p.replace(/Ę/g,'%c4%98');

	p=p.replace(/ł/g,'%c5%82');
	p=p.replace(/Ł/g,'%c5%81');

	p=p.replace(/ń/g,'%c5%84');
	p=p.replace(/Ń/g,'%c5%83');

	p=p.replace(/ó/g,'%c3%b3');
	p=p.replace(/Ó/g,'%c3%93');

	p=p.replace(/ś/g,'%c5%9b');
	p=p.replace(/Ś/g,'%c5%9a');

	p=p.replace(/ż/g,'%c5%bc');
	p=p.replace(/Ż/g,'%c5%bb');

	p=p.replace(/ź/g,'%c5%ba');
	p=p.replace(/Ź/g,'%c5%b9');

	p=p.replace(/\?/g,'%3f');
	p=p.replace(/\,/g,'%2c');
	p=p.replace(/&/g,'%26');
	p=p.replace(/=/g,'%3d');
	p=p.replace(/\n/g,'%0a');


	return p;
}

function splitString(str,delim,howMany)
{

	if( howMany==0 )
	{
		var c=new Array();
		c[0]=str;
		return c;
	}


	var c=str.split(delim);

	if( howMany==null )
		return c;

	if( (c.length-1)<=howMany )
		return c;

	var rest="";
	for(var i=howMany;i<c.length;i++)
		rest=rest+c[i]+delim;

	if( rest.length>0 )
		rest=rest.substr(0,rest.length-1);

	while( c.length>howMany )
		c.pop();

	c.push(rest);
	return c;
}

function trimString(sInString) {
	if( sInString==null )
		return null;
	if( typeof(sInString)=='undefined' )
		return null;
	if( typeof(sInString)!='string' )
		return null;
	sInString = sInString.replace( /^\s+/g, "" );// strip leading
    return sInString.replace( /\s+$/g, "" );// strip trailing
}





        var oldTextSelectFunc=null;
        function enableSelection() {
                if( !Prototype.Browser.IE  )
                {
                        //document.body.style.MozUserSelect="on";
                        document.body.onmousedown=oldTextSelectFunc;
                        oldTextSelectFunc=null;
                }
                return;
        }
        function disableSelection() {
                if( !Prototype.Browser.IE  )
                {
                        oldTextSelectFunc=document.body.onmousedown;
                        document.body.onmousedown=function(){return false}
                }
                return;
        }


function decodeHtml(s)
{
	s=s.replace(/&lt;/g, "<");
	s=s.replace(/&gt;/g, ">");

	s=s.replace(/&amp;/g, "&");

	return s;

}


function handleAjaxResponse(content,r) {
	var ar=splitString(content,'\n',1);

	if( ar.length<1 ) return content;
	var ar2=splitString(ar[0],':');
	if( ar2[0]!='<control>' )
		return content;
	if( ar2[1]=='redirect' ) {

		window.location=ar2[2];
		r.stopExecute=true;
	}
	return ar[1];
}




function Set() {
	var values=new Array();

	this.remove=function(val) {
		var idx=-1;
		for(var i=0;i<values.length;i++)
			if( values[i]==key ) {
				idx=i;
				i=values.lengyh;
			}
		if( idx>=0 )
			values[idx]=null;


	}

	this.put=function(val) {
		var idx=-1;
		for(var i=0;i<values.length;i++)
			if( values[i]==val ) {
				idx=i;
				i=values.lengyh;
			}
		if( idx<0 )
			values.push(val);
	}

	this.values=function() {
		return values.compact();
	}

	this.size=function() {
		return values.compact().size();
	}

	this.each=function(fptr) {
		for(var i=0;i<values.length;i++) {
			if( values[i]!=null )
				if( fptr(values[i]) )
					values[i]=null;
		}
	}
}

function Map() {
	var keys=new Array();
	var values=new Array();

	this.remove=function(key) {
		var idx=-1;
		for(var i=0;i<keys.length;i++)
			if( keys[i]==key ) {
				idx=i;
				i=keys.lengyh;
			}
		if( idx>=0 ) {
			values[idx]=null;
			keys[idx]=null;
		}
	}

	this.put=function(key,object) {
		var idx=-1;
		for(var i=0;i<keys.length;i++)
			if( keys[i]==key ) {
				idx=i;
				i=keys.lengyh;
			}
		if( idx<0 ) {
			keys.push(key);
			idx=keys.length-1;
		}

		values[idx]=object;
	}

	this.get=function(key) {
		var idx=-1;
		for(var i=0;i<keys.length;i++)
			if( keys[i]==key ) {
				idx=i;
				i=keys.lengyh;
			}
		if( idx<0 )
			return null;
		return values[idx];
	}

	this.keys=function() {
		return keys.compact();
	}

	this.values=function() {
		return values.compact();
	}

	this.size=function() {
		return keys.compact().size();
	}

	this.each=function(fptr) {
		for(var i=0;i<keys.length;i++) {
			if( keys[i]!=null )
				if( fptr(keys[i],values[i]) ) {
					values[i]=null;
					keys[i]=null;
				}
		}
	}
}

function CommandQueue() {
	function Command(fnt,args) {
		this.fnt=fnt;
		this.args=args;
	}

	var queue=new Array();

	this.queueCommand=function(fnt,args) {
		var c=new Command(fnt,args);
		queue.push(c);
	}

	this.execute=function() {
		var obj=queue.pop();
		if( obj!=null ) {
			obj.fnt(obj.args);
		}
		setTimeout("GCommandQueue.execute()",1);
	}

	this.start=function() {
		setTimeout("GCommandQueue.execute()",1);
	}
}
var GCommandQueue=new CommandQueue();
GCommandQueue.start();


function TimeoutManger() {
	var thisObj=this;
	function Action(functionPtr,args) {
		this.functionPtr=functionPtr;
		this.args=args;
	}

	var actions=new Array();
	this.add=function(miliseconds,functionPtr,args) {
		var act=new Action(functionPtr,args);
		GCommandQueue.queueCommand(this.addSynchronized,[functionPtr,args,miliseconds]);
	}

	this.addSynchronized=function(args) {
		var act=new Action(args[0],args[1]);
		actions.push(act);
		setTimeout("GTimeoutManager.execute("+(actions.length-1)+")",args[2]);
	}

	this.execute=function(idx) {
		var act=actions[idx];
		if( act!=null )
			act.functionPtr(act.args);
	}
}
var GTimeoutManager=new TimeoutManger();





function MouseTrapEventManager() {
	var thisObj=this;
	function Action(x1,x2,y1,y2,toHide,button,callBackIfHidden) {
		this.x1=x1;
		this.x2=x2;
		this.y1=y1;
		this.y2=y2;
		this.toHide=toHide;
		this.button=button;
		this.callBackIfHidden=callBackIfHidden;
	}

	var events=new Array();

	this.hide=function(openButton) {
		for(var b in events) {
			var a=events[b];
			if( events[b]!=null ) {
				if( a.button==openButton ) {
					events[b]=null;
					Effect.Fade(a.toHide,{ duration: 0.1 });
				}
			}
		}
	}

	this.analyze=function(event) {
		var x=Event.pointerX(event);
		var y=Event.pointerY(event);

		for(var i=0;i<events.length;i++)
		{
			var ac=events[i];
			if( ac==null )
				continue;

			if( x>=ac.x1 && x<=ac.x2 && y>=ac.y1 && y<=ac.y2 )
				continue;

			events[i]=null;

			Effect.Fade(ac.toHide,{ duration: 0.1 });
			if( ac.callBackIfHidden!=null )
				ac.callBackIfHidden(ac.button);
		}
	}

	getLocation=function(obj,current) {
		var o=Element.extend(obj);
		var pos=o.cumulativeOffset();

		var locNew=new Array();

		locNew['x1']=pos[0];
		locNew['y1']=pos[1];

		locNew['x2']=pos[0]+o.getWidth();
		locNew['y2']=pos[1]+o.getHeight();

		if( current!=null )
		{
			if( locNew['x1']>current['x1'] )
				locNew['x1']=current['x1'];

			if( locNew['x2']<current['x2'] )
				locNew['x2']=current['x2'];

			if( locNew['y1']>current['y1'] )
				locNew['y1']=current['y1'];

			if( locNew['y2']<current['y2'] )
				locNew['y2']=current['y2'];
		}
		return locNew;
	}

	this.addReal=function(args) {
		var loc=getLocation(args[0]);
		for(var i=0;i<args[1].length;i++)
			loc=getLocation(args[1][i],loc);
		events.push(new Action(loc['x1'],loc['x2'],loc['y1'],loc['y2'],args[0],args[2],args[3]));
	}

	this.add=function(regionObjects,objectToHide,button,callBackH) {
		Effect.Appear(objectToHide,{ duration: 0.1 });
		GTimeoutManager.add(200,this.addReal,[objectToHide,regionObjects,button,callBackH])
	}


	Event.observe(document.body,"mousemove",this.analyze);
}
var GMouseTrapEventManager=null;




function MenuList(table) {
	var opacityPanel=null;
	var showOpacityPanel=function() {
		/*
		var body=Element.extend(document.body);
		if( opacityPanel==null ) {
			opacityPanel=Element.extend(document.createElement("div"));
			opacityPanel.absolutize();

			opacityPanel.setStyle({margin: 0, padding: 0, backgroundColor: "white", zIndex: 1, width: body.getWidth(), height: body.getHeight()});
			opacityPanel.setOpacity(0.7);
			document.body.appendChild(opacityPanel);
		}

		opacityPanel.show();
		*/
		if( table!=null )
			table.setOpacity(0.4);

	}
	var hideOpacityPanel=function() {
		/*
		if( opacityPanel!=null )
			opacityPanel.hide();
		*/
		if( table!=null )
			table.setOpacity(1);
	}

	var openMenus=new Map();
	this.clickMenu=function(button,panel) {
		if( openMenus.get(button)!=null ) {
			GMouseTrapEventManager.hide(button);
			openMenus.remove(button);
			hideOpacityPanel();
		}
		else {

			openMenus.each(function(key,value){
				if( value!=null ) {
					GMouseTrapEventManager.hide(key);
					return true;
				}
			});


			openMenus.put(button,true);

			var b=Element.extend(button);
			var p=Element.extend(panel);
			p.setStyle({left: (b.getWidth()+b.cumulativeOffset()[0])});
			p.setStyle({top: (b.getHeight()+b.cumulativeOffset()[1])});

			GMouseTrapEventManager.add([button],panel,button,this.selfHidden);
			p.setStyle({zIndex: 2});
			showOpacityPanel();

		}
	}

	this.selfHidden=function(button) {
		openMenus.remove(button);
		hideOpacityPanel();
	}
}






function loadLinkList(url,dest,callback,hrefPattern,pCl,aCl)
{
	ajax.callPageArgs(url,feedListOfLinks,{obj:dest, callback: callback, hrefPattern: hrefPattern, pClass: pCl, aClass: aCl});
}


function loadSelect(url,select,value,callback)
{
	ajax.callPageArgs(url,feedSelection,{obj:select, value:value, callback: callback});
}

function parseContentList2d(content,delim)
{

	var result=new Array();
	var ar=splitString(content,"\n");

	for(var i=0;i<ar.length;i++)
	{
		if( delim!="\n" && delim!=null )
		{
			var tmp=splitString(ar[i],delim,1);

			tmp[0]=tmp[0].replace("\r","");
			tmp[1]=tmp[1].replace("\r","");

			result.push(tmp);
		}
		else
		{
			var tmp=new Array();
			tmp[0]=ar[i];
			i++;

			if( i<ar.length )
			{
				tmp[1]=ar[i];

				tmp[0]=tmp[0].replace("\r","");
				tmp[1]=tmp[1].replace("\r","");

				result.push(tmp);
			}
		}
	}
	return result;
}

function clearSelect(obj)
{
	obj.options.length=0;
}
function feedSelection(content,args)
{
//	alert('+'+content+'+');
	if( typeof(handleControlMessage)=='function' )
		content=handleControlMessage(content);
//	alert('='+content+'=');



	var obj=args.obj;
	clearSelect(obj);
	var list=parseContentList2d(content);
	for(var i=0;i<list.length;i++) {
		if( args.value==list[i][0] || (args.value==null && i==0) )
			obj.options[i]=new Option(list[i][1],list[i][0], true);
		else
			obj.options[i]=new Option(list[i][1],list[i][0]);
	}

	if( args.value!=null )
		obj.value=args.value;
	else {
		if( obj.options.length>0 )
			obj.value=obj.options[0].value;
	}

	if( args.callback )
		args.callback();
}

function feedListOfLinks(content,args)
{
	if( typeof(handleControlMessage)=='function' )
		content=handleControlMessage(content);

	var obj=args.obj;
	obj.update('');
	var list=parseContentList2d(content);



	for(var i=0;i<list.length;i++)
	{
		var a=Element.extend(document.createElement('a'));

		if( args.aClass!=null )
			a.addClassName(args.aClass);

		var href=list[i][0];

		if( args.hrefPattern!=null )
			href=args.hrefPattern.replace('{href}',href);
		a.href=href;
		//if( linkStyleClass )
		//a.class=linkStyleClass;

		a.update(list[i][1]);

		var p=Element.extend(document.createElement('p'));

		if( args.pClass!=null )
			p.addClassName(args.pClass);

		p.appendChild(a);


		obj.appendChild(p);
	}

	if( args.callback )
		args.callback();
}


function stripPathFromFileName(fileName)
{
	if( fileName.match(/^[a-zA-Z]\:/) )
	{
		// Windows
		return fileName.substring(fileName.lastIndexOf('\\')+1,fileName.length);
	}
	else if( fileName.match(/^\//) )
	{
		// Linux
		return fileName.substring(fileName.lastIndexOf('/')+1,fileName.length);
	}
	else
	{
		// Already relative
		return fileName;
	}
}

function spanElementOverPage(element)
{
	var a1=new Array();//Element.extend(document.body).cumulativeOffset();
	a1[0]=Element.extend(document.body).getWidth();
	a1[1]=Element.extend(document.body).getHeight();


	var d=parseInt(element.getStyle('margin'));



	var a2=new Array();
	if( Prototype.Browser.IE ) {
//		a1[0]-=20;
//		a1[1]+=40;

//		a2[0]=window.innerWidth-19;
//		a2[1]=window.innerHeight-8;

		a1[0]-=22;
		a1[1]-=10;
		a1[0]-=d;
		a1[1]-=d;
	}
	else {
//		a1[0]+=13;
//		a1[1]+=13;

//		a2[0]=window.innerWidth-19;
//		a2[1]=window.innerHeight-8;

		a1[0]-=2;
		a1[1]-=2;
		a1[0]-=d;
		a1[1]-=d;
	}

//	if( a1[0]<a2[0] ) a1[0]=a2[0];
//	if( a1[1]<a2[1] ) a1[1]=a2[1];





	element.setStyle({width: a1[0], height: a1[1]});

}


function TextBoxSearchable(source,inputElement,dropDownElement,size,callBackSelect,noSearch,overflowMin)
{
	var thisObj=this;
	if( overflowMin==null )
		overflowMin=0;

	var handleCallback=function(row) {
		if( callBackSelect==null )
			return;
		callBackSelect(row.readAttribute("lp"),row.readAttribute("value"));
	}

	this.onClick=function(e) {
		var el=Event.element(e);
		thisObj.selectedRow=el;

		thisObj.divElement.hide();
		var row=thisObj.selectedRow;
		if( row!=null ) {
			handleCallback(row);
			var v=row.readAttribute('value');
			inputElement.value=decodeHtml(v.replace(/&quot;/g,'"'));
		}
	}

	var createCaption=function(text,search) {
		var i=text.toLowerCase().indexOf(search.toLowerCase());


		if( i>=0 )
			text=text.substr(0,i) + '<b>' + text.substr(i,search.length) + '</b>' + text.substr(i+search.length);

		return text;
	}

	var selectCurrent=function() {
		var tmp=thisObj.selectedRow;

		if( tmp!=null )
			tmp.setStyle({backgroundColor: "#f0f0f0"});
	}

	var unselectCurrent=function() {
		var tmp=thisObj.selectedRow;
		if( tmp!=null )
			tmp.setStyle({backgroundColor: "white"});
	}

	this.search=function(text) {
		var e=thisObj.divElement;

		e.update('');

		thisObj.selectedRow=null;

		var shown=0;
		var toShow=false;
		for(var i=0;i<source.length;i++) {
			if( source[i].toLowerCase().indexOf(text.toLowerCase())>=0 || noSearch ) {

				toShow=true;
				shown++;

				var cap=createCaption(source[i],text);
				cap=cap.replace(/ /g,"&nbsp;");

				var p=Element.extend(document.createElement("p"));
				p.writeAttribute("value",source[i]);
				p.writeAttribute("lp",i);

				p.setStyle({padding: 1, margin: 1});

				p.observe("click",thisObj.onClick);
				p.setStyle({cursor: "default"});

				if( thisObj.selectedRow==null ) {
					thisObj.selectedRow=p;
					selectCurrent();
				}

				p.update(cap);

				e.appendChild(p);
			}
		}

		if( toShow ) {

			if( shown>=overflowMin )
				e.setStyle({height: size, overflowY: "auto"});
			else
				//e.setStyle({height: "", overflowY: "none"});
				e.setStyle({height: "", overflowY: "visible"});

			e.show();
			inputElement.noAdd=true;
		}
		else {
			e.hide();
			inputElement.noAdd=false;
		}
		e.scrollTop=0;
	}

	this.dropDownOrHide=function(e) {
		if( thisObj.divElement.visible() ) {
			thisObj.divElement.hide();
			inputElement.noAdd=false;
		}
		else {
			thisObj.search(inputElement.value);
			if( e!=null )
				Event.stop(e);
		}
	}
	this.hide=function() {
		thisObj.divElement.hide();
		inputElement.noAdd=false;
	}

	this.onUpdate=function(e) {
		if( e.keyCode>=65 && e.keyCode<=90 || e.keyCode>=48 && e.keyCode<=57 || thisObj.divElement.visible() )
			if( e.keyCode!=40 && e.keyCode!=38 && e.keyCode!=27 && e.keyCode!=13 && e.keyCode!=18 && e.keyCode!=9 && e.keyCode!=33 && e.keyCode!=34 )
				thisObj.search(inputElement.value);
	}

	this.keyPressed=function(e) {
		if( e.keyCode==9 ) {
			thisObj.divElement.hide();
			inputElement.noAdd=false;
			//Event.stop(e);
			thisObj.handledEvent=e;
		}
		if( e.keyCode==27 ) {
			thisObj.divElement.hide();
			inputElement.noAdd=false;
			Event.stop(e);
			thisObj.handledEvent=e;
		}
		else if( e.keyCode==13 && thisObj.divElement.visible()) {
			thisObj.divElement.hide();
			var row=thisObj.selectedRow;
			if( row!=null ) {
				handleCallback(row);
				var v=row.readAttribute('value');
				inputElement.value=decodeHtml(v.replace(/&quot;/g,'"'));
			}
			Event.stop(e);
		}
		else if( e.keyCode==13 && !thisObj.divElement.visible()) {
			if( thisObj.oldKeyPressFunc!=null )
				thisObj.oldKeyPressFunc(e);
		}
		else if( e.keyCode==40 && !thisObj.divElement.visible() )
			thisObj.search(inputElement.value);
		else if( e.keyCode==40 || e.keyCode==34 ) {
			var current=thisObj.selectedRow;
			if( current!=null ) {
				var n=current.next();



				if( n!=null && typeof(n)!='undefined') {

					if( e.keyCode==34 )
						for(var i=0;i<10 && n.next()!=null && typeof(n.next())!='undefined';i++)
							n=n.next();


					unselectCurrent();
					thisObj.selectedRow=n;
					selectCurrent();

					var h=n.cumulativeOffset()[1] - thisObj.divElement.cumulativeOffset()[1] + n.getHeight();

					while( h > (thisObj.divElement.getHeight() + thisObj.divElement.scrollTop) ) {
						thisObj.divElement.scrollTop+=1;
					}

				}
			}
		}
		else if( e.keyCode==38 || e.keyCode==33 ) {
			var current=thisObj.selectedRow;
			if( current!=null ) {
				var n=current.previous();



				if( n!=null && typeof(n)!='undefined' ) {

					if( e.keyCode==33 )
						for(var i=0;i<10 && n.previous()!=null && typeof(n.previous())!='undefined';i++)
							n=n.previous();

					unselectCurrent();
					thisObj.selectedRow=n;
					selectCurrent();

					var h=n.cumulativeOffset()[1] - thisObj.divElement.cumulativeOffset()[1];

					while( h < thisObj.divElement.scrollTop ) {
						thisObj.divElement.scrollTop-=1;
					}

				}
			}
		}

	}

	this.divElement=Element.extend(document.createElement('div'));

	Element.extend(inputElement).observe('keydown',this.keyPressed);
	Element.extend(inputElement).observe('keyup',this.onUpdate);
	Element.extend(dropDownElement).observe('click',this.dropDownOrHide);

	var ie=Element.extend(inputElement);

	if( size==null )
		size=50;

	this.divElement.hide();
	inputElement.noAdd=false;

	document.body.appendChild(this.divElement);



	this.divElement.absolutize();

	this.divElement.setStyle({border: "solid 1px #a0a0a0", padding: 1, margin: 0, backgroundColor: "white"});
	this.divElement.setStyle({width: ie.getWidth(), height: size, overflowY: "auto", overflowX: "hidden"});
	this.divElement.setStyle({left: ie.cumulativeOffset()[0], top: (ie.cumulativeOffset()[1] + ie.getHeight() +2)});


	inputElement.dropDownBox=this;

	this.oldKeyPressFunc=inputElement.onKeyPressFunc;

	if( this.oldKeyPressFunc!=null )
		ie.stopObserving("keypress",this.oldKeyPressFunc);

	Element.extend(document.body).observe("click",this.hide);
}

function normalizeXml(xml) {
	var tmp=new String(xml);

	tmp=tmp.replace(/\s*\/>/g,'/>');
	tmp=tmp.replace(/<br\/>\s*/g,'<br/>');
	tmp=tmp.replace(/<pre>\s*/g,'<pre>');
	tmp=tmp.replace(/<p>\s*/g,'<p>');
	tmp=tmp.replace(/<div>\s*/g,'<div>');
	tmp=tmp.replace(/>\s+/g,'> ');
	tmp=tmp.replace(/\s+</g,' <');
	return tmp;
}

