/*
 * @todo:
 * - put all strings (id's, classes) in configuration
 * - outsource event's-code
 * - manage cart in cart-class (?)
 * - update bought/cart-count's on menu
 *
 * Ajax-Api:
 * every ajax-call to order/cancel menu's or to add/remove menu's from cart
 * must return the following data in json-format:
 * data
 *   .content            => the rendered Cart for this Day                                             --> to show in facebox on the right
 *   .menu_id            => the ID of the "updated" menu (e.g. ordered, deleted, added to cart ...)    --> to markt the boxes in week/dayView as ordernd/incart
 *   .num_cart_items     => Number of Menus in Cart (not only this day)                                --> to update toolbar
 *   .num_day_cart_items => Number of Menus of menu_id in cart at this day                             --> to decide if box should marked as in_cart or not
 *   .num_order_items    => Number of Menus of menu_id ordered this day                                --> to decide if box should marked as ordered or not
 *   .cart_total         => the Amount of the whole cart                                               --> to update toolbar
 *   .user_total         => the Amount of users balance                                                --> to update toolbar
 *   .all_total          => tuser_total - cart_total                                                   --> to update toolbar
 *   .all_total_class    => 'positive' or 'negative'                                                   --> to show Ammount in Toolbar in red or green
 *   
 * @see: modules/cart/templates/showAjaxSuccess.php
 * 
 * All Events, except inetmenue.balance_changed are triggerd with all these parameters
 **/

App = {};

App.inetmenue = {
  is_initialized: false,
  init: function() {
    
    $('body').addClass('js');
    
    if(this.is_initialized == false)
      this.is_initialized = true;
    else
      return;
    
    //show facebox, if link is clicked
    $('a.menu_order').live('click', function() {
      $.facebox({ajax: this.href});
      return false;
    });
    // direct order menu if oneclick order is possible
    $('a.menu_order_forth').live('click', function() {      
      var der_link = this;      
      $.ajax({
        url: this.href,
        type: 'POST',
        dataType: 'json',
        success: function(data) {
          App.inetmenue.order_placed(null, data); 
          var e = $(der_link).children('p.order');
          if(e.html() == "Stornieren") e.html("Bestellen").removeClass('storno');
          else e.html("Stornieren").addClass('storno');
        },
        error: function(jqXHR, textStatus, errorThrown) {
          if(jqXHR.status == 400)
          {
            alert(jqXHR.responseText);
          }
        }
      });
      return false;
    });     
    
    //show facebox, if link is clicked -- supervision-module
    $('a.course_info').live('click', function() {
      $.facebox({ajax: this.href});
      return false;
    });
    
    //Set the witdh of facebox to 640px;
    $(document).bind('afterReveal.facebox', function() {
      $('#facebox .content').width('640px');
    });
    
    //Attach internal events
    $(this).bind('inetmenue.balance_changed', this.balance_changed);
    $(this).bind('inetmenue.toprint_changed', this.toprint_changed);    
    $(this).bind('inetmenue.order_placed', this.order_placed);
    $(this).bind('inetmenue.order_cancelled', this.order_cancelled);    
    
    // Print Slips clicken   
    $('a.print_slips').click(function(event) {                  
      event.preventDefault();
      w = window.open(this.href, "print", "menubar=0,resizable=0,scrollbars=1,width=760,height=800");
      w.scrollbars.visible = true;
      $(App.inetmenue).trigger('inetmenue.toprint_changed', 0);
    });
    
    //Delete from Cart
    $('a.delete_from_cart').live('click', function() {
      id = this.id.replace('remove_order_cart_id_');
      return App.inetmenue.cart.remove(id, this.href);
    });
    
    //Cancel a Menu
    $('a.storno').css('display', 'inline');
    $('a.storno').live('click', function() {
      id = this.id.replace('storno_order_id_');
      return App.inetmenue.cancel_order(id, this.href);
    });
  
    //Just close the facebox
    $('#facebox .close_submit').live('click', function() {   
      $.facebox.close();
    });
    $('#facebox button.close_submit_submit').live('click', function(e) {
      e.preventDefault();
      $.facebox.close();     
    });    
    $('#facebox button.close_submit').live('click', function(e) {
      e.preventDefault();
      $.facebox.close();     
    });    
    
    // order and add_to_cart-buttons
    //@todo: put this into separate functions
    $('.cart_actions_submit').live('click', function() {
      url = $('.order_container form').attr('action');
      var _this = this;
      $.ajax({
        url: url+'?'+this.name+'=1',
        data: $('.order_container form').serialize(),
        dataType: 'json',  
        type: 'post',
        success: function(data) {

          $('#show_cart').html(data.content);
          if(_this.name == 'save_to_cart')
            $(App.inetmenue.cart).trigger('inetmenue.cart.item_added', data); 
          else if(_this.name == 'save')
            $(App.inetmenue).trigger('inetmenue.order_placed', data); 

          //App.inetmenue.update_classes_and_cart(data);
        },
        error: function(jqXHR, textStatus, errorThrown) {
          if(jqXHR.status == 400)
          {
            $('#order_form_fields').replaceWith(jqXHR.responseText);
          }
          if(jqXHR.status == 406)
          {
            alert(jqXHR.responseText);
          }
        }
      });    
      return false;
    });
    
    $('.suv_actions_submit').live('click', function(e) {
      e.preventDefault();      
      url = $('.order_container form').attr('action');
      var _this = this;
      $.ajax({
        url: url+'?'+this.name+'=1',
        data: $('.order_container form').serialize(),          
        type: 'post',
        cache: false,
        success: function(data) {         
          $('#facebox .content').html(data);   
          
          $.ajax({
            url: document.location,
            data: $('.order_container form').serialize(),          
            type: 'get',
            cache: false,
            success: function(data) {         
              $('table.week_table tbody').html(data);                         
            }
          });     
          //App.inetmenue.update_classes_and_cart(data);
        },
        error: function(jqXHR, textStatus, errorThrown) {          
          if(jqXHR.status == 400)
          {
            ('#facebox .content').html(data); 
          }
          if(jqXHR.status == 406)
          {
            alert(jqXHR.responseText);
          }
        }
      });    
      return false;
    });

  }, 
  balance_changed: function(evt, total)
  {
    //console.log('balance_changed' + total)
    $('#toolbar_user_balance').html(total); 
  },
  toprint_changed: function(evt, num)
  {
    //console.log('toprint_changed' + num)
    if(num > 0) {
      $('#print_btn').css('display', 'block');
      $('#toolbar_print_num_items').html(num);
    } else {
      $('#print_btn').css('display', 'none'); 
      $('.print_form').css('display', 'none'); 
    }
  },
  order_placed: function(evt, data)
  {
    //console.log('order_placed');
    $(App.inetmenue).trigger('inetmenue.balance_changed', data.user_total);
    $(App.inetmenue).trigger('inetmenue.toprint_changed', data.to_print);
    this.orders_changed(data);
  },
  cancel_order: function(order_id, url)
  {
    $.ajax({
      url: url,
      type: 'post',
      data: 'sf_method=delete',
      dataType: 'json',
      cache: false,
      success: function(data) {
        $(App.inetmenue).trigger('inetmenue.order_cancelled', data);        
      },
      error: function(e) {
        alert(e.responseText);
      }
    });
    return false; 
  },
  order_cancelled: function(evt, data)
  {
    //console.log('order_cancelled');
    $(App.inetmenue).trigger('inetmenue.balance_changed', data.user_total);
    $(App.inetmenue).trigger('inetmenue.toprint_changed', data.to_print);
    this.orders_changed(data);
  },
  orders_changed: function(data)
  {
    //Update today's cart'
    $('#show_cart').html(data.content);
   
   //Update order-count of the menu's box'
    $('#inet_menu_item_'+data.menu_id+' span.menu_ordered').html(data.num_order_items);
    
    //Update available portions in the menu's box'
    if(data.menu_quantity !== true)
    {
      $('#inet_menu_item_'+data.menu_id+' span.menu_quantity').html('noch ' + data.menu_quantity);
    }
    
    //Update amount after cart is ordered
    $('#toolbar_all_total').html(data.all_total).removeClass().addClass(data.all_total_class);
    
    if(data.num_order_items > 0)
      $('#inet_menu_item_'+data.menu_id).addClass('ordered');
    else
      $('#inet_menu_item_'+data.menu_id).removeClass('ordered');
  }
};

