/*
 * Floormap base class to be used for visitor FM
 * created by Christian Müller [kitsunet] <christian@kitsunet.de>
 * copyright easyFairs 2010
 */

var floorMap = {};
var currentModule = {};
var anchoredElem = null;


/*******************************************************************************
 * Class FloorMap
 ******************************************************************************/
var FloorMap = new Class({
  Implements:Events,
  initialize: function(ratio, width, height, resizer, minWidth, minHeight, openAreaLeft, openAreaTop, openAreaWidth, openAreaHeight, scrollLeft, scrollTop
    , background_color, bookable_background_color, bookable_border_color, unbookable_background_color, unbookable_border_color){
    this.ratio = ratio;
    this.width = width;
    this.height = height;
    this.resizer = resizer;
    this.minWidth = minWidth;
    this.minHeight = minHeight;
    this.openAreaLeft = openAreaLeft;
    this.openAreaTop = openAreaTop;
    this.openAreaWidth = openAreaWidth;
    this.openAreaHeight = openAreaHeight;
    this.scrollLeft = scrollLeft;
    this.scrollTop = scrollTop;
    this.background_color = background_color;
    this.bookable_background_color = bookable_background_color;
    this.bookable_border_color = bookable_border_color;
    this.unbookable_background_color = unbookable_background_color;
    this.unbookable_border_color = unbookable_border_color;
    this.floorZones = [];
    this.shows = [];
    this.newBooking = [];
    this.stands = [];
    this.items = [];
    this.locked = true;
    this.lastClick = 0;
    this.addOpenSideId = 0;
    this.lastDrag = 0;
    this.addInfoDisplay = 0;
    this.ratioChanged = true;
    this.notClickable = false;
    this.standSelection = [];
   this.highlightStandColor = 'rgba(153,202,3,1)';
   this.standsHover = true;
   this.standsOnClick = true;
    this.moduleSelection = [];


  },

  init: function(){
    if($('FloorMap')){
      this.ratioChanged = true;
      this.resize();
      window.addEvent('resize', function(){
        floorMap.resize();
      });

      // toolsbar's events triggers
      $('StandInfo').addEvent('click', function(e){
        e.stop();
      });

      $('CloseStandInfo').addEvent('click', function(e){
        e.stop();
        floorMap.unlock();
      });
      $('StandInfoCrossX').addEvent('click', function(e){
        e.stop();
        floorMap.unlock();
      });

      $('StandInfo').makeDraggable({
        container: 'LockScreen'
      });

      $('OpenArea').makeDraggable({
        onDrag: function() {
          //$('FloorMap').removeEvent('mousemove', floorMapHover);
       	 $('FloorMap').setStyle('cursor', 'pointer');
          // console.log(floorMap.openAreaWidth);
          // console.log($('FloorMap').getStyle('width').toInt()-$('OpenArea').getStyle('left').toInt());
          // console.log(floorMap.openAreaWidth*floorMap.ratio);
          floorMap.checkOpenArea();
        },
        onComplete: function() {
         	//$('FloorMap').addEvent('mousemove', floorMapHover);
       		$('FloorMap').setStyle('cursor', 'auto');
        }
      });

      var arrowEventHandler = (function(event, context){
        if($('FloorMap').getStyle('overflow') == 'hidden') {
          var left = $('OpenArea').getStyle('left').toInt();
          var top  = $('OpenArea').getStyle('top' ).toInt();
          var step = 3;
          var treated = true;
          switch(event.code) {
            case 37:
              left += step;
              break;
            case 38:
              top += step;
              break;
            case 39:
              left -= step;
              break;
            case 40:
              top -= step;
              break;
            default:
              treated = false;
          }
          if(treated) {
            $('OpenArea').setStyle('left', left+"px");
            $('OpenArea').setStyle('top' , top+"px");

            floorMap.checkOpenArea();
            return true;
          }
        }
        return false;
      });

      registerShortcutCode(37, false, false, false, $('FloorMap'), null, arrowEventHandler);
      registerShortcutCode(38, false, false, false, $('FloorMap'), null, arrowEventHandler);
      registerShortcutCode(39, false, false, false, $('FloorMap'), null, arrowEventHandler);
      registerShortcutCode(40, false, false, false, $('FloorMap'), null, arrowEventHandler);

      $('FloorMap').addEvent('click', function(event){

        floorMap.click(getRealX(event), getRealY(event), event.client.x, event.client.y);
      });

      $('FloorMap').addEvent('mousemove', floorMapHover);



    }


    this.ratioChanged = false;
  },

  initSelection: function(){



    window.easyFairs.cart.addEvent('serverMsg', function(event){
      this.updateStandSelection();
    }.bindWithEvent(this));

    var showsList = '';
    this.shows.each(function(item, index){
      if(index > 0){
        showsList += ',';
      }
        showsList += item.id;

    });
    window.easyFairs.cart.load(showsList);

  },

  updateStandSelection: function(){
    var type = 'stand';
      this.standSelection = [];
      this.shows.each(function(item, index){
        if (window.easyFairs.cart.data[item.id] && window.easyFairs.cart.data[item.id][type] && typeof window.easyFairs.cart.data[item.id][type] == 'object') {
          for(var standID in window.easyFairs.cart.data[item.id][type]){
              this.standSelection.push(Number(standID));
          }
        }
      }, this);

    this.redraw();
  },

  lock: function(andWait){
    if(!this.locked){
      this.locked = true;

      this.floorZones.each(function(item, index){
        if(item.mouseMoveOutEventFloorZone)
          item.mouseMoveOutEventFloorZone(-1, -1);
      });


      $('LockScreen').setStyle('display', 'block');
      if(andWait){
        $('AjaxLoader').setStyle('display', 'block');
       $('LockScreen').removeEvents();
      $('LockScreen').addEvent('click', function(e){
          e.stop();
          //floorMap.unlock();
        });
      } else {
      $('LockScreen').removeEvents();
      $('LockScreen').addEvent('click', function(e){
          e.stop();
          //floorMap.unlock();
        });

    }
    }
  },

  isLocked: function(){
    return this.locked;
  },

  unlock: function(){
    if(this.locked)
    {
      $('AjaxLoader').setStyle('display', 'none');
      $('StandInfo').setStyle('display', 'none');
      $('LockScreen').setStyle('background-color', 'transparent');
      $('LockScreen').setStyle('display', 'none');
      this.locked = false;
    }
  },


  // add an floorzone in the floorzone
  addFloorZone: function(id, name, image, width, height, top, left, tagname, guides_image){
    var floorZone = new FloorZone(this, id, name, image, width, height, top, left, tagname);
    floorZone.guides_image = guides_image;
    this.floorZones.push(floorZone);

    var newFloorZone = new Element('div', {
      'class':'floorZone',
      'id':name
    });
    newFloorZone.adopt(new Element('canvas', {
      'class':'floorZone',
      'id':name+'_canvas',
      'width':width,
      'height':height
    }));
    newFloorZone.adopt(new Element('img', {
      'class':'floorZone',
      'id':name+'_FZImg',
      'src':'../uploads/tx_ef/'+image
      }));

    $('fz_container').adopt(newFloorZone);



    return floorZone;
  },

  checkOpenArea: function(){
    var offset = 20;
    if($('FloorMap').getStyle('overflow') == 'hidden'){
      if($('OpenArea').getStyle('width').toInt() < $('FloorMap').getStyle('width').toInt()){
        $('OpenArea').setStyle('left', (($('FloorMap').getStyle('width').toInt()-$('OpenArea').getStyle('width').toInt())/2).toInt()+'px');
      }
      else if($('OpenArea').getStyle('left').toInt() > offset){
        $('OpenArea').setStyle('left', offset+'px');
      }
      else if(($('FloorMap').getStyle('width').toInt()-$('OpenArea').getStyle('left').toInt()) > ((floorMap.openAreaWidth*floorMap.ratio)+offset)){
        $('OpenArea').setStyle('left', ($('FloorMap').getStyle('width').toInt()-(floorMap.openAreaWidth*floorMap.ratio)-offset)+'px');
      }

      if($('OpenArea').getStyle('height').toInt() < $('FloorMap').getStyle('height').toInt()){
        $('OpenArea').setStyle('top',(($('FloorMap').getStyle('height').toInt()-$('OpenArea').getStyle('height').toInt())/2).toInt()+'px');
      }
      else if($('OpenArea').getStyle('top').toInt() > offset){
        $('OpenArea').setStyle('top', offset+'px');
      }
      else if( ($('FloorMap').getStyle('height').toInt()-$('OpenArea').getStyle('top').toInt()) > ((floorMap.openAreaHeight*floorMap.ratio)+offset) ){
        $('OpenArea').setStyle('top', ($('FloorMap').getStyle('height').toInt()-(floorMap.openAreaHeight*floorMap.ratio)-offset)+'px');
      }

      floorMap.scrollTop = -$('OpenArea').getStyle('top').toInt();
      floorMap.scrollLeft = -$('OpenArea').getStyle('left').toInt();
    }
  },


  click: function(x, y, clickX, clickY){
    if(this.notClickable){
      $('StandInfo').setStyle('display', 'block');
      $('OrderModule').setStyle('display', 'none');
      $('ClearSelection').setStyle('display', 'none');
      $('StandInfoContent').empty().adopt((new Element('h3')).appendText(window.tx_ef_pifloormap_jslabels.label_floormap__nochanges));
    } else if(!this.locked) {
		var isClicked = false;
      var realX = x+this.openAreaLeft;
      var realY = y+this.openAreaTop;
	 	var cLeft = (clickX+getScrollLeft()-findPosX($('FloorMap'))).round();
		var cTop = (clickY+getScrollTop()-findPosY($('FloorMap'))).round();
		for(var i = 0; i < this.floorZones.length; i++){
			if(this.floorZones[i].clickFloorZone(realX, realY, cLeft, cTop)){
				isClicked = true;
				break;
			}
		}

		return true;
    }
  // treat click here for floormap (if it's needed)
  },

  hoverStand: function(){

  },

  getStand: function(stand_id){
    var theStand = null;
    for(var i = 0; i < this.floorZones.length; ++i) {
       theStand = this.floorZones[i].getStand(stand_id);
       if(theStand != null){
           break;
       }
    }
    return theStand;
  },

  getModule: function(module_id){
    var theModule = null;
    for(var i = 0; i < this.floorZones.length; ++i) {
       theModule = this.floorZones[i].findModuleById(stand_id);
       if(theModule != null){
           break;
       }
    }
    return theModule;
  },


  getFloorZone: function(floorZoneId){
    for(var i = 0; i < this.floorZones.length; ++i) {
      if( this.floorZones[i].id == floorZoneId) {
        return this.floorZones[i];
      }
    }
    return false;
  },

  getShow: function(showId){
    for(var i = 0; i < this.shows.length; ++i) {
        if(this.shows[i].id == showId){
        return this.shows[i];
      }
    }
    return null;
  },

  getItem: function(itemId){
    for(var i = 0; i < this.items.length; ++i) {
      if(this.items[i].id == itemId){
        return this.items[i];
      }
    }
    return null;
  },


  addStand: function(show, id, stand_name, logo, left, top, width, height, path, floorZoneId, remark, standNumber){

    var currentFZ = this.getFloorZone(floorZoneId)
    var stand = new Stand(this, show, id, stand_name, logo, left, top, width, height, path, currentFZ, remark, standNumber);
    this.stands.push(stand);

    if(currentFZ){
      currentFZ.stands.push(stand);
      // TODO CLEANUP
      /*
      var standDiv  = new Element('div', {'id': 'stand_'+id, 'class': 'Stand'});

      if(remark){
      var remarkDiv = new Element('div', {'id': 'remark_'+id, 'class': 'remarkDiv'});
      remarkDiv.appendText(remark);
      remarkDiv.inject(standDiv);
      // remarkDiv.inject($(currentFZ.name));
      }


      if(logo){
      var standName  = new Element('img', {'id': 'standName_'+id, 'class': 'standName', 'src': logo});
      } else {
      var standName  = new Element('span', {'id': 'standName_'+id, 'class': 'standName'});
      standName.appendText(stand_name);
      }

      standName.inject(standDiv);
      standDiv.inject($(currentFZ.name));
      */
    }
    return stand;
  },

  addShow: function(id, name, bookable_background_color, bookable_border_color){
    var show = new Show(this, id, name, bookable_background_color, bookable_border_color);
    this.shows.push(show);
    return show;
  },

  // first draw
  draw: function(){


    this.ratioChanged = true;
    this.lock(true);

    $('FloorMap').setStyle('background-color', this.background_color.rgbToHex());

    if(this.resizer){
    this.createResizer();
    }
    else{
      $('FloorMapResizableAnchor').setStyle('display', 'none');
    }
    this.ratioChanged = true;
    this.resize();

    this.floorZones.each(function(item, index){
      this.ratioChanged = true;
      item.drawFloorZone();
    });


    if($('FloorMap_LogoArea')){
        var logoAreaProperties = JSON.decode($('FloorMap_LogoArea').getProperty('json'));
        $('FloorMap_LogoArea').setStyles({
          left: logoAreaProperties.left*this.ratio+'px',
          top: logoAreaProperties.top*this.ratio+'px',
          width: logoAreaProperties.width*this.ratio+'px',
          height: logoAreaProperties.height*this.ratio+'px'
        });
        $$('#FloorMap_LogoArea .logoarea_logo').setStyles({
          width: ((logoAreaProperties.singleBaseSize*this.ratio)+logoAreaProperties.padding*2)+'px',
          height: ((((logoAreaProperties.singleBaseSize / 2 ) * 1)*this.ratio)-logoAreaProperties.padding*2)+'px'

        });
    }

    (function(){

      this.ratioChanged = true;
      floorMap.redraw();


      // open area
      if(floorMap.openAreaHeight == 0 || floorMap.openAreaWidth == 0) {
        var maxX = 0;
        var maxY = 0;
        floorMap.floorZones.each(function(item, index){
          if((item.left+item.width) > maxX)
            maxX = item.left+item.width;
          if((item.top+item.height) > maxY)
            maxY = item.top+item.height;
        });
        floorMap.openAreaWidth = maxX;
        floorMap.openAreaHeight = maxY;
      }
      floorMap.drawOpenArea();

      if($('FloorMap').getStyle('overflow') == 'hidden'){
        $('OpenArea').setStyle('top', (-floorMap.scrollTop)+'px');
        $('OpenArea').setStyle('left', (-floorMap.scrollLeft)+'px');
      }
      else {
        $('FloorMap').scrollTop = floorMap.scrollTop;
        $('FloorMap').scrollLeft = floorMap.scrollLeft;
      }


      // $('clickableFM').addClass('transparent_class');
      floorMap.checkOpenArea();
      floorMap.unlock();
      this.ratioChanged = false;
    }).delay(100);// temporise le chargement des backgroound!!

  },

  createResizer: function(){
    // here only dummy, see FloorPlan.js for BE MOD

  },


// first draw

  drawOpenArea: function(){
    $('OpenArea').setStyle('height', (this.openAreaHeight*this.ratio).limit(1,40000));
    $('OpenArea').setStyle('width', (this.openAreaWidth*this.ratio).limit(1,40000));
  },

  resize: function(noWidth){
    $('FloorMap').setStyle('height', this.height.limit(1,40000)+'px');
    $('FloorMap').setStyle('width', this.width.limit(1,40000)+'px');

    var borderWidth = $('FloorMap').getStyle('border-width').toInt();
    $('LockScreen').setStyle('top', borderWidth+'px');
    $('LockScreen').setStyle('left', borderWidth+'px');

    if(Browser.Engine.trident) { // hack ie
      $('LockScreen').setStyle('height', (this.height-2*borderWidth).limit(1,40000)+'px');
      $('LockScreen').setStyle('width', (this.width-2*borderWidth).limit(1,40000)+'px');
      $('FloorMapResizableAnchor').setStyle('top', (this.height - 16 )+'px');
      $('FloorMapResizableAnchor').setStyle('left', (this.width - 16 )+'px');
    }
    else {
      $('LockScreen').setStyle('height', this.height.limit(1,40000)+'px');
      $('LockScreen').setStyle('width', this.width.limit(1,40000)+'px');
      $('FloorMapResizableAnchor').setStyle('top', (this.height - 13 )+'px');
      $('FloorMapResizableAnchor').setStyle('left', (this.width - 13 )+'px');
    }
  },

  // redraw all floorzones if something has changed
  redraw: function(){
    this.floorZones.each(function(item, index){
      item.redrawFloorZone();
    })
  },

  setAddOpenSideId: function(id){
    this.addOpenSideId = id;
  },

  canBeBookable: function(module){
    for(var i = 0; i < this.floorZones.length; ++i) {
      if( !this.floorZones[i].canBeBookableFloorZone(module) ) {
        return false;
      }
    }
    return true;
  },

  addItem: function(id, name, superficy, prices, priceForOther, show_id){
    var item = new Item(id, name, superficy, prices, priceForOther, show_id);
    this.items.push(item);
  },

  zoom: function(newRatio){
    this.ratioChanged = true;
    if(!this.locked) {
      var factor = newRatio/this.ratio;
      this.ratio = newRatio;

      if(factor > 1){
        var top = $('FloorMap').scrollTop;
        var left = $('FloorMap').scrollLeft;
        if($('FloorMap').getStyle('overflow') == 'hidden'){
          top = -$('OpenArea').getStyle('top').toInt();
          left = -$('OpenArea').getStyle('left').toInt();
        }

        var centery = factor*(top+($('FloorMap').getStyle('height').toInt()/2));
        var centerx = factor*(left+($('FloorMap').getStyle('width').toInt()/2));
        this.scrollTop = (centery-($('FloorMap').getStyle('height').toInt()/factor)).toInt();
        this.scrollLeft = (centerx-($('FloorMap').getStyle('width').toInt()/factor)).toInt();
      }
      else{
        var top = $('FloorMap').scrollTop;
        var left = $('FloorMap').scrollLeft;
        if($('FloorMap').getStyle('overflow') == 'hidden'){
          top = -$('OpenArea').getStyle('top').toInt();
          left = -$('OpenArea').getStyle('left').toInt();
        }

        var height = $('FloorMap').getStyle('height').toInt();
        var width  = $('FloorMap').getStyle('width').toInt();


        this.scrollTop =  (top*factor + ( ((height*factor)-height)/2 ) ).toInt(); // +(($('FloorMap').getStyle('height').toInt()/2)-mousey);
        this.scrollLeft = (left*factor + ( ((width*factor)-width)/2 )).toInt(); // +(($('FloorMap').getStyle('height').toInt()/2)-mousey);
      }
      this.draw();
      this.ratioChanged = false;
    }
  },

  zoomIn: function(mousex, mousey){
    this.zoom(this.ratio*2);
  },

  zoomOut: function(){
    this.zoom(this.ratio/2);
  },

  addStandsToSelection: function(newStands){
    newStands.each(function(item, index){
       window.easyFairs.cart.add(item.show.id, 'stand', item.id);
     }.bind(this));
  },

  removeStandsFromSelection: function(removedStands){
     removedStands.each(function(item, index){
      window.easyFairs.cart.remove(item.show.id, 'stand', item.id);
     }.bind(this));
   }
});




