///////////////////////////////////
// CAPTCHA
var Captcha=new Object();
Captcha.captchaBufImage=new Array();
Captcha.captchaNewKey=function(content,args)
{
	var m=JSWorkspace.parseJSON(content);
	if( m==null )
		return;
	var key=m["key"];

	if( Captcha.captchaBufImage[key]==null )
		Captcha.captchaBufImage[key]=new Image();

	if( args['form']!=null )
	{
		args['form'].elements[args['captchaKey']].value=key;
		if( args.captchaCode!=null )
			args['form'].elements[args.captchaCode].value='';
	}

	Captcha.captchaBufImage[key].src=Root+'captcha/img,key,'+key;

	GTimeoutManager.add(500,Captcha.captchaNewImgLoaded,{key:key,realImage:args['captchaImg'],covers:args.covers});
}

Captcha.captchaNewImgLoaded=function(args)
{
	if( Captcha.captchaBufImage[args['key']]==null )
		return;
	if( Captcha.captchaBufImage[args['key']].complete )
	{
		args['realImage'].src=Captcha.captchaBufImage[args['key']].src;

		jsWorkspace.coverHide(args.covers.id);
	}
	else
	{
		GTimeoutManager.add(500,Captcha.captchaNewImgLoaded,args);
	}
}

Captcha.reloadCaptcha=function(img,form,key,code)
{
	var covers=jsWorkspace.coverElement({where:img,what:$('coverWaitIcon'),hcenter:true,vcenter:true});
	jsWorkspace.requestGet(Root+'captcha/genkey',null,{callback:Captcha.captchaNewKey,form:form,captchaKey:key,captchaCode:code,captchaImg:img,covers:covers});
}

// CAPTCHA
///////////////////////////////////

function SearchableControl(container)
{
	var xmlType=function() { return 'searchableControl'; }
	var thisObj=this;
	if( container==null )
		return;

	var float=container.readAttribute(xmlType()+'Float')=="true";
	var floatDiv=container.select('[type='+xmlType()+'FloatDiv]')[0];
	var floatLink=container.select('[type='+xmlType()+'FloatLink]')[0];

	var closeLink=container.select('[type='+xmlType()+'LinkClose]')[0];


	var contentDiv=container.select('[type='+xmlType()+'Content]')[0];

	var listType=container.readAttribute(xmlType()+'ListType');

	var selectedValueName=container.readAttribute(xmlType()+"ValueName");
	var selectedValueId=container.readAttribute(xmlType()+"ValueId");

	var searchable=container.readAttribute(xmlType()+"Searchable")=="true";

	var maxRows=parseInt(container.readAttribute(xmlType()+"MaxRows"));
	var maxInRow=parseInt(container.readAttribute(xmlType()+"MaxInRow"));

	var inputElement=container.select('input[type=text]')[0];
	thisObj.inputElement=inputElement;

	var hiddenValue=container.select('[typeInput='+xmlType()+'HiddenValue]')[0];
	var hiddenCaption=container.select('[typeInput='+xmlType()+'HiddenCaption]')[0];


	var spanCaption=container.select('[type='+xmlType()+'Caption]')[0];

	// Properties
	var searchDelay=1000; // Search delay in ms

	// Events methods
	this.onChoosen=function(e)
	{
		var p=Event.element(e).up();
		while(p!=null && p.tagName!='P')
			p=p.up();
		choosen(p);
		thisObj.hideFloat();
	}
	this.onFloatLink=function()
	{
		if( floatDiv==null )
			return;
		if( floatDiv.visible() ) {
			thisObj.hideFloat();
		}
		else
		{
			inputElement.focus();
			if( thisObj.entries==null || true)
				GTimeoutManager.add(1,thisObj.searchFromServer,{searchText:inputElement.value},thisObj);
			thisObj.showFloat();
		}
	}

	this.hasFocus=true;
	this.onBlur=function(e)
	{
		thisObj.hasFocus=false;
		GTimeoutManager.add(100,thisObj.hideFloatOnBlur);
	}
	this.onFocus=function(e)
	{
		thisObj.hasFocus=true;
	}

	this.onKey=function(e) {

		if( e.keyCode==9 && float ) {
			thisObj.hideFloat();
		}
		if( e.keyCode==27 && float ) {
			thisObj.hideFloat();
			Event.stop(e);
		}
		else if( e.keyCode==13 && floatDiv.visible()) {
			thisObj.hideFloat();

			if(thisObj.selectedP!=null )
				choosen(thisObj.selectedP);
			Event.stop(e);
		}
		else if( e.keyCode==13 && !floatDiv.visible()) {
			if( thisObj.oldKeyPressFunc!=null )
				thisObj.oldKeyPressFunc(e);
			Event.stop(e);
		}
		else if( e.keyCode==40 && !floatDiv.visible() )
		{
		//	unselectValue();
			GTimeoutManager.add(1,thisObj.searchFromServer,{searchText:inputElement.value},thisObj);
			Event.stop(e);
		}
		else if( e.keyCode==40 || e.keyCode==34 ) {
			thisObj.selectDown();
			Event.stop(e);
		}
		else if( e.keyCode==38 || e.keyCode==33 ) {
			thisObj.selectUp();
			Event.stop(e);
		}
		else if( e.keyCode==37 ) {
			thisObj.selectLeft();
			if( floatDiv.visible() )
				Event.stop(e);
		}
		else if( e.keyCode==39 ) {
			thisObj.selectRight();
			if( floatDiv.visible() )
				Event.stop(e);
		}
	}
	this.onUpdate=function(e) {
		if( e.keyCode>=65 && e.keyCode<=90 || e.keyCode>=48 && e.keyCode<=57 || floatDiv.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 && e.keyCode!=37 && e.keyCode!=39  )
			{
				unselectValue();
				GTimeoutManager.add(searchDelay,thisObj.searchFromServer,{searchText:inputElement.value},thisObj);
			}
	}

	// Binding events
	if( floatLink!=null ) floatLink.observe('click',this.onFloatLink);
	if( inputElement!=null ) inputElement.observe('keydown',this.onKey);
	if( inputElement!=null ) inputElement.observe('keydown',this.onUpdate);
	if( inputElement!=null ) inputElement.observe('blur',this.onBlur);
	if( inputElement!=null ) inputElement.observe('focus',this.onFocus);


	container.select().each(function(o) {o.observe('focus',this.onFocus)});

	// Position float
	this.positionFloat=function()
	{
		// Positioning
		var x=0;
		var y=0;

		if( inputElement!=null )
		{
			if( inputElement.up()==null )
				return;

			x=inputElement.cumulativeOffset()[0];
			y=inputElement.cumulativeOffset()[1]+1+inputElement.getHeight();

			floatDiv.setStyle({left:x+"px",top:y+"px"});
		}
		else
		{
			if( spanCaption.up()==null )
				return;

			x=spanCaption.cumulativeOffset()[0];
			y=spanCaption.cumulativeOffset()[1]+1+spanCaption.getHeight();

			floatDiv.setStyle({left:x+"px",top:y+"px"});
		}

	}

	jsWorkspace.registerRepositionMethod(this.positionFloat);


	// Show float div
	this.showFloat=function()
	{
		if( floatDiv!=null  )
		{
			floatDiv.show();

			thisObj.positionFloat();
			jsWorkspace.doReposition();

		}
	}

	// Hide float div
	this.hideFloatOnBlur=function()
	{
		if( thisObj.hasFocus )
			return;
		//thisObj.hideFloat(); - wylaczamy to, trszeba kliknac na zamknij
	}
	this.hideFloat=function()
	{
		if( floatDiv!=null && float)
		{
			floatDiv.hide();
			jsWorkspace.doReposition();
		}
	}
	if( closeLink!=null ) closeLink.observe('click',this.hideFloat);


	// Change list type
	this.changeToList=function()
	{
		if( listType=="1" )
			return;
		listType="1";
		GTimeoutManager.add(1,thisObj.searchFromServer,{},thisObj);
		if( inputElement!=null ) inputElement.focus();
	}
	var linkToList=container.select('[type='+xmlType()+'LinkToList]')[0];
	if( linkToList!=null ) linkToList.observe('click',this.changeToList);

	this.changeToMap=function()
	{
		if( listType=="2" )
			return;
		listType="2";
		GTimeoutManager.add(1,thisObj.searchFromServer,{},thisObj);
		if( inputElement!=null ) inputElement.focus();
	}
	var linkToMap=container.select('[type='+xmlType()+'LinkToMap]')[0];
	if( linkToMap!=null ) linkToMap.observe('click',this.changeToMap);

	// Scroll if needed
	var scrollIfNeeded=function() {
		if( thisObj.selectedP==null )
			return;

		if( contentDiv.style.overflow!='auto' )
			return;

		var tmp1;


		tmp1=false;
		var h=thisObj.selectedP.cumulativeOffset()[1] - contentDiv.cumulativeOffset()[1] + thisObj.selectedP.getHeight();
		while( h > (contentDiv.getHeight() + contentDiv.scrollTop ) ) {
			contentDiv.scrollTop+=1;
			tmp1=true;
		}
		if( tmp1 )
			contentDiv.scrollTop+=12;

		h=thisObj.selectedP.cumulativeOffset()[1] - contentDiv.cumulativeOffset()[1];
		while( h < (contentDiv.scrollTop) )
			contentDiv.scrollTop-=1;

		tmp1=false;
		var w=thisObj.selectedP.cumulativeOffset()[0] - contentDiv.cumulativeOffset()[0] + thisObj.selectedP.getWidth();
		while( w > (contentDiv.getWidth() + contentDiv.scrollLeft ) ) {
			contentDiv.scrollLeft+=1;
			tmp1=true;
		}
		if( tmp1 )
			contentDiv.scrollLeft+=12;

		w=thisObj.selectedP.cumulativeOffset()[0] - contentDiv.cumulativeOffset()[0];
		while( w < (contentDiv.scrollLeft) )
			contentDiv.scrollLeft-=1;
	}

	// Select methods
	this.selectUp=function()
	{
		if( thisObj.selectedX==null || thisObj.selectedY==null )
			return;
		thisObj.select(thisObj.selectedX-1,thisObj.selectedY);
	}
	this.selectDown=function()
	{
		if( thisObj.selectedX==null || thisObj.selectedY==null )
			return;
		thisObj.select(thisObj.selectedX+1,thisObj.selectedY);
	}
	this.selectLeft=function()
	{
		if( thisObj.selectedX==null || thisObj.selectedY==null )
			return;
		thisObj.select(thisObj.selectedX,thisObj.selectedY-1);
	}
	this.selectRight=function()
	{
		if( thisObj.selectedX==null || thisObj.selectedY==null )
			return;
		thisObj.select(thisObj.selectedX,thisObj.selectedY+1);
	}
	this.select=function(x,y)
	{
		if( thisObj.entries==null )
			return false;

		var idx;

		if( x<0 || y<0 )
			return false;

		if( x>=maxRows && maxRows>0)
			return false;


		if( listType=='1' )
		{
			if( y!=0 )
				return false;
			idx=x;
		}
		else if( listType=='2' )
		{
			if( y>=maxInRow )
				return false;

			idx=y + x * maxInRow;
		}
		else
			return false;


		if( idx>=thisObj.entries.length )
			return false;

		thisObj.selectedX=x;
		thisObj.selectedY=y;

		if( thisObj.selectedP!=null )
			thisObj.selectedP.removeClassName("selected");

		if( listType=='1' )
			thisObj.selectedP=contentDiv.childElements()[x];
		else if( listType=='2' )
			thisObj.selectedP=contentDiv.down().down().childElements()[x].childElements()[y].down();

		thisObj.selectedP.addClassName("selected");

		scrollIfNeeded();

		return true;
	}

	var choosen=function(p)
	{
		if( p==null )
			return;
		var idx=parseInt(p.readAttribute('idx'));
		if( idx==null )
			return;
		if( thisObj.entries==null )
			return;
		if( idx>=thisObj.entries.length )
			return;

		thisObj.selectedValue=thisObj.getValue(thisObj.entries[idx]);
		thisObj.selectedCaption=thisObj.getCaption(thisObj.entries[idx]);

		if( hiddenValue!=null ) hiddenValue.value=thisObj.selectedValue;
		if( hiddenCaption!=null ) hiddenCaption.value=thisObj.selectedCaption;

		if( inputElement!=null ) inputElement.value=thisObj.selectedCaption;
		if( spanCaption!=null ) spanCaption.update(thisObj.selectedCaption);

		if( thisObj.selectCallback!=null )
			thisObj.selectCallback(thisObj.selectedValue, thisObj.selectedCaption);
	}


	this.searchFromServerResult=function(content)
	{



		var m=JSWorkspace.parseJSON(content);
		if( m==null )
			return;
		if( m.list==null )
			return;

		if( !thisObj.hasFocus )
			return;

		thisObj.entries=m.list;

		contentDiv.update('');

		var tmp1=null;
		var currentRow=null;

		if( listType==2 )
		{

			contentDiv.appendChild(new Element('table'));
			tmp1=new Element('tbody');
			contentDiv.down().appendChild(tmp1);

			currentRow=new Element('tr');
			tmp1.appendChild(currentRow);
		}

		for(var i=0;i<m.list.length;i++) {
			var p;

			if( maxRows>0 && i>=maxRows )
				continue;

			if( listType=="1" )
			{
				p=thisObj.createList1P(m.list[i]);
				contentDiv.appendChild(p);
			}
			else if( listType=="2" )
			{
				p=thisObj.createList2P(m.list[i]);
				var td=new Element('td');
				currentRow.appendChild(td);
				td.appendChild(p);

				if( currentRow.childElements().length>=maxInRow )
				{
					currentRow=new Element('tr');
					tmp1.appendChild(currentRow);
				}
			}

			p.writeAttribute('idx',i);

		}

		if( m.list.length>0 )
		{
			thisObj.showFloat();
			thisObj.select(0,0);
		}

	}

	var unselectValue=function()
	{
		thisObj.selectedValue=null;
		if( hiddenValue!=null ) hiddenValue.value="";

		if( inputElement!=null )
		{
			thisObj.selectedCaption=inputElement.value;
			if( hiddenCaption!=null ) hiddenCaption.value=inputElement.value;
		}

		if( thisObj.selectCallback!=null )
			thisObj.selectCallback(thisObj.selectedValue, thisObj.selectedCaption);
	}

	// Init
	if( float && floatDiv!=null ) floatDiv.absolutize();
}
SearchableControl.registered=new Map();
SearchableControl.init=function()
{
	var ar=Element.extend(document.body).select('div[type=searchableControl]');
	for(var i=0;i<ar.length;i++)
	{
		var obj=ar[i];
		if( !SearchableControl.registered.containsKey(obj) ) {
			var className=obj.readAttribute('jsClassName');
			var inst=eval('new '+className+'(obj)');
			SearchableControl.registered.put(obj,inst);
		}
	}
}



