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

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 = '/cell-phones/phones/vip-pass';
      break;
    case 'mc-plan-redir':
      redirect = '/cell-phones/phones/vip-pass';
      break;
    case 'internet':
      redirect = '/cell-phones/phones/vip-pass';
      break;
	case 'mobileConnect':
      redirect = '/cell-phones/phones/vip-pass';
      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 = '/internet-home-phone/internet-home-phone-plans/';
      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() {
  $.get("/cart/empty/", {}, redirectOrBuildCart, "json");
}

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() {
  $.get("/cart/get/", {}, getCartForBuildComplete, "json");
}

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

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

function addPassItemHtml(selector, id, name, price) {
  $(selector).append('<p>' + name +' $' + price + '</p>');
}

// End buildCart

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

function addItemToCartComplete(resuls) {
  redirectOrBuildCart();
}
// 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();
}
// 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;
    window.location = url;
  } else {
    buildCart();
  }
}

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

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

function add50PlanToCart() {
  addItemToCart(build50PlanSlug(), '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, '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_TxtInt', 'txtint');
  
  return toReturn;
}

function build50PlanSlug() {
  slug = '50-a-month-plan';
  toReturn = slug;
  
  toReturn = toReturn + "_" + getOptionSlug(slug, '50_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) {
  addItemToCart($('input.ihp-plan:checked').val(), 'ihp-plan');
  addItemToCart($('input.mc-plan:checked').val(), 'mc-plan');

}

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

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