/*******************************************************************************
 * Class FloorZone
 ******************************************************************************/
var FloorZone = new Class({
  initialize: function(floorMap, id, name, image, width, height, top, left, tagname){
    this.floorMap = floorMap;
    this.id = id;
    this.name = name;
    this.image = image;
    this.width = width;
    this.height = height;
    this.top = top;
    this.left = left;
    this.tagname = tagname;
    this.modules = [];
    this.stands = [];
    this.lastClick = 0;
    this.lastDrag = 0;
    this.gridSize = Math.abs(3);
    this.gridOffsetX = 0;
    this.gridOffsetY = 0;
   this.modulesOnClick = false;

    if(!this.gridSize){
      this.gridSize = 1;
    }

  },

  inBoundingBox: function(x, y){
    return x >= this.left && x <= (this.left+this.width)
    && y >= this.top && y <= (this.top+this.height);
  },

  getStand: function(standId){
    for(var i = 0; i < this.stands.length; ++i) {
      if(this.stands[i].id == standId)
      {
        return this.stands[i];
      }
    }
    return null;

  },

  clickFloorZone: function(x, y, cLeft, cTop){
    if(this.inBoundingBox(x, y)){
	    var relX = (x-this.left);
	    var relY = (y-this.top);
	      // alert("fz"+this.id);
		 var itsClicked = false;
	    if(this.modulesOnClick){

		 	for(var i=0;i < this.modules.length;i++){
				if(this.modules[i].clickModule(relX, relY)){
					itsClicked = true;
					break;
				}
			}
			if(itsClicked){
				return true;
			}
	    }
		 if(this.floorMap.standsOnClick) {
	      $('FloorMap').removeEvent('mousemove', floorMapHover);
			for(i = 0; i < this.stands.length; i++){
				if(this.stands[i].clickStand(relX,relY,cLeft,cTop)){
					itsClicked = true;
					break;
				}
			}
	      $('FloorMap').addEvent('mousemove', floorMapHover);
			if(itsClicked){
				return true;
			}
	    }


      return false;
    }
    return false;
  },

  canBeBookableFloorZone: function(module){
    var bookedModCount = 0;
    var nearCount = 0;
    var otherCount = 0;
    for(var i = 0; i < this.modules.length; ++i) {
      if(this.modules[i].booked)
      {
        ++bookedModCount;
        nearCount += this.modules[i].nearCount(module.path);
        otherCount += module.nearCount(this.modules[i].path);
      }
    }
    return (bookedModCount == 0 || nearCount > 1 || otherCount > 1);
  },

  drawFloorZone: function(){
    $(this.name).setStyle('top', this.getTop()+"px");
    $(this.name).setStyle('left', this.getLeft()+"px");
    $(this.name+"_FZImg").setStyle('height', (this.height*this.floorMap.ratio).limit(1,40000)+"px");
    $(this.name+"_FZImg").setStyle('width', (this.width*this.floorMap.ratio).limit(1,40000)+"px");

    if($(this.name+"_canvas")) {
      $(this.name+"_canvas").set('height', (this.height*this.floorMap.ratio).limit(1,40000));
      $(this.name+"_canvas").set('width', (this.width*this.floorMap.ratio).limit(1,40000));
    }
  },

  redrawFloorZone: function(){
    ctx = this.getCTX();
    if(ctx) {
      ctx.clearRect(0, 0, this.width*this.floorMap.ratio, this.height*this.floorMap.ratio);

    this.stands.each(function(item, index){
        item.redrawStand(ctx);
      });

      this.modules.each(function(item, index){
        item.redrawModule(ctx);
      });

      return true;
    }
   return false;
  },

  getCTX: function(){
     if(!this.ctx){
     var el = $(this.name+"_canvas");
      if(el){
        if(Browser.Engine.trident)
          G_vmlCanvasManager.initElement(el);
        if(el.getContext) {
          var ctx = el.getContext('2d');
          if(ctx) {
           this.ctx = ctx;
            return this.ctx;
          }
        }
      }
   } else{
     return this.ctx;
   }
    alert('This browser does\'t support canvas element!');
    return false;
  },


  // return the displayed left value
  getLeft: function(){
    return (this.left-floorMap.openAreaLeft)*this.floorMap.ratio;
  },

  // return the displayed top value
  getTop: function(){
    return (this.top-floorMap.openAreaTop)*this.floorMap.ratio;
  },

  // return the displayed width value
  getWidth: function(){
    return this.width*this.floorMap.ratio;
  },

  // return the displayed height value
  getHeight: function(){
    return this.height*this.floorMap.ratio;
  },


// add a module in the floorzone

  addModule: function(floorMap, floorZone, id, name, x1, y1, x2, y2, x3, y3, x4, y4, bookable, stand_id, show_id, items, image, remark){
    var module = new Module(floorMap, floorZone, id, name, x1, y1, x2, y2, x3, y3, x4, y4, bookable, stand_id, show_id, items, image, remark, false);
    module.items = module.items.erase(0);
    this.modules.push(module);
   // TODO remove if canvas text is successful
   /*
    //if(window.floorMap.addInfoDisplay){
    var moduleDiv  = new Element('div', {
      'id': 'module_'+id,
      'class': 'Module'
    });
    var moduleName  = new Element('div', {
      'class': 'moduleName'
    });
    moduleName.appendText(name);
    moduleName.inject(moduleDiv);
    moduleDiv.inject($(this.name));
    //}
   */
    return module;
  }
});



