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




/*************************************************************************************************************************************************
*  Class FloorZone
**************************************************************************************************************************************************/
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;

    //alert('The floormap is curently under maintenance. Some actions can be disabled for debug purpose.');
    //console.log(this.ratio);
    },

    fillForm: function(form){
    var boothCount = 0;
    for(var i = 0; i < this.floorZones.length; ++i) {
      for(var j = 0; j < this.floorZones[i].modules.length; ++j) {
        if(this.floorZones[i].modules[j].booked){
//					console.log('Add booth '+this.floorZones[i].modules[j].id+' to a new stand');
          var newField = new Element('input', {type: 'hidden', name: 'booths['+boothCount+']', value: this.floorZones[i].modules[j].id});
          newField.inject(form);
          ++boothCount;
        }
      }
    }
  },

    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();
      });

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

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

      $('OrderModule').addEvent('click', function(e){

        e.stop();
        $('StandInfo').setStyle('display', 'none');
        floorMap.lock(true);

        if(currentModule != null)
        {
          if(floorMap.canBeBookable(currentModule))
          {

            //in booking, number of module can be limited.
            if(window.piBookVar_maxModule){
              if(floorMap.newBooking.length>=window.piBookVar_maxModule){
                alert(window.piBookVar_maxModule+' modules max!');
                floorMap.unlock();
                return false;
              }
            }

            currentModule.booked = true;
            floorMap.newBooking.push(currentModule);
            floorMap.fireEvent('moduleUpdate');
            //alert(currentModule.id);
            currentModule.floorZone.redrawFloorZone();
            currentModule.floorZone.redrawFloorZone();
            floorMap.unlock();
          }
          else
          {
            if(confirm(window.tx_ef_pifloormap_jslabels.label_booking__on_uncontiguous_module_click))
            {
              for(var i=0; i < floorMap.floorZones.length; ++i){
                for(var j=0; j < floorMap.floorZones[i].modules.length; ++j){
                  floorMap.floorZones[i].modules[j].booked = false;
                }
              }

              floorMap.newBooking = [currentModule];
              floorMap.fireEvent('moduleUpdate',[floorMap.newBooking]);
              currentModule.booked = true;
              floorMap.draw();
            }
            else {
              floorMap.unlock();
            }
          }
        }
      });

      $('ClearSelection').addEvent('click', function(e){
        e.stop();
        $('StandInfo').setStyle('display', 'none');
        floorMap.newBooking.empty();
        floorMap.fireEvent('moduleUpdate',[floorMap.newBooking]);
        floorMap.lock(true);
        if(currentModule != null)
        {
          currentModule.floorZone.modules.each(function(item, index){
            item.booked = false;
          });
          currentModule.floorZone.redrawFloorZone();
          floorMap.draw();
        }
        //floorMap.unlock();
      });/**/




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



      $('OpenArea').makeDraggable({
        onDrag: function() {
          //console.log(floorMap.openAreaWidth);
          //console.log($('FloorMap').getStyle('width').toInt()-$('OpenArea').getStyle('left').toInt());
          //console.log(floorMap.openAreaWidth*floorMap.ratio);
          floorMap.checkOpenArea();
        }
      });

      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();
            //myDragSM.fireEvent('drag', $('ModuleMover'));
            //console.log("pressed"+event);
            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);

      /*$('zoomin').addEvent('click', function(e){
        e.stop();
        floorMap.zoomIn($('FloorMap').getStyle('width').toInt()/2, $('FloorMap').getStyle('height').toInt()/2);
      });

      $('zoomout').addEvent('click', function(e){
        e.stop();
        floorMap.zoomOut();
      });/**/




      //floormap events triggers
      /*$('FloorMap').addEvent('mousewheel', function(event){
        event.stop();
        //var event = new Event(e);

        // Mousewheel UP
        if (event.wheel > 0) {
          floorMap.zoomIn(event.client.x-findPosX($('FloorMap')), event.client.y-findPosY($('FloorMap')));
        }
        // Mousewheel DOWN
        else if (event.wheel < 0) {
          floorMap.zoomOut();
        }
      });/**/



      $('FloorMap').addEvent('click', function(event){
        event.stop();
        floorMap.click(getRealX(event), getRealY(event));
      });/**/

    }


    this.ratioChanged = false;
  },

    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'); //cache si pas déjà cacher
    }
    },

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

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

      if($('OpenArea').getStyle('height').toInt() < $('FloorMap').getStyle('height').toInt()){
        //console.log('centre verticalement');
        $('OpenArea').setStyle('top',(($('FloorMap').getStyle('height').toInt()-$('OpenArea').getStyle('height').toInt())/2).toInt()+'px');
      }
      else if($('OpenArea').getStyle('top').toInt() > offset){
        //console.log('trop bas');
        $('OpenArea').setStyle('top', offset+'px');
      }
      else if( ($('FloorMap').getStyle('height').toInt()-$('OpenArea').getStyle('top').toInt()) > ((floorMap.openAreaHeight*floorMap.ratio)+offset) ){
        //console.log('trop haut');
        $('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();
    }
  },

    unlock: function(){
    if(this.locked)
    {
      $('AjaxLoader').setStyle('display', 'none'); //cache si pas déjà cacher
      $('StandInfo').setStyle('display', 'none');  //cache si pas déjà cacher
      $('LockScreen').setStyle('background-color', 'transparent'); //est opaque initialement -> devient transparent
      $('LockScreen').setStyle('display', 'none');
      this.locked = false;
    }
  },

    click: function(x, y){
    if(!this.locked) {
      //console.log("("+x+","+y+")");
      var realX = x+this.openAreaLeft;
      var realY = y+this.openAreaTop;
    //alert("("+this.openAreaLeft+","+this.openAreaTop+")");
    //alert("("+this.ratio+")");

      this.floorZones.each(function(item, index){
        if(item.clickFloorZone(realX, realY))
          return;
      });
    }
    //treat click here for floormap (if it's needed)
    },


  //add an floorzone in the floorzone
    addFloorZone: function(id, name, image, width, height, top, left, tagname){
    var floorZone = new FloorZone(this, id, name, image, width, height, top, left, tagname);
    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;
    },

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

    }
});

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

    }
});

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

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

    if(currentFZ){
      currentFZ.stands.push(stand);

      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;
    }
});