ProducerSearch.prototype = new SearchableControl();
function ProducerSearch(container)
{
	SearchableControl.call(this, container);
	var thisObj=this;

	this.searchFromServer=function(args)
	{
		if( !thisObj.hasFocus )
			return;

		if( thisObj.inputElement!=null )
			jsWorkspace.requestGet(Root+'producer/list,searchText,'+JSWorkspace.encodeUrl(thisObj.inputElement.value),null,{callback:thisObj.searchFromServerResult});
		else
			jsWorkspace.requestGet(Root+'producer/list,searchText,',null,{callback:thisObj.searchFromServerResult});
	}

	this.createList1P=function(entry)
	{
		var p=new Element('p');
		var a=new Element('a');
		a.writeAttribute('href','javascript:;');
		a.update(entry.name);
		p.appendChild(a);
		a.observe('click',thisObj.onChoosen);
		a.observe('focus',thisObj.onFocus);
		return p;
	}

	this.createList2P=function(entry)
	{
		var p=new Element('p');

		var tab1=new Element('table');
		tab1.appendChild(new Element('tbody'));

		p.appendChild(tab1);

		var tr=new Element('tr');
		tab1.down().appendChild(tr);
		tr.appendChild(new Element('td'));

		var a=new Element('a');
		a.writeAttribute('href','javascript:;');

		tr.down().appendChild(a);
		a.observe('click',thisObj.onChoosen);
		a.observe('focus',thisObj.onFocus);


		a.appendChild(new Element('img'));
		tr.down().setStyle({height: "80px", width: "80px"});
		a.down().src=Root+'producer/img,noimg,no-photo-80.png,w,80,h,80,id,'+entry.id;


		tr=new Element('tr');
		tab1.down().appendChild(tr);
		tr.appendChild(new Element('td'));
		a=new Element('a');
		a.writeAttribute('href','javascript:;');
		a.update(entry.name);

		tr.down().appendChild(a);
		a.observe('click',thisObj.onChoosen);
		a.observe('focus',thisObj.onFocus);


		return p;
	}

	this.getValue=function(entry)
	{
		return entry.id;
	}

	this.getCaption=function(entry)
	{
		return entry.name;
	}

}





PredefinedItemSearch.prototype = new SearchableControl();
function PredefinedItemSearch(container)
{
	SearchableControl.call(this, container);
	var thisObj=this;

	this.searchFromServer=function(args)
	{
		if( !thisObj.hasFocus )
			return;

		if( thisObj.inputElement!=null )
			jsWorkspace.requestGet(Root+'predefineditem/list,max,30,producerId,'+thisObj.producerId+',categoryId,'+thisObj.categoryId+',searchText,'+JSWorkspace.encodeUrl(thisObj.inputElement.value),null,{callback:thisObj.searchFromServerResult});
		else
			jsWorkspace.requestGet(Root+'predefineditem/list,max,30,producerId,'+thisObj.producerId+',categoryId,'+thisObj.categoryId+',searchText,',null,{callback:thisObj.searchFromServerResult});
	}

	this.createList1P=function(entry)
	{
		var p=new Element('p');
		var a=new Element('a');
		a.writeAttribute('href','javascript:;');
		a.observe('click',thisObj.onChoosen);
		a.observe('focus',thisObj.onFocus);
		a.update(entry.name);
		p.appendChild(a);
		return p;
	}

	this.createList2P=function(entry)
	{
		var p=new Element('p');

		var tab1=new Element('table');
		tab1.appendChild(new Element('tbody'));

		p.appendChild(tab1);

		var tr=new Element('tr');
		tab1.down().appendChild(tr);
		tr.appendChild(new Element('td'));

		var a=new Element('a');
		a.writeAttribute('href','javascript:;');
		a.observe('click',thisObj.onChoosen);
		a.observe('focus',thisObj.onFocus);

		tr.down().appendChild(a);


		a.appendChild(new Element('img'));
		tr.down().setStyle({height: "80px", width: "80px"});
		a.down().src=Root+'predefineditem/img,noimg,no-photo-80.png,w,80,h,80,id,'+entry.id;


		tr=new Element('tr');
		tab1.down().appendChild(tr);
		tr.appendChild(new Element('td'));

		a=new Element('a');
		a.writeAttribute('href','javascript:;');
		a.observe('click',thisObj.onChoosen);
		a.observe('focus',thisObj.onFocus);
		a.update(entry.name);

		tr.down().appendChild(a);


		return p;
	}

	this.getValue=function(entry)
	{
		return entry.id;
	}

	this.getCaption=function(entry)
	{
		return entry.name;
	}

}