/*******************************************************************************
 * Class module
 ******************************************************************************/
var Module = new Class({
  initialize: function(floorMap, floorZone, id, name, x1, y1, x2, y2, x3, y3, x4, y4, bookable, stand_id, show_id, items, image, remark, hidden){
    this.floorMap = floorMap;
    this.floorZone = floorZone;
    this.id = id;
    this.name = name;
    this.somethingChanged = false;
    this.lastLeft = 0;
    this.lastTop = 0;
    this.booked = (stand_id != 0);
    this.bookable = bookable;
    this.stand_id = stand_id;
    this.show_id = show_id;
    this.lastClick = 0;
    this.lastDrag = 0;
    this.items = items;
    this.image = image;
    this.remark = remark;
    this.hidden = hidden;
    this.selected = false;
    this.origPath = [[x1, y1], [x2, y2], [x3, y3], [x4, y4]];


    this.path = [
    [((Math.round(x1 / this.floorZone.gridSize) * this.floorZone.gridSize) + this.floorZone.gridOffsetX), ((Math.round(y1 / this.floorZone.gridSize) * this.floorZone.gridSize) + this.floorZone.gridOffsetY)],
    [((Math.round(x2 / this.floorZone.gridSize) * this.floorZone.gridSize) + this.floorZone.gridOffsetX), ((Math.round(y2 / this.floorZone.gridSize) * this.floorZone.gridSize) + this.floorZone.gridOffsetY)],
    [((Math.round(x3 / this.floorZone.gridSize) * this.floorZone.gridSize) + this.floorZone.gridOffsetX), ((Math.round(y3 / this.floorZone.gridSize) * this.floorZone.gridSize) + this.floorZone.gridOffsetY)],
    [((Math.round(x4 / this.floorZone.gridSize) * this.floorZone.gridSize) + this.floorZone.gridOffsetX), ((Math.round(y4 / this.floorZone.gridSize) * this.floorZone.gridSize) + this.floorZone.gridOffsetY)]
    ];
  },

  clickModule: function(x, y){

    if(this.inBoundingBox(x, y)){
	    $('StandInfo').setStyle('display', 'block');
	      $('StandInfo').setStyle('left', x+20+'px');
	      $('StandInfo').setStyle('top', y+20+'px');
	      $('StandInfoContent').empty();
	    $('StandInfoContent').adopt((new Element('h2')).appendText(this.name));
	    $('StandInfoButton').setStyle('display', 'block');
	    $('StandInfoCrossX').setStyle('display', 'block');
		 $('ClearSelection').setStyle('display', 'block');
	    return true;
    }
    return false;
  },

  inBoundingBox: function(x_pos, y_pos){
    return inBoundingBox(x_pos, y_pos, this.path);
  },

  getSuperficy: function(){

    var sum_superficy = 0;
    for(var k = 0; k < this.items.length; ++k){
      var item = floorMap.getItem(this.items[k]);
      if(item){
        if(Number(item.superficy) > 0){
          sum_superficy +=  Number(item.superficy);
        }
      }

    }

    return sum_superficy;
  },

  nearCount: function(path){
    var nearCount = 0;
    var hysteresis = 6;

    for(var i = 0; i < path.length; ++i)
    {
      if( this.inBoundingBox(path[i][0], path[i][1])
        || this.inBoundingBox(path[i][0]-hysteresis, path[i][1]-hysteresis)
        || this.inBoundingBox(path[i][0]-hysteresis, path[i][1]+hysteresis)
        || this.inBoundingBox(path[i][0]+hysteresis, path[i][1]-hysteresis)
        || this.inBoundingBox(path[i][0]+hysteresis, path[i][1]+hysteresis)
        || this.inBoundingBox(path[i][0]+hysteresis, path[i][1])
        || this.inBoundingBox(path[i][0]-hysteresis, path[i][1])
        || this.inBoundingBox(path[i][0], path[i][1]+hysteresis)
        || this.inBoundingBox(path[i][0], path[i][1]-hysteresis)
        )
        {
        ++nearCount;
        /** speed up if we already find two points inside */
        if(nearCount > 1){
          return nearCount;
        }
      }
    }
    return nearCount;
  },

  findLeftTop: function(){
    // search leftmost coordinate
    var left = this.path[0][0];
    for (var i = 0; i < this.path.length; i++){
      if(this.path[i][0] < left){
        left = this.path[i][0];
      }
    }

    // search topmost coordinate
    var top = this.path[0][1];
    for (var i = 0; i < this.path.length; i++){
      if(this.path[i][1] < top){
        top = this.path[i][1];
      }
    }

    this.leftmost = left;
    this.topmost = top;

  },

  findRightBottom: function(){
    // search rightmost coordinate
    var right = this.path[0][0];
    for (var i = 0; i < this.path.length; i++){
      if(this.path[i][0] > right){
        right = this.path[i][0];
      }
    }

    // search bottommost coordinate
    var bottom = this.path[0][1];
    for (var i = 0; i < this.path.length; i++){
      if(this.path[i][1] > bottom){
        bottom = this.path[i][1];
      }
    }

    this.rightmost = right;
    this.bottommost = bottom;


  },

  redrawModule: function(ctx){

    if(ctx==null){
      ctx = this.floorZone.getCTX();
    }


    this.findLeftTop();

    ctx.beginPath();
    ctx.moveTo(this.path[0][0]*this.floorMap.ratio, this.path[0][1]*this.floorMap.ratio);
    ctx.lineTo(this.path[1][0]*this.floorMap.ratio, this.path[1][1]*this.floorMap.ratio);
    ctx.lineTo(this.path[2][0]*this.floorMap.ratio, this.path[2][1]*this.floorMap.ratio);
    ctx.lineTo(this.path[3][0]*this.floorMap.ratio, this.path[3][1]*this.floorMap.ratio);
    ctx.closePath();
    //ctx.lineWidth = Math.max(1, this.floorMap.ratio);
    var show = floorMap.getShow(this.show_id);
    if(!this.bookable && !this.booked){
      if(floorMap.addInfoDisplay && (this.show_id == 0 || (this.floorMap.shows.length == 1 && this.floorMap.shows[0].id == this.show_id))){
        // Create gradient
        this.findRightBottom();
        var lingrad = ctx.createLinearGradient((this.leftmost*this.floorMap.ratio),(this.topmost*this.floorMap.ratio),(this.leftmost*this.floorMap.ratio),(this.bottommost*this.floorMap.ratio));
        lingrad.addColorStop(0.5, 'rgba('+this.floorMap.bookable_background_color+')');
        lingrad.addColorStop(0.5, 'rgba('+this.floorMap.unbookable_background_color+')');
        ctx.fillStyle = lingrad;
        ctx.strokeStyle = 'rgb('+this.floorMap.unbookable_border_color+')';
      } else {
        ctx.strokeStyle = 'rgb('+this.floorMap.unbookable_border_color+')';
        ctx.fillStyle = 'rgba('+this.floorMap.unbookable_background_color+')';

        /* override eF blue */
		 ctx.fillStyle = 'rgba(1,56,110,0.5)';
		 ctx.strokeStyle = 'rgb(255,255,255)';
        ctx.fillStyle = 'rgba(1,56,110,1)';
      }

    }
    else if(this.booked) {
      ctx.strokeStyle = "rgb(0, 0, 0)";
		ctx.strokeStyle = 'rgb(255,255,255)';
      ctx.fillStyle = "rgba(200, 0, 0, 1)";
    // stay with fixed red color for selected, to avoid problems with colors
    // ctx.strokeStyle = 'rgb('+floorMap.unbookable_border_color+')';
    // ctx.fillStyle = 'rgba('+floorMap.unbookable_background_color+')';
    }
    else if(this.bookable && this.items.filter(function(item){
      return item != floorMap.addOpenSideId;
    }).length == 0) {
      /*
      ctx.strokeStyle = 'rgb(0, 0, 0)';
			ctx.strokeStyle = 'rgb(255,255,255)';
      ctx.fillStyle = 'rgba(153,202,3,1)';
      */
      ctx.strokeStyle = 'rgb(255,255,255)';
      ctx.fillStyle = 'rgba(1,56,110,0.5)';
      ctx.fillStyle = 'rgba(1,56,110,1)';
    }
    else if(this.bookable) {
      if(show != null) {
        ctx.strokeStyle = 'rgb('+show.bookable_border_color+')';
        ctx.fillStyle = 'rgba('+show.bookable_background_color+')';
		 ctx.strokeStyle = 'rgb(255,255,255)';
        ctx.fillStyle = 'rgba(1,56,110,0.5)';
        ctx.fillStyle = 'rgba(1,56,110,1)';

      }
      else {
        ctx.strokeStyle = 'rgb('+this.floorMap.bookable_border_color+')';
        ctx.fillStyle = 'rgba('+this.floorMap.bookable_background_color+')';
		 ctx.strokeStyle = 'rgb(255,255,255)';
      ctx.fillStyle = 'rgba(1,56,110,0.5)';
      ctx.fillStyle = 'rgba(1,56,110,1)';
      }
    }
    else {
      ctx.strokeStyle = 'rgb('+this.floorMap.unbookable_border_color+')';
      ctx.fillStyle = 'rgba('+this.floorMap.unbookable_background_color+')';
      /* override eF blue */
				 ctx.strokeStyle = 'rgb(255,255,255)';
      ctx.fillStyle = 'rgba(1,56,110,0.5)';
      ctx.fillStyle = 'rgba(1,56,110,1)';
    }
    ctx.stroke();
    ctx.fill();

    ctx.fillStyle = 'rgba(255, 255, 255, 1)';


		tempFontSize = parseInt(this.floorMap.ratio*(this.floorMap.openAreaWidth/250)).limit(1, 13);

   	ctx.font = 'normal normal '+(tempFontSize)+'px helvetica, sans-serif';
		ctx.textBaseline = 'top';
		ctx.fillText(this.name, (this.leftmost*this.floorMap.ratio)+2, (this.topmost*this.floorMap.ratio)+2);
  /*
    if($('module_'+this.id)){

      width = ((this.path[1][0]-this.path[0][0])*this.floorMap.ratio);
      height = ((this.path[2][1]-this.path[0][1])*this.floorMap.ratio);
      $('module_'+this.id).setStyle('top', (this.topmost*this.floorMap.ratio)+2+'px');
      $('module_'+this.id).setStyle('left', (this.leftmost*this.floorMap.ratio)+2+'px');
      // $('module_'+this.id).setStyle('width', width+'px');
      // $('module_'+this.id).setStyle('height', height+'px');
      moduleDiv = $('module_'+this.id);
      moduleDiv.empty();

      var moduleName  = new Element('div', {
        'class': 'moduleName'
      });
      moduleSuperficy = this.getSuperficy();
      moduleName.appendText(this.name+' - '+moduleSuperficy+'sqm');
      // ep: commented so booking can work!
      // var rgb = ctx.fillStyle.match(/\d{1,3}/g);
      var rgb = [1000,200,300];

      colorTotal = rgb[0]+rgb[1]+rgb[2];
      myColor = '#FFFFFF';
      if((colorTotal/3) > 128){
        myColor = '#000000';
      }
      moduleName.inject(moduleDiv);
      $('module_'+this.id).getElement('.moduleName').setStyle('color', myColor);


      var maxFS = 11;
      var minFS = 1;
      var size = [];
      do{
        var newIdx = 0.5*(maxFS+minFS);
        // $('standName_'+this.id).setStyle('font-size', newIdx+'px');
        if(newIdx>0) $('module_'+this.id).setStyle('font-size', newIdx+'px');
        size = $('module_'+this.id).getSize();
        if((size.x > width || size.y > height)){
          maxFS = newIdx;
        }
        else {
          minFS = newIdx;
        }
      }while( (maxFS-minFS) >= 1);

      if((size.x > width || size.y > height) ){
        // $('standName_'+this.id).setStyle('font-size', minFS+'px');
        if(minFS>0) $('module_'+this.id).setStyle('font-size', minFS+'px');
      // size = $('module_'+this.id).getSize();
      }
    }
   */

  }
});