FloorMap.implement({
    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
FloorMap.implement({
    draw: function(){
    this.ratioChanged = true;
    this.lock(true);

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

    //var result = $try(function(){
      if(this.resizer)
      {
        var tempFloorMap = this;
        $('FloorMapResizableAnchor').setStyle('display', 'block');
         $('FloorMapResizableAnchor').makeDraggable({
          onDrag: function() {
            tempFloorMap.height = this.element.getStyle('top').toInt()+this.element.getStyle('height').toInt()-$('FloorMap').getStyle('border-width').toInt();
            tempFloorMap.width = this.element.getStyle('left').toInt()+this.element.getStyle('width').toInt()-$('FloorMap').getStyle('border-width').toInt();

            if( tempFloorMap.height < tempFloorMap.minHeight)
            {
              tempFloorMap.height = tempFloorMap.minHeight;
            }
            if( tempFloorMap.width < tempFloorMap.minWidth)
            {
              tempFloorMap.width = tempFloorMap.minWidth;
            }
            this.ratioChanged = true;
            tempFloorMap.resize();
          }
        });
      }
      else
      {
        $('FloorMapResizableAnchor').setStyle('display', 'none');
      }
      this.ratioChanged = true;
      this.resize();

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

      (function(){

        var ctx = null;
        while(!ctx) {
          var el = document.createElement('canvas');
          if(Browser.Engine.trident)
            G_vmlCanvasManager.initElement(el);
          ctx = el.getContext('2d');
          if(!ctx && !confirm(window.tx_ef_pifloormap_jslabels.label_floormap__browser_do_not_support_canvas)){
            return;
          }
        }

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


        //opean 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(1000);//temporise le chargement des backgroound!!
    //});
    //if(	result ){
      /*}
    else
    {
      alert('The floor map manager is not compatible with this browser!!!');
    }/**/

  }
});


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



//redraw if something has changed
FloorMap.implement({
    resize: function(){
    $('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 if something has changed
FloorMap.implement({
    redraw: function(){

    this.floorZones.each(function(item, index){
      item.redrawFloorZone();
    })


    }
});


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

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

FloorMap.implement({
    canBeBookable: function(module){

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

    }
});



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



FloorMap.implement({
    zoom: function(newRatio){
      this.ratioChanged = true;
    if(!this.locked) {
      /*
      if(newRatio.toInt() >= 1){
        newRatio = newRatio.toInt();
      }
       */
      //newRatio = newRatio=='Infinity'?1:newRatio;
      //console.log('zoom:',newRatio);
      var factor = newRatio/this.ratio;
      //console.log(factor);
      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.scrollLeft = ((left * factor)  - (($('FloorMap').getStyle('width').toFloat()))).toInt();//+(($('FloorMap').getStyle('width').toInt()/2)-mousex);/**/
      }
      this.draw();
      this.ratioChanged = false;
    }
  }
});

FloorMap.implement({
    zoomIn: function(mousex, mousey){

  this.zoom(this.ratio*2);
  /*
    if(!this.locked) {
      //console.log('zoomIn');
      this.ratio *= 2;

      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 = 2*(top+mousey);
      var centerx = 2*(left+mousex);
      this.scrollTop = (centery-($('FloorMap').getStyle('height').toInt()/2)).toInt();
      this.scrollLeft = (centerx-($('FloorMap').getStyle('width').toInt()/2)).toInt();
      this.draw();

    }
  */
  }
});

FloorMap.implement({
    zoomOut: function(){
    //console.log('zoomOut');
    this.zoom(this.ratio/2);
  }
});




/*************************************************************************************************************************************************
*  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;

    }
});

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


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

    }
});


FloorZone.implement({
    clickFloorZone: function(x, y){
    //alert("("+x+","+y+")");
    if(this.inBoundingBox(x, y))
    {
      var relX = (x-this.left);
      var relY = (y-this.top);
        //alert("fz"+this.id);


      this.modules.each(function(item, index){
        if(item.clickModule(relX, relY))
          return true;
      });
      return true;
    }
    return false;
  }
});


FloorZone.implement({
    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);
  }
});




//add an floorzone in the floorzone
FloorZone.implement({
    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));
    }
  }
});

//add an floorzone in the floorzone
FloorZone.implement({
    redrawFloorZone: function(){

    var el = $(this.name+"_canvas");
    if(el)
    {
      if(Browser.Engine.trident)
        G_vmlCanvasManager.initElement(el);
      if(el.getContext) {
        var ctx = el.getContext('2d');
        CanvasTextFunctions.enable(ctx);

        if(ctx) {
          //console.log(this.width,this.floorMap.ratio,this.height,this.floorMap.ratio,'floormap:',this.floorMap);
          ctx.clearRect(0, 0, this.width*this.floorMap.ratio, this.height*this.floorMap.ratio);
          this.modules.each(function(item, index)
          {
            item.redrawModule(ctx);
          });
          this.stands.each(function(item, index){
            //alert(item);
            item.redrawStand(ctx);
          })
          return;
        }
      }
    }
    alert('This browser does\'t support canvas element!');
  },

  getCTX: function(){
    var el = $(this.name+"_canvas");
    if(el)
    {
      if(Browser.Engine.trident)
        G_vmlCanvasManager.initElement(el);
      if(el.getContext) {
        var ctx = el.getContext('2d');
        //CanvasTextFunctions.enable(ctx);

        if(ctx) {
          //ctx.clearRect(0, 0, this.width*this.floorMap.ratio, this.height*this.floorMap.ratio);
          return ctx;
        }
      }
    }
    alert('This browser does\'t support canvas element!');


  }
});

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

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

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

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

//add an floorzone in the floorzone
FloorZone.implement({
    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);
    module.items = module.items.erase(0);
    this.modules.push(module);
    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){
    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.path = [[x1, y1], [x2, y2], [x3, y3], [x4, y4]];
    }
});

Module.implement({
    clickModule: function(x, y){


    if(this.inBoundingBox(x, y) && this.bookable)// && this.stand_id == 0)
    {
      cu_symbol_left = '€';
      currency = 49;
      cu_symbol_right = '';/**/

      $try(function(){
        currency = piBookObj.currentCurrency.currency;
        cu_symbol_left = piBookObj.currentCurrency.cu_symbol_left;
        cu_symbol_right = piBookObj.currentCurrency.cu_symbol_right;
      });

      currentModule = this;
      var sum_superficy = 0;
      var sum_price = 0;
      var nextDate = 0;
      var sum_nextPrice = 0;
      var addOpenSide = 0;
      for(var k = 0; k < this.items.length; ++k){
        var item = floorMap.getItem(this.items[k]);
        if(Number(item.superficy) > 0){
          sum_superficy +=  Number(item.superficy);
        }
        else {
          addOpenSide += 1;
        }
        for(var l = 0; l < item.prices.length; ++l){
          if(item.prices[l].cid == currency){
            //sum_price += (item.prices[l].price/item.prices[l].cu_sub_divisor);
            sum_price += item.prices[l].price;
            //sum_nextPrice += (item.prices[l].next_web_price/item.prices[l].cu_sub_divisor);
            sum_nextPrice += item.prices[l].next_web_price;
            nextDate = item.prices[l].price_date;
            break;
          }
        }
      }

      var listing = (new Element('ul'))
        .adopt((new Element('li')).appendText(window.tx_ef_pifloormap_jslabels.label_floormap__surface+' : '+sum_superficy+' m²'))
        //one line .adopt((new Element('li')).appendText(window.tx_ef_pifloormap_jslabels.label_floormap__price+' : '+cu_symbol_left+sum_price.round(2)+cu_symbol_right + ' ' + window.tx_ef_pifloormap_jslabels.label_floormap__date_of_price_change+' '+nextDate))
        .adopt((new Element('li')).appendText(window.tx_ef_pifloormap_jslabels.label_floormap__price+' : '+cu_symbol_left+sum_price.round(2)+cu_symbol_right));
      if(nextDate!=0)
        listing.adopt((new Element('li')).appendText(window.tx_ef_pifloormap_jslabels.label_floormap__date_of_price_change+' '+nextDate))
      if(sum_nextPrice.round(2)!=sum_price.round(2))
        listing.adopt((new Element('li')).appendText(window.tx_ef_pifloormap_jslabels.label_floormap__next_price+' : '+cu_symbol_left+sum_nextPrice.round(2)+cu_symbol_right));

      if(addOpenSide == 1){
        listing.adopt((new Element('li')).appendText(window.tx_ef_pifloormap_jslabels.label_booking__additional_openside));
      }
      else if (addOpenSide > 1){
        listing.adopt((new Element('li')).appendText(''+addOpenSide+' '+window.tx_ef_pifloormap_jslabels.label_booking__additional_opensides));
      }/**/

      floorMap.lock(false);
      $('StandInfo').setStyle('display', 'block');

      $('StandInfoContent').empty()
        .adopt((new Element('h2')).appendText(window.tx_ef_pifloormap_jslabels.label_floormap__module+' '+this.name))
        .adopt(listing);

      if(this.remark){
        $('StandInfoContent')
          .adopt(new Element('p').adopt((new Element('b')).appendText(window.tx_ef_pifloormap_jslabels.label_floormap__remarks)))
          .adopt((new Element('p')).appendText(this.remark));
      }

      if(this.booked) {
        $('OrderModule').setStyle('display', 'none');
        $('ClearSelection').setStyle('display', '');
      }
      else {
        $('OrderModule').setStyle('display', '');
        $('ClearSelection').setStyle('display', 'none');
      }
      /*$('StandInfo').empty();
      var orderLink = new Element('a', {
          'href': '#'+this.id,
          'events': {
              'click': function(){
            floorMap.unlock();
              },
          }
      });
      orderLink.appendText('Order this module');
      orderLink.inject($('StandInfo'));

      var closeLink = new Element('a', {
          'href': '#'+this.id,
          'events': {
              'click': function(){
            floorMap.unlock();
              },
          }
      });
      closeLink.appendText('Close');
      closeLink.inject($('StandInfo'));/**/


      return true;
    }
    return false;
  }
});




Module.implement({
    inBoundingBox: function(x_pos, y_pos){

    return inBoundingBox(x_pos, y_pos, this.path);

    }
});

Module.implement({
  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;
  }
});


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

    for(var i = 0; i < path.length; ++i)
    {
      if(    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))
      {
        ++nearCount;
      }
    }
    return nearCount;
    }
});

