 
var PiShowList = new Class({

	Implements: [Events, Options],

	initialize: function(containerId,options){
		var self = this;
		this.setOptions(options);
		this.listContainer = $(containerId);
		if($(containerId+'-taxo'))
		this.taxoContainer = $(containerId+'-taxo');
		if($(containerId+'-country'))
		this.scountry = $(containerId+'-country');
		if($(containerId+'-sword'))
		this.sword = $(containerId+'-sword');
		this.loader = $(containerId+'-loader');
		this.timeSpan = $(containerId+'-time');
		if(this.sword)
		this.swordFixedValue = this.swordInitValue = this.sword.value;

		//get lng
		/*
		var jsonRequest = new Request.JSON({url: "typo3conf/ext/ef/res/ajax/ll2json.php", onComplete: function(lngObj){
			this.lngLabels = lngObj;
		}}).get({'lng': 'fr','xmlFile':'/var/lib/typo3-dummy/typo3conf/ext/ef/pishowlist/locallang.xml'});
		*/

		//this.updateList();

		//sword init
		if(this.sword){
			this.sword.addEvent('focus',function(){
				if(this.value==self.swordInitValue) this.value='';
			});
			this.sword.addEvent('blur',function(){
				if(this.value=='') this.value=self.swordInitValue;
			});
			this.updateSwordValue.periodical(1000,this);
		}


		//scountry init
		if(this.scountry){
			this.scountry.addEvent('change', this.updateList.bind(this));
		}


		//taxonomy init
		if(this.taxoContainer){
			this.taxoCountTotal = 0;
			this.taxoContainer.getElements('input').each(function(item){
				item.addEvent('click',self.updateList.bind(self));
				self.taxoCountTotal++;
			});
		}

		//init tootltip if mode=myShows
		/*
		if(this.options.mode=='myShows'){
			this.bookingCompletionTooltip = new Element('div',{
				id:'pishowList-bookingCompletionTooltip',
				html:'The booking completion is random. Reload the page to get another one !'
			}).inject(document.body);

			//and preload image !
			var t = new Image();
			t.src = '/fileadmin/templates/efcorp/images/bookingCompletionTooltip.png';
		}
		*/

		var _get = $get();
		if(_get['tx_ef_pishowlist[sword]'] || _get['tx_ef_pishowlist%5bsword%5d'] || _get['tx_ef_pishowlist%5Bsword%5D']){
			this.swordFixedValue = this.sword.value = _get['tx_ef_pishowlist[sword]'] || _get['tx_ef_pishowlist%5bsword%5d'] || _get['tx_ef_pishowlist%5Bsword%5D'];
		}

		this.updateList();
	},

	updateList: function(showAll){
		showAll=(typeof(showAll)=="number"?showAll:0);
		
		console.log("update list");
		var self = this;
		this.loader.setStyle('visibility','visible');
		this.timeBeforeReq = (new Date()).getTime();
		//gather taxo state
		var taxoData = [];
		if(this.taxoContainer){
			this.taxoContainer.getElements('input').each(function(item){
				if(item.checked){
					taxoData.push(item.getProperty('uid'));
				}
			});
		}

		if(taxoData.length==this.taxoCountTotal){
			//everything is checked = nothing checked
			taxoData = [];
		}

		//ajax request
		var htmlRequest = new Request.HTML({
			url: "index.php?showAll="+showAll,
			noCache: true,
			update: this.listContainer,
			evalScripts:true,
			onComplete: function(){
				self.loader.setStyle('visibility','hidden');
				self.timeSpan.set('html',(((new Date()).getTime())-self.timeBeforeReq)+'ms');
				
				//showAll
				var showAllEls = self.listContainer.getElements('.showAll');
				if(showAllEls){
					for(var i=0;i<showAllEls.length;i++){
						showAllEls[i].addEvent('click',function(e){
							e.stop();
							this.getParent().addClass("ajaxLoadMsg");
							self.updateList(1);
						});
					}
				}
				
				var bookingCompletionEls = self.listContainer.getElements('.completionBar');
				/*
				if(bookingCompletionEls){
					bookingCompletionEls.each(function(item){

						item.addEvent('mouseover',function(){
							var pos = item.getPosition();
							self.bookingCompletionTooltip.setStyles({
								'display':'block',
								'top':pos.y-70,
								'left':pos.x-40
							});
						});
						item.addEvent('mouseout',function(){
							self.bookingCompletionTooltip.setStyle('display','none');
						});

					});
				}
				*/
				
				//docshow
				var docshowLinks = self.listContainer.getElements('.docshow');
				if(docshowLinks){
					docshowLinks.each(function(linkEl){
						linkEl.addEvent('click',function(){
							this.blur();
							var showID = this.getProperty('rel');
							with(ui.popup){
								title = tx_ef_pishowlist_jslabels.label_docshow__popup_title;
								content = '<div id="pidocshow-target"></div>';
								loading = true;
								mayClose=true;
							}
							ui.showPopup();
							new Request.HTML({
								url:'index.php',
								method:'get',
								data:{
									id:84,
									L:window.easyFairs.lid,
									show_ll:window.easyFairs.show_ll,
									isAjax:1,
									'tx_ef_pidocshow':{'showID':showID},
									nc:Math.random()
								},
								update:$('pidocshow-target'),
								onComplete:function(){
									ui.popup_hideLoad();
								},
								evalScripts:true
							}).send();
						});
					});
				}
				
				//edit Taxo
				var editTaxoLinks = self.listContainer.getElements('.editTaxo');
				if(docshowLinks){
					editTaxoLinks.addEvent('click',function(e){
						e.stop();
						var showID = this.getProperty('rel');
						
						//eID:'tx_ef_editTaxo'
						openEfPopup("index.php?eID=tx_ef_editTaxo&L="+easyFairs.lid+"&showID="+showID+"&nc="+Math.random(),
								this.getProperty("title"),function(){ui.popup_hideLoad();ui.popup_ajaxize(null,0);},null,{},true);
						
					});
				}
				
				//item list
				var itemListLinks = self.listContainer.getElements('.itemList');
				if(docshowLinks){
					itemListLinks.addEvent('click',function(e){
						e.stop();
						var showID = this.getProperty('rel');
						
						//eID:'tx_ef_itemList'
						openEfPopup("index.php?eID=tx_ef_itemList&L="+easyFairs.lid+"&showID="+showID+"&c="+Math.random(),
								this.getProperty("title"),function(){ui.popup_hideLoad();ui.popup_ajaxize(null,0);},null,{},false);
						
					});
				}
				
				//n200Link
				var n200Links = self.listContainer.getElements('.n200Link');
				if(n200Links){
					//build 
					self.n200_popup = new Element("div",{"class":"n200_popup_wrap ajaxLoad-big",styles:{"backgroundColor":"#FFF"}});
					self.n200_popup.inject(document.body);
					new Element("div",{"class":'i',"html":'<div class="topbar"><a href="#" class="close"></a></div><div class="iframe"></div>'}).inject(self.n200_popup);
					
					self.n200_popup.getElement(".close").addEvent("click",function(e){
						e.stop();
						self.n200_popup.setStyle("display","none");
						ui.hideOverlay();
						self.n200_iframe.dispose();//free memory
					});
					
					//events
					n200Links.addEvent("click",function(e){
						e.stop();
						ui.showOverlay();
						self.n200_popup.setStyle("display","block");
						self.n200_iframe = new Element("iframe").inject(self.n200_popup.getElement(".iframe"));
						self.n200_iframe.src = this.href;
					});
				}
				
				//extend links
				var extLinks = self.listContainer.getElements('.extender');
				if(extLinks && extLinks.length>3){
					extLinks.each(function(extender){
						if(extender.getElement('span')) extender.store('openText',extender.getElement('span').get('text'));
						extender.addEvent('click',function(){ 
							var rel = this.getProperty('rel');
							self.listContainer.getElements('.extended-'+rel).toggleClass('extended');
							var extenders = self.listContainer.getElements('.extender[rel='+rel+']');
							for(var i=0;i<extenders.length;i++){
								if(extenders[i].getElement('span')) extenders[i].getElement('span').set('text',extenders[i].getElement('span').get('text')==extenders[i].retrieve('openText')?window.easyFairs.ll.label_close:extenders[i].retrieve('openText'));
							}
							
						});
					});
				}else if(extLinks.length==3){
					extLinks.setStyle('display','none');
					self.listContainer.getElements('.extender-nohide').setStyle('display','');
					self.listContainer.getElements('.extended').removeClass('extended');
				}

				
				//standName
				var standNameEls = self.listContainer.getElements('.standName'),stand_id,form;
				if(standNameEls.length>0){
					
					function saveStandName(stand_id){
						if(standNames[stand_id].input.value==standNames[stand_id].input.retrieve('prev')) return false;
						
						var formEl = standNames[stand_id].form;
						standNames[stand_id].saveBtn.setProperty('class','saveBtn loading');
						new Request.JSON({
							'url':'index.php',
							method:'post',
							data:{
								eID:'tx_ef_catalog2standname',
								stand_name:formEl.getElement('input').value.trim(),
								stand_id:stand_id//formEl.retrieve('stand_id')
							},
							onComplete:function(response){
								if(response.error){
									alert(response.error);
									return;
								}
								if(response.result=='ok'){
									standNames[response.stand_id].saveBtn.setProperty('class','saveBtn saved');
									standNames[response.stand_id].input.store('prev',standNames[response.stand_id].input.value);
								}
							}
						}).send();
					}
					
					function autoSaveStandName(){
						var d = new Date();
						var now = d.getTime();
						for(var stand_id in standNames){
							if(!isNaN(stand_id) && (now-standNames[stand_id].lastPressed)>1000) saveStandName(stand_id);
						}
					}
					
					var standNames = {};
					var standNameAS;
					var maxchars = 100;
					for(var i=0,j=standNameEls.length;i<j;i++){
						stand_id = standNameEls[i].getProperty('stand_id');
						
						form = standNameEls[i].getParent('form');
						form.store('stand_id',stand_id);
						saveBtn = standNameEls[i].getElement('.saveBtn');
						saveBtn.store('stand_id',stand_id);
						inputEl = standNameEls[i].getElement('input');
						inputEl.store('stand_id',stand_id);
						inputEl.store('prev',inputEl.value);
						
						var charcount = inputEl.value.length;
						if(charcount>maxchars) inputEl.value = inputEl.value.substring(0,maxchars);
						standNameEls[i].getElement('.textarea-charcount').getElement('span').set('text',(maxchars-inputEl.value.length));
						
						standNames[stand_id] = {
							'element':standNameEls[i],
							'form':form,
							'saveBtn':saveBtn,
							'input':inputEl,
							'lastPressed':0
						};
						
						inputEl.addEvent('keyup',function(e){
							if(this.value!=this.retrieve('prev')){
								//trim first - do not, slow people will have a pain entering space separated words.
								//this.value = this.value.trim();
								
								var stand_id = this.retrieve('stand_id');
								standNames[stand_id].saveBtn.setProperty('class','saveBtn unsaved');
								var d = new Date();
								standNames[stand_id].lastPressed = d.getTime();
								
								var charcount = standNames[stand_id].input.value.length;
								if(charcount>maxchars) standNames[stand_id].input.value = standNames[stand_id].input.value.substring(0,maxchars);
								standNames[stand_id].element.getElement('.textarea-charcount').getElement('span').set('text',(maxchars-standNames[stand_id].input.value.length));
								
								if(!standNameAS) standNameAS = autoSaveStandName.periodical(1500);
							}
						});
						
						saveBtn.addEvent('click',function(e){
							e.stop();
							saveStandName(this.retrieve('stand_id'));
						});
						
						form.addEvent('submit',function(e){
							e.stop();
							saveStandName(this.retrieve('stand_id'));
						});

						form.getElement('a.pishowlist-stand-preview').addEvent('click',function(e){
							e.stop();
							window.location.href=this.href+'&nc='+Math.random();
						});
					}
					
					
					
				}
				
				
				
				var mgmStandDescrLinks = self.listContainer.getElements('.mng-stand-descr');
				if(mgmStandDescrLinks.length>0){
					mgmStandDescrLinks.addEvent("click",function(e){
						e.stop();
						ui.popup.width = 600;
						openEfPopup('index.php?id='+tx_ef_pishowlist_dest_standDescr+"&L="+easyFairs.lid+"&isAjax=1&tx_ef_picatalog2[standUid]="+this.getAttribute("stand_id")+'&nc='+Math.random(),
								this.getProperty("title"),ui.popup_hideLoad.bind(ui));
					});
				}
				
				var mgmStandCatLinks = self.listContainer.getElements('.mng-stand-catalog');
				if(mgmStandCatLinks.length>0){
					mgmStandCatLinks.addEvent("click",function(e){
						e.stop();
						ui.popup.width = 600;
						var url = 'index.php?id='+tx_ef_pishowlist_dest_standCatalog+"&L="+easyFairs.lid+"&isAjax=1&tx_ef_picatalog2[standUid]="+this.getAttribute("stand_id")+'&nc='+Math.random();
						var title = this.getProperty("title");
						openEfPopup(url,
								title,function(){ui.popup_hideLoad();ui.popup_ajaxize(null,0);},function(){ui.setPrevPopup(null);},{},true);
						window.picatalog2_standcat_popup_url = url;
						window.picatalog2_standcat_popup_title = title;
					});
				}

				var mgmPrintedLinks = self.listContainer.getElements('.mng-printed-catalog');
				if(mgmPrintedLinks.length>0){
					mgmPrintedLinks.addEvent("click",function(e){
						e.stop();
						ui.popup.width = 600;
						var url = 'index.php?id='+tx_ef_pishowlist_dest_printedCatalog+"&L="+easyFairs.lid+"&show_ll="+window.easyFairs.show_ll+"&isAjax=1&tx_ef_piprinted[stand_id]="+this.getAttribute("stand_id")+'&nc='+Math.random();
						var title = this.getProperty("title");
						openEfPopup(url,
							title,function(){ui.popup_hideLoad();ui.popup_ajaxize(null,0);},function(){ui.setPrevPopup(null);},{},true);
						window.picatalog2_printedcat_popup_url = url;
						window.picatalog2_printedcat_popup_title = title;
					});
				}
				
				self.fireEvent('change',self);
			}
		}).get({
			eID:'tx_ef_pishowlist',
			lid:this.options.lid,
			L:this.options.lid,
			mode:this.options.mode,
			tpl:this.options.tpl,
			taxo:JSON.encode(taxoData),
			scountry:this.scountry.value,
			sword:(this.swordFixedValue==this.swordInitValue?'':this.swordFixedValue),
			show_ll:window.easyFairs.show_ll,
			randomHash: $random(1,100000)+$time()+$random(1,100000)
		});
	},

	updateSwordValue: function(){
		if(this.swordFixedValue!=this.sword.value){
			try{
				console.log('update because of sword (old:'+this.swordFixedValue+', new:'+this.sword.value+')');
			}catch(e){}
			this.swordFixedValue=this.sword.value;
			this.updateList();
		}
	}


});


function picatalog2_createDocFromBoost(obj){
	alert(obj);
	console.log(obj);
}