/*******************************************************************************
 * Class Stand
 ******************************************************************************/
var Stand = new Class({
  initialize: function(floorMap, show, id, name, logo, left, top, width, height, path, floorZone, remark, standNumber){
    this.floorMap = floorMap;
    this.show = show;
    this.id = id;
    this.name = name;
    this.logo = logo;
    this.left = left;
    this.top = top;
    this.width = width;
    this.height = height;
    // this.modules = modules;
    this.floorZone = floorZone;
    this.remark = remark;
    this.lastClick = 0;
    this.lastDrag = 0;
    this.path = path;
    this.highlight = false;
    this.coExhibitors = new Array;
     this.standNumber = standNumber;
    if(this.path.length > 0){
      for(var i=0; i < this.path.length; ++i) {
        this.path[i][0] = ((Math.round(this.path[i][0] / this.floorZone.gridSize) * this.floorZone.gridSize) + this.floorZone.gridOffsetX);
        this.path[i][1] = ((Math.round(this.path[i][1] / this.floorZone.gridSize) * this.floorZone.gridSize) + this.floorZone.gridOffsetX);
      }
    }
  /*
   * if(modules) { var toAdd = []; var after = []; toAdd.combine(modules); var
   * bb = [modules[0].path]; this.path = modules[0].path; this.floorZone =
   * modules[0].floorZone;
   *
   * while(toAdd.length > 0) { var newMod = toAdd.pop(); var temp =
   * newMod.mergePath(this.path, bb); if(temp.length == 0) {
   * after.push(newMod); } else { this.path = temp; bb.push(newMod.path); }
   *
   * if(toAdd.length == 0) { toAdd = after; after = []; } }
   * this.path[this.path.length] = this.path[0]; }
   */


  },

  addCoExhibitor: function(id,name,logo){
    this.coExhibitors.push(new CoExhibitor(id,name,logo, this));
  },


  inBoundingBox: function(x_pos, y_pos){
    var pLength = this.path.length;
    var firstVal = 0;

    for(i=0; i < pLength; ++i)
    {
      var nI = mod((i+1), pLength);
      var Ax = this.path[i][0];
      var Ay = this.path[i][1];
      var Bx = this.path[nI][0];
      var By = this.path[nI][1];
      var currentVal = ((y_pos - Ay) * (Bx - Ax) - (x_pos - Ax) * (By - Ay));
      if(firstVal == 0)
        firstVal = currentVal;
      else if((firstVal*currentVal) < 0)
      {
        return false;
      }
    }
    return true;
  },


  hoverStand: function(x, y, cLeft, cTop){
    if(this.inBoundingBox((x-this.floorZone.left), (y-this.floorZone.top))){

      $('StandInfoContent').empty();
      var standIsOption = false;
      var tempName = this.name;
      if(this.name.join(' ').trim() == ''){
        tempName = window.tx_ef_pifloormap_jslabels.label_floormap__stand_option;
		  	$('StandInfoContent').adopt((new Element('h2')).appendText(tempName));
		  	standIsOption = true;
      } else {
			tempName = this.name.join(' ').trim();

	      if ($('piexhlist-container') && $('piexhlist-container').getElement('.proxy-' + this.id)) {
	          refEl = $('StandInfoContent');
	          refEl.set('html', $('piexhlist-container').getElement('.proxy-' + this.id).get('html'));
	          var theid = refEl.getElement('.cart-ticker').getProperty("forlabel");
	          refEl.getElement('.cart-ticker').setProperty("forlabel",theid+"fp");
	          refEl.getElement('.cart-ticker-label').setProperty("id",theid+"fp");
	          refEl.getElement('.cart-ticker').removeEvents('click');
	          easyFairs.cart.updateTicker(refEl.getElement('.cart-ticker'));
	          easyFairs.cart.enableTicker(refEl.getElement('.cart-ticker'));
				 easyFairs.cart.enableTickerLabel(refEl.getElement('.cart-ticker'));

	      }
	      else if(!standIsOption) {
	        $('StandInfoContent').adopt((new Element('h2')).appendText(tempName));
	        $('StandInfoContent').adopt((new Element('div')).appendText(window.tx_ef_pifloormap_jslabels.label_catalog__stand + ' ' + this.standNumber));
	        if(this.logo){
	          $('StandInfoContent').adopt((new Element('img', {
	            'style': 'max-width: 250px;',
	            'class': 'standLogo',
	            'src': this.logo
	            })));
	        }
	      }

				if(!standIsOption) {
				 	$('StandInfoContent').adopt(this.printCoExhibitorList(false));
				}




      }

      $('StandInfo').setStyle('left', cLeft+20+'px');
      $('StandInfo').setStyle('top', cTop+20+'px');
		$('StandInfo').setStyle('display', 'block');



      $('StandInfoButton').setStyle('display', 'none');
      $('StandInfoCrossX').setStyle('display', 'none');

      return true;
    }
    return false;
  },


  clickStand: function(x, y, cLeft, cTop){
  //	(x-this.floorZone.left)
    if(this.inBoundingBox((x-this.floorZone.left), (y-this.floorZone.top))){
      var tempName = this.name;


		floorMap.lock(false);
     // var cLeft = x-this.floorZone.left;
      //var cTop = y-this.floorZone.top;
		$('StandInfo').setStyle('left', cLeft+20+'px');
      $('StandInfo').setStyle('top', cTop+20+'px');
      $('StandInfoContent').empty();

      if(this.name.join(' ').trim() == ''){
        tempName = window.tx_ef_pifloormap_jslabels.label_floormap__stand_option;
		  $('StandInfoContent').adopt((new Element('h2')).appendText(tempName));
			$('OrderModule').setStyle('display', 'none');
      } else {


        tempName = this.name.join(' ').trim();


	      if($('piexhlist-container') && $('piexhlist-container').getElement('.proxy-'+this.id)){
	          refEl = $('StandInfoContent');
	          refEl.set('html', $('piexhlist-container').getElement('.proxy-' + this.id).get('html'));
	          var theid = refEl.getElement('.cart-ticker').getProperty("forlabel");
				 refEl.getElements('a[href!=#]').each(function(el){
				 	el.removeEvents();
					el.addEvent('click',function(event){
						window.location = this.getProperty('href');
					});
				 });
	          refEl.getElement('.cart-ticker').setProperty("forlabel",theid+"fp");
	          refEl.getElement('.cart-ticker-label').setProperty("id",theid+"fp");
	          refEl.getElement('.cart-ticker').removeEvents('click');
	          easyFairs.cart.updateTicker(refEl.getElement('.cart-ticker'));
	          easyFairs.cart.enableTicker(refEl.getElement('.cart-ticker'));
				 easyFairs.cart.enableTickerLabel(refEl.getElement('.cart-ticker'));
				 refEl.getElements('p.in_taxo a').each(function(inTaxoEl){
		            var rel = inTaxoEl.getProperty('rel');
		            inTaxoEl.addEvent('click',function(e){
		                e.stop();
		                window.piexhlist_containerEl.getElements('ul.efTabs li[rel=2]').fireEvent('click');
		                window.piexhlist_containerEl.getElements('li.group-taxo[rel!='+rel+']').each(function(groupEl){
		                    groupEl.retrieve('accord').hide();
		                    groupEl.getElement('h3').removeClass('open');
		                });
		                window.piexhlist_containerEl.getElement('li.group-taxo[rel='+rel+']').retrieve('accord').slideIn();
		                new Fx.Scroll(window).toElement(window.piexhlist_containerEl.getElement('li.group-taxo[rel='+rel+']'));
		            });
		        });

	          $('OrderModule').setStyle('display', 'none');
	      } else {
	        $('StandInfoContent').adopt((new Element('h2')).appendText(tempName));
	        $('StandInfoContent').adopt((new Element('div')).appendText(window.tx_ef_pifloormap_jslabels.label_catalog__stand + ' ' + this.standNumber));
	        if(this.logo){
	          $('StandInfoContent').adopt((new Element('img', {
	            'style': 'max-width: 250px;',
	            'class': 'standLogo',
	            'src': this.logo
	            })));
	        }
	        $('OrderModule').setStyle('display', 'block');
	      }

	  $('StandInfoContent').adopt(this.printCoExhibitorList(true));


      }



  	 $('StandInfo').setStyle('display', 'block');
	 $('ClearSelection').setStyle('display', 'none');
	 $('OrderModule').setStyle('display', 'none');
    $('StandInfoButton').setStyle('display', 'block');
    $('StandInfoCrossX').setStyle('display', 'block');
/*
    $('OrderModule').removeEvents();
    if (this.floorMap.standSelection.contains(this.id)) {
      $('OrderModule').set('text', window.tx_ef_pifloormap_jslabels.label_floormap__popup_deselect_stand);
    } else {
      $('OrderModule').set('text', window.tx_ef_pifloormap_jslabels.label_floormap__popup_select_stand);
    }
    $('OrderModule').addEvent('click', function(e){
      if(this.floorMap.standSelection.contains(this.id)){
        this.floorMap.removeStandsFromSelection([this]);
      } else {
        this.floorMap.addStandsToSelection([this]);
      }

      this.floorMap.unlock();
      $('StandInfo').setStyle('display', 'none');

    }.bindWithEvent(this));

    // (re)assign event for button
    $('ClearSelection').removeEvents();
      $('ClearSelection').addEvent('click', function(e){
        e.stop();
        this.floorMap.standSelection.empty();
      this.floorMap.redraw();
      this.floorMap.unlock();
      $('StandInfo').setStyle('display', 'none');
      }.bindWithEvent(this));
*/
      return true;
    }
    return false;
  },


  printCoExhibitorList: function(withCartTicker){
      var coexhList = new Element('div', {'class': 'coexhList', 'id': 'coexhList-'+this.id});
      this.coExhibitors.each(function(coexh, index){
        var coexhLine = new Element('div', {'class': 'coexhline', 'id': 'coexhline-'+coexh.id});
        if(withCartTicker){
          coexhLine.adopt(new Element('div',{
            'class': 'cart-ticker',
            'cart': 'this-stand-'+coexh.id,
            'style': 'float: left; margin-right: 5px;'
          }));
        }

        coexhLine.adopt(new Element('h4', {
          'text': coexh.name,
          'style': 'float: left;'
          }));

        if (withCartTicker) {
           easyFairs.cart.updateTicker(coexhLine.getElement('.cart-ticker'));
           easyFairs.cart.enableTicker(coexhLine.getElement('.cart-ticker'));
        }
        coexhList.adopt(coexhLine);
      }, this);
      return coexhList;
  },


  redrawStand: function(ctx){

    if(anchoredElem && anchoredElem == this)
    {
      this.placeAnchors();
    }

    var top = Math.floor(this.top*this.floorMap.ratio);
    var left = Math.floor(this.left*this.floorMap.ratio);
    var width = Math.floor(this.width*this.floorMap.ratio);
    var height = Math.floor(this.height*this.floorMap.ratio);
     /*
    if($('stand_'+this.id)){

      $('stand_'+this.id).setStyle('top', top+'px');
      $('stand_'+this.id).setStyle('left', left+'px');
      $('stand_'+this.id).setStyle('width',Math.abs(width)+'px');
      $('stand_'+this.id).setStyle('height', Math.abs(height)+'px');
      $('stand_'+this.id).setStyle('overflow', 'hidden');


       * if($('standImage_'+this.id) &&
       * $('standImage_'+this.id).getProperty('width')) { var imgW =
       * $('standImage_'+this.id).getProperty('width').toInt(); var imgH =
       * $('standImage_'+this.id).getProperty('height').toInt();
       *
       * if( (imgW/imgH) > ((width*0.9)/(height*0.7))) {
       * $('standImage_'+this.id).setStyle('width',(width*0.9)+'px');
       * $('standImage_'+this.id).setStyle('height',
       * ((width*0.9)*(imgH/imgW))+'px'); } else {
       * $('standImage_'+this.id).setStyle('width',((height*0.7)*(imgW/imgH))+'px');
       * $('standImage_'+this.id).setStyle('height', (height*0.7)+'px'); } }


      var myColor = '#FFFFFF';


      $('stand_'+this.id).getElement('.standName').setStyle('color', myColor);

      if(this.remark){
        var sizeBase = 'remark_';
        $('stand_'+this.id).getElement('.remarkDiv').setStyle('color', myColor);
        height  = height - 11;
      } else {
        var sizeBase = 'standName_';
      }
      sizeBase = 'standName_';

      // if(this.floorMap.ratioChanged){
      var maxFS = 14;
      var minFS = 1;
      var size = [];

      do{
        var newIdx = 0.5*(maxFS+minFS);
        // $('stand_'+this.id).setStyle('font-size', newIdx+'px');
        if(newIdx>0) $('stand_'+this.id).getElement('.standName').setStyle('font-size', newIdx+'px');
        size = $(sizeBase+this.id).getSize();
        if((size.x > width || size.y > height)){
          maxFS = newIdx;
        }
        else {
          minFS = newIdx;
        }
      }while( (maxFS-minFS) >= 1);
      size = $(sizeBase+this.id).getSize();

      if((size.x > width || size.y > height) ){
        // $('standName_'+this.id).setStyle('font-size', minFS+'px');
        if(minFS>0) $('stand_'+this.id).getElement('.standName').setStyle('font-size', minFS+'px');
      // size = $(sizeBase+this.id).getSize();
      }


      // $('standName_'+this.id).setStyle('font-size', (height*0.3)+'px');

      } else { size = $(sizeBase+this.id).getSize(); }

      var offset = 0;
      if(((height-size.y)/2) > 10){
        offset = 11;
      }
      $('standName_'+this.id).setStyle('top', (((height-size.y)/2)+offset)+'px');
      $('standName_'+this.id).setStyle('width', (width)+'px');
      $('standName_'+this.id).setStyle('height', Math.abs(height)+'px');
    // $('standName_'+this.id).setStyle('left', ((width-size.x)/2)+'px');


    // console.log(;
    // console.log($('standName_'+this.id).getSize());

    }

*/
    if(ctx != null) {
      ctx.beginPath();
      if(this.path.length > 0) {
        ctx.moveTo(this.path[0][0]*this.floorMap.ratio, this.path[0][1]*this.floorMap.ratio);

        for(var i=1; i < this.path.length; ++i) {
          ctx.lineTo(this.path[i][0]*this.floorMap.ratio, this.path[i][1]*this.floorMap.ratio);
        }
        ctx.closePath();
        ctx.strokeStyle = 'rgb('+floorMap.unbookable_border_color+')';
        ctx.fillStyle = 'rgba('+floorMap.unbookable_background_color+')';
        /* override eF blue */
		  ctx.strokeStyle = 'rgb(255,255,255)';
        ctx.fillStyle = 'rgba(1,56,110,1)';
        if(this.floorMap.standSelection.contains(this.id) || this.highlight){
          ctx.fillStyle = this.floorMap.highlightStandColor;
        }
        this.coExhibitors.each(function(item, index){
          if(item.mainStand.floorMap.standSelection.contains(Number(item.id))){
            ctx.fillStyle = item.mainStand.floorMap.highlightStandColor;
          }
        });
        ctx.stroke();
        ctx.fill();
      }
      ctx.fillStyle = 'rgba(255,255,255,1)';
		if(this.floorMap.standSelection.contains(this.id) || this.highlight){
          ctx.fillStyle = 'rgba(0,0,0,1)';
        }
        this.coExhibitors.each(function(item, index){
          if(item.mainStand.floorMap.standSelection.contains(Number(item.id))){
            ctx.fillStyle = 'rgba(0,0,0,1)';
          }
        });
        tempFontSize = parseInt(this.floorMap.ratio*(this.floorMap.openAreaWidth/175)).limit(1, 15);
		 ctx.font = 'normal normal '+tempFontSize+'px helvetica, sans-serif';
       ctx.textBaseline = 'top';
	   if(!this.floorMap.disableStandNames){
			/*
			var length = 0;
			var longest = 0;
			for(i = 0; i < this.name.length; i++){
				if(this.name[i].length > length){
					length = this.name[i].length;
					longest = i;
				}
		   }
	      var textMeasure = ctx.measureText(this.name[longest]);
			var j = 0;
	      while(textMeasure.width > (this.width*this.floorMap.ratio) && tempFontSize > 0){
			  j++;
	        tempFontSize = (this.floorMap.ratio*(8-(j/3)));
			  ctx.font = 'normal normal '+tempFontSize+'px helvetica, sans-serif';
			  textMeasure = ctx.measureText(this.name[longest]);
	      }
	      */
			if(tempFontSize > 0){
		      ctx.font = 'normal normal '+tempFontSize+'px helvetica, sans-serif';
		      for(i = 0; i < this.name.length; i++){
				  	ctx.fillText(this.name[i], left, top+(i*tempFontSize), (this.width*this.floorMap.ratio));
		      }
			}
		}
    }




  }
});


