
/*
 * Listener of events on the cart popin and restaurant menu :
 * - delete item
 * - edit item
 * - add one item
 * - remove one item
 * - clear cart
 */
var loaded = false;
jQuery(document).ready(function() { 
  
  animate_cart();
  cart_popin();
  send_cart();
  
  var ajax_loader_sm = '/images/vac/loader/ajax-loader.gif';
  var ajax_loader_bg = '/images/vac/loader/transparent-big.gif';
  var bag_link_img = '/images/vac/icone_bag.png';
  var delete_img = '/images/vac/navigation_icons_small/delete.png';
  
  if(jQuery('#checkout_cart_form_rhcm_code').length != 0)
  {
    is_checkout_form = jQuery('#checkout_cart_form_rhcm_code').attr('value');
  }
  else
  {
    is_checkout_form = false;
  }
  
  /*
   * Step 5, save favorite
   */
  jQuery('a#save_favorite').live('click', function(event) {
    event.preventDefault();
    jQuery('#form_favorite').submit();
  });
  
  /*
   * Delete an item
   * From popin, user click on the delete icon of an item
   */
  jQuery('table#my_order a[href*="panier/retirer"]').live('click', function(event) {
  	event.preventDefault();
  	
  	var link = jQuery(this);
  	
  	// ajax loader
  	link.children('img').attr('src', ajax_loader_sm);
  	
  	// hash (from vacShoppingCart) attribute on every cells of the table that are bound to the item
  	var hash = link.parents('tr').attr('hash');
  	
  	var is_checkout_form = jQuery('#checkout_cart_form_rhcm_code').val();
    if(is_checkout_form == '')
    {
      is_checkout_form = null;
    }
  	jQuery.ajax({
  	  url: link.attr('href') + '/' + is_checkout_form,
  	  type: 'GET',
  	  dataType: 'json',
  	  //data: {is_checkout_form: },
  	  success: function(result) {
    		if(result['action'] == 'remove') {
    	    remove_cart_item(hash, result);
    		}
    		else {
    		  cart_gone_empty();
    		}
  	  },
  	  error: function(result) {
  		  show_notice('Une erreur est survenue, impossible de supprimer cet article pour l\'instant.');
  	  }
  	});
  });
  
  /*
   * Plus one item
   * From popin, user has click on "+" for an item
   */
  jQuery('a.cartplus1').live('click', function(event) {
  	event.preventDefault();
  	var link = jQuery(this);
  	
  	// hash (from vacShoppingCart) attribute on every cells of the table that are bound to the item
  	var hash = link.attr('hash');
  	// ajax loader
  	change_loader(1);
  	jQuery('#qty_' + hash).html('<img src="'+ajax_loader_sm+'" />');
  	
  	var is_checkout_form = jQuery('#checkout_cart_form_rhcm_code').val();
    if(is_checkout_form == '')
    {
      is_checkout_form = null;
    }
  	jQuery.ajax({
  	  url: link.attr('href') + '/' + is_checkout_form,
  	  type: 'GET',
  	  dataType: 'json',
  	  //data: {is_checkout_form: jQuery('#checkout_cart_form_rhcm_code').attr('value')},
  	  success: function(result) {
    		if(result['action'] == 'plus') {
          refreshIfRhcmConflictInDom();
    		  update_cart_dom(result);
    		}
        if (result['action'] == 'rhcm')
        {
          location.reload();
        }
        change_loader(0);
  	  },
  	  error: function(result) {
  		  show_notice('Une erreur est survenue, impossible de modifier la quantité de cet article pour l\'instant.');
  	  }
  	});
  });
  
  /*
   * Minus one item
   * From popin, user has click on "-" for an item
   */
  jQuery('a.cartminus1').live('click', function(event) {
  	event.preventDefault();
  		
  	var link = jQuery(this);

  	// hash (from vacShoppingCart) attribute on every cells of the table that are bound to the item
  	var hash = link.parents('tr').attr('hash');
  	
  	// ajax loader
  	change_loader(1);
  	jQuery('#qty_' + hash).html('<img src="'+ajax_loader_sm+'" />');
  	
  	var is_checkout_form = jQuery('#checkout_cart_form_rhcm_code').val();
    if(is_checkout_form == '')
    {
      is_checkout_form = null;
    }
  	jQuery.ajax({
  	  url: link.attr('href') + '/' + is_checkout_form,
  	  type: 'GET',
  	  dataType: 'json',
  	  //data: {is_checkout_form: jQuery('#checkout_cart_form_rhcm_code').attr('value')},
  	  success: function(result) {
    		if(result['action'] == 'minus') {
          refreshIfRhcmConflictInDom();
    		  update_cart_dom(result);
    		}
    		else if(result['action'] == 'remove') {
          refreshIfRhcmConflictInDom();
    		  remove_cart_item(hash, result);
    		}
        else if (result['action'] == 'rhcm')
        {
          location.reload();
        }
    		else {
    		  cart_gone_empty();
    		}
    		change_loader(0);
  	  },
  	  error: function(result) {
  		  show_notice('Une erreur est survenue, impossible de modifier la quantité de cet article pour l\'instant.');
  	  }
  	});
  });
  
  
  /*
   * Clear cart
   * From popin, user click on "clear the cart"
   */
  jQuery('table#my_order a[href*="panier/vider"]').live('click', function(event) {
  	event.preventDefault();

  	var is_checkout_form = jQuery('#checkout_cart_form_rhcm_code').val();
  	if(is_checkout_form == '')
  	{
  	  is_checkout_form = null;
  	}
  	var link = jQuery(this);
  	jQuery.ajax({
  	  url: link.attr('href'),
  	  type: 'GET',
  	  dataType: 'json',
  	  //data: {is_checkout_form: jQuery('#checkout_cart_form_rhcm_code').attr('value')},
  	  success: function(result) {
    		cart_gone_empty();
    		// popin is closed
    		setTimeout("jQuery().popinClose()", 1000);
  	  },
  	  error: function(result) {
  		  show_notice('Une erreur est survenue, impossible de vider le panier pour l\'instant.');
  	  }
  	});
  });
  
  /*
   * Clear cart
   * From bottom cart, user click on "clear cart"
   */
  jQuery('#cart_bottom_content a[href*="panier/vider"]').live('click', function(event) {
  	event.preventDefault();
  	
  	jQuery('#cart_bottom_middle a img').attr('src', ajax_loader_sm);
  	
  	var link = jQuery(this);
  	
  	jQuery.ajax({
  	  url: link.attr('href'),
  	  type: 'GET',
  	  dataType: 'json',
  	  data: {is_checkout_form: is_checkout_form},
  	  success: function(result) {
        cart_gone_empty();
    		//jQuery('#cart_bottom').slideToggle(); // make cart_bottom disappear
    		//check_page();
  	  },
  	  error: function(result) {
  		  jQuery('#cart_bottom_middle a').text('Erreur, merci de réessayer');
  	  }
  	});  
  });
  
  
  
  
  
  /*
   * Click on a setDishOption in a menu
   * a link named by a dish is clicked
   */
  //var htmldata = new Array();
  //var clickcount = new Array();
  
  $.cart = {};
  $.cart.cache = {};
   
  jQuery('a[class*="cart_item"][href*="panier/plat"]').live('click', function(event) {
    event.preventDefault();
    
    var link = jQuery(this);
    var link_id = link.attr('id');
    var bag_img = link.parents('tr').children('.item_add_to_cart').children('a.cart_item').children('img');
    
    // transition 1 : "Ajout au panier en cours"
    if ( $.cart.cache[ link_id ] == undefined )
    {
      $.cart.cache[ link_id ] = jQuery('#'+link_id).html();
    }
    
    jQuery('#'+link_id).css('backgroundColor', '#D9D9D9'); 
    jQuery('#'+link_id).animate({
        backgroundColor: "#f0f0f0",
        color: "#000000"
      }, 200 );
    if ( link.hasClass('without_option') )
    {
      jQuery('#'+link_id).html('<p align="center" class="item_adding"><img src="/images/ajax-loader-f0f0f0.gif"> Ajout au panier en cours ...</p>');
    }
    else
    {
      jQuery('#'+link_id).html('<p align="center" class="item_adding"> Récupération des informations en cours ...</p>');
    }

    // ajax loader
    bag_img.attr('src', ajax_loader_sm);
    
    jQuery.ajax({
      url: link.attr('href'),
      type: 'GET',
      dataType: 'json',
      cache: false,
      success: function(result) {
    	// action == add
    	// for non custom not with options dish (drinks for example)
    	// item has been added to the cart, user has no choice to do
    	if(result['action'] == 'add') {
    	 
         
  	// transition 2 : "Article bien ajouté au panier" sur fond vert
        jQuery('#'+link_id).css('zIndex', 14999);
        jQuery('#'+link_id).animate({
            backgroundColor: "#BCD168",
            color: "#000000"
          }, 250 );    
	      jQuery('#'+link_id).html('<p align="center" class="item_added"><img src="/images/fleche-panier.png" style="width:20px;" /> Article bien ajouté au panier ! (en bas de page) <img src="/images/fleche-panier.png" style="width:20px;" /></p>');
    	
 
    	// transition 3 : On revient à l'article de base
        setTimeout( function(){
          jQuery('#'+link_id).animate({
              backgroundColor: "#ffffff",
              color: "#808080"
            }, 300 );
        }, 3600);    	 
        setTimeout( function(){
       	  jQuery('#'+link_id).html(  $.cart.cache[ link.attr('id') ]  );    
    	    jQuery('#'+link_id).css('backgroundColor', ''); 
    	    jQuery('#'+link_id).css('color', '');
        }, 4100);    	
    	  
    	  // transition 4 : si c'est la première commmande de l'utilisatuer
    	  // on affiche le paneau noir glissant
        if ( link.hasClass('without_option') )
        {
      	  if ( $.fknowledge.command_end_command <= 1 )
      	  {
      	    ergonomicWhereIsTheCart("Votre article a bien été ajouté au panier", 'fast', 'without_option');
      	  }
    	  }
    	  
    	  // dish was added to the cart
    	  if(result['newcart']) {
    		  cart_is_new(result);
    	  }
    	  else {
    		  update_cart_dom(result);
    	  }
    	  // remove loader, back to bag img
      	bag_img.attr('src', bag_link_img);
    	}
    	else if(result['action'] == 'options') {
    	  // dish require options to be set
    	  window.location = link.attr('href');
    	  // we keep the loader image to keep impression
    	  // to user that something is still going on,
    	  // the time to relocate the page
    	  
    	  // we prevent some browsers (IE) to run the URL as non-XHR one
    	  //return false;
    	}
    	else {
    	  // display some error message
  		  jQuery().popinOnDemand({
          width: 520,
          height: 250,
          className: 'helppopin',
          loaderImg: ajax_loader_bg
  	    }, result['action']);
  		  // remove loader, back to bag img
	      bag_img.attr('src', bag_link_img);
    	}
    	
      },
      error: function(result) {
        window.location = link.attr('href');
      }
    });
  });



  // Manipulation du dom: cacher 'domicile' en fonction du mode de commande choisi [...]

  jQuery('#command_command_mode').change(function() {

    if (jQuery(this).val() == "1")
    {
      jQuery('#command_address_id').parent('div').show();
    }
    else
    {
      jQuery('#command_address_id').parent('div').hide();
    }

  });
});

