$(function() {
  $('#table_order_link').click(function() {
    if($('#order-table-container').css('display') == 'none') {
      $('#order-table-container').fadeIn();
    } else {
      $('#order-table-container').fadeOut();
    }
    return false;
  });
  
  var container = $('#order-table-container');
  
  $('#order-table-close').click(function() {
    $('#order-table-container').fadeOut();
  });
  
  $('#order-table-back').click(function() {
    if($('#order-table-floors').css('left') == '-740px') {
      $('#order-table-floors').animate({'left': '0px'});
      $(this).removeClass('active');
      $('#order-table-forward').addClass('active');
    }
  });
  
  $('#order-table-forward').click(function() {
    if($('#order-table-floors').css('left') == '0px') {
      $('#order-table-floors').animate({'left': '-740px'});
      $(this).removeClass('active');
      $('#order-table-back').addClass('active');
    }
  });
  
  $('.table').click(function() {
    $(this).toggleClass('active');
  });
  
  $('#order-table-order').click(function() {
    var tables = [];
    $('.table.active').each(function() {
      tables.push(this.id.split('-')[1]);
    });
    if(!tables.length) {
      alert('А ни одного столика то не выбрано! :-O');
    } else {
      if(confirm('Вы действительно хотите забить ' + (tables.length > 1? 'все эти столики:\n' + tables + '\n?': 'столик ' + tables + '?'))) {
        $.ajax({
          url: location.protocol + '//' + location.host + location.pathname + 'index.php?do=ordertable&tables[]=' + tables.join('&tables[]='), 
          success: function(data, textStatus) {
            alert(data);
          },
          error: function() {
            alert('Не удалось отправить заявку, пожалуйста повторите попытку позднее');
          }
        });
      } else {
        alert('Очень жаль :\'(');
      }
    }
    return false;
  });
  
  $('.table').hover(function() {
    $('.tablehint:visible').fadeOut();
    if(!this.jHint) {
      this.jHint = $('<div class="tablehint hint-' + this.className.replace(/table /, '').replace(/ /, '-') + '"><div class="sign"></div><div class="arrow"></div></div>').appendTo(this.parentNode).css({left: parseInt($(this).css('left')) -107, top: parseInt($(this).css('top')) + parseInt($(this).css('height')) - 25}).fadeIn();
    } else {
      if(this.foTO) return;
      this.jHint.fadeIn();
    }
  }).mouseout(function() {
    if(this.foTO) return;
    var that = this;
    this.foTO = setTimeout(function() { that.foTO = false; that.jHint.fadeOut();}, 1000);
  });
});