function CategoryTree(container)
{
	var omitCats=null;
	var thisObj=this;
	if( container==null )
		return;

	var staticTree=container.readAttribute("categoryTreeStatic")=="true";
	var float=container.readAttribute("categoryTreeFloat")=="true";
	var nullable=container.readAttribute("categoryTreeNullable")=="true";
	var allowRoot=container.readAttribute("categoryTreeAllowRoot")=="true";
	this.selected=parseInt(container.readAttribute("categoryTreeSelected"));
	if( this.selected.toString()=='NaN' )
		this.selected=null;
	var levels=container.readAttribute("categoryTreeLevels");

	var spanName=container.select('[type=categoryTreeName]')[0];
	var spanNameFullTree=false;
	if( spanName!=null ) if( spanName.readAttribute('categoryTreeNameFullTree')=='true' ) spanNameFullTree=true;

	var divContent=container.select('[type=categoryTreeContent]')[0];;
	var divFloat=container.select('[type=categoryTreeFloat]')[0];;
	var divLinkUp=container.select('[type=categoryTreeLinkUp]')[0];;
	var inputHidden=container.select('input')[0];

	var startEmpty=container.readAttribute("categoryTreeStartEmpty")=="true";
	
	var tmp1=container.readAttribute("omitCategoryIds");
	if( tmp1!=null ) 
	{
		var tmp2=tmp1.split(",");
		omitCats=new Array();
		for(var i=0;i<tmp2.length;i++)
		{
			var tmp3=parseInt(tmp2[i]);
			if( tmp3>0 )
				omitCats.push(tmp3);
		}
	}
		
	if( omitCats!=null && this.selected!=null )
	{
		if( omitCats.indexOf(this.selected)>=0 )
		{
			this.selected=null;
			startEmpty=true;
		}
	}

	this.entries=null;
	this.selectedEntry=null;

	var loaded=false;
	var shown=false;

	this.updateFirst=function(content)
	{
		var m=JSWorkspace.parseJSON(content);
		if( m!=null )
		{
			if( m.entries!=null )
			{
				var i=0;
				while(m.entries[i]!=null && omitCats!=null && omitCats.indexOf(m.entries[i].id)>=0 ) i++;
				
				if( m.entries[i]!=null )
				{
					if( spanName!=null )
						updateName(spanName,m.entries[i]);

					thisObj.selected=m.entries[i].id;
					thisObj.selectedEntry=m.entries[i];

					if( inputHidden!=null )
						inputHidden.value=m.entries[i].id;
				}
			}
		}
	}

	this.selectRoot=function()
	{


		if( spanName!=null )
			spanName.update('- główna -');

		thisObj.selected=0;
		thisObj.selectedEntry=null;

		if( inputHidden!=null )
			inputHidden.value=0;

		if( divLinkUp!=null )
			divLinkUp.hide();

		var ar=divContent.select('a');
		for(var i=0;i<ar.length;i++)
			ar[i].removeClassName('selected');

		if( thisObj.selectCallback!=null )  {
			var tmp=new Object();
			tmp.id=thisObj.selected;
			thisObj.selectCallback(tmp);
		}

	}


	this.up=function()
	{
		thisObj.select(thisObj.selectedEntry.parentId);
	}

	if( container.select('[type=categoryTreeUp]').length>0 )
		container.select('[type=categoryTreeUp]')[0].observe('click',this.up);
	if( container.select('[type=categoryTreeRoot]').length>0 )
		container.select('[type=categoryTreeRoot]')[0].observe('click',this.selectRoot);

	if( float )
	{
		divFloat.hide();
		divFloat.absolutize();
		divFloat.setStyle({height: '30px', width: '200px'});
	}

	this.run=function(onevent)
	{
		if( !loaded )
		{

			loaded=true;
			jsWorkspace.requestGet(Root+'category/tree,selectedId,'+this.selected+',levels,'+levels+',fullTree,'+spanNameFullTree,null,{callback:this.divUpdate});
		}

		if( shown && onevent!=null )
		{
			shown=false;
			if( float )
			{
				thisObj.hide();
			}
			return;
		}
		if( onevent!=null )
		{
			shown=true;
			if( float )
			{
				openDivFloat(onevent);
			}
		}
	}

	this.categoryClicked=function(e)
	{
		var element=Event.element(e);
		thisObj.select(element.readAttribute('value'));
	}

	var findEntry=function(l,id)
	{
		for(var i=0;i<l.length;i++)
		{
			if( l[i].id==id )
				return l[i];

			if( l[i].children!=null )
			{
				var r=findEntry(l[i].children,id);
				if( r!=null )
					return r;
			}
		}
		return null;
	}

	this.select=function(id,name)
	{
		if( id!=null ) 
		{
			if( omitCats!=null && omitCats.indexOf(parseInt(id))>=0 ) 
			{
				jsWorkspace.coverElement({where:$('content'),msg:'Aby mieć dostęp do branży alkohole : przeglądać, kupować i sprzedawać musicie Państwo przejść dodatkową weryfikację posiadania odpowiednich zezwoleń na obrót alkoholem. <a href="'+Root+'regulamin#alkohol" target="_blank" style="font-size: 12px; text-decoration: underline;">Czytaj więcej</a> <a href="'+Root+'akcyza" target="_blank" style="font-size: 12px; text-decoration: underline;">Chcę przejść weryfikację</a>',hcenter:true,msgClass:'classCoverMessageBigRed',closeButton:true});
				return;
			}
		}
		
		
		thisObj.selected=parseInt(id);

		thisObj.selectedEntry=findEntry(thisObj.entries,id);
		
		updateName(spanName,thisObj.selectedEntry);
		
		if( inputHidden!=null )
			inputHidden.value=id;

		if( thisObj.selectCallback!=null ) {
			if( thisObj.selectedEntry==null ) {
				var tmp=new Object();
				tmp.id=thisObj.selected;
				tmp.name='';
				
				if( staticTree )
					thisObj.selectCallback(tmp);
				else
					thisObj.postponedCallback=thisObj.selectCallback;
			}
			else
				thisObj.selectCallback(thisObj.selectedEntry);
		}

		if( !staticTree )
			jsWorkspace.requestGet(Root+'category/tree,selectedId,'+thisObj.selected+',levels,'+levels+',fullTree,'+spanNameFullTree,null,{callback:thisObj.divUpdate});
	}


	this.hide=function() {
		shown=false;
		if( float )
		{
			divContent.hide();
			divFloat.hide();
		}

		jsWorkspace.doReposition();
	}

	var openDivFloat=function(e) {

		var top=Event.pointerY(e);
		var left=Event.pointerX(e);


		divFloat.show();
		divContent.show();

		thisObj.reposition();
		jsWorkspace.doReposition();

	}

	var mouseTrapId=null;
	this.reposition=function()
	{
		if( !float )
			return;

		if( container.up()==null ) // Dziwny blad w IE
			return;

		var top=container.cumulativeOffset()[1]+container.getHeight();
		divFloat.setStyle({top:top+"px"});

		var left=container.cumulativeOffset()[0];
		divFloat.setStyle({left:left+"px"});

		if( mouseTrapId!=null )
			GMouseTrapEventManager.remove(mouseTrapId);

		if( divContent.getWidth()>0 )
			mouseTrapId=GMouseTrapEventManager.add([divContent],null,null,thisObj.hide,null,[10,30],false);
	}



	this.buildList=function(c,l)
	{
		for(var i=0;i<l.length;i++)
		{
			var p=new Element('p');
			c.appendChild(p);

			var a=new Element('a');
			p.appendChild(a);
			a.update(l[i].name);
			a.href="javascript:;";
			
			if( omitCats!=null && omitCats.indexOf(l[i].id)>=0 ) {
				a.addClassName('doomed');
			}

			a.observe('click',thisObj.categoryClicked);
			
			a.writeAttribute('value',l[i].id);
			a.writeAttribute('caption',l[i].name);
			if( l[i].selected ) {
				a.addClassName('selected');
				if( spanName!=null )
					updateName(spanName,l[i]);

				thisObj.selectedEntry=l[i];

				if( divLinkUp!=null )
				{
					if( l[i].hasParent )
						divLinkUp.show();
					else
						divLinkUp.hide();
				}

			}

			if( l[i].children.length>0 )
			{
				var div=new Element('div');
				c.appendChild(div);
				this.buildList(div,l[i].children);
			}
		}
	}

	var updateName=function(span,entry) {
		if( span==null )
			return;
		if( entry==null )
		{
			span.update('');
			return;
		}
		if( !spanNameFullTree )
		{
			if( entry.name==null )
				span.update('');
			else
				span.update(entry.name);
		}
		else {
			var tmp='';
			for(var i=0;i<entry.nameFull.length;i++)
				if( entry.nameFull[i]!=null )
					tmp+=(i>0?' &raquo; ':'')+entry.nameFull[i];
			span.update(tmp);
		}
	}


	this.divUpdate=function(content) {
		
		
		divContent.update("");
		var m=JSWorkspace.parseJSON(content);
		if( m!=null )
		{
			thisObj.buildList(divContent,m.entries);
			thisObj.entries=m.entries;
			
			if( divLinkUp!=null && thisObj.selectedEntry!=null )
			{
				if( thisObj.selectedEntry.hasParent )
					divLinkUp.show();
				else
					divLinkUp.hide();
			}

			if( !nullable && thisObj.selected==null && !startEmpty )
			{
				if( allowRoot )
					selectRoot();
				else if( thisObj.entries.length>0 )
				{
					if( spanName!=null )
						updateName(spanName,m.entries[0]);

					thisObj.selected=m.entries[0].id;
					thisObj.selectedEntry=m.entries[0];

					if( inputHidden!=null )
						inputHidden.value=m.entries[0].id;

					if( thisObj.selectCallback!=null )
						thisObj.selectCallback(thisObj.selectedEntry);
				}
			}
		}
		
		if( thisObj.selected!=null && thisObj.selectedEntry==null )
			thisObj.selectedEntry=findEntry(thisObj.entries,thisObj.selected);
		
		if( thisObj.selected==null )
			thisObj.selectedEntry=null;
		
		if( thisObj.postponedCallback!=null )
		{
			thisObj.postponedCallback(thisObj.selectedEntry);
			thisObj.postponedCallback=null;
		}
		
		

		thisObj.reposition();
		jsWorkspace.doReposition();

	}

	jsWorkspace.registerRepositionMethod(thisObj.reposition);
}
CategoryTree.registered=new Map();
CategoryTree.run=function(obj,event)
{
	var objExt=Element.extend(obj);
	if( !CategoryTree.registered.containsKey(obj) ) {
		var ct=new CategoryTree(objExt);
		CategoryTree.registered.put(obj,ct);
	}
	CategoryTree.registered.get(obj).run(event);
}

CategoryTree.init=function()
{
	var ar=Element.extend(document.body).select('div[type=categoryTree]');
	for(var i=0;i<ar.length;i++)
	{
		var obj=ar[i];
		CategoryTree.run(obj);
	}
}

function InputPopup(args)
{
	var div=new Element('div');
	document.body.appendChild(div);

	if( args.multiline )
	{
		var pattern=$('inputPopupMultilinePattern');
		div.update(pattern.innerHTML);
	}
	else
	{
		var pattern=$('inputPopupPattern');
		div.update(pattern.innerHTML);
	}


	div.show();
	div.setStyle({margin: "0px"});
	div.setStyle({padding: "0px"});
	div.absolutize();

	this.reposition=function() {
		div.setStyle({top: args.where.cumulativeOffset()[1]+"px"});
		div.setStyle({left: args.where.cumulativeOffset()[0]+"px"});
	}

	this.reposition();
	jsWorkspace.registerRepositionMethod(this.reposition);

	div.setStyle({width: "1px"});
	div.setStyle({height: "1px"});
	div.setStyle({zIndex: 90});



	div.select('[typeInput=inputPopupInput]')[0].focus();

	var thisObj=this;

	this.keypress=function(e)
	{
		if( e.keyCode==13 && args.multiline==null && !args.multiline )
		{
			thisObj.accept();
			return false;
		}
		else if( e.keyCode==27 )
		{
			thisObj.cancel();
			return false;
		}
		return true;
	}

	this.cancel=function()
	{
		div.hide();
		div.remove();

		jsWorkspace.doReposition();
	}

	this.accept=function()
	{
		var newValue=div.select('[typeInput=inputPopupInput]')[0].value;
		div.hide();
		div.remove();
		args.callback(newValue,args);

		jsWorkspace.doReposition();
	}

	div.select('[type=inputPopupOk]')[0].observe('click',this.accept);
	div.select('[type=inputPopupCancel]')[0].observe('click',this.cancel);
	div.select('[typeInput=inputPopupInput]')[0].observe('keypress',this.keypress);

	if( args.currentValue!=null )
		div.select('[typeInput=inputPopupInput]')[0].value=args.currentValue;

}