// an action that was performed require DOM to be modified
function update_cart_dom(result)
{
  var old_html = '';
  var checkpage = false;
  var upanddown = true;
  for(index in result) {
    if(index != 'action') {
  	  jQuery('#' + index).html(result[index]);
  	  jQuery('.' + index).html(result[index]); // si sur cart/index, màj les valeurs du contenu
    }
    else if(index == 'action')
    {
      if(result[index] == 'remove' || result[index] == 'empty')
      {
        checkpage = true;
        if(result[index] == 'empty')
        {
          upanddown = false;
        }
      }
    }
  }
  if(checkpage == true)
  {
    check_page();
  }
  if(upanddown == true)
  {
    loaded = false;
    cart_up(jQuery('#cart_bottom'));
    animate_cart();
  }
  cart_popin();
}

// item has to be removed from the dom
function remove_cart_item(hash, result)
{
  jQuery('tr[hash="' + hash + '"]').fadeOut();
  update_cart_dom(result);
}

// cart is empty, we remove it from the dom
function cart_gone_empty()
{
  jQuery('table#my_order').fadeOut();
  show_notice('Votre panier est vide.', '#notice_top');
  jQuery('#include_cart').fadeOut();// make cart_bottom disappear
  check_page();
}

// cart is newly created with first item added
function cart_is_new(result)
{
  jQuery('#include_cart').html(result['newcart']);
  // as the DOM is modified, the following jQuery calls
  // have to be called again on new DOM elements
  cart_popin();
  loaded = false;
  animate_cart();
}

