var getCartUrl = "/cart/get/";
var addToCartUrl = "/cart/add/";
var removeFromCartUrl = "/cart/remove/";
var pickupPassUrl = "/vip-pickup/";
var passInfoUrl = "/about/vip/";
var checkoutUrl = "/checkout"

var redirect = undefined;

var cartTotal = 0;
var hardwareTotal = 0;
var planTotal = 0;

var currentPhone = undefined;

function getCartTotal() { return hardwareTotal + planTotal; }

/**
* getAddRedirect(type, slug) 
* Returns the URL to redirect to after an item is added to the cart
* based on the type. Slug is only necessary for adding phones to 
* direct to the right accessory page.
**/

function getAddRedirect(type, slug) {
  switch(type) {
    case 'phone':
      //redirect = '/cell-phones/phones/' + slug + '/accessories';
      break;
    case 'accessory':
      //redirect = '/cell-phones/phones/cell-phone-plans/';
      break;
    case 'plan':
      redirect = '/checkout';
      break;
    case 'mc-plan-redir':
      redirect = pickupPassUrl;
      break;
    case 'internet':
      redirect = pickupPassUrl;
      break;
    case 'ihp-plan':
      redirect = checkoutUrl;
      break;
	case 'mobileConnect':
      redirect = pickupPassUrl;
      break;
  }
}

/**
* getRemoveRedirect(type, slug)
* Returns the URL to redrect to aftern and item is removed
* from the cart based on the type. Slug is only necessary for 
* phones.
**/

function getRemoveRedirect(type, slug) {
  switch(type) {
    case 'phone':
      //redirect = '/cell-phones/phones/';
      break;
    case 'accessory':
      
      if (currentPhone == undefined) {
        //redirect = '/cell-phones/accessories';
      } else {
        //redirect = '/cell-phones/phones/' + currentPhone + '/accessories';
      }
      
      break;
    case 'plan':
      //redirect = '/cell-phones/phones/cell-phone-plans/';
      break;
	case 'internet':
      redirect = '/checkout';
      break;
	case 'mobileConnect':
      //redirect = '/internet-home-phone/internet-home-phone-plans/';
      break;
  }
}

/**
* clearCart()
* Clears all the accessories and plans from a cart.
* Should be used when a phone is removed.
**/

function clearCart() {
  if (confirm("Are you sure you want to clear your cart?")) { 
  	$.get("/cart/empty/", {}, reload, "json");
  }
}

function reload() {
	window.location.reload();
}

function getCartForClearComplete(results) {
  $.each(results, function(index, value){    
    switch(value.category) {
      case 'cell-phones':
      case 'accessories':
      case 'cell-phone-plans':
        $.post(removeFromCartUrl, {
          cartitem: value.id,
          quantity: 1
        }, function(){}, "json");
        break;
    };
  });

  redirectOrBuildCart();
}


/**
* buildCart()
* Gets the current cart and updates the HTML accordingly
**/

function buildCart(cartId) {
	
	if (cartId) {
		$.get("/cart/get/?cart_id=" + cartId, {}, getCartForBuildComplete, "json");
	} else {
		$.get("/cart/get/", {}, getCartForBuildComplete, "json");
	}
}

/*
* setAccessories()
* Sets up the accessories page based on the cart
**/

function setAccessories() {
  $.get("/cart/get/", {}, getCartForAccessoriesComplete, "json");
}

function getCartForAccessoriesComplete(results) {
	
	$('.remove').hide();
	$('.addToCart').show();
	
	var phone_slug = $('#wrongPhone').attr('slug');
	
	$.each(results, function(idx, value) {
		
		if (value.category == 'accessories') {
			
			jQuery('#doneAdding').show();
			
			var selector_add = '#acc_add_' + value.product_id;
			var selector_remove = '#acc_remove_' + value.product_id;
		
			jQuery(selector_add).hide();
			jQuery(selector_remove).show();
			jQuery(selector_remove).attr('cart_id', value.id);
			jQuery(selector_remove).attr('slug', value.slug);
		}
		
		if (value.category == 'cell-phones' && value.slug == phone_slug) {
			
			jQuery('#wrongPhone').attr('cart_id', value.id);
			
		}
		
	});
	
}

var cartSectionIds = ['selectedPhones', 'selectedAccessories', 'selectedPlans', 'selectedInternet', 'selectedMobileConnect'];

