(function($) {
	BBCS.namespace('cart');
	
	function output(msg) {
    $('#flashcontent-home').html($('#flashcontent-home').html() + '<br />' + msg)
  }
	/**
	 * Adds a product to the users cart.
	 * @param {String | Number} product_id Product id
	 * @param {String | Number} facet Facet number
	 * @param {Number} quantity
	 */
	BBCS.cart.add_product = function(product_id, facet, quantity) {
		var data = {};
		if(facet) data['facet_id'] = facet;
		if(quantity) data['quantity'] = quantity;
		
		if ($.isEmptyObject(data)) data = null;
    
		$.unblockUI();
		BBCS.lock(function(unlock){
      addProductToCart(product_id, data, function(shoppingCartHtml){
        if (shoppingCartHtml)
          displayMyShoppingCartModal(shoppingCartHtml);
        BBCS.cart.updated();
        unlock();
      });
    });
	}
	
	/**
	 * Adds a gift certificate to the users cart.
	 * @param {String | Number} product_id Product id
	 * @param {String} Name of person to send it to
	 * @param {String} Message
	 * @param {String} Email to send certificate to
	 */
	BBCS.cart.add_gift_certificate = function(product_id, name, message, email) {
		var data = {};
		if (name) data['gc_to'] = name;
		if (message) data['gc_message'] = message;
		if (email) data['gc_email'] = email;
		
		if ($.isEmptyObject(data)) data = null;
    
		$.unblockUI();
		BBCS.lock(function(unlock){
      addProductToCart(product_id, data, function(shoppingCartHtml){
        if (shoppingCartHtml)
          displayMyShoppingCartModal(shoppingCartHtml);
        BBCS.cart.updated();
        unlock();
      });
    });
	}
  
	/**
	 * Legacy support for adding products by item number.
	 * @param {String | Number} item_number Item number
	 * @param {String | Number} facet Facet number
	 * @param {Number} quantity
	 */
  BBCS.cart.add_product_by_item = function(item_number, facet, quantity) {
    var data = { item_number: item_number };
    
		if(facet) data['facet_id'] = facet;
		if(quantity) data['quantity'] = quantity;
		
		if ($.isEmptyObject(data)) data = null;
    
		$.unblockUI();
		BBCS.lock(function(unlock){
      addProductToCartByItemNumber(data, function(shoppingCartHtml) {
        if (shoppingCartHtml)
          displayMyShoppingCartModal(shoppingCartHtml);
        BBCS.cart.updated();
        unlock();
      });
    });
  }
  
	/**
	 * Legacy support for adding mutiple products by item number via the quickshop interface.
	 * @param {Array} item_numbers Item numbers
	 */
  BBCS.cart.batch_add_product_by_item = function(item_numbers) {
		if (!item_numbers.length) return;
		
		if (item_numbers.length == 1) {
			BBCS.cart.add_product_by_item(item_numbers.shift(), null, 1);
		} else {
			var data = { item_number: item_numbers.shift(), quantity: 1 };
			addProductToCartByItemNumber(data, function() {
				BBCS.cart.batch_add_product_by_item(item_numbers);
      });
		}
  }
  
  /**
   * Proxy function which constructs the correct url for adding product to cart.
	 * @param {String | Number} product_id Product id
	 * @param {Object} data {facet: 1, quantity: 1}
	 * @param {Function} callback Layout returned by the server is passed to this function.
   */
  function addProductToCart(product_id, data, callback) {
    cartAddRequest('/cart/add/' + product_id, data, callback);
  }
  
  /**
   * Proxy function which constructs the correct url for adding product to cart by item number.
	 * @param {Object} data {facet: 1, quantity: 1, item_number}
	 * @param {Function} callback Layout returned by the server is passed to this function.
   */
  function addProductToCartByItemNumber(data, callback) {
    cartAddRequest('/cart/add/', data, callback);
  }
  
  /**
   * Makes an ajax request to the server
   * @param {String} url
   * @param {Object} data {facet: 1, quantity: 1}
	 * @param {Function} callback Layout returned by the server is passed to this function.
   */
  function cartAddRequest(url, data, callback) {
    $.ajax({
			url: url,
			type: 'GET',
			data: data,
			success: function(result) {
        if(typeof result != 'string') {
          if(result.error != null && result.error == -1)
            BBCS.error.unableToAddProductModal();
            
          callback();
        } else {
          callback(result);
        }
			}
		});
  }
  
  /**
   * Using blockUI, centers the layout. Also sets up the click event on the close button.
   * @param {String} layout
   */
  function displayMyShoppingCartModal(layout) {
  	var posTop  = (100);
   	var getViewportHeight = $(window).height();
    if  (getViewportHeight < 700) {
    	var posTop = (20);
    }
    
    var html = $(layout);
    $.unblockUI();
    $.blockUI({
      message: html,
      css: {
        textAlign: 'left',
        cursor: 'default',
        border: 'none',
        backgroundColor: '#fff',
        width: 'auto',
        height: 'auto',
        top: posTop + 'px',
        position: 'fixed'
      },
      overlayCSS: {
        cursor: 'default'
      }
    });
    html.find('.title a, .continue-shopping').click(function() { $.unblockUI(); return false; });
    html.find('.view-cart-checkout').click(function() { location.href = '/cart'; return false; });
    html.find('.view-cart-checkout').click(function() { location.href = '/cart'; return false; });
    setupUnblockEvents();
  }
  
  
  $('.more-shipping-info').click(function() {

    var posTop  = (100);
   	var getViewportHeight = $(window).height();
    if  (getViewportHeight < 700) {
    	var posTop = (20);
    }
   
  	if (BBCS.site.getCountryCode() == 'USA') {
  		var html = $('.usa-shipping-notice').html();
  		var centerModal = ($(window).width() - 550) / 2 + 'px';
  	}  else {
    	var html = $('.can-shipping-notice').html();
    	var centerModal = ($(window).width() - 450) / 2 + 'px';
    }

    $.unblockUI();
    $.blockUI({
      message: html,
      css: {
        textAlign: 'left',
        cursor: 'default',
        border: 'none',
        backgroundColor: '#fff',
        width: 'auto',
        height: 'auto',
        left: centerModal,
        top: posTop + 'px',
        position: 'fixed'
      },
      overlayCSS: {
        cursor: 'default'
      }
    });
 	
 	$('.can-shipping-notice-content a.close, .usa-shipping-notice-content a.close').click(function() { $.unblockUI(); return false; });
 	
 	$(document).unbind();
    $('.can-shipping-notice-content.cart-modal, .usa-shipping-notice-content.cart-modal').unbind();
    $('.can-shipping-notice-content.cart-modal, .usa-shipping-notice-content.cart-modal').click(function(e){
    	e.stopPropagation();
    });
    
    $(document).keyup(function(e){
		if (e.keyCode == 27 && $('.usa-shipping-notice-content.cart-modal:visible').length) $.unblockUI();
	});
  });
  
   
  function setupUnblockEvents() {
    //event cleanup first
    $(document).unbind();
    $('.my-shopping-cart.cart-modal').unbind();
    
    
    $('.my-shopping-cart.cart-modal').click(function(e){
      e.stopPropagation();
    });
    
    $(document).keyup(function(e){
      if(e.keyCode == 27 && $('.my-shopping-cart.cart-modal').length)
        $.unblockUI();
    }).click(function(){
      if($('.my-shopping-cart.cart-modal').length)
        $.unblockUI();
    })
  }
	
	/**
	 * Addes a product the users cart.
	 * @param {String | Number} Product id
	 */
	BBCS.cart.remove_product = function(product_id, facet) {
		var data = {}
		if(facet) data['facet_id'] = facet;
		
		if ($.isEmptyObject(data)) data = null;
		$.ajax({
			url: '/cart/remove/' + product_id,
			type: 'GET',
			data: data,
			success: function() {
				BBCS.cart.updated();
			}
		});
	}
	
  /**
   * Must be called each time a change has happened to the cart. Forces the re-fetch of the minicart layout and updating of shopping cart items.
   */
	BBCS.cart.updated = function() {
		if(miniCartLayout) $(miniCartLayout).remove();
		
		miniCartLayout = null;
    
    //Update shopping cart button item count
    //Assumes user just added an item and the 'My Shopping Cart' modal is on screen/dom.
    var itemCount = $('p[data-item-count]').attr('data-item-count');
    if (itemCount) $('a.mini-cart-btn span').html(itemCount);
	}
	
  //For preventing double initiations
  var init = false;
  
	/**
	 * Initiates all events for the mini cart
	 */
	BBCS.cart.init_minicart = function() {
    if(init == true) return;
    
    var token;
    var minicart_triggers = $('.mini-cart-btn, .mini-cart-wrapper');
    
    //initializing mouse hover
    minicart_triggers.mouseover(function() {
			clearTimeout(token);
			token = setTimeout(BBCS.cart.show_minicart, 100);
		}).mouseout(function() {
			clearTimeout(token);
			token = setTimeout(BBCS.cart.hide_minicart, 700);
		});
    
    //indicates minicart_triggers elements where found and initialization was successful.
    if(minicart_triggers.length && init == false) init = true;
	}
	
  //Buffer variable which holds the mini cart layout.
	var miniCartLayout = null;
	
  /**
   * If the mini cart layout is not available, it is fetched from the server and inserted into the DOM.
   * @param {Function} callback Indicates that the mini cart layout is in the DOM. The minicart layout is passed to this function.
   */
	BBCS.cart.insert_minicart = function(callback) {
		callback = callback || function() {};
		
		if (miniCartLayout != null) {
      callback(miniCartLayout);
    } else {
      $.ajax({
        url: '/cart/minicart',
        cache: false,
        type: 'GET',
        success: function(miniCartHtml) {
          miniCartLayout = $(miniCartHtml);
          $('.mini-cart-wrapper').append(miniCartLayout);
          $('.mini-cart .view-edit-cart, .mini-cart .title a').click(function() { location.href = '/cart'; return false; });
          $('.mini-cart button.orange-button').click(function(){ location.href = '/cart'; return false; })
          callback(miniCartLayout);
        }
      });
		}
	}
	
	BBCS.cart.show_minicart_loading = function() {
		$('.mini-cart.loading').show();
	}
	
	BBCS.cart.hide_minicart_loading = function() {
		$('.mini-cart.loading').hide();
	}
	
  /**
   * Displays mini cart on the screen.
   */
	BBCS.cart.show_minicart = function() {
		BBCS.lock(function(unlock) {
			BBCS.cart.show_minicart_loading();
			$('.mini-cart-wrapper').slideDown('fast');
			BBCS.cart.insert_minicart(function() {
				BBCS.cart.hide_minicart_loading();
				unlock();
			});	
		});
		
	}
	 
	BBCS.cart.hide_minicart = function() {
		$('.mini-cart-wrapper').slideUp('fast');
	}
	
	$(document).ready(BBCS.cart.init_minicart);
	
})(jQuery); 