/*******************************************************************************
 * Class Show
 ******************************************************************************/
var Show = new Class({
  initialize: function(floorMap, id, name, bookable_background_color, bookable_border_color){
    this.floorMap = floorMap;
    this.id = id;
    this.bookable_background_color = bookable_background_color;
    this.bookable_border_color = bookable_border_color;
    this.name = name;
  }
});


/*******************************************************************************
 * Class Item
 ******************************************************************************/
var Item = new Class({
  initialize: function(id, name, superficy, prices, priceForOther, showID){
    this.id = id;
    this.name = name;
    this.superficy = superficy;
    this.prices = prices;
    this.priceForOther = priceForOther;
    this.show_id = showID;
  }
});


/*******************************************************************************
 * Class CoExhibitor
 ******************************************************************************/
var CoExhibitor = new Class({
  initialize: function(id, name, logo, mainStand){
    this.id = id;
    this.name = name;
    this.logo = logo;
    this.mainStand = mainStand;
  }
});



/*******************************************************************************
 * Others functions
 ******************************************************************************/
function getRealX(event){
  if($('FloorMap').getStyle('overflow') == 'hidden'){
    return ((event.client.x+getScrollLeft()-findPosX($('FloorMap'))-$('OpenArea').getStyle('left').toInt())/floorMap.ratio).round();
  }
  return ((event.client.x+getScrollLeft()-findPosX($('FloorMap'))+$('FloorMap').scrollLeft)/floorMap.ratio).round();
}
function getRealY(event){
  if($('FloorMap').getStyle('overflow') == 'hidden'){
    return ((event.client.y+getScrollTop()-findPosY($('FloorMap'))-$('OpenArea').getStyle('top').toInt())/floorMap.ratio).round();
  }
  return ((event.client.y+getScrollTop()-findPosY($('FloorMap'))+$('FloorMap').scrollTop)/floorMap.ratio).round();
}