function cart_popin()
{
  jQuery("a.cart-popin").popin({
  	width: 800,
  	height: 500,
  	className: "helppopin",
  	loaderImg: "/images/vac/loader/transparent-big.gif"
  });
}

/**
 * On step3 (checkout form where to define time and mode of command),
 * we display a link "send my command to restaurant". It's not part
 * of the form, to this function will submit the checkout form when called
 * @return
 */
function send_cart()
{
  if(jQuery('form#checkout').length != 0) {
  	jQuery('a#send_to_restaurant').live('click', function(event) {
  	  event.preventDefault();
  	  
  	  jQuery('form#checkout').submit();
  	});
  }
}


/*
 * If user is on cart/index page, with cart not empty,
 * ready to send checkout information to restaurant,
 * he might edit his cart via popin. If so, we have to
 * reload form#checkout because values may have
 * changed (price for example)
 */
function check_page(identifier)
{
  if(jQuery('form#checkout').length != 0) {
    show_notice('<img src="/images/vac/loader/ajax-loader.gif" /> Rechargement du formulaire de finalisation de la commande...', identifier);
    setTimeout("window.location.reload()", 100);
  }
}

/*
 * Helper to display a notice on the popin
 */
function show_notice(text, identifier)
{
  var identifier = (identifier == null) ? '.cart_popin_notice' : identifier;
  jQuery(identifier).html(text).fadeIn('fast');
}

