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');
  }
});
function piexhlist_getPreviewPaneContent(stand_id){
	if ($(document.body).getElement('#piexhlist-standpreviewpanes')) {
   	if ($('piexhlist-standpreviewpanes').getElement("li[stand_id=" + stand_id + "] .previewPane")) {
   		return $("piexhlist-standpreviewpanes").getElement("li[stand_id=" + stand_id + "] .previewPane").innerHTML;
   	}
   }
	 	return '';
}


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){
        if(item.max_qty==0 || typeof(item.max_qty)=="undefined" || self.items[i].data.qty+1 <= item.max_qty){
          self.items[i].data.qty+=1;//item.qty;
        }else{
          alert(window.tx_ef_pibook_jslabels.label_booking__item_max_qty_reached.substitute({max_qty:item.max_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();
        item.data.qty=1;
      }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{
          if(theItem.max_qty==0 || item.data.qty+1 <= theItem.max_qty){
            item.data.qty++;
          }else{
            alert(window.tx_ef_pibook_jslabels.label_booking__item_max_qty_reached.substitute({max_qty:theItem.max_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'
  ],
  
  cart:[],
  cartUids:[],
  cartUid2I:{},

	item_search_lastKey: 0,

  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
    if(typeof(this.ui.loaderEl)!="undefined"){
    	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{
    	if(!piBookVar_has365){
	      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)
	        }
	      ];
    	}else{
    		
    		this.steps = [
                {
    	          id: 'floorMap',
    	          canContinue: false,
    	          ready: false,
    	          load: this.loadStep_floorMap.bind(this)
    	        },
    	        {
      	          id:'365',
      	          canContinue: false,
      	          load: this.loadStep_365.bind(this) /*,
      	          refresh: this.refreshStep_365.bind(this)*/,
      	          afterRender:this.afterRender_365.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));
      console.log('add event to '+'ef_block-'+step.id+'-toggler');
    });

    //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();


    this.allowPageUnload = true;
    window.onbeforeunload = this.onBeforeUnload.bind(this);

    this.importedData = null;

    if(piBookVar_isAdditionalBooking){
    	self.ui.loaderEl.fade('out');
    }

  },

  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
    };

    
    
    //if(window.location.href.contains('debug')) ui=null;
    
    try{
    if(typeof(ui)!=undefined && typeof(ui.loaderEl)!=undefined && ui && ui.loaderEl) //for ie8. unreproducible
    this.ui.loaderEl = ui.loaderEl;
    }catch(e){
    	this.ui.loaderEl=new Element('div').inject(document.body);
    }

    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);
        if(this.steps[step].afterRender) this.steps[step].afterRender();
        this.currentStep = step;
      }else{
    	if(piBookVar_has365){
    	  if(blockingStep>2) blockingStep--;
    	  else if(blockingStep==1) blockingStep=14;
    	}
        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();
    
    if(ui) ui.scrollTo(0,200);
    else{
    	var scroller = new Fx.Scroll(window);
		scroller.start(0,200);
    }
    
    if(window.parent.ui){
    	window.parent.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));

  },
  
  login_callBack: function(){
	  if($('pass')){
		  //alert('not logged in'); 
	  }else{
		  //alert('logged in !');
		  piBookObj.onLoginSuccess();
	  }
  },

  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(),
      nc:Math.random()
    });

  },

  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();
          
          piBookObj.allowPageUnload = true;
          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');

        //change intro message
        $('pibook-info-introtext_notloggedin').setStyle('display','none');
        $('pibook-info-introtext_loggedin').setStyle('display','block');

        //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;
    var modules_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);
          //modules_price += item.priceForOther['c'+piBookObj.currentCurrency.currency];

        });
      });
    }

    
    //piBookObj.cartResetNonRemovables();


    //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 = piBookObj.getCartTotalPrice();
    	
    //}

    //final_price = final_price.round(2);

    if(!piBookVar_isAdditionalBooking){
      $('modulesNames').set('text',modulesNames.join(', '));
      $('totalSuperficy').set('text',totalSuperficy);
    }
    if($('final_price')) $('final_price').set('html',piBookObj.formatPrice(final_price)+(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',function(){
    	  //console.log('FP module update event');
    	  piBookObj.cartResetNonRemovables();
    	  piBookObj.updateMiniCart(); 
      });

      if(piBookVar_stand_id){
        floorMap.selectStand(piBookVar_stand_id);
      }
      
      clicknLoadInit(document.body.getElement('.clicknLoadInit_async'));

    });

  },
  
  loadStep_365: function(){
	  var thisStep = this.getStep('365');
	  var self=this;
	  
	  //format prices
	  $('piBook_price_365').set('text', this.formatPrice($('piBook_price_365').get('text').toInt()));
	  $('piBook_price_365_and_booster_365').set('text', this.formatPrice($('piBook_price_365_and_booster_365').get('text').toInt()));
	  $('piBook_price_365_and_booster_booster').set('text', this.formatPrice($('piBook_price_365_and_booster_booster').get('text').toInt()));
	  $('piBook_price_365_and_booster').setProperty('title','= '+this.formatPrice($('piBook_price_365_and_booster').getProperty('title').toInt()))
	  
	  $('piBook_goItems_365only').addEvent('click',function(e){
		  e.stop();
		  thisStep.canContinue = true;
		  self.goNextStep();
	  });
	  $('piBook_goItems_365booster').addEvent('click',function(e){
		  e.stop();
		  
		  //add default boosters
		  for(var i=0;i<piBookVar_default_boosters.length;i++){
			  self.addToCart(piBookVar_default_boosters[i], null);
		  }
		  
		  thisStep.canContinue = true; 
		  self.goNextStep();
	  });
	  
	  
	  
	  thisStep.ready = true;
  },

  afterRender_365: function(){
	//make sure the 2 .cont have the same height
	  $('piBook-o365div').getElements('.cont').setStyle('height',$('piBook-o365div').getHeight().toInt());
  },
  
  loadStep_items: function(){
    var thisStep = this.getStep('items');
    thisStep.req=null;
    
    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;
      }
    });
    
    thisStep.itemsCache = {};
    
    //init item groups
    var lis = $("ef_block-items-addItem").getElements("li.hasChild");
    var lis_span = $("ef_block-items-addItem").getElement("ul").getElements("span");
   
    var group_boost_el=null;
    for(var i=0;i<lis_span.length;i++){
    	//lis_span[i].setStyle("border","1px solid green");
    	
    	var itemList = new Element('ul',{'class':'itemList'});
    	$('pibook-itemLists').adopt(itemList);
    	lis_span[i].store('itemList',itemList);
    	
    	if(lis_span[i].get('text').toLowerCase().contains("booster")) group_boost_el=lis_span[i];
    }
    
    $("pibook-search-el").store('itemList',$("pibook-search-list"));
    //lis_span.addEvent("click",function(e){
    for(var i=0;i<lis_span.length;i++){
    	
	    lis_span[i].addEvent("click",function(e){
	    	//alert("click beg");
	    	var par = this.getParent();
	    	if(par.hasClass('cart')){
	    		piBookObj.showCart();
	    		return;
	    	}
	    	
	    	
	    	if(par.hasClass("hasChild")){
		    	var childUl = par.getElement("ul");
		    	if(childUl.getStyle("display")=="none"){
		    		childUl.setStyle("display",'block');
		    		par.removeClass("closed");
		    		par.addClass("open");
		    	}else{
		    		childUl.setStyle("display",'none');
		    		par.addClass("closed");
		    		par.removeClass("open");
		    	}
	    	}
	    	if(thisStep.req) thisStep.req.cancel();
	    	
	    	var groupId = this.getProperty('group_uid');
	    	var itemList = this.retrieve('itemList');
	    	
	    	itemList.getParent().getElements("ul.itemList").setStyle('display','none');
	    	$("pibook-item-splash").setStyle("display","none");
	    	
	    	this.items_currentCat=groupId;
	    	
	    	if(itemList.innerHTML!=''){ 
	    		//from cache
	    		itemList.setStyle('display','block');
	    		
	    	}else{
	    		//from ajax
	    		var children = par.getElements('ul li span');
	    		var subcatUids=[];
	    		if(children.length>0){
	    			for(var i=0;i<children.length;i++) subcatUids.push(children[i].getProperty('group_uid'));
	    		}
	    		$('pibook-itemList-loading').setStyle('display','block');
	    		thisStep.req = new Request.HTML({
	        		'url':'index.php',
	        		'method':'get',
	        		'data':{
	        			'eID':'tx_ef_itemGroup',
	        			'showID':easyFairs.showID,
	        			'L':easyFairs.lid,
	        			'group':groupId,
	        			'currency':$('ef_block-items-currency_select').value,
	        			'subc':subcatUids.join(","),
	        			'isCoexh':(piBookVar_isCoexh?'1':'0'),
	        			'nc':Math.random()
	        		},
	        		'onComplete':(function(e,ee){
	        			$('pibook-itemList-loading').setStyle('display','none');
	        			this.retrieve('itemList').setStyle('display','block').adopt(e);
	        			//add title to the list
	        			//new Element('li',{"class":'title','text':this.get('text')}).inject(this.retrieve('itemList'),'top');
	        			//add events
	        			piBookObj.items_initItemList(this.retrieve('itemList'));
	        		}).bind(this)
	        	}).send();
	    	}
	    	
	    	//alert("click end");
	    
	    });
    }
    for(var i=0;i<lis.length;i++){
    	lis.getElement("ul").setStyle("display",'none');
    	lis.addClass("closed");
    }
    //itemGroup init end
    
    //search
    this.item_search_lastQ="";
    $("pibook-search-input").addEvent("keyup",function(){var d = new Date();piBookObj.item_search_lastKey=d.getTime();});
    (function(){
	    if (piBookObj.steps[piBookObj.currentStep].id != 'items') { return false; };
    	var d = new Date();
    	var thisStep = piBookObj.getStep('items');
    	//console.log(d.getTime()>piBookObj.item_search_lastKey+1000 , $("pibook-search-input").value.trim()!='' , !thisStep.req , $("pibook-search-input").value.trim()!=piBookObj.item_search_lastQ);
    	if(d.getTime()>piBookObj.item_search_lastKey+1000 && $("pibook-search-input").value.trim()!=''  && $("pibook-search-input").value.trim()!=piBookObj.item_search_lastQ){
    		$("pibook-search-list").getParent().getElements("ul.itemList").setStyle('display','none');
    		$('pibook-itemList-loading').setStyle('display','block');
    		$("pibook-item-splash").setStyle("display","none");
    		if(thisStep.req) thisStep.req.cancel();
    		thisStep.req = new Request.HTML({
        		'url':'index.php',
        		'method':'get',
        		'data':{
        			'eID':'tx_ef_itemGroup',
        			'showID':easyFairs.showID,
        			'L':easyFairs.lid,
        			'currency':$('ef_block-items-currency_select').value,
        			'search':$("pibook-search-input").value.trim(),
        			'cats':piBookVar_productgroup_flat
        		},
        		'onComplete':(function(e,ee){
        			$('pibook-itemList-loading').setStyle('display','none');
        			this.retrieve('itemList').setStyle('display','block').empty().adopt(e);
        			piBookObj.items_initItemList(this.retrieve('itemList'));
        		}).bind($("pibook-search-el"))
        	}).send();
    		piBookObj.item_search_lastQ=$("pibook-search-input").value.trim();
    	}
    }).periodical(500);

    //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;
        }
      });
    });

    //console.log('def & force');
    //force & default qtys
    if(piBookVar_defaultQtys.length>0){
    	for(var i=0;i<piBookVar_defaultQtys.length;i++){
    		piBookVar_defaultQtys[i].removable = true;
    		this.addToCart(piBookVar_defaultQtys[i]);
    	}
    }
    
    
    //insert anim block
    $(document.body).adopt(new Element('div',{'id':'pibook-addToCartAnim'}));

    //splash init
    if(group_boost_el){
    	//console.log($("pibook-item-splash").getElements(".openboostcat"),group_boost_el);
    	$("pibook-item-splash").getElements(".openboostcat").addEvent('click',function(e){e.stop();group_boost_el.fireEvent("click");})
    }else{
    	//booster group not found, remove ad for booster
    	$("pibook-item-splash").getElements(".openboostcat").setStyle("display",'none');
    }

    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');

    if(this.items_currentCat==0){//cart
    	this.showCart();
    	this.updateCartDisplay();
  	  	this.updateMiniCart();
    }
    
    //this.cartResetNonRemovables();
    

    //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);
    }
    */
  },
  
  addToCart: function(obj,cartEl){
	  
	  if(typeof(obj.qty)=="string") obj.qty = obj.qty.toInt();
	  
	  //console.log("addToCart(",obj,')');
	  if(this.cartUids.contains(obj.uid)){
		  //only add qty
		  this.cart[this.cartUid2I[obj.uid]].qty = this.cart[this.cartUid2I[obj.uid]].qty.toInt()+obj.qty.toInt();
		  if(obj.element!=null){
			  this.cart[this.cartUid2I[obj.uid]].element.getElement('input').value = this.cart[this.cartUid2I[obj.uid]].qty;
		  }
	  }else{
		  
		  if(obj.element!=null){
			  //ensure we have a price in obj
			  obj.price = obj.element.getProperty('price');
			  obj.prices = null;
			  
			  //ensure we have a add_taxonomy_count in obj
			  obj.add_taxonomy_count = obj.element.getProperty("add_taxonomy_count").toInt();
			  
			  //ensure we have a name
			  obj.name = obj.element.getElement('h3.name').get('text');
			  
			  obj.element.getElement('input').value = obj.qty;
		  }
		  
		  var index = this.cart.length;
		  this.cart.push(obj);
		  this.cartUids.push(obj.uid);
		  this.cartUid2I[obj.uid] = index;
		  
		  
		  if(obj.element!=null){
			  //animation !
			  var pos = obj.element.getPosition();
			  var siz = obj.element.getSize();
			  $('pibook-addToCartAnim').setStyles({
				  'display':'block',
				  'top':pos.y.toInt(),
				  'left':pos.x.toInt(),
				  'width':siz.x.toInt(),
				  'height':siz.y.toInt()
			  });
			  var cartPos = $('pibook-cart-el').getPosition();
			  var cartSize = $('pibook-cart-el').getSize();
			  var addToCartAnim = new Fx.Morph( $('pibook-addToCartAnim') ,{onComplete:function(){$('pibook-addToCartAnim').setStyle('display','none')}});
			  addToCartAnim.start({
				'width':cartSize.x,
				'height':cartSize.y,
				'top':cartPos.y,
				'left':cartPos.x
			  });
			  //animation end
		  }
	  }
	  
	  
	  //limit max qty
	  if(piBookVar_maxQtys[obj.uid] && this.cart[this.cartUid2I[obj.uid]].qty.toInt() > piBookVar_maxQtys[obj.uid].toInt()){
		  this.cart[this.cartUid2I[obj.uid]].qty = piBookVar_maxQtys[obj.uid].toInt();
		  alert(tx_ef_pibook_jslabels.label_booking__item_max_qty_reached.substitute({'max_qty':piBookVar_maxQtys[obj.uid].toInt()}));
	  }
	  
	  //forced ?
	  if(piBookVar_forceQtys[obj.uid] && this.cart[this.cartUid2I[obj.uid]].qty.toInt() > piBookVar_forceQtys[obj.uid].toInt()){
		  //bring back the minus
		  if(obj.element) obj.element.getElement('.minus').setStyle('display','block');
		  if(cartEl) cartEl.getElement('.minus').setStyle('display','block');
	  }
	  
	  
	  this.updateCartDisplay();
	  this.updateMiniCart();
  },
  
  removeFromCart: function(obj,cartEl){
	  if(this.cartUids.contains(obj.uid)){
		  this.cart[this.cartUid2I[obj.uid]].qty = this.cart[this.cartUid2I[obj.uid]].qty.toInt() - obj.qty.toInt();
		  
		  //forced ?
		  if(piBookVar_forceQtys[obj.uid] && this.cart[this.cartUid2I[obj.uid]].qty.toInt() <= piBookVar_forceQtys[obj.uid].toInt()){
			  this.cart[this.cartUid2I[obj.uid]].qty = piBookVar_forceQtys[obj.uid].toInt();//be sure it's not less than forceQty
			  if(cartEl) cartEl.getElement('.minus').setStyle('display','none');
		  }
		  
		  if(obj.element) obj.element.getElement('input').value = this.cart[this.cartUid2I[obj.uid]].qty;
		  if(this.cart[this.cartUid2I[obj.uid]].qty<=0){
			  this.cart[this.cartUid2I[obj.uid]] = null;
			  delete this.cartUids[this.cartUid2I[obj.uid]];
			  delete this.cartUid2I[obj.uid];
			  if(obj.element) obj.element.removeClass('inCart');
		  }
	  }else{
		  alert('Error: Trying to remove an item that is not in cart!');
	  }
	  this.updateCartDisplay();
	  this.updateMiniCart();
  },
  
  cartResetNonRemovables: function(){
	  
	  

		//only add items from plan at the top of table
		if(!piBookVar_isAdditionalBooking){
		  var itemsFromPlan = this.floorMapObj.getItems();
		  //console.log('>>>>>> itemsFromPlan:',itemsFromPlan);
		}
		
		//clear all non removables
		for(var i=0;i<this.cart.length;i++){
			if(this.cart[i] && !this.cart[i].removable) this.removeFromCart({'uid':this.cart[i].uid,qty:this.cart[i].qty});
		}
	    
		//re-add them from floormap
	    if(!piBookVar_isAdditionalBooking){
	      itemsFromPlan.each(function(item,i){
	        //thisStep.sysItemTable.add(item,'top',true);
	    	  
	    	  var fullItem = piBookObj.floorMapObj.getItemByUid(item.uid);
	    	  
	    	  var hasBom = false;
	    	  for (key in fullItem.bom) {
	    		  if (fullItem.bom.hasOwnProperty(key)){
	    			  hasBom=true;
	    			  break;
	    		  }
	    	  }

	    	  
	    	  piBookObj.addToCart({
	    		  element:null,
	    		  name:item.desc,
	    		  prices:item.price,
	    		  qty:item.qty,
	    		  removable:item.removable,
	    		  uid:item.uid,
	    		  add_taxonomy_count:0,
	    		  bom:(hasBom) ? fullItem.bom : null
	    	  });
	      });
	    }

	    //add the special rebate item
	    //piBookVar_rebate = 20;
	    ///@TODO: implement rebate
	    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);*/
	    }
	    
	    
	    console.log('cart after reset',this.cart);

  },
  
  updateCartDisplay: function(){
	 $("ef_block-items-itemList-final-total").set('text',this.formatPrice(this.getCartTotalPrice())) 
  },
  
  formatPrice: function(num){
	  num=num.toFloat();
	  return this.currentCurrency.cu_symbol_left+num.round(2)+this.currentCurrency.cu_symbol_right;
  },
  getCartTotalPrice: function(){
	  var total=0;
	  for(var i=0;i<this.cart.length;i++){
		  if(this.cart[i]){
			  var itemPrice = 0;
			  if(this.cart[i].prices!=null){
				  itemPrice = (this.cart[i].prices['c'+this.currentCurrency.currency] * this.cart[i].qty);
			  }else{
				  itemPrice = (this.cart[i].price * this.cart[i].qty);
			  }
			  
			  
			  //if rebate, decrease price of modules
			  if(piBookVar_rebate>0){
			      var rebate_amount = (itemPrice/100)*piBookVar_rebate;
			      itemPrice -= rebate_amount;
			  }
			    
			  total += itemPrice;
			  
		  }
	  }
	  return total;
  },
  
  showCart: function(){
	  //hide current cat
	  this.items_currentCat=0;
	  $("pibook-item-splash").setStyle("display","none");
	  $('pibook-itemLists').getElements('ul').setStyle('display','none');
	  $('pibook-cart-list').empty();
	  for(var i=0;i<this.cart.length;i++){
		  if(this.cart[i]){
			  var refEl = $('pibook-itemLists').getElement('li[uid='+this.cart[i].uid+']');
			  if(refEl){
				  var clone = refEl.clone();
				  clone.store('refEl',refEl);
			  }else{
				  if(!this.cart[i].removable){
					  //forced from FP
					  var clone = new Element('li',{
						  'class':'inCart',
						  'uid':this.cart[i].uid
					  }).adopt(
						  new Element('div',{'class':'descr'}).adopt(
								  new Element('h3',{'class':'name','text':this.cart[i].name}),
								  (this.cart[i].image? new Element('div',{html:this.cart[i].image}) :null),
								  (this.cart[i].bom? new Element('div',{html:'<a href="#" style="text-decoration:underline;">'+tx_ef_pibook_jslabels.label_booking__bom_button+'</a>'}): null),
								  (this.cart[i].descr? new Element('div',{'class':'text',text:this.cart[i].descr}) :null)
						  ),
						  new Element('div',{'class':'bar'}).adopt(
								  new Element('div',{'class':'price','text':this.formatPrice(this.cart[i].prices['c'+this.currentCurrency.currency])}),
								  new Element('div',{'class':'cart forced','html':'<div class="qty"><input type="text" value="'+this.cart[i].qty+'" /></div>'})
						  )
					  );
				  }else{
					  //already in cart, but not yet loaded
					  var minus = '<a href="#" class="minus">-</a>';
					  if(piBookVar_forceQtys[this.cart[i].uid] && this.cart[this.cartUid2I[this.cart[i].uid]].qty.toInt() <= piBookVar_forceQtys[this.cart[i].uid].toInt()){
						  minus = '<a href="#" class="minus" style="display:none;">-</a>';
					  }
					  
					  var plus = '<a href="#" class="plus">+</a>';
					  if(piBookVar_forceQtys[this.cart[i].uid] && piBookVar_maxQtys[this.cart[i].uid] && piBookVar_forceQtys[this.cart[i].uid] == piBookVar_maxQtys[this.cart[i].uid]){
						  plus = '<a href="#" class="plus" style="display:none;">+</a>';
					  }
					  
					  var clone = new Element('li',{
						  'class':'inCart',
						  'uid':this.cart[i].uid
					  }).adopt(
						  new Element('div',{'class':'descr'}).adopt(
								  new Element('h3',{'class':'name','text':this.cart[i].name}),
								  (this.cart[i].image? new Element('div',{html:this.cart[i].image}) :null),
								  (this.cart[i].descr? new Element('div',{'class':'text',text:this.cart[i].descr}) :null)
						  ),
						  new Element('div',{'class':'bar'}).adopt(
								  new Element('div',{'class':'price','text':this.formatPrice(this.cart[i].prices['c'+this.currentCurrency.currency])}),
								  new Element('div',{'class':'cart','html':'<div class="qty">'+minus+'<input type="text" value="'+this.cart[i].qty+'" />'+plus+'</div>'})
						  )
					  );
				  }
			  }
			  $('pibook-cart-list').adopt( clone );
			  clone.store('uidforie',this.cart[i].uid);
		  }
	  }
	  
	  var pluses = $('pibook-cart-list').getElements('.plus');
	  pluses.addEvent('click',function(e){
		  e.stop();
		  var li = this.getParent('li');
		  var uid = li.getProperty('uid');
		  if(Browser.Engine.trident) uid = li.retrieve('uidforie');
		  var realEl = li.retrieve('refEl');
		  var theElement = null;
		  if(realEl){
			 theElement= realEl;
		  }
		  piBookObj.addToCart({'element':realEl,'uid':uid,'qty':1},li);
		  //mimic in cart
		  li.getElement('input').value = piBookObj.cart[piBookObj.cartUid2I[uid]].qty;
		  this.blur();
	  });
	  var minuses = $('pibook-cart-list').getElements('.minus');
	  minuses.addEvent('click',function(e){
		  e.stop();
		  var li = this.getParent('li');
		  var uid = li.getProperty('uid');
		  if(Browser.Engine.trident) uid = li.retrieve('uidforie');//fuck ie
		  var realEl = li.retrieve('refEl');
		  var theElement=null;
		  if(refEl) theElement=realEl;
		  piBookObj.removeFromCart({'element':theElement,'uid':uid,'qty':1},li);
		  //mimic in cart
		  if(piBookObj.cartUid2I[uid]!=null){
			  //qty changed
			  var qty = piBookObj.cart[piBookObj.cartUid2I[uid]].qty;
			  li.getElement('input').value = qty;
		  }else{
			  //out of cart
			  li.dispose();
		  } 
		  this.blur();
	  });
	  
	  //click for more
	  $('pibook-cart-list').getElements(".descr").addEvent("click",function(e){
		 e.stop();
		 var li = this.getParent("li");
		 var uid = li.getProperty("uid");
		 openEfPopup("index.php?eID=tx_ef_itemDetail&item_id="+uid+"&L="+easyFairs.lid+"&show_id="+easyFairs.showID+"&currency="+piBookObj.currentCurrency.currency,this.getElement(".name").get('text'),function(){ui.popup_hideLoad();ui.popup_ajaxize();});
	  });
	  
	  //disable inputs
	  $('pibook-cart-list').getElements("input").addEvent("focus",function(e){this.blur();});
	  
	  $('pibook-cart-list').setStyle('display','block');
  },
  
  items_initItemList: function(ul){
	 var buys = ul.getElements('.buy');
	 
	 
	 
	 for(var i=0;i<buys.length;i++){
		 var li = buys[i].getParent('li');
		 var uid = li.getProperty("uid");
		 
		 //already in cart ?
		 if(this.cartUids.contains(uid)){
			 li.addClass('inCart');
			 li.getElement(".qty input").value = this.cart[this.cartUid2I[uid]].qty;
			 this.cart[this.cartUid2I[uid]].element=li;
		 }
		 li.getElement(".qty input").addEvent("focus",function(e){this.blur();});
	 }
	 
	 
	 buys.addEvent("click",function(){
		 var li = this.getParent('li');
		 
		 //add to cart
		 piBookObj.addToCart({'element':li,'uid':li.getProperty('uid'),'qty':1,removable:true});
		 
		 //display
		 //this.setStyle('display','none');
		 //var qty = this.getParent().getElement('.qty');
		 //qty.setStyle('display','block');
		 li.addClass('inCart');
		 
	 });
	 
	 var pluses = ul.getElements('.plus');
	 pluses.addEvent('click',function(e){
		 e.stop();
		 var li = this.getParent('li');
		 piBookObj.addToCart({'element':li,'uid':li.getProperty('uid'),'qty':1});
		 this.blur();
	 });
	 
	 var minuses = ul.getElements('.minus');
	 minuses.addEvent('click',function(e){
		 e.stop();
		 var li = this.getParent('li');
		 piBookObj.removeFromCart({'element':li,'uid':li.getProperty('uid'),'qty':1});
		 this.blur();
	 });
	 
	 //title
	 var titleEl = ul.getElement("li.title");
	 //subcats, breadcrumb
	 var subcatsLinks = titleEl.getElements(".subcat a,h2 a");
	 if(subcatsLinks.length>0){
		 subcatsLinks.addEvent('click',function(e){e.stop();$("ef_block-items-addItem").getElement("span[uid="+this.getProperty("uid")+"]").fireEvent("click");})
	 }
	 //list style toggle
	 titleEl.getElement(".list-style-toggler").getElement(".grid").addEvent("click",function(e){e.stop();$("pibook-itemLists").removeClass("compact");})
	 titleEl.getElement(".list-style-toggler").getElement(".list").addEvent("click",function(e){e.stop();$("pibook-itemLists").addClass("compact");})
	 //orderby
	 titleEl.getElement(".orderby").getElement("select").addEvent("change",function(e){
		 //create array
		 var els = ul.getElements("li.item");
		 var items = [];
		 for(var i=0;i<els.length;i++){
			 items.push({index:i,name:els[i].getElement("h3.name").get('text'),price:els[i].getProperty("price")});
		 }
 
		 function sortByName(a,b){
			 var x = a.name.toLowerCase();
		     var y = b.name.toLowerCase();
		     return ((x < y) ? -1 : ((x > y) ? 1 : 0));
		 }
		 function sortByPriceAsc(a,b){
			 var x = a.price.toFloat();
		     var y = b.price.toFloat();
		     return ((x < y) ? -1 : ((x > y) ? 1 : 0));
		 }
		 function sortByPriceDesc(a,b){
			 var x = a.price.toFloat();
		     var y = b.price.toFloat();
		     return ((x < y) ? 1 : ((x > y) ? -1 : 0));
		 }
		 items.sort(this.value=="name"?sortByName:(this.value=="price_asc"?sortByPriceAsc:sortByPriceDesc));
		 var itemsIndex = [];
		 for(var i=0;i<items.length;i++) itemsIndex.push(items[i].index);
		 var mySort = new Fx.Sort(els);
		 mySort.rearrangeDOM(itemsIndex);
	 });
	 
	 var subcatsLinks = ul.getElements(".found-cats a");
	 if(subcatsLinks.length>0){
		 subcatsLinks.addEvent('click',function(e){e.stop();$("ef_block-items-addItem").getElement("span[uid="+this.getProperty("uid")+"]").fireEvent("click");})
	 }
	 
	 
	 //click for more
	 ul.getElements(".descr").addEvent("click",function(e){
		 e.stop();
		 var li = this.getParent("li");
		 var uid = li.getProperty("uid");
		 openEfPopup("index.php?eID=tx_ef_itemDetail&item_id="+uid+"&L="+easyFairs.lid+"&show_id="+easyFairs.showID+"&currency="+piBookObj.currentCurrency.currency,this.getElement(".name").get('text'),function(){ui.popup_hideLoad();});
	 });
	 
	 
	 
	 
  },
  
  
  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 || this.taxonomy_getAvailCount()<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<this.cart.length;i++){
      if(this.cart[i]){
	      var item_count = this.cart[i].add_taxonomy_count;
	      if(item_count > 0){
	        this.taxonomy_boosterPack += this.cart[i].qty;
	        this.taxonomy_maxBoosted += (item_count * this.cart[i].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 = [];
    var retId = [];
    $('ef_block-taxonomy-taxos').getElements('li').each(function(li,i){
      var input = li.getElement('input[type=checkbox]');
      if(!input) return;
      var label = li.getElement('label');
      var t = {
        id:input.value,
        label:label.get('text'),
        checked:input.checked
      };
      if(!retId.contains(t.id)){
	      retId.push(t.id);
	      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,
      'vat':(piBookVar_vatMandatory ? formValidator.notEmpty : function(){return true;} )
    };
    var error = false;
    
    //questions
    if($('pibook-bookquestions')){
    	var questions = $('pibook-bookquestions').getElements("textarea");
    	for(var i=0;i<questions.length;i++){
    		if(questions[i].getProperty("mandatory")=="true"){
	    		if(questions[i].value.trim()==''){
	    			questions[i].addClass('error');
	    			error = true;
	    		}else questions[i].removeClass('error');
    		}
    	}
    }
    
    
    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;
  },

  
  validate_canGoSave: function(){
	 if($("pibook-cangosave").checked) return true;
	 alert( window.tx_ef_pibook_jslabels.label_booking__you_need_to_agree_terms );
	 return false;
  },

  loadStep_validate: function(){
    console.log('loadStep_validate');

    if(piBookVar_onlinepay){
    	
    	//init doSave btn - old style
	    $('ef_block-validate-doSaveBtn').addEvent('click',(function(e){
	      new Event(e).stop();
	      if(this.validate_canGoSave()) this.refreshStep_validate(true,false);
	    }).bind(this));
    	
    	//init doSave w/ onlinepay
	    $('ef_block-validate-doSaveBtn-op').addEvent('click',(function(e){
	    	e.stop();
	    	if(this.validate_canGoSave()) this.refreshStep_validate(true,true);
		}).bind(this));
	    
    	
    }else{

	    //init doSave btns
	    $$($('ef_block-validate-doSaveBtn'),$('ef_block-validate-doSaveBtn2')).addEvent('click',(function(e){
	      new Event(e).stop();
	      if(this.validate_canGoSave()) this.refreshStep_validate(true,false);
	    }).bind(this));
    
    }

    this.getStep('validate').ready = true;
  },

  refreshStep_validate: function(doSave,onlinepay){
    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(piBookVar_isAdditionalBooking){
      infos.add_stand_id = piBookVar_add_standID;
    }

    if(doSave===true){
      infos.doSave=true;
    }
    
    
    infos.doOnlinepay = false;
    if(onlinepay===true){
    	infos.doOnlinepay = 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);
    });
    */
    for(var i=0;i<this.cart.length;i++){
    	if(!this.cart[i]) continue;
    	var priceObj = {};
    	if(this.cart[i].prices) priceObj=this.cart[i].prices;
    	else priceObj['c'+piBookObj.currentCurrency.currency] = this.cart[i].price;
    	var item = {
    		data:{
    			qty:this.cart[i].qty,
    			price:priceObj,
    			uid:this.cart[i].uid,
    			removable:this.cart[i].removable,
    			add_taxonomy_count:this.cart[i].add_taxonomy_count,
    			desc:this.cart[i].name 
    		}
    	};
    	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');

      }
    }
    
    //yourref
    infos.yourref = $("pibook-yourref").value.trim();

    //currency
    infos.currency = $('ef_block-items-currency_select').value;

    //rebate
    infos.rebate = piBookVar_rebate;

    //questions
    if($('pibook-bookquestions')){
    	infos.questions = [];
    	var questions = $('pibook-bookquestions').getElements("textarea");
        for(var i=0;i<questions.length;i++){
        	infos.questions.push({q:questions[i].getProperty('uid'),a:questions[i].value.trim()});
        }
    }
    
    
    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),
        stand_id:piBookVar_stand_id,
        c:Math.random()
      },
      onComplete: this.validate_onRequestComplete.bind(this)
    }).send();
    //*/


  },

  validate_onRequestComplete: function(response,responseText){
    var targetHTML = $('ef_block-validate-target');

    targetHTML.getElement('.wait').setStyle('display','none');

    if(response==null || response==undefined){
      response = {
        error:true,
        errorMsg:'There was an error in transferring your data. Please try again.   '+responseText
      };
    }

    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','');
          
      
    	  if(!response.onlinepay){
        	  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+'&nkd='+(window.location.href.contains('nkd=1')?'1':'0');
        	  if(response.redirect_addParams){
            	  redirect_url += response.redirect_addParams;
              }
              
              this.allowPageUnload = true;
              window.location.href = redirect_url;
    	  }else{
    		  //onlinepay
    		  //create fields and submit the form
    		  var formHTML = "";
    		  for (var opfield in response.onlinepay_data) {
    			  if (response.onlinepay_data.hasOwnProperty(opfield)) {
    				  console.log(opfield,response.onlinepay_data[opfield]);
    				  formHTML+='<input type="hidden" name="'+opfield+'" value="'+response.onlinepay_data[opfield]+'" />';
    			  }
    		  }
    		  $('pibook-onlinepay-form').innerHTML = formHTML;
    		  this.allowPageUnload = true;
    		  $('pibook-onlinepay-form').submit();
    		  
    	  }
         
          
          
          

        }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();
          }
          
          
          var total_superficy = 0;
          var total_modules_price = 0;
          if(!piBookVar_isAdditionalBooking){
            // modules
            
            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':piBookObj.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',piBookObj.formatPrice(total_modules_price));
          }

          // items
          var total_items_price = 0;
          if(piBookVar_onlinepay){
        	  var total_items_price_onlinepay = 0;
        	  for(var i=0;i<this.validate_data.items.length;i++){
        		  var item = this.validate_data.items[i];
        		  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;
        		  var price_op = response.items[item.data.uid].op_price*item.data.qty;
        		  total_items_price_onlinepay += price_op;
        		  
        		  new Element('tr').adopt(
  	                new Element('td',{
  	                  'class':'table-col1',
  	                  'html':label,
  	                  'styles':{'width':'60%'}
  	                }),
  	                new Element('td',{
  	                  'class':'table-col2',
  	                  'html':piBookObj.formatPrice(price)
  	                })
  	              ).inject(insert_items_el);
        	  }
        	  
        	  $('ef_block-validate-confirm-total_items').set('html',piBookObj.formatPrice(total_items_price));
        	  $('ef_block-validate-confirm-total_items_op').set('html',piBookObj.formatPrice(total_items_price_onlinepay));
        	  
        	  $('ef_block-validate-confirm-total_vat').set('html',piBookObj.formatPrice(response.allAddVAT));
        	  $('ef_block-validate-confirm-total_vat_op').set('html',piBookObj.formatPrice(response.allAddVAT_op));
        	  
          }else{
	          this.validate_data.items.each(function(item){
	            if(item.data.removable){
	              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':piBookObj.formatPrice(price)
	                })
	              ).inject(insert_items_el);
	            }
	          });
	          $('ef_block-validate-confirm-total_items').set('html',piBookObj.formatPrice(total_items_price));
          }
          //total_final
          if(piBookVar_isAdditionalBooking){
        	  
            var total_final = total_items_price + (piBookVar_onlinepay?response.allAddVAT:0);
          }else{
            var total_final = total_items_price+(piBookVar_onlinepay?response.allAddVAT:0) +total_modules_price;
          }
          $('ef_block-validate-confirm-total_final').set('html',piBookObj.formatPrice(total_final));
          
          if(piBookVar_onlinepay){
        	  var total_final_op = total_modules_price+total_items_price_onlinepay+response.allAddVAT_op;
        	  $('ef_block-validate-confirm-total_final_op').set('html',piBookObj.formatPrice(total_final_op));
        	  $('ef_block-validate-doSaveBtn-op').getElement('span').set('html',tx_ef_pibook_jslabels.label_booking__step5_btn_next_online_pay.substitute({"saved_amount":piBookObj.formatPrice(total_final-total_final_op)})+" &gt;");
          }

          //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){
    window.piBookObj = new tx_ef_pibook();
  }else{
	  if($('header-cart')){
		  $('header-cart').dispose();
	  }
    
  }
});