function mod(X, Y) {
    var t;
    t = X % Y;
    return t < 0 ? t + Y : t;
}

function inBoundingBox(x_pos, y_pos, path){
  var pLength = path.length;
  var firstVal = 0;

  for(i=0; i < pLength; ++i)
  {
    var nI = mod((i+1), pLength);
    var Ax = path[i][0];
    var Ay = path[i][1];
    var Bx = path[nI][0];
    var By = path[nI][1];
    var currentVal = ((y_pos - Ay) * (Bx - Ax) - (x_pos - Ax) * (By - Ay));
    if(firstVal == 0)
      firstVal = currentVal;
    else if((firstVal*currentVal) < 0)
    {
      return false
    }
  }
  return true;
}

function closestPoint(point, path){
  var min = distanceBetween(point, path[0]);
  var minIdx = 0;
  for(var i=1; i < path.length; ++i)
  {
    if( distanceBetween(point, path[i]) < min )
    {
      min = distanceBetween(point, path[i]);
      minIdx = i;
    }
  }
  return minIdx;
}


function distanceBetween(A, B) {
  var w = A[0]-B[0];
  var h = A[1]-B[1];
  return Math.sqrt(w*w+h*h);
}


function findPosX(obj)
  {
    var curleft = 0;
    if(obj.offsetParent)
  {
        while(1)
        {
          curleft += obj.offsetLeft;
          if(!obj.offsetParent)
            break;
          obj = obj.offsetParent;
        }
  }
    else if(obj.x)
  {
        curleft += obj.x;
  }
    return curleft;
  }

  function findPosY(obj)
  {
    var curtop = 0;
    if(obj.offsetParent)
  {
        while(1)
        {
          curtop += obj.offsetTop;
          if(!obj.offsetParent)
            break;
          obj = obj.offsetParent;
        }
  }
    else if(obj.y)
  {
        curtop += obj.y;
  }
    return curtop;
  }