/*
 * Force the page to reload if a RHCM
 * conflict has been return by the ShoppingCart
 * object during ajax action
 */
function refreshIfRhcmConflictInDom()
{
  if ($('#rhcm_conflict').length)
  {
    location.reload();
  }
}

var t_array = new Array();
function animate_cart()
{
  if(isTablet())
  {
    cart_up(jQuery('#cart_bottom'));
  }
  else
  {
    // on mouse over the cart, display it
    jQuery('#cart_bottom').mouseenter(function() {
      cart_up(jQuery(this));
      // clear all cart_down timeouts
      for(i in t_array)
      {
        clearTimeout(t_array[i]);
      }
      t_array = new Array();
    }).mouseleave(function() {
      // on mouse leaving, set timeout to cart_down
      t = setTimeout("cart_down(jQuery('#"+ jQuery(this).attr('id')+"'))",1000);
      t_array.push(t);
    });
    
    if(loaded === false)
    {
      // if page juste loaded or dish just added, set timeoutout to cart down
      t = setTimeout("cart_down(jQuery('#cart_bottom'))",2000);
      t_array.push(t);
      loaded = true;
    }
  }
}

function cart_up(object)
{
  if(object.css('height') == '32px')
  {
    object.animate({height:'102px'});
  }
}

function cart_down(object)
{
  if(object.css('height') == '102px')
  {
    object.animate({height:'32px'});
  }
}

/*
 * If ajax loader is not in the DOM, image
 * is shown. Otherwise image is removed
 */
function change_loader(val)
{
  if(val == 1)
  {
    jQuery('#cart_custom_loader').removeClass('nodisplay');
  }
  else
  {
    jQuery('#cart_custom_loader').addClass('nodisplay');
  }
}









$('#ergo_show_cart').live('click', function() {
  $('#ergo_show_cart').fadeOut(300);
})


// A afficher les premières fois que l'utilisateur passe une commande
// Tester avec ergonomicWhereIsTheCart("Votre article a bien été ajouté au panier.");
function ergonomicWhereIsTheCart(msg, speed, helper_name)
{

  if ( ( !isIe6or7() ) && ( can_we_show_helper(helper_name) ) )
  {

    add_helper(helper_name);
    
    // on cache le flash pour pas afficher 2 messages similaires
    if ( $('#flash_notice_message').length > 0 )
    {
      $('#flash_notice_message').hide();
    }

    if ( jQuery('#ergo_show_cart').length > 0 )
    {
      jQuery('#ergo_show_cart').remove();
    }
    
    // inline à virer après passe cross browser
    jQuery('body').append('<div id="ergo_show_cart"><div><span id="ergo_show_cart_1">'+msg+'</span><br><span id="ergo_show_cart_2">Votre panier se trouve toujours ici, en bas de l\'écran :</span><br><p id="ergo_show_cart_3">Cliquez sur "Choisir l\'horaire ►" pour poursuivre votre commande ...</p></div></div>');
    
    // réglage de vitesse
    if ( speed == 'fast' )
    {
      var time_msg1 = 2300;
      var time_msg2 = 5500;
      var time_clear = 9000;
    }
    else
    {
      var time_msg1 = 1700;
      var time_msg2 = 4500;
      var time_clear = 7000;
    }
    
    jQuery('#ergo_show_cart').show();
    jQuery('#ergo_show_cart_1').css('opacity', 1);
    jQuery('#ergo_show_cart_2').css('opacity', 0);
    jQuery('#ergo_show_cart_3').css('opacity', 0);
    
    var screen_max_available_height = $(window).height() - jQuery('#include_cart').height();
    jQuery('#ergo_show_cart').animate({'height':screen_max_available_height+'px'}, 1300 );

    // on check a nouveau la hauteur qui a peut être changé (augmenté avec l'ajax add Item Cart)
    setTimeout("jQuery('#ergo_show_cart').css('height', (jQuery(window).height() - jQuery('#include_cart').height())+'px');", 2000 );

    setTimeout("jQuery('#ergo_show_cart_1').animate({'opacity':0.2}, 1000 );", time_msg1);
    setTimeout("jQuery('#ergo_show_cart_2').animate({'opacity':1}, 1000 );", time_msg1);
    
    
    setTimeout("jQuery('#ergo_show_cart_2').animate({'opacity':0.2}, 1000 );", time_msg2);
    setTimeout("jQuery('#ergo_show_cart_3').animate({'opacity':1}, 1000 );", time_msg2);
    
    setTimeout("jQuery('#ergo_show_cart').animate({'opacity':0}, 1000 );", time_clear);
    setTimeout("jQuery('#ergo_show_cart').remove();", time_clear+1000);
    
    add_functionality('ergo_show_where_is_cart', '');
    
  } // endif
}