function OrderedTable(container)
{

	var newId=0;

	var classRowOdd=null;
	var classRowEven=null;

	classRowOdd=container.readAttribute('orderedTableClassRowOdd');
	classRowEven=container.readAttribute('orderedTableClassRowEven');

	var prefix=container.readAttribute('orderedTablePrefix');

	var afterOrderExpression=container.readAttribute('orderedTableAfterOrderExpression')

	var thisObj=this;

	var checkboxType=0;

	this.changeCheckboxType=function(n)
	{
		checkboxType=n;
		if( n!=0 )
		{
			var ar=container.select('[typeInput=orderedTableCheckbox]');
			var tmp=false;
			for(var i=0;i<ar.length;i++)
			{
				if( ar[i].checked )
				{
					if( tmp )
					{
						ar[i].checked=false;
					}
					tmp=true;
				}
			}
		}
	}

	this.add=function(content, input)
	{
		if( container.down()==null )
			container.appendChild(new Element('tbody'));
		var tr=new Element('tr');

		container.down().appendChild(tr);
		tr.update(content);

		initTrEvents(tr);

		revalidate();

		if( afterOrderExpression!=null )
			setTimeout(afterOrderExpression,1);

		if( input!=null )
		{
			input.value='';
			input.focus();
		}

	}

	this.changeCallback=function(newValue, args)
	{
		if( newValue.trim().empty() )
			return;
		var n=args.tr.select('[type=orderedTableName]')[0];
		var i=args.tr.select('[typeInput=orderedTableNameInput]')[0];

		n.update(newValue);
		i.value=newValue;
		n.addClassName('changed');
	}

	this.change=function(event)
	{
		var el=Event.element(event);
		while(el!=null && el.tagName!='TR')
			el=el.up();

		if( el==null )
			return;

		var cv=el.select('[type=orderedTableName]')[0].innerHTML;
		new InputPopup({tr:el,where:Event.element(event),callback:thisObj.changeCallback,currentValue:cv});

		if( afterOrderExpression!=null )
			setTimeout(afterOrderExpression,1);

	}

	this.remove=function(event)
	{
		var el=Event.element(event);
		while(el!=null && el.tagName!='TR')
			el=el.up();

		if( el==null )
			return;

		el.remove();

		revalidate();

		if( afterOrderExpression!=null )
			setTimeout(afterOrderExpression,1);

	}

	this.moveDown=function(event)
	{
		var el=Event.element(event);

		while(el!=null && el.tagName!='TR')
			el=el.up();

		if( el==null )
			return;

		if( el.next()==null )
			return;

		var tmp=el.next();


		container.down().insertBefore(el,tmp.next());

		revalidate();

		if( afterOrderExpression!=null )
			setTimeout(afterOrderExpression,1);

	}


	this.moveUp=function(event)
	{
		var el=Event.element(event);
		while(el!=null && el.tagName!='TR')
			el=el.up();

		if( el==null )
			return;

		if( el.previous()==null )
			return;

		var tmp=el.previous();

		el.remove();


		container.down().insertBefore(el,tmp);

		revalidate();

		if( afterOrderExpression!=null )
			setTimeout(afterOrderExpression,1);
	}

	var revalidate=function()
	{
		var ar=container.down().childElements();
		for(var i=0;i<ar.length;i++)
		{
			if( classRowOdd!=null && classRowEven!=null )
			{
				ar[i].removeClassName(classRowOdd,classRowEven);
				if( i%2!=0 )
					ar[i].addClassName(classRowOdd);
				else
					ar[i].addClassName(classRowEven);
			}



			if( i==0 && ar[i].select('[type=orderedTableLinkUpDiv]').length>0 )
				ar[i].select('[type=orderedTableLinkUpDiv]')[0].hide();
			if( i>0 && ar[i].select('[type=orderedTableLinkUpDiv]').length>0 )
				ar[i].select('[type=orderedTableLinkUpDiv]')[0].show();

			if( (i+1)>=ar.length && ar[i].select('[type=orderedTableLinkDownDiv]').length>0 )
				ar[i].select('[type=orderedTableLinkDownDiv]')[0].hide();
			if( (i+1)<ar.length && ar[i].select('[type=orderedTableLinkDownDiv]').length>0 )
				ar[i].select('[type=orderedTableLinkDownDiv]')[0].show();


			var o=ar[i].select('[typeInput=orderedTableNameInput]')[0];
			if( o!=null )
				o.name=prefix+'Name'+i;
			o=ar[i].select('[typeInput=orderedTableIdInput]')[0];
			if( o!=null )
				o.name=prefix+'Id'+i;
			o=ar[i].select('[typeInput=orderedTableCheckbox]')[0];
			if( o!=null )
				o.name=prefix+'Cb'+i;
		}
	}

	this.onCheckbox=function(event)
	{
		if( checkboxType==0 )
			return;
		var cb=Event.element(event);
		var c=cb.checked;

		var ar=container.select('[typeInput=orderedTableCheckbox]');
		for(var i=0;i<ar.length;i++)
		{
			if( ar[i].next().checked )
			{
				ar[i].next().checked=false;
				ar[i].value="false";
			}
		}

		if( c ) {
			cb.checked=true;
			cb.previous().value="true";
			return;
		}

		if( checkboxType==2 ) {
			cb.checked=true;
			cb.previous().value="true";
		}
	}

	var initTrEvents=function(obj)
	{
		if( obj.select('[type=orderedTableLinkUp]').length>0 )
			obj.select('[type=orderedTableLinkUp]')[0].observe('click',thisObj.moveUp);
		if( obj.select('[type=orderedTableLinkDown]').length>0 )
			obj.select('[type=orderedTableLinkDown]')[0].observe('click',thisObj.moveDown);
		if( obj.select('[type=orderedTableLinkRemove]').length>0 )
			obj.select('[type=orderedTableLinkRemove]')[0].observe('click',thisObj.remove);
		if( obj.select('[type=orderedTableLinkChange]').length>0 )
			obj.select('[type=orderedTableLinkChange]')[0].observe('click',thisObj.change);
		if( obj.select('[typeInput=orderedTableCheckbox]').length>0 )
			obj.select('[typeInput=orderedTableCheckbox]')[0].next().observe('click',thisObj.onCheckbox);
	}

	if( container.down()!=null )
	{
		var ar=container.down().childElements();
		for(var i=0;i<ar.length;i++)
			initTrEvents(ar[i]);
		revalidate();
	}
}
OrderedTable.init=function()
{
	var ar=Element.extend(document.body).select('table[type=orderedTable]');
	for(var i=0;i<ar.length;i++)
	{
		var ot=new OrderedTable(ar[i]);
		ar[i].orderedTable=ot;
	}
}
OrderedTable.add=function(obj,content,input)
{
	if( obj.orderedTable!=null )
		obj.orderedTable.add(content,input);
}
OrderedTable.changeCheckboxType=function(obj,n)
{
	if( obj.orderedTable!=null )
		obj.orderedTable.changeCheckboxType(n);
}


var photoPreviewArray=null;
var photoPreviewArrayIdx=0;
function photoPreviewGallery(idx,array)
{
	photoPreviewArray=array;
	photoPreviewArrayIdx=idx;
	
	photoPreview(array[idx].url,array[idx].name,array[idx].description);
	
}



function photoPreviewPrev()
{
	if( photoPreviewArray==null )
		return;
	
	if( photoPreviewArrayIdx==0 )
		return;
	
	
	photoPreviewArrayIdx--;
	
	$('photoPreviewDiv').select('[type=photoPreviewName]')[0].update(photoPreviewArray[photoPreviewArrayIdx].name);
	$('photoPreviewDiv').select('[type=photoPreviewDescription]')[0].update(photoPreviewArray[photoPreviewArrayIdx].description);
	
	$('photoPreviewDiv').tmpImg=new Image();
	$('photoPreviewDiv').tmpImg.onload=photoPreviewLoadedTmp1;
	$('photoPreviewDiv').tmpImg.src=photoPreviewArray[photoPreviewArrayIdx].url;
	
	
}


function photoPreviewNext()
{
	if( photoPreviewArray==null )
		return;
	
	if( photoPreviewArray.length<=(photoPreviewArrayIdx+1) )
		return;
	
	
	photoPreviewArrayIdx++;
	
	$('photoPreviewDiv').select('[type=photoPreviewName]')[0].update(photoPreviewArray[photoPreviewArrayIdx].name);
	$('photoPreviewDiv').select('[type=photoPreviewDescription]')[0].update(photoPreviewArray[photoPreviewArrayIdx].description);
	
	
	$('photoPreviewDiv').tmpImg=new Image();
	$('photoPreviewDiv').tmpImg.onload=photoPreviewLoadedTmp1;
	$('photoPreviewDiv').tmpImg.src=photoPreviewArray[photoPreviewArrayIdx].url;
	
	
}


function photoPreview(url, name, description)
{
	$('photoPreviewDiv').tCover=JSWorkspace.coverWithTransparent(Element.extend(document.body),50);
//	$('photoPreviewDiv').show();


	if( name!=null )
		$('photoPreviewDiv').select('[type=photoPreviewName]')[0].update(name);
	else
		$('photoPreviewDiv').select('[type=photoPreviewName]')[0].update("");

	if( description!=null )
		$('photoPreviewDiv').select('[type=photoPreviewDescription]')[0].update(description);
	else
		$('photoPreviewDiv').select('[type=photoPreviewDescription]')[0].update("");

	$('photoPreviewDiv').select('[type=photoPreviewName]')[0].setStyle({width:"250px",paddingLeft:"8px"});
	$('photoPreviewDiv').select('[type=photoPreviewDescription]')[0].setStyle({width:"250px",paddingLeft:"8px"});

	if( $('photoPreviewDiv').select('[type=photoPreviewName]')[0].innerHTML.strip().empty() )
		$('photoPreviewDiv').select('[type=photoPreviewName]')[0].setStyle({height: "0px"});
	else
		$('photoPreviewDiv').select('[type=photoPreviewName]')[0].setStyle({height: "auto"});

	if( $('photoPreviewDiv').select('[type=photoPreviewDescription]')[0].innerHTML.strip().empty() )
		$('photoPreviewDiv').select('[type=photoPreviewDescription]')[0].setStyle({height: "0px"});
	else
		$('photoPreviewDiv').select('[type=photoPreviewDescription]')[0].setStyle({height: "auto"});



	$('photoPreviewDiv').oldUrl=$('photoPreviewDiv').select('[type=photoPreviewImg]')[0].src;

	$('photoPreviewDiv').setStyle({top:JSWorkspace.getDocumentScrollOffset()[1]+"px"});
	$('photoPreviewDiv').setStyle({left:JSWorkspace.getDocumentScrollOffset()[0]+"px"});

	$('photoPreviewDiv').url=url;


	if( $('photoPreviewDiv').urls==null )
		$('photoPreviewDiv').urls=new Array();

	if( $('photoPreviewDiv').urls[url] ) {
		$('photoPreviewDiv').setOpacity(0);
		$('photoPreviewDiv').show();

		$('photoPreviewDiv').tmpImg=new Image();
		$('photoPreviewDiv').tmpImg.onload=photoPreviewLoadedTmp1;
		$('photoPreviewDiv').tmpImg.src=$('photoPreviewDiv').url;
	}
	else
		new Effect.Appear($('photoPreviewDiv'),{afterFinish: photoPreviewLoadedTmp2, duration: 0.1});
}
function photoPreviewLoadedTmp2()
{
	if( $('photoPreviewDiv').visible() )
		$('photoPreviewDiv').oldDim=[$('photoPreviewDiv').select('[type=photoPreviewDiv2]')[0].getWidth(),$('photoPreviewDiv').select('[type=photoPreviewDiv2]')[0].getHeight()];

	$('photoPreviewDiv').tmpImg=new Image();
	$('photoPreviewDiv').tmpImg.onload=photoPreviewLoaded;
	$('photoPreviewDiv').tmpImg.src=$('photoPreviewDiv').url;
}

function photoPreviewLoadedTmp1()
{
	$('photoPreviewDiv').select('[type=photoPreviewName]')[0].setStyle({width:$('photoPreviewDiv').tmpImg.width+"px"});
	$('photoPreviewDiv').select('[type=photoPreviewDescription]')[0].setStyle({width:$('photoPreviewDiv').tmpImg.width+"px"});

	$('photoPreviewDiv').select('[type=photoPreviewDiv2]')[0].setStyle({width: $('photoPreviewDiv').tmpImg.width+16+16+18+"px", height: $('photoPreviewDiv').tmpImg.height+"px"});
	$('photoPreviewDiv').select('[type=photoPreviewImg]')[0].src=$('photoPreviewDiv').tmpImg.src;
	new Effect.Appear($('photoPreviewDiv'),{duration: 0.1});
}

function photoPreviewLoaded()
{
	if( !$('photoPreviewDiv').visible() )
		return;


	$('photoPreviewDiv').urls[$('photoPreviewDiv').url]=true;


	new Effect.Fade($('photoPreviewDiv'), { afterFinish: photoPreviewLoadedTmp1, duration: 0.1 });



}
function photoPreviewClose()
{
	photoPreviewArray=null;
	
	
	if( !$('photoPreviewDiv').visible() )
		return;
	$('photoPreviewDiv').hide();
	$('photoPreviewDiv').tCover.remove();

	$('photoPreviewDiv').select('[type=photoPreviewImg]')[0].src=$('photoPreviewDiv').oldUrl;

	$('photoPreviewDiv').select('[type=photoPreviewDiv2]')[0].setStyle({width: $('photoPreviewDiv').oldDim[0]+"px", height: $('photoPreviewDiv').oldDim[1]+"px"});
}