function getCartForBuildComplete(results) {
  //Empty all the lists
  //$('ul#selectedPhones').empty();
  //$('ul#selectedAccessories').empty();
  //$('ul#selectedPlans').empty();
  //$('ul#selectedInternet').empty();
  //$('ul#selectedMobileConnect').empty();
  
  //Hide the lists
  $('ul.orderingSteps-listed').empty();
  
  //Hide the containers
  $('li.container').hide();
  
  //Empty the pass HTML
  //$('li#passPhonesAccessories').empty();
  //$('li#passPlans').empty();
  //$('li#passModems').empty();
  
  $('li.passList').empty();
  
  var emptyCart = true;
  
  $.each(results, function(index, value){
    
    emptyCart = false;
    
    switch(value.category) {
      case 'cell-phones':
        $('ul#selectedPhones').parent().show();
        addItemHtml('ul#selectedPhones', value.id, value.name, value.slug, 'phone', value.qty);
        addPassItemHtml('li#passPhonesAccessories', value.id, value.name, value.price);
        hardwareTotal += Number(value.price);
        currentPhone = value.slug;
        break;
      case 'accessories':
        $('#doneAdding').show();
        $('ul#selectedAccessories').parent().show();
        addItemHtml('ul#selectedAccessories', value.id, value.name, value.slug, 'accessory', value.qty);
        addPassItemHtml('li#passPhonesAccessories', value.id, value.name, value.price);
        hardwareTotal += Number(value.price);
        break;
      case 'cell-phone-plans':
        $('ul#selectedPlans').parent().show();
        addItemHtml('ul#selectedPlans', value.id, value.name, value.slug, 'plan', value.qty);
        addPassItemHtml('li#passPlans', value.id, value.name, value.price);
        planTotal += Number(value.price);
        break;
      case 'internet-home-phone-plans':
        $('ul#selectedInternet').parent().show();
        $('ul#modemsNotice').show();
		addItemHtml('ul#selectedInternet', value.id, value.name, value.slug, 'internet', value.qty);
        addPassItemHtml('li#passPlans', value.id, value.name, value.price);
        planTotal += Number(value.price);
        break;
      case 'mobile-connect':
        $('ul#selectedMobileConnect').parent().show();
        $('ul#modemsNotice').show();
        addItemHtml('ul#selectedMobileConnect', value.id, value.name, value.slug, 'mobileConnect', value.qty);
        addPassItemHtml('li#passPlans', value.id, value.name, value.price);
        planTotal += Number(value.price);
        break;
    }
    
    $('#plansTotal').text(planTotal.toFixed(2));
    $('#phonesTotal').text(hardwareTotal.toFixed(2));
    
  });
  
  //Display the appropriate cart text
  if (emptyCart) {
    $('#emptyCart').show();
    $('#fullCart').hide();
    $('#printPass').hide();
  } else {
    $('#emptyCart').hide();
    $('#fullCart').show();
    $('#printPass').show();
  }

  $('#id_cart_id').val(results.cart_id);
  
 
}

function addItemHtml(selector, id, name, slug, type, qty) {
  //qtyHtml = '(' + qty + ') ';
  qtyHtml = '';
  removeItemHtml = '<a href="#" onclick="javascript:removeItemFromCart(\'' + id + '\', \'' + type + '\', \'' + slug + '\')" style="display:block;">remove</a></li>';
  removeItemHtml = '<a href="#" onclick="javascript:removeItemFromCartAndReload(\'' + id + '\')" style="display:block;">remove</a></li>'
  
  $(selector).append('<li id="' + id + '"><span></span>' + qtyHtml + cleanCartName(name) + removeItemHtml)
}

function addPassItemHtml(selector, id, name, price) {
  if (name == "Pay As You Go Plan") {
    $("#passPayAsYouGo").show();
  } else {
    $(selector).append('<p>' + name +' $' + price + '</p>');
  }
}

// End buildCart

function addItemToCartAndReload(productSlug) {
	$.post(addToCartUrl, {
	    productname: productSlug,
	    quantity: '1'
	  }, addItemToCartAndReloadComplete, "json");
}

function addItemToCartAndReloadComplete(results) {
	window.location.reload();
}

function removeItemFromCartAndReload(cartItemId) {
	$.post(removeFromCartUrl, {
	    cartitem: cartItemId,
	    quantity: 1
	  }, removeItemFromCartAndReloadComplete, "json");
}

function removeItemFromCartAndReloadComplete(results) {
    window.location.reload();
}

/**
* addItemToCart(productSlug, type)
* Adds an item to the cart, redirects if necessary.
**/
function addItemToCart(productSlug, type, redirect, ignoreBuild) {
  
  if (redirect == undefined) {
    redirect = true;
  }
  
  if (ignoreBuild == undefined) {
    ignoreBuild = false;
  }
  
  if (redirect) {
    getAddRedirect(type, productSlug);
  }
  
  if (ignoreBuild) {
    redirect = "nobuild";
  }
  
  $.post(addToCartUrl, {
    productname: productSlug,
    quantity: '1'
  }, addItemToCartComplete, "json");
}

function addItemToCartComplete(resuls) {
  redirectOrBuildCart();
  //make it flash
  $('.orderingSteps').fadeTo("slow", 0.5);$('.orderingSteps').fadeTo("slow", 1);
}
// End addItemToCart

/**
* removeItemFromCart(cartItemId, type, productSlug)
* Removes an item to the cart, redirects if necessary.
**/
function removeItemFromCart(cartItemId, type, productSlug) {
  
  getRemoveRedirect(type, productSlug);
  
  //if (type == "phone") {
  //  clearCart();
  //  return;
  //}
  
  $.post(removeFromCartUrl, {
    cartitem: cartItemId,
    quantity: 1
  }, removeItemFromCartComplete, "json");
}