Module.implement({
  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;

  }


});


Module.implement({
    redrawModule: function(ctx){
    if(1==1)
      // this.stand_id == 0 || this.bookable == true
    {
      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.booked) {
        ctx.strokeStyle = "rgb(0, 0, 0)";
        ctx.fillStyle = "rgba(200, 0, 0, 0.7)";
        // 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.items.filter(function(item){return item != floorMap.addOpenSideId;}).length == 0) {
        ctx.strokeStyle = 'rgb(0, 0, 0)';
        ctx.fillStyle = 'rgba(255, 0, 0, 1)';
      }
      else if(this.bookable) {
        if(show != null) {
          ctx.strokeStyle = 'rgb('+show.bookable_border_color+')';
          ctx.fillStyle = 'rgba('+show.bookable_background_color+')';
        }
        else {
          ctx.strokeStyle = 'rgb('+this.floorMap.bookable_border_color+')';
          ctx.fillStyle = 'rgba('+this.floorMap.bookable_background_color+')';
        }
      }
      else {
        ctx.strokeStyle = 'rgb('+this.floorMap.unbookable_border_color+')';
        ctx.fillStyle = 'rgba('+this.floorMap.unbookable_background_color+')';
      }
      ctx.stroke();
      ctx.fill();
    }
    if(floorMap.addInfoDisplay && $('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');
      var rgb = ctx.fillStyle.match(/\d{1,3}/g);
      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();
      }
    }

   }
});