//////////////////////////////////
// ItemEdit
function ItemEdit(item,copy,preview)
{
	debugText('d19');

	if( preview==null )
	{
		Hurcik.beforeItemEditUrl=null;
		
		if( Hurcik.urlStack.length>1 )
		{
			Hurcik.beforeItemEditUrl=Hurcik.urlStack[Hurcik.urlStack.length-2];
		}
		else
			Hurcik.beforeItemEditUrl=null;
	}
	
	var thisObj=this;

	var category=null;
	var predefinedItem=null;


	var step=0;
	var noFeatures=false;

	var editStep=-1;

	var quantityCounter=false;
	
	
	var blockCatsds=null;
	
	var showElement=function(el)
	{
		if( el.visible() )
			return;
		el.show();
	}

	var hideElement=function(el)
	{
		if( !el.visible() )
			return;
		el.hide();
	}

	var coverWithDiv=function(name,cover)
	{
		if( cover ) {
			jsWorkspace.showWaitCover({noscroll:true,what:$(name+'Cover'),where:$(name+'Div')});
			$(name+'Cover').show();
			$(name+'Cover').setOpacity(0.5);
		}
		else
		{
			if($(name+'Cover')!=null)
				$(name+'Cover').hide();
		}


	}

	var showHide=function()
	{
		if( item!=null )
		{
			
			hideElement($('predefinedItemDiv'));

			if( editStep!=0 ) hideElement($('categoryDiv')); else showElement($('categoryDiv'));
			if( editStep!=1 ) hideElement($('producerDiv')); else showElement($('producerDiv'));
			if( editStep!=3 ) hideElement($('featuresDiv')); else showElement($('featuresDiv'));
			if( editStep!=4 ) hideElement($('basicDataDiv')); else showElement($('basicDataDiv'));
			if( editStep!=5 ) hideElement($('deliveryPaymentDiv')); else showElement($('deliveryPaymentDiv'));
			if( editStep!=6 ) hideElement($('photosDiv')); else showElement($('photosDiv'));
			if( editStep!=7 ) hideElement($('optionsDiv')); else showElement($('optionsDiv'));

			$('categoryForwardDiv').hide();
			$('producerForwardDiv').hide();
			$('predefinedItemForwardDiv').hide();
			$('featuresForwardDiv').hide();
			$('basicDataForwardDiv').hide();
			$('deliveryPaymentForwardDiv').hide();
			$('photosForwardDiv').hide();

			$('categoryEditDiv').show();
			$('producerEditDiv').show();
			$('featuresEditDiv').show();
			$('basicDataEditDiv').show();
			$('deliveryPaymentEditDiv').show();
			$('photosEditDiv').show();
			$('optionsEditDiv').show();

			$('categoryEditAcceptDiv').hide();

			if( editStep<0 )
				$('editSelectDiv').show();
			else
				$('editSelectDiv').hide();

			showElement($('categorySelectDiv'));
			showElement($('producerSelectDiv'));

			if( noFeatures )
				$('featuresEditLinkDiv').hide();
			else
				$('featuresEditLinkDiv').show();


			jsWorkspace.doReposition();
			return;
		}

		showElement($('categoryDiv'));
		
		if( step>0 ) hideElement($('categorySelectDiv'));

		if( parseInt(document.itemForm.categoryId.value)>0 && step==0 )
			showElement($('categoryForwardDiv'));
		else
			hideElement($('categoryForwardDiv'));
		if( step==0 ) showElement($('categorySelectDiv'));


		

		if( step<1 ) hideElement($('producerDiv'));
		if( step>=1 ) showElement($('producerDiv'));

		if( step==1 ) showElement($('producerSelectDiv'));
		if( step==1 ) showElement($('producerForwardDiv'));
		if( step==1 ) hideElement($('producerCaptionDiv'));

		if( step>1 ) hideElement($('producerSelectDiv'));
		if( step>1 ) hideElement($('producerForwardDiv'));
		if( step>1 ) showElement($('producerCaptionDiv'));



		if( step<2 ) hideElement($('predefinedItemDiv'));
		if( step>=2 ) showElement($('predefinedItemDiv'));

		if( step==2 ) showElement($('predefinedItemSelectDiv'));
		if( step==2 ) showElement($('predefinedItemForwardDiv'));
		if( step==2 ) showElement($('predefinedItemCaptionDiv'));

		if( step>2 ) hideElement($('predefinedItemSelectDiv'));
		if( step>2 ) hideElement($('predefinedItemForwardDiv'));
		if( step>2 ) showElement($('predefinedItemCaptionDiv'));


		if( step<3 || noFeatures ) hideElement($('featuresDiv'));
		else showElement($('featuresDiv'));

		if( step==3 ) showElement($('featuresForwardDiv'));
		if( step>3 ) hideElement($('featuresForwardDiv'));



		if( step<4 ) hideElement($('basicDataDiv'));
		if( step>=4 ) showElement($('basicDataDiv'));

		if( step==4 ) showElement($('basicDataForwardDiv'));
		if( step>4 ) hideElement($('basicDataForwardDiv'));


		if( step<5 ) hideElement($('deliveryPaymentDiv'));
		if( step>=5 ) showElement($('deliveryPaymentDiv'));

		if( step==5 ) showElement($('deliveryPaymentForwardDiv'));
		if( step>5 ) hideElement($('deliveryPaymentForwardDiv'));




		if( step<6 ) hideElement($('photosDiv'));
		if( step>=6 ) showElement($('photosDiv'));

		if( step==6 ) showElement($('photosForwardDiv'));
		if( step>6 ) hideElement($('photosForwardDiv'));

		if( step<7 ) hideElement($('optionsDiv'));
		if( step>=7 ) showElement($('optionsDiv'));

		if( item==null )
		thisObj.coverReposition();


		if( item==null )
		{
			if( step==0 ) document.body.scrollTo();
			if( step==1 ) $('producerForwardDiv').scrollTo();
			if( step==2 ) $('predefinedItemForwardDiv').scrollTo();
			if( step==3 ) $('featuresForwardDiv').scrollTo();
			if( step==4 ) $('basicDataForwardDiv').scrollTo();
			if( step==5 ) $('deliveryPaymentForwardDiv').scrollTo();
			if( step==6 ) $('photosForwardDiv').scrollTo();
			if( step==7 ) $('optionsForwardLink').scrollTo();
		}


		jsWorkspace.doReposition();
	}

	this.coverReposition=function()
	{

		coverWithDiv('category',step>0);
		coverWithDiv('producer',step>1);
		coverWithDiv('predefinedItem',step>2);
		coverWithDiv('features',step>3);
		coverWithDiv('basicData',step>4);
		coverWithDiv('deliveryPayment',step>5);
		coverWithDiv('photos',step>6);


		if( noFeatures )
			$('featuresCover').hide();

	}

	this.backward=function()
	{
		if( item!=null )
		{
			editStep=-1;
			showHide();

//			goto(Root+'sale,id,'+item,'new ItemEdit('+item+')');
			return;
		}
		step--;
		showHide();

		if( step==3 && noFeatures )
		{
			step--;
			showHide();
		}
	}

	this.categoryCallback=function(entry)
	{
		if( entry==null )
			return;
		
		
		
		
		category=entry;

		var caption='';

		if( entry.parentNameFull!=null )
		{
			for(var i=0;i<entry.parentNameFull.length;i++)
				caption+=entry.parentNameFull[i]+((i+1)<entry.parentNameFull.length?' - ':"");
		}
		else
			caption+=entry.name;


		$('categoryCaption').update(caption);

		
		var block=false;
		
		if( thisObj.blockCatsIds!=null ) {
			if( category.id in blockCatsIds )
			{
				block=true;
				$('categoryAlkoholeMsg').show();
			}
			else
			{
				block=false;
				$('categoryAlkoholeMsg').hide();
			}
				
		}
		
		if( entry.hasChildren || block) {
			if( item==null )
				$('categoryForwardDiv').hide();
			else
				$('categoryEditAcceptDiv').hide();
		}
		else {
			if( item==null )
				$('categoryForwardDiv').show();
			else
				$('categoryEditAcceptDiv').show();
		}
	}

	this.categoryAccepted=function()
	{
		var catId;
		if( category!=null )
			catId=category.id;
		else
			catId=thisObj.categoryTree.selectedEntry.id;

		if( item!=null )
			jsWorkspace.requestGet(Root+'item/update,id,'+item+',prefix,feature,categoryId,'+catId,{noscroll:true,where:$('content'),what:$('coverWaitIconBig'),vcenter:true,hcenter:true},{callback:thisObj.categoryFeaturesLoaded});
		else
			jsWorkspace.requestGet(Root+'feature/form,prefix,feature,categoryId,'+catId+',valueItemId,'+copy,{noscroll:true,where:$('content'),what:$('coverWaitIconBig'),vcenter:true,hcenter:true},{callback:thisObj.categoryFeaturesLoaded});
	}

	this.producerAccepted=function()
	{
		var catId;
		if( category!=null )
			catId=category.id;
		else
			catId=thisObj.categoryTree.selectedEntry.id;


		if( document.itemForm )
		{
			if( document.itemForm.elements['producerName'].value.empty() ) {
				$('producerCaption').update('n/a');
			}
			else
				$('producerCaption').update(document.itemForm.elements['producerName'].value);
	
	
			if( document.itemForm.elements['producerId'].value.empty() )
				thisObj.predefinedItemSearchableControl.producerId=null;
			else
				thisObj.predefinedItemSearchableControl.producerId=document.itemForm.elements['producerId'].value;
			}


		if( item==null )
			thisObj.predefinedItemSearchableControl.categoryId=catId;

		step++;

		editStep=-1;

		if( copy!=null )
		{
			step++;
			if( noFeatures )
				step++;
		}

		showHide();

		if( item!=null )
			jsWorkspace.requestGet(Root+'item/update,id,'+item+',producerId,'+document.itemFormProducer.producerId.value+',producerProposal,'+JSWorkspace.encodeUrl(document.itemFormProducer.elements['producerName'].value),{noscroll:true,where:$('content'),what:$('coverWaitIconBig'),vcenter:true,hcenter:true},{msg:'Dane zaktualizowane',msgClass:'classCoverMessageBig',msgTimeout:3000});

	}

	this.predefinedItemCallback=function(id,caption)
	{
		if( id!=null )
		{
			$('predefinedItemCaptionDiv').show();
			$('predefinedItemCaption').update(caption);
		}
		else
			$('predefinedItemCaptionDiv').hide();

		predefinedItem={id:id,name:caption};
	}


	this.predefinedItemAccepted=function(entry)
	{
		var tmp=predefinedItem!=null;

		if( tmp )
			tmp=predefinedItem.id!=null && predefinedItem.id!=0;

		if( tmp )
		{
			jsWorkspace.requestGet(Root+'predefineditem,id,'+predefinedItem.id,{noscroll:true,where:$('content'),what:$('coverWaitIconBig'),vcenter:true,hcenter:true},{callback:thisObj.predefinedItemLoaded});
		}
		else
		{
			step++;

			if( noFeatures )
				step++;

			showHide();
		}
	}

	this.predefinedItemLoaded=function(content)
	{
		var m=JSWorkspace.parseJSON(content);

		if( m!=null )
		{
			document.itemForm.name.value=m.predefinedItem.name;
			document.itemForm.description.value=m.predefinedItem.description;

			if( m.photos!=null )
			{
				var tmp2="";
				for(var i=0;i<m.photos.length;i++)
				{
					var tmp=$('predefinedItemPhotoForm').innerHTML;

					tmp=tmp.replace(/key.id/g,m.photos[i].id);
					tmp=tmp.replace(/key.name/g,m.photos[i].photoName);
					tmp=tmp.replace(/key.description/g,m.photos[i].photoDescription);

					tmp2+=tmp;

				}

				$('photos').update(tmp2+$('photos').innerHTML);
			}
			step++;

			if( noFeatures )
				step++;

			editStep=-1;

			showHide();
		}
	}

	this.updateProvisionItem=function(content)
	{
		var m=JSWorkspace.parseJSON(content);
		if( m!=null )
		{
			provisionItem=m.itemProvision;
			thisObj.provision();
		}

	}

	this.categoryFeaturesLoaded=function(content,args)
	{

		if( content.strip().empty() )
		{
			noFeatures=true;

			$('featuresContentDiv').update(content);

			step++;

			editStep=-1;

			showHide();

			quantityCounter=false;

			if( item!=null )
				jsWorkspace.requestGet(Root+'item/provision,id,'+item,{noscroll:true,where:$('content'),what:$('coverWaitIconBig'),vcenter:true,hcenter:true},{callback:thisObj.updateProvisionItem,msg:'Dane zaktualizowane',msgTimeout:3000,msgClass:'classCoverMessageBig'});
		}
		else
		{
			noFeatures=false;

			if( item!=null )
				content+='<input type="hidden" name="categoryChangedId" value="'+category.id+'"/>';

			$('featuresContentDiv').update(content);


			step++;

			editStep=3;

			showHide();

			if( $('featuresContentDiv').select('[inputType=categoryFeatureQuantity]').length>0 )
				quantityCounter=true;
			else
				quantityCounter=false;

		}

		if( quantityCounter )
		{
			$('content').select('[name=quantity]')[0].disabled=true;
			$('content').select('[name=unit]')[0].disabled=true;
		}
		else
		{
			$('content').select('[name=quantity]')[0].disabled=false;
			$('content').select('[name=unit]')[0].disabled=false;
		}

		if( item==null )
			jsWorkspace.requestGet(Root+'item/provision,categoryId,'+category.id,{noscroll:true,where:$('content'),what:$('coverWaitIconBig'),vcenter:true,hcenter:true},{callback:thisObj.updateProvisionItem});


	}

	this.basicDataAccepted=function(entry)
	{
		var v;
		if( $('basicDataDiv').select('[name=unit]')[0].value=='0' )
			v=new Validator({containerElement:$('basicDataDiv'), entries:[
			{caption:'Nazwa',key:'name',classNameInputError:'inputTextError',classNameInputOk:'inputText',notEmpty:true},
			{caption:'Opis',key:'description',classNameInputError:'inputTextError',classNameInputOk:'inputText',notEmpty:true},
			{caption:'Ilość',key:'quantity',type:'int',min:1,classNameInputError:'inputTextError',classNameInputOk:'inputText',notEmpty:true},
			{caption:'Cena Jednostkowa',key:'price',type:'float',min:0.01,classNameInputError:'inputTextError',classNameInputOk:'inputText',notEmpty:true},
			{caption:'Minimalna ilość',key:'multiplier',type:'int',min:1,classNameInputError:'inputTextError',classNameInputOk:'inputText',notEmpty:false}

			]});
		else
			v=new Validator({containerElement:$('basicDataDiv'), entries:[
			{caption:'Nazwa',key:'name',classNameInputError:'inputTextError',classNameInputOk:'inputText',notEmpty:true},
			{caption:'Opis',key:'description',classNameInputError:'inputTextError',classNameInputOk:'inputText',notEmpty:true},
			{caption:'Ilość',key:'quantity',type:'float',min:0.001,classNameInputError:'inputTextError',classNameInputOk:'inputText',notEmpty:true},
			{caption:'Cena Jednostkowa',key:'price',type:'float',min:0.01,classNameInputError:'inputTextError',classNameInputOk:'inputText',notEmpty:true},
			{caption:'Minimalna ilość',key:'multiplier',type:'float',min:0.001,classNameInputError:'inputTextError',classNameInputOk:'inputText',notEmpty:false}

			]});


		if( v.validate().validAll )
		{
			step++;
			editStep=-1;

			showHide();
			if( item!=null )
				jsWorkspace.requestPost('itemFormBasicData',{where:$('content'),what:$('coverWaitIconBig'),vcenter:true,hcenter:true},{msg:'Dane zaktualizowane',msgClass:'classCoverMessageBig',msgTimeout:3000});

		}
		showHide();
	}


	this.deliveryPaymentAccepted=function(entry)
	{
		var v=new Validator({containerElement:$('deliveryPaymentDiv'), entries:[
			{caption:'Koszt przesyłki',key:'price1',type:'float',min:0.00,classNameInputError:'inputTextError',classNameInputOk:'inputText',notEmpty:false},
			{caption:'Koszt przesyłki',key:'price1a',type:'float',min:0.00,classNameInputError:'inputTextError',classNameInputOk:'inputText',notEmpty:false},
			{caption:'Koszt przesyłki',key:'price2',type:'float',min:0.00,classNameInputError:'inputTextError',classNameInputOk:'inputText',notEmpty:false},
			{caption:'Koszt przesyłki',key:'price2a',type:'float',min:0.00,classNameInputError:'inputTextError',classNameInputOk:'inputText',notEmpty:false},
			{caption:'Koszt odbioru osobistego',key:'price3',type:'float',min:0.00,classNameInputError:'inputTextError',classNameInputOk:'inputText',notEmpty:false},
			{caption:'Czas przesyłki',key:'integer1',type:'int',min:0,classNameInputError:'inputTextError',classNameInputOk:'inputText',notEmpty:false},
			{caption:'Czas przesyłki',key:'integer2',type:'int',min:0,classNameInputError:'inputTextError',classNameInputOk:'inputText',notEmpty:false},
			{caption:'Czas przesyłki',key:'integer3',type:'int',min:0,classNameInputError:'inputTextError',classNameInputOk:'inputText',notEmpty:false}
			]});

		if( v.validate().validAll )
		{
			step++;
			editStep=-1;

			showHide();
			if( item!=null )
				jsWorkspace.requestPost('itemFormDeliveryPayment',{where:$('content'),what:$('coverWaitIconBig'),vcenter:true,hcenter:true},{msg:'Dane zaktualizowane',msgClass:'classCoverMessageBig',msgTimeout:3000});

		}
		showHide();
	}

	this.featuresAccepted=function()
	{
		var v=new Validator({containerElement:$('featuresDiv')});

		if( v.validate().validAll )
		{
			var valQ=0;
			var valUnit=0;

			if( quantityCounter ) {


				if( document.itemForm )
					valUnit=document.itemForm.quantityCounterUnit.value;
				else
					valUnit=document.itemFormFeatures.quantityCounterUnit.value;

				if( valUnit=='0' )
					$('content').select('[inputType=categoryFeatureQuantity]').each(function(o) { if( o.up().visible() ) { if( !validateIntegerValue(o.value) ) {o.value='';}else { var tmp=parseInt(o.value);   valQ+=tmp;}  }} );
				else
					$('content').select('[inputType=categoryFeatureQuantity]').each(function(o) { if( o.up().visible() ) { if( !validateFloatValue(o.value) ) {o.value='';}else { var tmp=parseFloat(o.value.replace(',','.'));   valQ+=tmp;}  }} );

				if( valQ<=0 )
				{
					Hurcik.msgError('Musisz wybrać prznajmniej jedną z opcji i podać ilość',$('featuresQuantity'));

					showHide();
					return;
				}
			}

			if( $('featuresQuantity')!=null )
				Hurcik.msgOk('',$('featuresQuantity'));


			step++;
			editStep=-1;

			showHide();
			if( item!=null )
				jsWorkspace.requestPost('itemFormFeatures',{where:$('content'),what:$('coverWaitIconBig'),vcenter:true,hcenter:true},{callback:thisObj.updateProvisionItem,msg:'Dane zaktualizowane',msgTimeout:3000,msgClass:'classCoverMessageBig'});

			// Calculate items count
			if( quantityCounter )
			{
				$('content').select('[name=quantity]')[0].value=""+valQ;
				$('content').select('[name=unit]')[0].value=valUnit;
			}
		}

		showHide();
	}

	this.photosAccepted=function()
	{
		editStep=-1;
		step++;
		showHide();
		if( item!=null ) {
			preparePhotos(Element.extend(document.itemFormPhotos));
			jsWorkspace.requestPostIframe('itemFormPhotos',{where:$('content'),what:$('coverWaitIconBigWithProgress'),vcenter:true,hcenter:true},{msg:'Dane zaktualizowane',msgClass:'classCoverMessageBig',msgTimeout:3000,expression:'Hurcik.goto(Root+"sale/edit,id,'+item+'",{noStack:true,afterJSExpr:"new ItemEdit('+item+',null,'+preview+')"})',expressionTimeout:3000});
		}
	}

	this.accepted=function()
	{
		if( item!=null )
		{
			editStep=-1;
			showHide();
				jsWorkspace.requestPost('itemFormOptions',{noscroll:true,where:$('content'),what:$('coverWaitIconBig'),vcenter:true,hcenter:true},{msg:'Dane zaktualizowane',msgClass:'classCoverMessageBig',msgTimeout:3000,expression:'jsWorkspace.requestGet(Root+"item/provision/details,id,'+item+'",{noscroll:true,where:$("divProvisionDetails"),what:$("coverWaitIcon"),hcenter:true,vcenter:true},{destId:"divProvisionDetails"})',expressionTimeout:3000});
		}
		else
		{
			preparePhotos(Element.extend(document.itemForm));
			//jsWorkspace.requestPostIframe('itemForm',{noscroll:true,what:$('coverWaitIconBigWithProgress'),where:$('content'),vcenter:true,hcenter:true},{callback:thisObj.afterAccept})
			
			$('itemEditNavi').update('<img src="'+Root+'img/wait16trans.gif"/>');
			jsWorkspace.requestPostIframe('itemForm',null,{callback:thisObj.afterAccept});
		}
	}

	var itemId=null;
	this.afterAccept=function(content)
	{
		var m=JSWorkspace.parseJSON(content);
		if( m!=null )
		{
			if( m.result==0 ) {

				step=0;
				//showHide();

				itemId=m.id;
			//	jsWorkspace.coverElement({where:$('content'),msg:'Dane zaktualizowane',hcenter:true,vcenter:true,msgTimeout:3000,actionTimeout:3000,actionExpression:'Hurcik.goto(Root+"sale",{afterJSExpr:"new ItemEdit();"})',msgClass:'classCoverMessageBig'});
				Hurcik.goto(Root+'sale/preview,id,'+m.id);
//				jsWorkspace.requestGet(Root+'item/get,id,'+m.id,{what:$('coverWaitIconBig'),where:$('content'),vcenter:true,hcenter:true},{callback:thisObj.preview})
			}
			else {
				jsWorkspace.coverElement({noscroll:true,where:$('content'),msg:'Wystąpił błąd',msgError:true,hcenter:true,vcenter:true,coverTimeout:2000,msgClass:'classCoverMessageBig'});
				showHide();
			}
		}

	}

	this.preview=function(content)
	{
		step++;
		showHide();

		$('previewContentDiv').update(content);
	}

	this.publish=function()
	{
		if( itemId!=null )
		{
			var backUrl=Hurcik.beforeItemEditUrl;

			if( backUrl!=null )
			{
				jsWorkspace.requestGet(Root+'item/publish,id,'+itemId,{what:$('coverWaitIconBig'),where:$('content'),vcenter:true,hcenter:true,msg:'Oferta opublikowana',msgTimeout:3000,actionTimeout:3000,actionExpression:'Hurcik.goto(Root+"sale",{afterJSExpr:"Hurcik.goto(&quot;'+backUrl+'&quot;)"})'})
			}
			else
				jsWorkspace.requestGet(Root+'item/publish,id,'+itemId,{what:$('coverWaitIconBig'),where:$('content'),vcenter:true,hcenter:true,msg:'Oferta opublikowana',msgTimeout:3000,actionTimeout:3000,actionExpression:'Hurcik.goto(Root+"mycenter",{})'})
		}
	}
	this.correct=function()
	{
		if( itemId!=null )
			Hurcik.goto(Root+'sale,id,'+itemId,{afterJSExpr:"new ItemEdit("+itemId+");"});
	}

	var provisionItem=null;

	this.provision=function()
	{
		var form=document.itemFormOptions;
		if( form==null )
			form=document.itemForm;

		var n=1;
		if( provisionItem!=null )
			n=provisionItem/100;

		if( form.optionPosition.value=='true' )
			n+=3;
		if( form.optionBold.value=='true' )
			n+=1;
		if( form.optionPageCategory.value=='true' )
			n+=8;
		if( form.optionPageHome.value=='true' )
			n+=20;

		$('provision').update(n);
	}

	this.categoryTree=CategoryTree.registered.get($('content').select('[type=categoryTree]')[0]);
	this.categoryTree.selectCallback=this.categoryCallback;

	this.predefinedItemSearchableControl=SearchableControl.registered.get($('content').select('[jsClassName=PredefinedItemSearch]')[0]);
	this.predefinedItemSearchableControl.selectCallback=this.predefinedItemCallback;

	if( item!=null )
	{
		$('categoryEditLink').observe('click',function() {editStep=0; showHide();});
		$('producerEditLink').observe('click',function() {editStep=1; showHide();});
		$('basicDataEditLink').observe('click',function() {editStep=4; showHide();});
		$('deliveryPaymentEditLink').observe('click',function() {editStep=5; showHide();});
		$('featuresEditLink').observe('click',function() {editStep=3; showHide();});
		$('photosEditLink').observe('click',function() {editStep=6; showHide();});
		
		if( $('optionsEditLink')!=null )
		$('optionsEditLink').observe('click',function() {editStep=7; showHide();});

	}

		$('content').select('[id=categoryForwardLink]').each(function(o) {o.observe('click',thisObj.categoryAccepted)});
		$('content').select('[id=producerForwardLink]').each(function(o) {o.observe('click',thisObj.producerAccepted)});
		$('content').select('[id=predefinedItemForwardLink]').each(function(o) {o.observe('click',thisObj.predefinedItemAccepted)});
		$('content').select('[id=basicDataForwardLink]').each(function(o) {o.observe('click',thisObj.basicDataAccepted)});
		$('content').select('[id=deliveryPaymentForwardLink]').each(function(o) {o.observe('click',thisObj.deliveryPaymentAccepted)});
		$('content').select('[id=featuresForwardLink]').each(function(o) {o.observe('click',thisObj.featuresAccepted)});
		$('content').select('[id=photosForwardLink]').each(function(o) {o.observe('click',thisObj.photosAccepted)});
		$('content').select('[id=optionsForwardLink]').each(function(o) {o.observe('click',thisObj.accepted)});




	var tmp2=$('content').select('[id=backwardLink]');
	for(var i=0;i<tmp2.length;i++) tmp2[i].observe('click',this.backward);

	if( preview )
	{
		$('previewLinkDiv').show();
		$('backLinkDiv').hide();
	}

	if( item==null )
		jsWorkspace.registerRepositionMethod(thisObj.coverReposition);

	var t=new Element('div'); t.writeAttribute('type','photoFormRoot');   t.update($('newPhotoForm').innerHTML);  $('photos').appendChild(t);

	if( item!=null )
		noFeatures=$('featuresContentDiv').innerHTML.trim().empty();

	$('content').select('[typeHurcik=provision]').each(function(o) {o.observe('click',thisObj.provision)});

	if( copy )
	{
		step=4;
		if( $('quantityCounter')!=null )
			step=3;
	}
	
	
	debugText('d20');
	showHide();
	

	if( $('featuresContentDiv').select('[inputType=categoryFeatureQuantity]').length>0 )
		quantityCounter=true;
	else
		quantityCounter=false;
	

	if( quantityCounter ) {
		$('content').select('[name=quantity]')[0].disabled=true;
		$('content').select('[name=unit]')[0].disabled=true;
	}
 	else {
		$('content').select('[name=quantity]')[0].disabled=false;
		$('content').select('[name=unit]')[0].disabled=false;
	}

	if( item!=null )
		jsWorkspace.requestGet(Root+'item/provision,id,'+item,{where:$('content'),what:$('coverWaitIconBig'),vcenter:true,hcenter:true},{callback:thisObj.updateProvisionItem});
	
}
// ItemEdit
//////////////////////////////////