function sortNumber(a,b)
{
  return a - b;
}

var floorMapHover  = function(event){
    var realX = getRealX(event)+floorMap.openAreaLeft;
    var cLeft = (event.client.x+getScrollLeft()-findPosX($('FloorMap'))).round();

    var realY = getRealY(event)+floorMap.openAreaTop;
    var cTop = (event.client.y+getScrollTop()-findPosY($('FloorMap'))).round();

   window.ef_hovered = false;
   if(floorMap.standsHover){
		for (var i = 0; i < floorMap.stands.length; i++) {
			if(floorMap.stands[i].hoverStand(realX, realY, cLeft, cTop)){
            window.ef_hovered = true;
       		break;
        }
		}
   }

  if(floorMap.modulesHover && window.ef_hovered != true){
  		for(var i=0;i < floorMap.floorZones.length;i++){
			if(floorMap.floorZones[i].hoverFloorZone(realX, realY, cLeft, cTop)){
				window.ef_hovered = true;
				break;
			}
		}
  }
  $('FloorMap').setStyle('cursor', 'pointer');
    if(!window.ef_hovered){
      $('StandInfo').setStyle('display', 'none');
		$('StandInfoContent').empty();
		/*
      $('StandInfoButton').setStyle('display', 'block');
      $('StandInfoCrossX').setStyle('display', 'block');
      $('StandInfo').setStyle('left', '20%');
      $('StandInfo').setStyle('top', '20%');
      */
    	$('FloorMap').setStyle('cursor', 'auto');
    }

}