/*************************************************************************************************************************************************
*  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 tx_ef_pibook_floorMap = new Class({

  Implements: [Events, Options],

  options: {

  },

  initialize: function(options){
    var self = this;
    this.setOptions(options);

    var jsonRequest = new Request.HTML({
      url: 'index.php',
      update:$('ef_block-floorMap-main'),
      onComplete: function(rT){
        self.fireEvent('floorMapLoaded');
      }
    }).get({
      isAjax:1,
      id:106,
      show_id:window.easyFairs.showID,
      event_id:window.easyFairs.eventID,
      show_ll:window.easyFairs.show_ll,
      L:window.easyFairs.lid
    });
  },

  canContinue: function(){
    return (floorMap.newBooking.length > 0);
  },
  getModules: function(currencyId){
    var out = [];
    for(var i = 0; i < floorMap.floorZones.length; ++i) {
      for(var j = 0; j < floorMap.floorZones[i].modules.length; ++j) {
        if(floorMap.floorZones[i].modules[j].booked){
          var sum_superficy = 0;
          var sum_price = 0;
          for(var k = 0; k < floorMap.floorZones[i].modules[j].items.length; ++k){
            var item = floorMap.getItem(floorMap.floorZones[i].modules[j].items[k]);
            sum_superficy = sum_superficy + Number(item.superficy);
            for(var l = 0; l < item.prices.length; ++l){
              if(item.prices[l].cid == currencyId){
                //sum_price += (item.prices[l].price/item.prices[l].cu_sub_divisor);
                sum_price += (item.prices[l].price);
                break;
              }
            }
            //sum_price = sum_price + (floorMap.getItem(floorMap.floorZones[i].modules[j].items[k]).prices).toInt();
          }
          var temp = {id:floorMap.floorZones[i].modules[j].id, label:floorMap.floorZones[i].modules[j].name, superficy: sum_superficy, price: sum_price};
          out.push(temp);
        }
      }
    }
    return out;
  },

  getItems: function(){
    var out = [];
    for(var i = 0; i < floorMap.newBooking.length; ++i){
      //alert(''+floorMap.newBooking[i].items.length);
      var itemsCopy = $A(floorMap.newBooking[i].items);
      for(var j=0; j < itemsCopy.length; ++j){
        var item = floorMap.getItem(itemsCopy[j]);
        if(item){
          var ItemDef = {
              uid: item.id,
              desc: item.name,
              qty:1,
              price: item.priceForOther,
              removable:false
            };
          /*for(var k=0; k < item.prices.length; ++k){
            //ItemDef.price.setValue('c'+item.prices[k].cid, item.prices[k].price);
            //alert('salut');
          }/**/

