
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(){
		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",
			noCache: true,
			update: this.listContainer,
			evalScripts:true,
			onComplete: function(){
				self.loader.setStyle('visibility','hidden');
				self.timeSpan.set('html',(((new Date()).getTime())-self.timeBeforeReq)+'ms');

				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;
							}
							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}
								},
								update:$('pidocshow-target'),
								onComplete:function(){
									ui.popup_hideLoad();
								},
								evalScripts:true
							}).send();
						});
					});
				}
				
				//extend links
				var extLinks = self.listContainer.getElements('.extender');
				if(extLinks && extLinks.length>1){
					extLinks.each(function(extender){
						extender.store('openText',extender.getElement('span').get('text'));
						extender.addEvent('click',function(){
							var rel = this.getProperty('rel');
							self.listContainer.getElements('.extended-'+rel).toggleClass('extended');
							this.getElement('span').set('text',this.getElement('span').get('text')==this.retrieve('openText')?window.easyFairs.ll.label_close:this.retrieve('openText'));
						});
					});
				}else if(extLinks.length==1){
					extLinks.setStyle('display','none');
					self.listContainer.getElements('.extended').removeClass('extended');
				}

				//catalog completion
				var completion_items = ['logo','product','document'],comp_item,links;
				for(var i=0,j=completion_items.length;i<j;i++){
					comp_item = completion_items[i];
					links = self.listContainer.getElements('.completion_'+comp_item);
					if(links.length){
						for(var ii=0,jj=links.length;ii<jj;ii++){
							if(links[ii].hasClass('no')){
								links[ii].setStyle('cursor','pointer').addEvent('click',(function(comp_item){
									switch(comp_item){
										case 'logo':
											myEFObj.goTab(2);
											break;
										case 'product':
											myEFObj.goTab(1);
											break;
										case 'document':
											myEFObj.goTab(1);
											break;
									}
								}).pass(comp_item));
							}
						}
					}
				}
				
				//boosted products
				var boostedEls = self.listContainer.getElements('.boosted'),boostedEl,show_id,selectEl,boosted,boosted_uids,boosted_rough;
				if(boostedEls.length>0){
					console.log('all products: ',tx_ef_pishowlist_prods);
					
					function boosted_buildItem(item_id){
						var item,item_index;
						//find item
						for(var ii=0,jj=tx_ef_pishowlist_prods.length;ii<jj;ii++){
							if(tx_ef_pishowlist_prods[ii].uid==item_id){
								item = tx_ef_pishowlist_prods[ii];
								item_index = ii;
								break;
							}
						}
						
						//build and inject item
						var el = new Element('div',{
							'class':'boosted-product'
						}).adopt([
						    new Element('div',{
						    	'class':'removeBtn',
						    	prods_index:item_index,
						    	events:{
						    		click:function(e){
						    			e.stop();
						    			var el = e.target;
						    			var item_index = this.getProperty('prods_index');
						    			var standID = this.getParent('.boosted').getProperty('stand_id');
						    			new Request.JSON({
						    				url:'index.php',
						    				method:'post',
						    				data:{
						    					'eID':'tx_ef_catalog2boosted',
						    					'action':'delete',
						    					'standID':standID,
						    					'docID':tx_ef_pishowlist_prods[item_index].uid
						    				},
						    				onComplete:function(response){
						    					if(response.error){
													alert(response.error);
													return;
												}
												if(response.result=='ok'){
													var selectEl = el.getParent('.boosted').getElement('select');
									    			selectEl.options[selectEl.options.length] = new Option(tx_ef_pishowlist_prods[item_index].name,tx_ef_pishowlist_prods[item_index].uid);
									    			el.getParent().dispose();
												}
						    				}
						    			}).send();
						    			
						    		}
						    	}
						    }),
						    new Element('div',{
						    	'text':item.name
						    })
						]);
						return el;
					}
					
					for(var i=0,j=boostedEls.length;i<j;i++){
						boostedEl = boostedEls[i];
						stand_id = boostedEl.getProperty('stand_id');
						boosted = window['tx_ef_pishowlist_boosted_'+stand_id];
						selectEl = boostedEl.getElement('select');
						
						console.log('boosted prods for stand#'+stand_id+':',boosted);
						
						//populate selectEl
						selectEl.options.length = 0;
						selectEl.options[selectEl.options.length] = new Option(window.tx_ef_pishowlist_jslabels.label_catalog2__add_product,0);
						for(var ii=0,jj=tx_ef_pishowlist_prods.length;ii<jj;ii++){
							if(!boosted.contains(tx_ef_pishowlist_prods[ii].uid)){
								//not boosted, in select
								selectEl.options[selectEl.options.length] = new Option(tx_ef_pishowlist_prods[ii].name,tx_ef_pishowlist_prods[ii].uid);
							}else{
								//boosted, before select
								boosted_buildItem(tx_ef_pishowlist_prods[ii].uid).inject(selectEl,'before');
							}
						}
						selectEl.addEvent('change',function(){
							var item_id = this.value;
							var standID = this.getParent('.boosted').getProperty('stand_id');
							var selectEl = this;
							new Request.JSON({
								'url':'index.php',
								'method':'post',
								'data':{
									'eID':'tx_ef_catalog2boosted',
									'action':'add',
									'standID':standID,
									'docID':item_id
								},
								onComplete:function(response){
									if(response.error){
										alert(response.error);
										return;
									}
									console.log(response.boosted);
									if(response.result=='ok'){
										var itemEl = boosted_buildItem(response.docID);
										itemEl.inject(selectEl,'before');
									
										//remove from select
										for(var i=0,j=selectEl.options.length;i<j;i++){
											if(selectEl.options[i].selected){
												selectEl.remove(i);
												break;
											}
										}
									}
									if(response.result=='maxreached'){
										
										alert('You must buy a booster pack to boost more products.');
									}
									selectEl.value = 0;
								}
							}).send();
							
							
							
						});
						
					}
				}
				
				
				//standName
				var standNameEls = self.listContainer.getElements('.standName'),show_id,form;
				if(standNameEls.length>0){
					
					function saveStandName(show_id){
						if(standNames[show_id].input.value==standNames[show_id].input.retrieve('prev')) return false;
						
						var formEl = standNames[show_id].form;
						standNames[show_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,
								show_id:show_id//formEl.retrieve('show_id')
							},
							onComplete:function(response){
								if(response.error){
									alert(response.error);
									return;
								}
								if(response.result=='ok'){
									standNames[response.show_id].saveBtn.setProperty('class','saveBtn saved');
									standNames[response.show_id].input.store('prev',standNames[response.show_id].input.value);
								}
							}
						}).send();
					}
					
					function autoSaveStandName(){
						var d = new Date();
						var now = d.getTime();
						for(var show_id in standNames){
							if(!isNaN(show_id) && (now-standNames[show_id].lastPressed)>1000) saveStandName(show_id);
						}
					}
					
					var standNames = {};
					var standNameAS;
					for(var i=0,j=standNameEls.length;i<j;i++){
						show_id = standNameEls[i].getProperty('rel');
						
						form = standNameEls[i].getParent('form');
						form.store('show_id',show_id);
						saveBtn = standNameEls[i].getElement('.saveBtn');
						saveBtn.store('show_id',show_id);
						inputEl = standNameEls[i].getElement('input');
						inputEl.store('show_id',show_id);
						inputEl.store('prev',inputEl.value);
						
						standNames[show_id] = {
							'element':standNameEls[i],
							'form':form,
							'saveBtn':saveBtn,
							'input':inputEl,
							'lastPressed':0
						};
						
						inputEl.addEvent('keyup',function(e){
							if(this.value!=this.retrieve('prev')){
								var show_id = this.retrieve('show_id');
								standNames[show_id].saveBtn.setProperty('class','saveBtn unsaved');
								var d = new Date();
								standNames[show_id].lastPressed = d.getTime();
								
								if(!standNameAS) standNameAS = autoSaveStandName.periodical(1500);
							}
						});
						
						saveBtn.addEvent('click',function(e){
							e.stop();
							saveStandName(this.retrieve('show_id'));
						});
						
						form.addEvent('submit',function(e){
							e.stop();
							saveStandName(this.retrieve('show_id'));
						});
					}
					
					
					
				}
				
				
				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();
		}
	}


});