App.inetmenue.cart = {
  item_count: 0,
  cart_price: 0,
  init: function() {
    $(this).bind('inetmenue.cart.item_added', this.item_added);
    $(this).bind('inetmenue.cart.item_removed', this.item_removed);
  },
  remove: function(cart_id, url)
  {
    $.ajax({
      url: url,
      type: 'get',
      dataType: 'json',
      cache: false,
      success: function(data) {
        $(App.inetmenue.cart).trigger('inetmenue.cart.item_removed', data); 
        //App.inetmenue.update_classes_and_cart(data);
      }
    });
    return false;
  },
  add: function(menu_id)
  {
    
  },
  item_added: function(evt, data)
  {
    this.cart_changed(data);
    
    $('#toolbar_cart_num_items').html(this.item_count);
    
    $('#all_total_hint').css('display', 'inline');
    $('#toolbar_all_total').css('display', 'inline');
    $('#toolbar_cart_total').css('display', 'inline');

    $('#logout_btn').hide();
    $('#order_now_btn').css('display', 'block');
  },
  item_removed: function(evt, data)
  {
    this.cart_changed(data);
    $('#toolbar_cart_num_items').html(this.item_count);
    
    if(this.item_count == 0)
    {
      $('#all_total_hint').hide();
      $('#toolbar_all_total').hide();
      $('#toolbar_cart_total').hide();

      $('#logout_btn').css('display', 'block');
      $('#order_now_btn').hide();
    }
  },
  cart_changed: function(data)
  {
    this.item_count = data.num_cart_items;
    this.cart_price = data.cart_total;
    
    //Update amounts
    $('#toolbar_cart_total').html(data.cart_total);
    $('#toolbar_all_total').html(data.all_total).removeClass().addClass(data.all_total_class);
    
    //Update Cart in facebox
    $('#show_cart').html(data.content);
    
    //Update Cart-Count
    $('#inet_menu_item_'+data.menu_id+' span.menu_cart').html(data.num_day_cart_items);      
    
    //Highlight Boxes, if menu is in Cart
    if(data.num_day_cart_items > 0) {
      $('#inet_menu_item_'+data.menu_id).addClass('in-cart');
    }
    else {
      $('#inet_menu_item_'+data.menu_id).removeClass('in-cart');
    }
  }
}


