var dummyAccord = new Class({
	Implements: [Events, Options],
	initialize: function(contentEl,options){
		var self = this;
		this.setOptions(options);
		this.contentEl = $(contentEl);
	},
	show:function(){
		this.contentEl.setStyle('display','');
	},
	hide:function(){
		this.contentEl.setStyle('display','none');
	}
});


var itemTable = new Class({
	Implements: [Events, Options],
	options:{
		currencyHTML:'&euro;',
		onTotalUpdate:null
	},
	initialize: function(tableEl,options){
		var self = this;
		this.setOptions(options);
		this.tableEl = $(tableEl);
		this.tableEl_body = this.tableEl.getElement('tbody');
		this.totalEl = $(tableEl+'_total');
		//this.headerEl = $(tableEl+'_header');
		//this.footerEl = $(tableEl+'_footer');
		this.items = [];

	},
	//public add
	add:function(item,pos,sys){
		var self = this;
		var pos = pos!=null ? pos : 'bottom';

		if(sys) item.system = true;


		//this is the first item we add, remove teaser
		if(this.items.length==0){
			if(this.tableEl_body.getElement('tr.teaser')){
				this.tableEl_body.getElement('tr.teaser').dispose();
			}
		}

		//this item alreay in list ?
		var found = false;
		this.items.each(function(iitem,i){
			if(iitem.data.uid==item.uid){
				self.items[i].data.qty+=item.qty;
				found = true;
				//(function(){self.items[i].el.highlight();}).delay(500);
			}
		});
		if(!found){
			var el = this.build(item);
			this.items.push({
				data:item,
				el:el
			});
			this.addRow(el,pos);
		}

		this.updateTotal();
	},
	build: function(item){
		var delEl,minus_btn,plus_btn;
		if(item.removable){
			delEl = new Element('td',{
				'class':'table-col5'
			}).adopt(
				new Element('a',{
					'html':'<span>'+window.tx_ef_pibook_jslabels.label_delete+'</span>',
					'events':{
						'click':this.remove.pass(item,this)
					},
					'class':'button1'
				})
			);
			minus_btn = new Element('td',{		// - btn
				'class':'table-col2 minus_btn'
			}).adopt(
				new Element('a',{
					'class':'decrease',
					'html':'decrease',
					'events':{
						'click': this.modifyQty.pass([item,'-'],this)
					}
				})
			);
			plus_btn = new Element('td',{		// + btn
				'class':'table-col4 plus_btn'
			}).adopt(
				new Element('a',{
					'class':'increase',
					'html':'increase',
					'events':{
						'click': this.modifyQty.pass([item,'+'],this)
					}
				})
			);
		}else{
			delEl = new Element('td',{'html':'&nbsp;'});
			minus_btn = new Element('td',{		// - btn
				'class':'table-col2 minus_btn',
				'html':'&nbsp;'
			});
			plus_btn = new Element('td',{		// + btn
				'class':'table-col4 plus_btn',
				'html':'&nbsp;'
			});
		}

		var el = new Element('tr',{
			'class': item.removable?'':'sysItem'
		}).adopt(
			new Element('td',{		//product name
				'html':item.desc,
				'class':'table-col1'
			}),
			minus_btn,
			new Element('td',{		// quantity
				'class': 'table-col3 qty',
				'html':(item.is_rebate?'':item.qty)
			}),
			plus_btn,
			delEl,
			new Element('td',{		//price
				'class':'table-col6 priceqty',
				'html':this.formatPrice((item.qty * this.getPrice(item)))
			})

		);
		return el;
	},
	//private addRow
	addRow:function(el,pos){
		/* old:
		if(pos=='bottom'){
			el.injectBefore(this.footerEl);
			//(function(){el.highlight();}).delay(500);
		}else{
			el.injectAfter(this.headerEl);
		}*/
		el.inject(this.tableEl_body);
	},
	updateTotal:function(){
		var self = this;
		var total = this.getTotal();
		var has_rebate = false;
		var rebate_amount;
		this.items.each(function(iitem){
			var item = iitem.data;


			//update qty element
			if(!item.is_rebate){
				iitem.el.getElement('.qty').set('html',item.qty);
				if(item.qty==1 && item.removable){
					iitem.el.getElement('a.decrease').setStyle('opacity',.5);
				}else if(item.removable){
					iitem.el.getElement('a.decrease').setStyle('opacity',1);
				}
			}


			//update price
			var priceToDisplay;
			if(item.is_rebate){
				has_rebate = true;
				rebate_amount = (total/100)*item.rebate_int;
				priceToDisplay = '- '+self.formatPrice(rebate_amount);
			}else{
				priceToDisplay = self.formatPrice((item.qty * self.getPrice(item)))
			}
			iitem.el.getElement('.priceqty').set('html',priceToDisplay);

		});

		if(has_rebate){
			total -= rebate_amount;
		}

		this.totalEl.set('html',this.formatPrice(total));

		this.fireEvent('totalUpdate',[total,this.options.id]);
	},
	clearSystem:function(){
		var newItems = [];
		this.items.each(function(item){
			if(item.data.system) item.el.dispose();
			else newItems.push(item);
		});
		this.items = newItems;
		this.updateTotal();
	},
	//public remove
	remove:function(theItem){

		//if this is a _used_ taxonomy booster pack, do not remove
		if(theItem.add_taxonomy_count){
			//this items adds taxonomy
			var total = piBookObj.taxonomy_getFullCount();
			if(total - (theItem.add_taxonomy_count*theItem.qty) < piBookObj.taxonomy_selected){
				alert('This item increases the number of available taxonomy, and is currently in use.\n\nYou must remove at least '+(piBookObj.taxonomy_selected - (total-(theItem.add_taxonomy_count*theItem.qty)))+' taxonomy(ies) in order to remove this item.');
				return;
			}
		}

		var newItems = [];
		this.items.each(function(item){
			if(item.data==theItem) item.el.dispose();
			else newItems.push(item);
		});
		this.items = newItems;
		this.updateTotal();
	},
	modifyQty: function(theItem,mode){
		if(mode=='-' && theItem.qty==1) return;
		this.items.each(function(item){
			if(item.data==theItem){
				if(mode=='-'){
					item.data.qty--;
				}else{
					item.data.qty++;
				}

			}
		});
		this.updateTotal();
	},
	formatPrice: function(price){
		return this.options.cu_symbol_left + price + this.options.cu_symbol_right;
	},
	getPrice: function(item){
		//return eval('item.price.c'+$('ef_block-items-currency_select').value);
		if(item.price===false) return 0;
		return item.price['c'+$('ef_block-items-currency_select').value];
	},
	getTotal: function(){ //returns total WITHOUT rebate
		var self = this;
		var total = 0;
		this.items.each(function(iitem){
			var item = iitem.data;
			total += (self.getPrice(item) * item.qty);
		});
		return total;
	}
});