/*						ItemDef.price.c49 = 500;
          ItemDef.price.c42 = 800;*/

          out.push(ItemDef);
        }
      }
    }
    return out;
/*		return [
      {
        uid: 1000,
        desc:'Open Side (A2)',
        qty:2,
        price:{c49:500, c42:800},
        removable:false
      },
      {
        uid: 1001,
        desc:'Stand A2 15m²',
        qty:1,
        price:{c49:5001, c42:8001},
        removable:false
      },
      {
        uid: 1003,
        desc:'Open Side (A3)',
        qty:1,
        price:{c49:5002, c42:8002},
        removable:false
      },
      {
        uid: 1002,
        desc:'Stand A3 15m²',
        qty:1,
        price:{c49:5003, c42:8003},
        removable:false
      }
    ];*/
  }
})


/*************************************************************************************************************************************************
*  Class Stand
**************************************************************************************************************************************************/
var Stand = new Class({
    initialize: function(floorMap, show, id, name, logo, left, top, width, height, path, floorZone, remark){
    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;
    /*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];
    }*/


    }
});

Stand.implement({
    redrawStand: function(ctx){

  /*var maxx=Math.max((this.modules[0].path[0][0]*this.floorMap.ratio)
          , (this.modules[0].path[1][0]*this.floorMap.ratio)
          , (this.modules[0].path[2][0]*this.floorMap.ratio)
          , (this.modules[0].path[3][0]*this.floorMap.ratio));
  var minx=Math.min((this.modules[0].path[0][0]*this.floorMap.ratio)
          , (this.modules[0].path[1][0]*this.floorMap.ratio)
          , (this.modules[0].path[2][0]*this.floorMap.ratio)
          , (this.modules[0].path[3][0]*this.floorMap.ratio));
  var maxy=Math.max((this.modules[0].path[0][1]*this.floorMap.ratio)
          , (this.modules[0].path[1][1]*this.floorMap.ratio)
          , (this.modules[0].path[2][1]*this.floorMap.ratio)
          , (this.modules[0].path[3][1]*this.floorMap.ratio));
  var miny=Math.min((this.modules[0].path[0][1]*this.floorMap.ratio)
          , (this.modules[0].path[1][1]*this.floorMap.ratio)
          , (this.modules[0].path[2][1]*this.floorMap.ratio)
          , (this.modules[0].path[3][1]*this.floorMap.ratio));

  /*for(var i=1; i < this.modules.length; ++i)
  {
    maxx=Math.max((this.modules[i].path[0][0]*this.floorMap.ratio)
          , (this.modules[i].path[1][0]*this.floorMap.ratio)
          , (this.modules[i].path[2][0]*this.floorMap.ratio)
          , (this.modules[i].path[3][0]*this.floorMap.ratio), maxx);
    minx=Math.min((this.modules[i].path[0][0]*this.floorMap.ratio)
          , (this.modules[i].path[1][0]*this.floorMap.ratio)
          , (this.modules[i].path[2][0]*this.floorMap.ratio)
          , (this.modules[i].path[3][0]*this.floorMap.ratio), minx);
    maxy=Math.max((this.modules[i].path[0][1]*this.floorMap.ratio)
          , (this.modules[i].path[1][1]*this.floorMap.ratio)
          , (this.modules[i].path[2][1]*this.floorMap.ratio)
          , (this.modules[i].path[3][1]*this.floorMap.ratio), maxy);
    miny=Math.min((this.modules[i].path[0][1]*this.floorMap.ratio)
          , (this.modules[i].path[1][1]*this.floorMap.ratio)
          , (this.modules[i].path[2][1]*this.floorMap.ratio)
          , (this.modules[i].path[3][1]*this.floorMap.ratio), miny);
  }*/


  //console.log('redraw stand '+this.id);

  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);

  $('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 colorString = this.floorMap.unbookable_background_color.toString();
  var rgb = colorString.match(/\d{1,3}/g);
  var colorTotal = ((rgb[0]+rgb[1]+rgb[2])*rgb[3])+((255-(255*rgb[3]))*3);
  var myColor = '#FFFFFF';
  if((colorTotal / 3) > 128){
    myColor = '#000000';
  }

  $('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+')';
      ctx.stroke();
      ctx.fill();
    }
  }




  }
});


/*************************************************************************************************************************************************
*  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;
  }
});
