jQuery(window).scroll(function() {
  if(jQuery('#cart_bottom').length != 0)
  {
    setBoxBottom(jQuery('#cart_bottom'));
    // make sure it's always well placed
    setInterval("setBoxBottom(jQuery('#cart_bottom'))", 3000);
  }
});


/*
 * Listener of events on the cart popin and restaurant menu :
 * - delete item
 * - edit item
 * - add one item
 * - remove one item
 * - clear cart
 */
jQuery(document).ready(function() { 
	
  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';
  
  /*
   * 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');
  	
  	jQuery.ajax({
  	  url: link.attr('href'),
  	  type: 'GET',
  	  dataType: 'json',
  	  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
  	jQuery('#qty_' + hash).html('<img src="'+ajax_loader_sm+'" />');
  	
  	jQuery.ajax({
  	  url: link.attr('href'),
  	  type: 'GET',
  	  dataType: 'json',
  	  success: function(result) {
    		if(result['action'] == 'plus') {
          refreshIfRhcmConflictInDom();
    		  update_cart_dom(result);
    		}
        if (result['action'] == 'rhcm')
        {
          location.reload();
        }
  	  },
  	  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.attr('hash');
  	
  	// ajax loader
  	jQuery('#qty_' + hash).html('<img src="'+ajax_loader_sm+'" />');
  	
  	jQuery.ajax({
  	  url: link.attr('href'),
  	  type: 'GET',
  	  dataType: 'json',
  	  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();
    		}
  	  },
  	  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 link = jQuery(this);
  	jQuery.ajax({
  	  url: link.attr('href'),
  	  type: 'GET',
  	  dataType: 'json',
  	  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_status 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',
  	  success: function(result) {
    		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
   */
  jQuery('a[class*="cart_item"][href*="panier/plat"]').live('click', function(event) {
    event.preventDefault();
    
    var link = jQuery(this);
    var bag_img = link.parents('tr').children('.item_add_to_cart').children('a.cart_item').children('img');
    
    // 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') {
    	  // 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: 400,
          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 [...]

  $('#command_checkout_how').change(function() {

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

  });





});

// an action that was performed require DOM to be modified
function update_cart_dom(result)
{
  var old_html = '';
  var checkpage = false;
  for(index in result) {
    if(index != 'action') {
  	  old_html = jQuery('#' + index).html();
  	  jQuery('#' + index).html(result[index]);
  		
  	  if(index == 'cart_bottom_item' && (jQuery('#' + index).html() != old_html)) {
    		// value will be different, we apply a color flash animation
    		// for user to notice for sure the change
    		jQuery('#cart_bottom_item a').colorFlash('#0f0', 300, 1200);
  	  }
    }
    else if(index == 'action')
    {
      if(result[index] == 'remove' || result[index] == 'empty')
      {
        checkpage = true;
      }
    }
  }
  if(checkpage == true)
  {
    check_page();
  }
}

// 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('#cart_bottom').slideToggle(); // make cart_bottom disappear
  
  check_page();
}

// cart is newly created with first item added
function cart_is_new(result)
{
  //jQuery('#include_cart').css('display', 'none');
  jQuery('#include_cart').html(result['newcart']);
  jQuery('#include_cart').fadeIn();
  jQuery('#cart_bottom_item a').colorFlash('#0f0', 300, 1200);
  
  // as the DOM is modified, the following jQuery calls
  // have to be called again on new DOM elements
  Cufon.replace('.cufon');
  cart_popin();
}

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