var tx_ef_pibook = new Class({

	Implements: [Events, Options],

	preloadImagesArray:[
		'fileadmin/templates/efcorp/images/progress2ok.png'
	],

	initialize: function(options){

		var self = this;
		this.setOptions(options);
		this.container = $('tx-ef-pibook');
		
		if(piBookVar_isAdditionalBooking){
			$('header-cart').dispose();
		}

		//init UI
		this.initUi();

		//show we are loading
		this.ui.loaderEl.fade('in');

		//init steps
		if(piBookVar_isAdditionalBooking){
			this.steps = [
	  			{
	  				id:'items',
	  				canContinue: false,
	  				load: this.loadStep_items.bind(this),
	  				refresh: this.refreshStep_items.bind(this)
	  			},
	  			{
	  				id:'validate',
	  				load:this.loadStep_validate.bind(this),
	  				refresh:this.refreshStep_validate.bind(this)
	  			}
	  		];
		}else{
			this.steps = [
				{
					id: 'floorMap',
					canContinue: false,
					ready: false,
					load: this.loadStep_floorMap.bind(this)
				},
				{
					id:'items',
					canContinue: false,
					load: this.loadStep_items.bind(this),
					refresh: this.refreshStep_items.bind(this)
				},
				{
					id: 'info',
					canContinue: this.checkStep_info.bind(this),
					load: this.loadStep_info.bind(this)
				},
				{
					id: 'taxonomy',
					canContinue: this.checkStep_taxonomy.bind(this),
					load: this.loadStep_taxonomy.bind(this),
					refresh: this.refreshStep_taxonomy.bind(this)
				},
				{
					id:'validate',
					load:this.loadStep_validate.bind(this),
					refresh:this.refreshStep_validate.bind(this)
				}
			];
		}
		
		this.currentStep = 0;

		//init tabs for each step
		this.steps.each(function(step,index){
			step.accordion = new dummyAccord($('ef_block-'+step.id).getElement('.acc-content'));
			if(index!=self.currentStep){
				step.accordion.hide();
			}else{
				$('ef_block-'+step.id+'-toggler').getParent().addClass('ok');
			}
			$('ef_block-'+step.id+'-toggler').addEvent('click',self.jumpToStep.pass(index,self));
		});

		//init "next" buttons
		$$('.piBook_nextBtn').each(function(btn){
			btn.addEvent('click',function(e){
				new Event(e).stop();
				self.goNextStep();
			});
		});

		//init piBook_goStepBtn buttons
		$$('.piBook_goStepBtn').each(function(btn){
			btn.addEvent('click',function(e){
				new Event(e).stop();
				var stepIndex = this.getProperty('go').toInt();
				if(!isNaN(stepIndex) && stepIndex>=0 && stepIndex<5){
					self.jumpToStep(stepIndex);
				}else{
					alert('Wrong go param: '+stepIndex);
				}
			});
		});

		//init this.currentCurrency
		piBookVar_currencies.each((function(cur,i){
			if($('ef_block-items-currency_select').value==cur.currency){
				this.currentCurrency = cur;
			}
		}).bind(this));

		//preload some images
		this.preloadImages();

		//init is done, we can show this.container
		this.container.fade('in');

		//load currentStep
		this.steps[this.currentStep].load();

		//@todo this should be executed only once we clicked on a booth
		//and disabled once booking is confirmed
		this.allowPageUnload = true;
		window.onbeforeunload = this.onBeforeUnload.bind(this);
		
		this.importedData = null;

	},

	preloadImages:function(){
		this.preloadImagesArray.each(function(imgSrc){
			var i = new Image();
			i.src = imgSrc
		});
	},

	onBeforeUnload: function(e){
		//code from pibookadd

		if(this.allowPageUnload){
			//page may unload
		}else{
			return "If you quit this page, be aware that the current booking will be cancelled!";
		}
	},

	initUi: function(){
		this.ui = {
			imgDir: 'typo3conf/ext/ef/res/js/ui/images/' //deprecated
		};

		//create a loading div
		/*
		this.ui.loaderEl = new Element('div',{
			'id':'ef_ui_loaderEl',
			'html':'Loading',
			'styles':{'opacity':0}
		}).inject(document.body);
		*/
		this.ui.loaderEl = ui.loaderEl;
		/*

		old jx ui:

		this.ui.alert = new Jx.Dialog({
			label: 'You may not continue',
			image: this.ui.imgDir+'error.png',
			modal: true,
			content:'<p>default content</p>',
			resize: false,
			height:120
		});


		this.ui.showAlert = function(content){
			//append close btn
			content += '<div style="text-align:right;padding:6px;"><input type="button" value="Close" onclick="piBookObj.ui.alert.close();" /></div>';

			piBookObj.ui.alert.options.content = content;
			piBookObj.ui.alert.loadContent(piBookObj.ui.alert.content);
			piBookObj.ui.alert.open();
		}
		*/

		this.ui.showAlert = function(content){
			ui.popup.title = 'easyFairs booking';
			ui.popup.content = content;
			ui.showPopup();
		}

	},

	getStep: function(id){
		var f;
		this.steps.each(function(item){
			if(item.id==id){
				f = item;
				return;
			}
		});
		return f;
	},

	jumpToStep: function(step){
		if(step!=0){
			var mayContinue = true;
			var blockingStep;
			for(var i = 0;i<step;i++){
				if(this.steps[i].id=='floorMap'){
					if(!this.floorMapObj.canContinue()){
						mayContinue = false;
						blockingStep = i;
						break;
					}
				}else if(this.steps[i].id=='info'){

					if(!this.steps[i].canContinue()){
						mayContinue = false;
						blockingStep = i;
						break;
					}
				}else if(this.steps[i].id=='taxonomy'){
					console.log(this.steps[i]);
					if(!this.steps[i].canContinue()){
						mayContinue = false;
						blockingStep = i;
						break;
					}

				}else{
					if(!this.steps[i].canContinue){
						mayContinue = false;
						blockingStep = i;
						break;
					}
				}
			}
			if(mayContinue){
				if(!this.steps[step].ready){
					this.steps[step].load();
				}
				if(this.steps[step].refresh!=undefined) this.steps[step].refresh();
				this.jumpToStepAccordion(step);
				this.currentStep = step;
			}else{
				this.ui.showAlert('<p>'+window.tx_ef_pibook_jslabels['label_booking__popup_step_'+(blockingStep+1)]+'</p>');
			}
		}else{
			//0 is the only step we dont have to check
			this.jumpToStepAccordion(step);
			this.currentStep = step;
		}
	},

	goNextStep: function(){
		piBookObj.jumpToStep(piBookObj.currentStep+1);
	},

	jumpToStepAccordion: function(step){

		//this.steps[this.currentStep].accordion.slideOut();
		//this.steps[step].accordion.slideIn();

		this.steps[this.currentStep].accordion.hide();
		//$('ef_block-'+this.steps[this.currentStep].id+'-toggler').getParent().removeClass('ok');
		this.steps[step].accordion.show();
		ui.scrollTo(0,200);
		$('ef_block-'+this.steps[step].id+'-toggler').getParent().addClass('ok');

		//emphasize the current step if not last
		this.steps.each((function(s,index){
			if(this.steps[(step+1)]==undefined){
				//last step
				//remove blue only
				$('ef_block-'+this.steps[index].id+'-toggler').getParent().removeClass('blue');
			}else{
				if(index==step && this.steps[(step+1)].ready && $('ef_block-'+this.steps[(step+1)].id+'-toggler').getParent().hasClass('ok')){
					//add blue
					$('ef_block-'+this.steps[index].id+'-toggler').getParent().addClass('blue');
				}else{
					//remove blue
					$('ef_block-'+this.steps[index].id+'-toggler').getParent().removeClass('blue');
				}
			}

		}).bind(this));

	},

	onLoginSuccess: function(){

		if(this.onLoginSuccess_done) return;
		this.onLoginSuccess_done = true;

		//show we are loading
		this.ui.loaderEl.fade('in');

		if(window.loginBlockIsOpen){
			close_loginBlock();
		}


		//we need to load taxonomy and items step if not yet,
		//since we use taxonomy_getAvailCount which needs data from items step
		stepItems = this.getStep('items');
		stepTaxo = this.getStep('taxonomy');
		if(!stepItems.ready){
			stepItems.load();
			stepTaxo.load(); //and of course this is not loaded neither
			console.log("loaded: items and taxo");
		}else{
			if(!stepTaxo.ready){
				stepTaxo.load();
				console.log("loaded:taxo");
			}
		}
		this.taxonomy_computeCount();

		var loginReq = new Request.JSON({
			url: "index.php",
			onComplete: this.onGetAccountInfo.bind(this)
		}).get({
			eID:'tx_ef_pibook-getAccountInfo',
			showID:window.easyFairs.showID,
			lid:window.easyFairs.lid,
			limit:this.taxonomy_getAvailCount()
		});

	},

	onGetAccountInfo:function(rT){
		if(rT){
			if(rT.success){

				//alert('success');
				this.importedData = rT;
				console.log('Imported Data',this.importedData);

				//already_booked ?
				if(this.importedData.already_booked){
					with(ui.popup){
						title = 'Attention !';
						content = '<p class="errorMsg">It seems you already booked this show !</p><p>Redirecting...</p>';
						mayClose=false;
					}
					ui.showPopup();

					window.location.reload();

					return;
				}

				//import taxonomy
				if(this.importedData.taxonomy!=null
				   && this.importedData.taxonomy!=undefined
				   && this.importedData.taxonomy!=''
				   && this.importedData.taxonomy!=0){
					this.taxonomy_import();
				}

				//import info
				if(this.importedData.info!=null
				   && this.importedData.info!=undefined
				   && this.importedData.info!=''
				   && this.importedData.info!=0){
					this.info_import();
				}

				//hide the login button
				$('pibook-loginbtn').setStyle('display','none');
				
				//hide the form
				$('pibook-infoNoNeedIfLoggedIn').setStyle('display','none');
				
				//show static data
				$('pibook-infoStatic').setStyle('display','block');

			}else{
				//mostly like user is not logged in
				alert(rT.error);
			}
		}else{
			alert('Error: incorrect response from getAccountInfo');
		}

		//hide loading
		this.ui.loaderEl.fade('out');
	},

	updateMiniCart: function(){
		piBookObj.allowPageUnload = false;
		var modulesNames = [];
		var totalSuperficy = 0;
		var final_price = 0;
		
		if(!piBookVar_isAdditionalBooking){
			floorMap.newBooking.each(function(module){
				modulesNames.push(module.name);
				module.items.each(function(item_id){
					var item = floorMap.getItem(item_id);
					console.log(item);
					totalSuperficy += Number(item.superficy);
					final_price += item.priceForOther['c'+piBookObj.currentCurrency.currency];
	
				});
			});
			console.log(final_price);
		}
		
		//if rebate, decrease price of modules
		if(piBookVar_rebate>0){
			var rebate_amount = (final_price/100)*piBookVar_rebate;
			final_price -= rebate_amount;
		}



		stepItems = piBookObj.getStep('items');
		if(stepItems.ready){
			stepItems.itemTable.items.each(function(item){
				final_price += item.data.price['c'+piBookObj.currentCurrency.currency] * item.data.qty;
			});
		}

		//final_price = final_price.round(2);
		
		if(!piBookVar_isAdditionalBooking){
			$('modulesNames').set('text',modulesNames.join(', '));
			$('totalSuperficy').set('text',totalSuperficy);
		}
		$('final_price').set('html',piBookObj.currentCurrency.cu_symbol_left+final_price+piBookObj.currentCurrency.cu_symbol_right+(piBookVar_rebate>0?' <small style="font-weight:normal;">( -'+piBookVar_rebate+'% on modules )</small>':''));
	},

	loadStep_floorMap: function(){
		var self = this;
		this.floorMapObj = new tx_ef_pibook_floorMap({
			'stepIndex': 0
		});
		this.floorMapObj.addEvent('floorMapLoaded',function(){
			
			if(window.easyFairs.feUser!==false){
				self.onLoginSuccess();
			}
			self.ui.loaderEl.fade('out');
			floorMap.addEvent('moduleUpdate',piBookObj.updateMiniCart.bind(piBookObj));
			
		});

	},

	loadStep_items: function(){
		var thisStep = this.getStep('items');

		if(!piBookVar_isAdditionalBooking)
			console.log('MODULES FROM FLOORMAP >>>',this.floorMapObj.getModules($('ef_block-items-currency_select').value));

		var cu_symbol_left,cu_symbol_right;
		piBookVar_currencies.each(function(cur,i){
			if($('ef_block-items-currency_select').value==cur.currency){
				cu_symbol_left = cur.cu_symbol_left;
				cu_symbol_right = cur.cu_symbol_right;
			}
		});

		//create itemTables
		thisStep.itemTable = new itemTable('ef_block-items-itemList_table',{
			'id':'itemTable',
			'cu_symbol_left':cu_symbol_left,
			'cu_symbol_right':cu_symbol_right,
			onTotalUpdate:this.items_onItemTableUpdateTotal.bind(this)
		});
		thisStep.sysItemTable = new itemTable('ef_block-items-sysItemList_table',{
			'id':'sysItemTable',
			'cu_symbol_left':cu_symbol_left,
			'cu_symbol_right':cu_symbol_right,
			onTotalUpdate:this.items_onItemTableUpdateTotal.bind(this)
		});


		//accordion
		$('ef_block-items-addItem').getElements('div.accordion-nest').each(function(item,i){
			if(item.getProperty('open').toInt()==0){
				var accordion = new Fx.Slide(item.getElement('div.accordion-content'),{duration:300});
				if(i!=0){
					accordion.hide();
				}else{
					item.getElement('a.accordion-title').addClass('active');
				}
				if(i!=0){
					item.getElement('a.accordion-title').addEvent('click',function(e){
						new Event(e).stop();
						this.blur();
						accordion.toggle();
						this.toggleClass('active');
					});
				}else{
					item.getElement('a.accordion-title').addEvent('click',function(e){
						new Event(e).stop();
						this.blur();
					});
				}
			}else{
				//always open accordion
				item.getElement('a.accordion-title').addClass('active');
				item.getElement('a.accordion-title').addEvent('click',function(e){new Event(e).stop();this.blur();});
			}
		});

		//items init
		$('ef_block-items-addItem').getElements('li').each(function(item){
			item.store('itemData',JSON.decode(item.getProperty('json')));

			item.getElements('a.addToCart').addEvent('click',function(e){
				new Event(e).stop();
				this.blur();
				thisStep.itemTable.add(JSON.decode(item.getProperty('json')));
			});
			item.getElements('.openDescription').addEvent('click',function(e){
				new Event(e).stop();
				this.blur();
				with(ui.popup){
					title = item.getElement('.name').get('text');
					content = '<div class="item_popup">'+item.getElement('.descriptionData').get('html')+'</div><div style="clear:both;"></div>';
				}
				ui.showPopup();
			});
		});


		//currency select init
		$('ef_block-items-currency_select').addEvent('change', function(){
			piBookVar_currencies.each(function(cur,i){
				if($('ef_block-items-currency_select').value==cur.currency){
					piBookObj.currentCurrency = cur;
					thisStep.itemTable.options.cu_symbol_left = cur.cu_symbol_left;
					thisStep.itemTable.options.cu_symbol_right = cur.cu_symbol_right;
					thisStep.sysItemTable.options.cu_symbol_left = cur.cu_symbol_left;
					thisStep.sysItemTable.options.cu_symbol_right = cur.cu_symbol_right;

					console.log('onchange',cur);
					thisStep.itemTable.updateTotal();
					thisStep.sysItemTable.updateTotal();

					//refresh prices in item list (display refresh)
					$('ef_block-items-addItem').getElements('li').each(function(item){
						var itemData = item.retrieve('itemData');
						item.getElement('em').set('html',thisStep.itemTable.options.cu_symbol_left+'<span>'+itemData.price['c'+cur.currency]+'</span>'+thisStep.itemTable.options.cu_symbol_right);

					});
					//refresh miniCart
					if(!piBookVar_isAdditionalBooking){
						piBookObj.updateMiniCart();
						console.log('miniCart refreshed');
					}
					//break;
				}
			});
		});



		thisStep.ready = true;
		thisStep.canContinue = true; //we dont need to validate anything here, but we make sure the step has been initialized...
	},

	refreshStep_items: function(){

		var self = this;
		var thisStep = this.getStep('items');

		//only add items from plan at the top of table
		if(!piBookVar_isAdditionalBooking){
			var itemsFromPlan = this.floorMapObj.getItems();
			console.log('>>>>>> itemsFromPlan:',itemsFromPlan);
		}
		thisStep.sysItemTable.clearSystem();
		if(!piBookVar_isAdditionalBooking){
			itemsFromPlan.each(function(item,i){
				thisStep.sysItemTable.add(item,'top',true);
			});
		}

		//add the special rebate item
		//piBookVar_rebate = 20;
		if(piBookVar_rebate>0){
			thisStep.sysItemTable.add({
				'desc':'Rebate '+piBookVar_rebate+'%',
				'qty':1,
				'price':false,
				'removable':false,
				'uid':false,
				'add_taxonomy_count':'0',
				'is_rebate':true,
				'rebate_int':piBookVar_rebate
			},'',true);
		}


		//refresh the total area
		if(!piBookVar_isAdditionalBooking){
			var totalSuperficy = 0;
			var item;
			floorMap.newBooking.each(function(module){
				module.items.each(function(item_id){
					item = floorMap.getItem(item_id);
					totalSuperficy += Number(item.superficy);
				});
			});
			$('ef_block-items-sysItemList_table_total_area').set('html',totalSuperficy);
		}
	},

	items_onItemTableUpdateTotal: function(total,tableId){
		console.log('onItemTableUpdateTotal:',total,tableId);
		var thisStep = this.getStep('items');
		var final_total;
		if(tableId=='itemTable'){
			var sysItemsTotal = thisStep.sysItemTable.getTotal();
			//rebate ?
			if(piBookVar_rebate>0) sysItemsTotal -= (sysItemsTotal/100)*piBookVar_rebate;
			final_total = total + sysItemsTotal;
		}else{
			final_total = total + thisStep.itemTable.getTotal();
		}

		//alert(total);
		$('ef_block-items-itemList-final-total').set('html',thisStep.itemTable.formatPrice(final_total));
		
		if(!piBookVar_isAdditionalBooking){
			piBookObj.updateMiniCart();
		}
	},

	loadStep_taxonomy: function(){
		var self = this;
		var thisStep = this.getStep('taxonomy');

		//init counter
		this.taxonomy_selected = 0;
		this.taxonomy_defaultSelectCount = window.easyFairs.show.default_taxonomy_count;

		this.taxonomy_boosterPack = 0; 	//number of booster pack
		this.taxonomy_maxBoosted = 0;	//amount of taxonomy given by booster pack

		//init checkboxes
		$('ef_block-taxonomy-taxos').getElements('input[type=checkbox]').each(function(cb){
			cb.addEvent('click',self.taxonomy_updateCountEl.bind(self));
		});

		thisStep.ready = true;
	},

	refreshStep_taxonomy: function(){
		var tmp = this.taxonomy_getAvailCount();
		this.taxonomy_computeCount();
		this.taxonomy_updateCountEl(tmp);
	},

	checkStep_taxonomy: function(){
		var thisStep = this.getStep('taxonomy');
		if(!thisStep.ready)this.loadStep_taxonomy();
		this.refreshStep_taxonomy();
		if(this.taxonomy_selected<=0){
			return false;
		}
		return true;
	},

	taxonomy_computeCount: function(){

		var allItems = this.getStep('items').itemTable.items;
		this.taxonomy_boosterPack = this.taxonomy_maxBoosted = 0;
		for(var i=0;i<allItems.length;i++){
			var item_count = allItems[i].data.add_taxonomy_count.toInt();
			if(item_count > 0){
				this.taxonomy_boosterPack += (1 * allItems[i].data.qty);
				this.taxonomy_maxBoosted += (item_count * allItems[i].data.qty);
			}
		}
		if(this.taxonomy_getAvailCount()<0){
			this.canContinue = false;
		}else{
			this.canContinue = true;
		}

	},

	taxonomy_getFullCount: function(){
		return (piBookObj.taxonomy_defaultSelectCount + piBookObj.taxonomy_maxBoosted);
	},
	taxonomy_getAvailCount: function(){
		this.taxonomy_updateCountCb();
		return (piBookObj.taxonomy_getFullCount() - piBookObj.taxonomy_selected);
	},

	/**
	*	Returns number of selected taxonomy
	*/
	taxonomy_countCb: function(){
		var count = 0;
		$('ef_block-taxonomy-taxos').getElements('input[type=checkbox]').each(function(cb){
			if(cb.checked){
				count++;
			}
		});
		return count;
	},

	/**
	*	Updates internal selected count var (taxonomy_selected)
	*/
	taxonomy_updateCountCb: function(){
		this.taxonomy_selected = this.taxonomy_countCb();
	},


	/**
	*	Updates the visual counter
	*/
	taxonomy_updateCountEl: function(tmp){
		var avail = piBookObj.taxonomy_getAvailCount();
		//update tree count
		if(avail<0){
			//$('pibook-taxonomyCounter').set('html','<strong style="color:red;">Limited to '+piBookObj.taxonomy_getFullCount()+'. Please unselect '+(avail*-1)+' item(s)</strong>');
			var markerObj = {
				'full_count':piBookObj.taxonomy_getFullCount(),
				'unselect_count':(avail*-1)
			};
			$('pibook-taxonomyCounter').set('html','<strong style="color:red;">'+tx_ef_pibook_jslabels.label_booking__too_much_taxo.substitute(markerObj)+'</strong>');
		}else{
			$('pibook-taxonomyCounter').set('html',avail);
		}
	},

	taxonomy_checkout: function(){
		var ret = [];
		$('ef_block-taxonomy-taxos').getElements('li').each(function(li,i){
			var input = li.getElement('input[type=checkbox]');
			var label = li.getElement('label');
			var t = {
				id:input.value,
				label:label.get('text'),
				checked:input.checked
			};
			ret.push(t);
		});
		return ret;
	},
	taxonomy_import: function(){

		this.taxonomy_computeCount();

		if(this.importedData!=null && this.importedData.taxonomy!=0 && piBookObj.taxonomy_selected==0){
			var el;
			this.taxonomy_importAffectedEls = [];
			for(var i=0;i<this.importedData.taxonomy.length;i++){
				if($('ef_block-taxonomy-taxos').getElement('li input[value='+this.importedData.taxonomy[i].taxonomy_id+']')){
					el = $('ef_block-taxonomy-taxos').getElement('li input[value='+this.importedData.taxonomy[i].taxonomy_id+']');
					el.checked = true;
					this.taxonomy_importAffectedEls.push(el);

					//remove undo link if user touches any imported cb
					el.addEvent('click',function(){
						if($('pibook-taxonomyImportNotify'))
							if($('pibook-taxonomyImportNotify').getElement('a'))
								$('pibook-taxonomyImportNotify').getElement('a').dispose();
					});
				}else{
					console.info('Can not find imported taxo #'+this.importedData.taxonomy[i].taxonomy_id);
				}
			}
			$('pibook-taxonomyImportNotify').setStyle('display','');
			//undo event
			$('pibook-taxonomyImportNotify').getElement('a').addEvent('click',this.taxonomy_import_undo.bind(this));
		}

	},

	taxonomy_import_undo: function(e){
		new Event(e).stop();
		if(this.taxonomy_importAffectedEls){
			this.taxonomy_importAffectedEls.each(function(cb){
				cb.checked = false;
			});
			$('pibook-taxonomyImportNotify').dispose();
		}

		delete this.taxonomy_importAffectedEls;

	},


	loadStep_info: function(){
		var thisStep = this.getStep('info');
		if(!window.easyFairs.feUser || this.importedData==null){
			this.info_checkEmail_last = '';
			this.info_checkEmailIntervalID = this.info_checkEmailField.periodical(1000,this);
		}
		
		//init textarea char counter
		$('pibook-info-comments').addEvent('keyup',function(){
			charLength = this.value.length;
			charMax = 250;
			charLeft = charMax - charLength;
			if(charLeft<0){
				this.value = this.value.substr(0,charMax);
				charLeft = 0;
			}
			
			$('pibook-info-commentsCharCount').set('text',charLeft);
		});
		$('pibook-info-commentsCharCount').set('text',250);
		
		
		thisStep.ready = true;
	},
	info_checkEmailField: function(){
		if(this.importedData!=null){
			$clear(this.info_checkEmailIntervalID);
			return;
		}
		var field = $('pibook-info-email');

		if(field.value!=this.info_checkEmail_last && formValidator.isEmail(field.value)){
			this.info_checkEmail_last = field.value;
			console.log('checking email field ('+field.value+')');
			$('pibook-info-email_onCorrectEmail').getElement('.ajaxLoadMsg').setStyle('display','block');
			$('pibook-info-email_onCorrectEmail').getElement('.email_ok').setStyle('display','none');
			$('pibook-info-email_onCorrectEmail').getElement('.email_ko').setStyle('display','none');
			$('pibook-info-email_onCorrectEmail').getElement('.email_exhibonly').setStyle('display','none');

			var r = new Request.JSON({
				url:'index.php',
				method:'get',
				data:{
					eID:'tx_ef_pibook-checkEmail',
					email:field.value,
					rnd:Math.random()
				},
				onComplete:this.info_checkEmailField_onComplete.bind(this)
			}).send();
		}
	},
	info_checkEmailField_onComplete: function(response){
		if(!$chk(response)) alert('Request error.');
		var part = $('pibook-info-email_onCorrectEmail');
		part.getElement('.ajaxLoadMsg').setStyle('display','none');
		if(response.logged_in){
			//user is already logged in !
			//alert('You are already logged in. You may continue.');
		}else{
			if(response.email_exists){
				part.getElement('.email_ko').setStyle('display','block');
			}else if(response.exhib_exists){
				this.exhibitor_data_exists = true;
				$('pibook-info-noneed-exhibisthere').setStyle('display','none');
				$('details').setStyle('display','none');
				part.getElement('.email_ok').setStyle('display','block');
				part.getElement('.email_exhibonly').setStyle('display','block');

			}else{
				part.getElement('.email_ok').setStyle('display','block');
			}
		}
	},

	info_import: function(){
		console.log('importing infos...');
		for(var k in this.importedData.info){
			switch(k){
				case 'country_str': break;
				case 'phone': 
					$('pibook-info-'+k).value = this.importedData.info[k];
					$('pibook-info-'+k).disabled = true;
					break;
				case 'country':
					$('pibook-info-'+k).value = this.importedData.info[k];
					$('pibook-info-'+k).disabled = true;
					$('pibook-infoStatic-country').set('text',this.importedData.info['country_str']);
					break;
				case 'first_name': 
					$('pibook-info-'+k).value = this.importedData.info[k];
					$('pibook-info-'+k).disabled = true;
					$('pibook-infoStatic-name').set('text',this.importedData.info[k]);
					break;
				case 'last_name': 
					$('pibook-info-'+k).value = this.importedData.info[k];
					$('pibook-info-'+k).disabled = true;
					break;
				default:
					$('pibook-info-'+k).value = this.importedData.info[k];
					$('pibook-info-'+k).disabled = true;
					$('pibook-infoStatic-'+k).set('text',this.importedData.info[k]);
			}
			console.log('pibook-info-'+k);
			
		}
		
		console.log('done.');
	},
	checkStep_info: function(){
		//dont check if imported
		if(this.importedData && this.importedData.info) return true;
		if(this.exhibitor_data_exists) return true;
		var requiredFields = {
			'email':formValidator.isEmail,
			'contact_firstname':formValidator.notEmpty,
			'contact_lastname':formValidator.notEmpty,
			'contact_phone':formValidator.notEmpty,
			'company_name':formValidator.notEmpty,
			'address1':formValidator.notEmpty,
			'city':formValidator.notEmpty,
			'country':formValidator.notEmpty
		};
		var error = false;
		var formElements = $$($('ef_block-info').getElements('input[type=text]'),$('ef_block-info').getElements('select'));
		formElements.each(function(input){
			var name = input.getProperty('name');
			if(requiredFields[name]!=undefined){
				//console.log(name,input.value);
				if(!requiredFields[name](input.value)){
					error = true;
					input.addClass('error');
				}else input.removeClass('error');
			}
		});

		return error?false:true;
	},


	loadStep_validate: function(){
		console.log('loadStep_validate');


		//init doSave btn
		$('ef_block-validate-doSaveBtn').addEvent('click',(function(e){
			new Event(e).stop();
			this.refreshStep_validate(true);
		}).bind(this));

		this.getStep('validate').ready = true;
	},

	refreshStep_validate: function(doSave){
		console.log('refreshStep_validate');

		var targetHTML = $('ef_block-validate-target');
		//show wait
		targetHTML.getElement('.wait').setStyle('display','');
		//hide everything else
		$('ef_block-validate-confirm').setStyle('visibility','hidden');
		targetHTML.getElement('.errorMsg').empty();
		targetHTML.getElement('.errorsUl').empty();
		targetHTML.getElement('.show_ll').empty();
		targetHTML.getElement('.errors').setStyle('display','none');
		targetHTML.getElement('.mailSuccess').setStyle('display','none');
		targetHTML.getElement('.mailFailed').setStyle('display','none');
		targetHTML.getElement('.success').setStyle('display','none');


		//gathering infos:
		var infos = {
			showID: window.easyFairs.showID,
			eventID: window.easyFairs.eventID
		};

		if(doSave===true){
			infos.doSave=true;
		}

		if(!piBookVar_isAdditionalBooking){
			// floorMap
			infos.floorMap = this.floorMapObj.canContinue();
		}
			
		// items
		var t = [];
		this.getStep('items').itemTable.items.each(function(item){
			t.push(item);
		});
		this.getStep('items').sysItemTable.items.each(function(item){
			if(!item.data.is_rebate)
			t.push(item);
		});
		infos.items = t;

		if(!piBookVar_isAdditionalBooking){
			//modules
			infos.modules = this.floorMapObj.getModules($('ef_block-items-currency_select').value);
	
			// taxo
			infos.taxonomy = this.taxonomy_checkout();
		}

		// info
		infos.info = {};
		if(!piBookVar_isAdditionalBooking){
			$('ef_block-info').getElements('input[type=text]').each(function(input){
				infos.info[input.getProperty('name')] = input.value;
			});
			infos.info.comments = $('ef_block-info').getElement('textarea[name=comments]').value;
			if(!this.exhibitor_data_exists){
				infos.info.country = $('ef_block-info').getElement('select[name=country]').value;
				infos.info.country_str = $('ef_block-info').getElement('select[name=country] option[value='+infos.info.country+']').get('text');
	
			}
		}
		
		//currency
		infos.currency = $('ef_block-items-currency_select').value;

		//rebate
		infos.rebate = piBookVar_rebate;

		console.log('Booking data : ',infos);
		this.validate_data = infos;


		var r = new Request.JSON({
			url:'index.php',
			method:'post',
			noCache:true,
			data:{
				eID:'tx_ef_pibook-validate',
				data:JSON.encode(infos),
				lid:window.easyFairs.lid,
				L:window.easyFairs.lid,
				show_ll:window.easyFairs.show_ll,
				add:(piBookVar_isAdditionalBooking?1:0)
			},
			onComplete: this.validate_onRequestComplete.bind(this)
		}).send();
		//*/


	},

	validate_onRequestComplete: function(response){
		var targetHTML = $('ef_block-validate-target');

		targetHTML.getElement('.wait').setStyle('display','none');

		if(response==null || response==undefined){
			response = {
				error:true,
				errorMsg:'Request error. Something, somewhere has been terribly wrong.'
			};
		}

		ui.scrollTo(0,200);

		if(response.error){

			var errorMsg = response.errorMsg ? response.errorMsg : 'Undefined error occured.';
			targetHTML.getElement('.errors').setStyle('display','');
			targetHTML.getElement('.errorMsg').set('html','<p>'+errorMsg+'</p>');

		}else{

			if(response.checkForm){

				if(response.validated){
					//redirect
					targetHTML.getElement('.success').setStyle('display','');

					var redirect_url = '/booking/confirm/?L='+window.easyFairs.lid+'&tx_ef_pibook[mailResult]='+response.mailSent+'&tx_ef_pibook[booking_id]='+response.booking_id+'&tx_ef_pibook[showID]='+window.easyFairs.showID+'&tx_ef_pibook[eventID]='+window.easyFairs.eventID;

					this.allowPageUnload = true;
					window.location.href = redirect_url;

					switch(response.mailSent){
						case 'success':
							targetHTML.getElement('.mailSuccess').setStyle('display','');
							break;
						case 'failed':
							targetHTML.getElement('.mailFailed').setStyle('display','');
							break;
						case 'none':
							//nothing... user has account already
							break;
						default:
							alert('Undefined mail result.'); //this alert should never show up. debug purpose
					}

				}else{
					//show confirm

					$('ef_block-validate-confirm').setStyle('visibility','visible');

					var itemTable = this.getStep('items').itemTable;

					//define targets
					var insert_items_el = $('ef_block-validate-confirm-insert_items');
					if(!piBookVar_isAdditionalBooking){
						var insert_modules_el = $('ef_block-validate-confirm-insert_modules');
						var insert_taxo_el = $('ef_block-validate-confirm-insert_taxonomy');
					}
					
					//empty targets
					insert_items_el.empty();
					if(!piBookVar_isAdditionalBooking){
						insert_modules_el.empty();
						insert_taxo_el.empty();
					}
					
					if(!piBookVar_isAdditionalBooking){
						// modules
						var total_superficy = 0;
						var total_modules_price = 0;
						this.validate_data.modules.each(function(module){
							total_superficy += Number(module.superficy);
							total_modules_price += module.price;
							new Element('tr').adopt(
								new Element('td',{
									'class':'table-col1',
									'html':module.label+' ('+module.superficy+'m²)'
								}),
								new Element('td',{
									'class':'table-col2',
									'html':itemTable.formatPrice(module.price)
								})
							).inject(insert_modules_el);
						});
	
						//rebate on total_modules_price
						if(piBookVar_rebate>0){
							var rebate_amount = (total_modules_price/100)*piBookVar_rebate;
							total_modules_price -= rebate_amount;
							new Element('tr').adopt(
								new Element('td',{
									'class':'table-col1',
									'html':'Rebate '+piBookVar_rebate+'%'
								}),
								new Element('td',{
									'class':'table-col2',
									'html':'- '+piBookObj.currentCurrency.cu_symbol_left+rebate_amount.round(2)+piBookObj.currentCurrency.cu_symbol_right
								})
							).inject(insert_modules_el);
						}
	
	
						$('ef_block-validate-confirm-total_superficy').set('html',total_superficy);
						$('ef_block-validate-confirm-total_modules').set('html',itemTable.formatPrice(total_modules_price));
					}
					
					// items
					var total_items_price = 0;
					this.validate_data.items.each(function(item){
						if(!item.data.system){
							var label = item.data.qty>1 ? item.data.desc+' (x'+item.data.qty+')' : item.data.desc;
							var price = (item.data.price['c'+piBookObj.validate_data.currency]*item.data.qty);
							total_items_price += price;
							new Element('tr').adopt(
								new Element('td',{
									'class':'table-col1',
									'html':label
								}),
								new Element('td',{
									'class':'table-col2',
									'html':itemTable.formatPrice(price)
								})
							).inject(insert_items_el);
						}
					});
					$('ef_block-validate-confirm-total_items').set('html',itemTable.formatPrice(total_items_price));

					//total_final
					if(piBookVar_isAdditionalBooking){
						var total_final = total_items_price;
					}else{
						var total_final = total_items_price+total_modules_price;
					}
					$('ef_block-validate-confirm-total_final').set('html',itemTable.formatPrice(total_final));


					//taxonomy
					if(!piBookVar_isAdditionalBooking){	
						this.validate_data.taxonomy.each(function(taxo){
							if(taxo.checked){
								new Element('li',{
									'text':taxo.label
								}).inject(insert_taxo_el);
							}
						});
					}

					
					//info
					if(!piBookVar_isAdditionalBooking){	
						$('ef_block-validate-confirm-insert_info_name').set('html',this.validate_data.info.contact_firstname+' '+this.validate_data.info.contact_lastname);
						$('ef_block-validate-confirm-insert_info_company').set('html',this.validate_data.info.company_name);
						$('ef_block-validate-confirm-insert_info_address').set('html',this.validate_data.info.address1+(this.validate_data.info.address2!=''?'<br/>'+this.validate_data.info.address2:''));
						$('ef_block-validate-confirm-insert_info_zipcountry').set('html',this.validate_data.info.zip+' '+this.validate_data.info.city+', '+this.validate_data.info.country_str);
						$('ef_block-validate-confirm-insert_info_email').set('text',this.validate_data.info.email);
					}else{
						$('ef_block-validate-confirm-insert_info_name').set('html',response.info.contact_firstname+' '+response.info.contact_lastname);
						$('ef_block-validate-confirm-insert_info_company').set('html',response.info.company_name);
						$('ef_block-validate-confirm-insert_info_address').set('html',response.info.address1+(response.info.address2!=''?'<br/>'+response.info.address2:''));
						$('ef_block-validate-confirm-insert_info_zipcountry').set('html',response.info.zip+' '+response.info.city+', '+response.info.country_str);
						$('ef_block-validate-confirm-insert_info_email').set('text',response.info.email);
					}
				}




			}else{

				targetHTML.getElement('.errors').setStyle('display','');
				var ul = targetHTML.getElement('.errorsUl');
				if(response.errorStack!=undefined){
					for(var i=0;i<response.errorStack.length;i++){
						ul.adopt(new Element('li',{'text':response.errorStack[i]}));
					}
				}else{
					ul.adopt(new Element('li',{'text':'Undefined error !'}));
				}



				if(response.reloadFloorMap){
					this.loadStep_floorMap();
					console.info('reload floorMap');
				}
			}
		}

		if(response.show_ll){
			targetHTML.getElement('.show_ll').set('html',response.show_ll);
		}
	}
});


var piBookObj;

window.addEvent('load',function(){
	if(window.piBookVar_enableScript){
		piBookObj = new tx_ef_pibook();
	}else{
		$('header-cart').dispose();
	}
});