function preparePhotos(form)
{
	var ar=form.select("[name=photo]");
	for(var i=0;i<ar.length;i++)
		ar[i].name="photo"+i;

	ar=form.select("[name=photoName]");
	for(var i=0;i<ar.length;i++)
		ar[i].name="photoName"+i;

	ar=form.select("[name=photoDescription]");
	for(var i=0;i<ar.length;i++)
		ar[i].name="photoDescription"+i;

	ar=form.select("[name=photoId]");
	for(var i=0;i<ar.length;i++)
		ar[i].name="photoId"+i;

	ar=form.select("[name=photoRemove]");
	for(var i=0;i<ar.length;i++)
		ar[i].name="photoRemove"+i;

	ar=form.select("[name=photoType]");
	for(var i=0;i<ar.length;i++)
		ar[i].name="photoType"+i;
}

//////////////////////////////////
// Filter
function Filter(args)
{
	var filterId=0;

	if( args.container==null )
		return;

	var filterListDiv=args.container.select('[type=filtersListDiv]')[0];
	var filterListContent=args.container.select('[type=filtersListContent]')[0];
	var input=args.container.select('input[type=text]')[0];
	var form=args.container.select('form')[0];

	var thisObj=this;


	this.categorySelectCallback=function(entry)
	{
		//jsWorkspace.requestGet(Root+'filter,id,'+filterId+',categoryId,'+entry.id,null,{dest:args.filterFeaturesDiv});
		thisObj.gotoPage(0);
		
		
	}

	if( args.categoryTree!=null ) {
		args.categoryTree.selectCallback=this.categorySelectCallback;
	}

	this.filterList=function()
	{
		filterListContent.update('Wczytywanie...');

		filterListDiv.show();
		filterListDiv.setStyle({left:input.cumulativeOffset()[0]+"px"});
		filterListDiv.setStyle({top:(input.cumulativeOffset()[1] + input.getHeight() + 1)+"px"});

		jsWorkspace.requestGet(Root+'filter/list',null,{dest:filterListContent,callback:thisObj.filterListCallback});
	}

	this.filterListCallback=function(content)
	{
		filterListContent.select('[type=linkDelete]').each(function(o) {o.observe('click',thisObj.filterListDelete)});
		filterListContent.select('[type=linkSelect]').each(function(o) {o.observe('click',thisObj.filterListSelect)});
	}

	this.filterListDelete=function(ev)
	{
		var obj=Event.element(ev);
		var id=obj.up().up().up().readAttribute("filterId");
		jsWorkspace.requestGet(Root+'filter/delete,id,'+id);
		obj.up().up().up().remove();
	}

	this.filterListClose=function()
	{
		filterListDiv.hide();
	}

	this.filterListSelect=function(ev)
	{
		filterListDiv.hide();
		var obj=Event.element(ev);
		var id=obj.up().up().readAttribute("filterId");
		if( id==null )
			return;

		Hurcik.goto(Root+args.action+',id,'+id,{afterJSExpr:args.afterJS});
	}

	this.gotoPage=function(n)
	{
		form=$('filterForm');
		form.elements['page'].value=n;
		form.action=Root+args.action;
		
		

		if( args.ajax )
			Hurcik.gotoForm('filterForm',{afterJSExpr:args.afterJS});
		else
			form.submit();
		

	}

	this.sort=function(by)
	{
		var current=form.elements['sortBy'].value
		form.elements['sortBy'].value=by;
		form.action=Root+args.action;

		if( by==current )
		{
			if( form.elements['sortDesc'].value=='true' )
				form.elements['sortDesc'].value='false';
			else
				form.elements['sortDesc'].value='true';
		}
		else
		{
			form.elements['sortDesc'].value='true';
		}

		if( args.ajax )
			Hurcik.gotoForm('filterForm',{afterJSExpr:args.afterJS});
		else		
			form.submit();
	}

	if( args.container.select('[type=FilterList]')[0] )
	args.container.select('[type=FilterList]')[0].observe('click',thisObj.filterList);
	if( args.container.select('[type=FilterListCloseLink]')[0] )
	args.container.select('[type=FilterListCloseLink]')[0].observe('click',thisObj.filterListClose);

}
// Filter
//////////////////////////////////