function removeItemFromCartComplete(results) {
  redirectOrBuildCart();
  //make it flash
  $('.orderingSteps').fadeTo("slow", 0.5);$('.orderingSteps').fadeTo("slow", 1);
}
// End removeItemFromCart

/**
* redirectOrBuildCart()
* Checks to see if a redirect is set, if so redirect otherwise
* regenerates the cart HTML
**/
function redirectOrBuildCart() {
  if (redirect != undefined) {
    url = redirect;
    redirect = undefined;
    
    if (url != "nobuild") {
      window.location = url;
    }

  } else {
    buildCart();
    setAccessories();
  }
}

function add30PlanToCart() {
  addItemToCart(build30PlanSlug(), 'plan');
}

function add40PlanToCart() {
  addItemToCart(build40PlanSlug(), 'plan');
}

function add50PlanToCart() {
  addItemToCart(build50PlanSlug(), 'plan');
}

function add65PlanToCart() {
  addItemToCart(build65PlanSlug(), 'plan');
}

function build30PlanSlug() {
  slug = '30-a-month-plan';
  toReturn = slug;
  
  toReturn = toReturn + "_" + getOptionSlug(slug, '100r', '100r');
  toReturn = toReturn + "_" + getOptionSlug(slug, 'Data', 'data');
  toReturn = toReturn + "_" + getOptionSlug(slug, 'Dir', 'dir');
  toReturn = toReturn + "_" + getOptionSlug(slug, 'LD', 'ld');
  toReturn = toReturn + "_" + getOptionSlug(slug, 'PM', 'pm');
  toReturn = toReturn + "_" + getOptionSlug(slug, 'TxtDom', 'txtdom');
  toReturn = toReturn + "_" + getOptionSlug(slug, 'TxtInt', 'txtint');
  
  return toReturn;
}

function build40PlanSlug() {
  slug = '40-a-month';
  toReturn = slug;
  
  toReturn = toReturn + "_" + getOptionSlug(slug, '40_100r', '100r');
  toReturn = toReturn + "_" + getOptionSlug(slug, '40_Data', 'data');
  toReturn = toReturn + "_" + getOptionSlug(slug, '40_Dir', 'dir');
  toReturn = toReturn + "_" + getOptionSlug(slug, '40_TxtInt', 'txtint');
  
  return toReturn;
}

function build50PlanSlug() {
  slug = '50-a-month-plan';
  toReturn = slug;
  
  toReturn = toReturn + "_" + getOptionSlug(slug, '50_100r', '100r');
  
  return toReturn;
}

function build65PlanSlug() {
  slug = '65-a-month-plan';
  toReturn = slug;
  
  toReturn = toReturn + "_" + getOptionSlug(slug, '65_100r', '100r');
  
  return toReturn;
}

function getOptionSlug(planSlug, optionId, val) {
  selector = '#' + optionId + '.' + planSlug;
  if ($(selector).is(':checked')) {
    return "u" + val;
  } else {
    return "n" + val;
  }
}

function cleanCartName(name) {
  endIndex = name.indexOf('(');
  
  if (endIndex != -1) {
    return name.substring(0, endIndex - 1);
  }
  
  return name
}

function addIhpPlans(redir) {
  var ihpPlan = $('input.ihp-plan:checked').val();
  var mcPlan = $('input.mc-plan:checked').val();
  
  if (redir) {
	  single = (ihpPlan && mcPlan) ? false : true;
	  
	  if (ihpPlan != undefined) {
	    addItemToCart(ihpPlan, 'ihp-plan', single, single);
	  }
	  
	  if (mcPlan != undefined) {
	    addItemToCart(mcPlan, 'mobileConnect', true, single);
	  }
  } else {
  	  	  
	  if (ihpPlan != undefined) {
	    addItemToCart(ihpPlan, 'ihp-plan', false, false);
	  }
	  
	  if (mcPlan != undefined) {
	    addItemToCart(mcPlan, 'mobileConnect', false, false);
	  }
	  
  }
  
  //redirect = '/cell-phones/phones/vip-pass';
  
  //goToPass();
  
}

function goToPass() {
  $.get(getCartUrl, {}, goToPassComplete, "json");
}

function goToPassComplete(results) {
  count = 0;
  $.each(results, function(){ count++; });
  navigateTo = (count > 0) ? pickupPassUrl : passInfoUrl;
  window.location = navigateTo;
}

$.fn.animateHighlight = function(highlightColor, duration) {
    var highlightBg = highlightColor || "#FFFF9C";
    var animateMs = duration || 1500;
    var originalBg = this.css("backgroundColor");
    this.stop().css("background-color", highlightBg).animate({backgroundColor: originalBg}, animateMs);
};

//Stop caching
$.ajaxSetup({ cache: false });