function PanelChanger(divs,container,args)
{
	if( divs.length==0 )
		return;
	if( container==null )
		return;

	var thisObj=this;
	var buttons=new Array();

	this.buttonCallback=function(e)
	{
		var nr=Event.element(e).up().readAttribute("nr");
		if( divs[nr]!=null )
			thisObj.switchTo(nr);

	}

	var current=-1;

	this.workHide=function(effect)
	{
		for(var i=0;i<divs.length;i++)
		{
			if( i!=current )
			{
				divs[i].hide();
				buttons[i].addClassName('ImageChangerButtonOut'); buttons[i].removeClassName('ImageChangerButtonOver');
			}
			else
			{
				buttons[i].addClassName('ImageChangerButtonOver'); buttons[i].removeClassName('ImageChangerButtonOut');
			}
		}
			divBg.setOpacity(0.5);

	}

	this.switchTo=function(n)
	{
		if( n==current )
			return;
		var old=current;
		current=n;

		if( divs[old]!=null )
		{
			divs[old].setStyle({zIndex:48});
		}
		divs[current].setStyle({zIndex:49});

		divs[current].setStyle({width:panelWidth+"px",height:panelHeight+"px"});


		Effect.Appear(divs[current],{afterFinish:thisObj.workHide, duration: 0.1});
		//divs[current].show();thisObj.workHide();
	}

	if( args.buttonSpaces==null )
		args.buttonSpaces=[4,4];

	if( args.buttonOffsets==null )
		args.buttonOffsets=[10,10];

	for(var i=0;i<divs.length;i++)
	{
		divs[i].absolutize();
		divs[i].setStyle({left:container.cumulativeOffset()[0]+"px"});
		divs[i].setStyle({top:container.cumulativeOffset()[1]+"px"});
	}


	for(var i=0;i<divs.length;i++)
	{
		var b=new Element('div');

		buttons[i]=b;

		document.body.appendChild(b);
		b.show();
		b.absolutize();
		b.addClassName("ImageChangerButtonOut");

		b.setStyle({zIndex:51});

		b.writeAttribute("nr",i);

		var p=new Element('p');
		b.appendChild(p);

		p.observe("click",thisObj.buttonCallback);
		p.observe("mouseover", function(ev){Event.element(ev).up().addClassName('ImageChangerButtonOver'); Event.element(ev).up().removeClassName('ImageChangerButtonOut'); } );
		p.observe("mouseout", function(ev){ if( Event.element(ev).up().readAttribute('nr')==current ) return; Event.element(ev).up().addClassName('ImageChangerButtonOut'); Event.element(ev).up().removeClassName('ImageChangerButtonOver'); } );

		var x=container.cumulativeOffset()[0];
		x+=args.buttonOffsets[0];
		x+=args.buttonSpaces[0]*i + b.down().getWidth()*i;

		var y=container.cumulativeOffset()[1]+container.getHeight();
		y-=args.buttonOffsets[1];
		y-=b.down().getHeight();

		b.setStyle({left:x+"px",top:y+"px",width:"1px"});

	}

	this.playClicked=function()
	{
		if( running )
			thisObj.stop();
		else
			thisObj.start();
	}


	var playDiv=new Element('div');
	var playLink=new Element('a');
	var playP=new Element('p');
	document.body.appendChild(playDiv);
	playDiv.appendChild(playLink);
	playLink.appendChild(playP);
	playLink.href="javascript:;";
	playDiv.absolutize();

	playDiv.addClassName("ImageChangerButtonPlayPlay");
	playLink.observe('click',this.playClicked);
	playDiv.setStyle({zIndex:51});


		var x=container.cumulativeOffset()[0];
		x+=args.buttonOffsets[0];
		x+=args.buttonSpaces[0]*divs.length + buttons[0].down().getWidth()*i;

		var y=container.cumulativeOffset()[1]+container.getHeight();
		y-=args.buttonOffsets[1];
		y-=buttons[0].down().getHeight();

		y=buttons[0].cumulativeOffset()[1];

		playDiv.setStyle({left:x+"px",top:y+"px",width:"1px"});

	var divBg=new Element('div');
	document.body.appendChild(divBg);
	divBg.show();
	divBg.absolutize();
	divBg.appendChild(new Element('p'));
	divBg.setStyle({zIndex:50});
	divBg.setOpacity(0.5);

	divBg.down().setStyle({backgroundColor:"white"});



	var h=buttons[0].down().getHeight()+2*args.buttonSpaces[1];
	var w=(buttons[0].down().getWidth()+args.buttonSpaces[0]) * divs.length+ playDiv.down().down().getWidth() + 2*args.buttonSpaces[0];
	divBg.down().setStyle({width:w+"px",height:h+"px"});

	var x=buttons[0].cumulativeOffset()[0]-args.buttonSpaces[0];
	var y=buttons[0].cumulativeOffset()[1]-args.buttonSpaces[1];

	divBg.setStyle({left:x+"px",top:y+"px",width:divBg.down().getWidth()+"px",height:divBg.down().getHeight()+"px"});





	this.runningFunc=function()
	{
		if( !running )
			return;

		var n=current+1;
		if( n>=divs.length )
			n=0;

		thisObj.switchTo(n);

		GTimeoutManager.add(6000,thisObj.runningFunc);
	}

	var running=false;
	this.start=function()
	{
		if( running )
			return;
		running=true;

		playDiv.removeClassName("ImageChangerButtonPlayStop");
		playDiv.addClassName("ImageChangerButtonPlayPlay");

		GTimeoutManager.add(6000,thisObj.runningFunc);
	}
	this.stop=function()
	{
		playDiv.addClassName("ImageChangerButtonPlayStop");
		playDiv.removeClassName("ImageChangerButtonPlayPlay");

		running=false;
	}

	var panelWidth=args.panelWidth;
	var panelHeight=args.panelHeight;

	this.hideAll=function()
	{
		thisObj.stop();
		divBg.hide();
		playDiv.hide();
		for(var i=0;i<divs.length;i++)
			buttons[i].hide();
	}
	this.recover=function()
	{
		divBg.show();
		playDiv.show();
		for(var i=0;i<divs.length;i++)
			buttons[i].show();
		thisObj.start();
	}

	this.switchTo(0);
	this.start();
}


/////////////////////


function messageSentAfter(content)
{
	var m=JSWorkspace.parseJSON(content);
	if( m==null )
		return;


	if( m.result==0 )
	{
		Hurcik.setMessageOk($("msg"),"Wiadomość wysłana");
	}
	else
	{
		Hurcik.setMessageError($("msg"),"Wystąpił błąd");
	}

}


////////////////////////////


function PanelOfItems(container)
{
	if( container.handler!=null )
		return;
	container.handler=this;
	
	var panels=new Array();
	
	var noajax=false;
	
	if( container.readAttribute('noajax')=='true' )
		noajax=true;
	
	var divContent=container.select('[type=PanelOfItemsContent]')[0];
	var divPanels=container.select('[type=PanelOfItemsPanels]')[0];
	
	var maxInRow=container.readAttribute("maxInRow");
	var max=container.readAttribute("max");
	var section=container.readAttribute("section");
	var catId=container.readAttribute("catId");
	
	var thisObj=this;
	
	panels.push(divContent);
	
	
	var position=panels[0].cumulativeOffset();
	
	
	var initHeight=divContent.getHeight()+0;
	divPanels.setStyle({height: initHeight+'px'});
	
	var current=0;
	var contentLocked=0;
	
	var lastIdle=new Date().getTime();
	
	var openNew=function()
	{
		contentLocked=1;
		
		var newDiv=new Element('div');
		divPanels.appendChild(newDiv);
		newDiv.hide();
		
		panels.push(newDiv);
		
		jsWorkspace.requestGet(Root+'panelofitems,max,'+max+',maxInRow,'+maxInRow+',section,'+section+',catId,'+catId+(noajax?',noajax,true':''),null,{callback:thisObj.openNewLoaded});
	}

	this.openNewLoaded=function(content)
	{
		
		panels[panels.length-1].update(content);


		setTimeout(thisObj.openNewWaitForImages,100);
	}
	

	
	this.openNewWaitForImages=function()
	{
		var div=panels[panels.length-1];
		
		var notLoaded=false;
		
		div.select('img').each(function(img) {if( !img.complete ) notLoaded=true; }  );
		
		if( notLoaded )
		{
			setTimeout(thisObj.openNewWaitForImages,100);
		}
		else
		{
			current++;

			switchPanels(panels[current-1],panels[current]);
		}
	}
	
	
	this.switchPanelsResize=function()
	{
		var initHeight=panels[current].getHeight()+0;
		divPanels.setStyle({height: initHeight+'px'});
	}
	var switchPanels=function(div1,div2)
	{
		new Effect.Fade(div1,{afterFinish: thisObj.switchPanelsResize, duration: 0.1});
		
		new Effect.Appear(div2, { queue: 'end',  afterFinish: thisObj.contentUnlock, duration: 0.1 });		
	}
	
	this.contentUnlock=function()
	{
		lastIdle=new Date().getTime();
		contentLocked=0;
	}
	
	
	this.goLeft=function()
	{
		if( contentLocked==1  )
			return;
		
		if( current>0 )
		{
			contentLocked=1;

			current--;
			switchPanels(panels[current+1],panels[current]);		
		}
	}
	
	this.goRight=function()
	{
		if( contentLocked==1 )
			return;
		
		if( (current+1)<panels.length )
		{
			contentLocked=1;

			current++;
			switchPanels(panels[current-1],panels[current]);
		}
		else
			openNew();
	}
	
	
	this.period=function()
	{
		if( contentLocked==1 )
		{
			return;
		}
		
		
		var time=new Date().getTime();

		if( (time-lastIdle)>5000 )
		{
			
			
			if( !(container.cumulativeOffset()[0]>0) || !(container.cumulativeOffset()[1]>0) ) {
				clearInterval(interval);
				return;
			}			
			
			thisObj.goRight();
			
		}
		periodLocked=0;
	}
	
	this.stop=function()
	{
		if( interval!=null )
		{
			clearInterval(interval);
			interval=null;
		}
	}
	
	container.select('[type=linkLeft]')[0].observe('click',this.goLeft);
	container.select('[type=linkRight]')[0].observe('click',this.goRight);
	var interval=new PeriodicalExecuter(this.period,0.5);

}
PanelOfItems.Instances=new Array();
PanelOfItems.Scan=function()
{
	var body=Element.extend(document.body);
	
	body.select('[type=PanelOfItems]').each(function(c){PanelOfItems.Instances.push(new PanelOfItems(c));});
}
PanelOfItems.StopInstances=function()
{
	PanelOfItems.Instances.each(function(o){if( o.stop ) o.stop();});
	PanelOfItems.Instances.clear();
}


//////////////////////////////

function Banner(container)
{
	if( container.handler!=null )
		return;
	container.handler=this;
	
	var divContent=container.select('[type=BannerContent]')[0];
	var divContentBuffer=container.select('[type=BannerContentBuffer]')[0];
	var zone=container.readAttribute("zone");
	
	var thisObj=this;
	
	//container.setStyle({width: divContent.getWidth()+"px",height: divContent.getHeight()+"px" });

	var contentLocked=0;
	
	var lastIdle=new Date().getTime();
	
	var openNew=function()
	{
		contentLocked=1;
		jsWorkspace.requestGet(Root+'banner,zone,'+zone,null,{callback:thisObj.openNewLoaded});
	}

	this.openNewLoaded=function(content)
	{
		divContentBuffer.update(content);
		setTimeout(thisObj.openNewWaitForImages,100);
	}
	
	this.openNewWaitForImages=function()
	{
		var div=divContentBuffer;
		var notLoaded=false;
		div.select('img').each(function(img) {if( !img.complete ) notLoaded=true; }  );
		
		if( notLoaded )
		{
			setTimeout(thisObj.openNewWaitForImages,100);
		}
		else
		{
			switchPanels();
		}
	}
	
	
	this.switchPanelsResize=function()
	{
		divContent.update(divContentBuffer.innerHTML);
		container.setStyle({width: divContent.getWidth()+"px",height: divContent.getHeight()+"px" });
		new Effect.Appear(divContent, { queue: 'end',  afterFinish: thisObj.contentUnlock, duration: 0.1 });		
	}
	var switchPanels=function(div1,div2)
	{
		new Effect.Fade(divContent,{afterFinish: thisObj.switchPanelsResize, duration: 0.1});
	}
	
	
	this.contentUnlock=function()
	{
		lastIdle=new Date().getTime();
		contentLocked=0;
	}
	
	
	this.goRight=function()
	{
		if( contentLocked==1 )
			return;
		
		openNew();
	}
	
	
	this.period=function()
	{
		
		if( contentLocked==1 )
		{
			return;
		}
		
		var time=new Date().getTime();

		if( (time-lastIdle)>3000 )
		{

			thisObj.goRight();
			
		}
		periodLocked=0;
	}
	
	this.stop=function()
	{
		if( interval!=null )
		{
			clearInterval(interval);
			interval=null;
		}
	}
	
	var interval=setInterval(this.period,500);
}
Banner.Instances=new Array();
Banner.Scan=function()
{
	var body=Element.extend(document.body);
	
	body.select('[type=Banner]').each(function(c){Banner.Instances.push(new Banner(c));});
}
Banner.StopInstances=function()
{
	Banner.Instances.each(function(o){if( o.stop ) o.stop();});
	
	Banner.Instances.clear();
}

