jQuery(document).ready(function() {
  //Declare Ajax Queue variable
  var cartQueue = jQuery.manageAjax.create('cartAjaxQueue', { queue: true, cacheResponse: false });
  /*if(!jQuery.browser.mozilla){
    jQuery.get('/shopping_carts/get_cart/', function(data){
      emptyCart();
      eval(data);
    });
  }*/
  if(!jQuery.browser.mozilla){
    var ajax_rand = (Math.floor(Math.random()*101));
    emptyCart();
    jQuery.get('/shopping_carts/get_qty_json/'+ajax_rand, function(data){
      jQuery('#total_quantity').html('Total ('+data+')');
    });
    jQuery.get('/shopping_carts/get_cart_json/'+ajax_rand, function(data){
      jQuery('#shopping_cart').append(data);
    });
    jQuery.get('/shopping_carts/get_total_json/'+ajax_rand, function(data){
      jQuery('#total_price').html(data);
    });
  }
});

if(jQuery.browser.mozilla){
  jQuery(window).bind('pageshow',function(){
    emptyCart();
    jQuery.get('/shopping_carts/get_cart_json/', function(data){
      jQuery('#shopping_cart').append(data);
    });
    jQuery.get('/shopping_carts/get_qty_json/', function(data){
      jQuery('#total_quantity').html('Total ('+data+')');
    });
    jQuery.get('/shopping_carts/get_total_json/', function(data){
      jQuery('#total_price').html(data);
    });
  });
}

function emptyCart(){
  jQuery('#total_price').html('0.00');
  jQuery('#total_quantity').html('Total (0)');
  jQuery('.cart_row').remove();
}

function checkOut() {
	var gguc = jQuery(document).data('gguc');
  if(gguc=='no'){
    quickAccount();
    return false;
  }
  var totalPriceHtml = jQuery('#total_price').html();
  var giftOnly = checkGiftOnly();
  totalPriceHtml = parseFloat(totalPriceHtml.replace('$', ''));
  //totalPriceHtml = totalPriceHtml.substring(1);
  if(totalPriceHtml >= 40 || giftOnly || gguc == 'nocap'){
     //window.location="/orders/checkout";
	 window.location="/checkout/wizard";
  }
  else { 
    jQuery.fn.colorbox({
      href:'/orders/minimum_order',
      width: 520,
      height: 190,
      scrolling: false
    });
  }
}

function checkGiftOnly(){
  if(jQuery('.gift').length && !jQuery('.itemInfo').length && !jQuery('.meal').length){
    return true;
  }
  return false;
}

function removeItem(id) {
  var qtyId = '#item_qty_' + id;
  var qtyHtml = jQuery(qtyId).html();
  var qty = parseInt(qtyHtml);
  //qty = qty * -1;
  var priceId = '#item_price_' + id;
  var priceHtml = jQuery(priceId).html();
  
  priceHtml = priceHtml.substring(1);
  
  var currentPrice = parseFloat(priceHtml); 
  
  currentPrice = currentPrice * -1;
  updateTotal(qty, currentPrice);
  //Remove item from the Cart session
  removeItemFromSession(id, priceHtml)
  jQuery('#item_' + id).remove();
}

function increaseItemQuantity(id, price, qty) {
   var qtyId = '#item_qty_' + id;
   var qtyHtml = jQuery(qtyId).html();

   qtyHtml = parseInt(qtyHtml) + parseInt(qty);
   jQuery(qtyId).html(qtyHtml);
   
   price = qty * price;

   // need to make ajax call to server and update

   updateItemPrice(id, price);
   updateItemQtySession(id, qtyHtml);
}

function decreaseItemQuantity(id, price) {
   var qtyId = '#item_qty_' + id;
   var qtyHtml = jQuery(qtyId).html();
   var qty = parseInt(qtyHtml);
   
   if (qty > 1) {
        qtyHtml = parseInt(qtyHtml) - 1;
      jQuery(qtyId).html(qtyHtml);
    var negPrice = price * -1;
      updateItemPrice(id, negPrice);
   }

   // need to make ajax call to server and update
   updateItemQtySession(id, qtyHtml)
}

function addItemToSession(id, qty) {
  jQuery('div.loadingCart').show();
  jQuery.manageAjax.add('cartAjaxQueue', { 
    url: "/shopping_carts/addItem/" + id + "/" + qty,
    success: function() {
      updateCartSessionTotals();
    }
  });
}

function updateItemQtySession(id, qty) {  
   jQuery('div.loadingCart').show();
   jQuery.manageAjax.add('cartAjaxQueue', { 
     url: "/shopping_carts/qtyChange/" + id + "/" + qty,
     success: function() {
        updateCartSessionTotals();
    }
   });
}

function removeItemFromSession(id) {  
   jQuery('div.loadingCart').show();
   jQuery.manageAjax.add('cartAjaxQueue', { 
     url: "/shopping_carts/removeItem/" + id,
     success: function() {
      updateCartSessionTotals();
    }
   });
}

function updateItemPrice(id, price) {
   var priceId = '#item_price_' + id;
   var priceHtml = jQuery(priceId).html();

   priceHtml = priceHtml.substring(1);

   var curPrice = parseFloat(priceHtml);
   // need to grab this price from server
   curPrice = parseFloat(curPrice) + parseFloat(price);
   curPrice = curPrice.toFixed(2);
   jQuery(priceId).html('$' + curPrice);
   
   //update the total
   updateTotal(1, price);
}

function updateTotal(amount, price) { 
  var totalHtml = jQuery('#total_quantity').html();
  var qty = totalHtml.substring(7, totalHtml.indexOf(')'));
  
  qty = parseInt(qty);
  amount = parseInt(amount);
  
  if (price > 0) {
    qty = qty + amount;
  }
  else {
    qty = qty - amount;
  }
  
  jQuery('#total_quantity').html('Total (' + qty + ')');
  
  var totalPriceHtml = jQuery('#total_price').html();
  
  totalPriceHtml = totalPriceHtml.substring(1);
  
  var totPriceFloat = parseFloat(totalPriceHtml);
  
  totPriceFloat = totPriceFloat + parseFloat(price);
  totPriceFloat = totPriceFloat.toFixed(2);
  jQuery('#total_price').html('$' + totPriceFloat);
}

function addToCart(info){
  if(jQuery(document).data('gguc')=='no'){
    quickAccount();
    return false;
  }
  if(info.type === undefined){
    return false;
  } else {
    switch(info.type){
      case 'gift':
        addGiftToCart(info);
      break;
      case 'item':
        addItemToCart(info);
      break;
      case 'meal':
        addMealToCart(info);
      break;
    }
  }
}

/*****************************************
**      ADDING ITEM TO CART     **
**  Needs:                **
**    ID: Database ID         **
**    Name: Name of Item        **
**    Price: Price of Item      **
**    Image: Image of Item      **
**    Qty: Amount to add        **
******************************************/
function isnum(n){
  return !isNaN(parseFloat(n)) && isFinite(n);
}

function addItemToCart(info){
  if(parseInt(info.id) <= 0){
    alert('There was an error adding this item to your cart.');
    return;
  }
  if(parseInt(info.qty) <= 0){
    alert('Quantity must be more than zero.');
    return;
  }
  if(!isnum(parseInt(info.qty))){
    alert('Quantity must be a number.');
    return;
  }
  info.qty = parseInt(info.qty);

  //check to see if its already in the cart
  existing = jQuery('#item_'+info.id).html();
  if(existing != null){
    increaseItemQuantity(info.id, info.price, info.qty);
  } else {
    jQuery("#shopping_cart").append(
      "<tbody id='item_" + info.id + "'>\
        <tr>\
          <td colspan='4' style='border:none'>\
            <input type='image' src='/img/removeBtn.gif' class='removeBtn' onclick='removeItem(" + info.id + ");'/>\
            <a class='itemName' href='#'>" + info.name + "</a>\
          </td>\
        </tr>\
        <tr class='itemInfo'>\
          <td>\
            <img src='/attachments/photos/small/" + info.image + "' />\
          </td>\
          <td id='item_qty_" + info.id + "'>" + info.qty + "</td>\
          <td>\
            <input type='image' src='/img/plusBtn.gif' class='' onclick='increaseItemQuantity(" + info.id + ", " + info.price + ", 1);'/>\
            <input type='image' src='/img/minusBtnActive.png' class='' onclick='decreaseItemQuantity(" + info.id + ", " + info.price + ");'/>\
          </td>\
          <td class='price' id='item_price_" + info.id +"'>$" + (info.price*info.qty).toFixed(2) + "</td>\
        </tr>\
      </tbody>"
    );

    updateTotal(info.qty, (info.price*info.qty));
    addItemToSession(info.id, info.qty);
  } 
}

/*****************************************
**    ADDING GIFT CARD TO CART    **
**  Needs:                **
**    ID: Database ID         **
**    Name: Name of Gift Card     **
**    Image: Image of Gift Card   **
**    Price: Amount of the gc     **
**    Qty: Name of Item       **
******************************************/
function addGiftToCart(info){
  for(i=0;i<info.qty;i++){
    var gid = jQuery('.gift:last').attr('id');
    if(gid != null){
      giftId = parseInt(gid.split("_")[1]) + 1;
    } else {
      giftId = 1;
    }
    var price = info.price.replace('$','');
    //alert(price);
    price = Math.abs(parseInt(price));

    if(price < 25){
      alert('Sorry, the minimum amount for a gift certificate is $25.');
      return false;
    }
    
    jQuery("#shopping_cart").append(
      "<tbody id='gift_" + giftId + "' class='gift'>\
        <tr>\
          <td colspan='4'>\
            <input type='image' src='/img/removeBtn.gif' class='removeBtn' onclick='removeGift(" + giftId + ", " + price.toFixed(2) + ", " + info.id + ");'/>\
            <a class='itemName' href='#'>" + info.name + "</a>\
          </td>\
        </tr>\
        <tr class='giftInfo'>\
          <td>\
            <img src='/attachments/photos/small/" + info.image + "' />\
          </td>\
          <td>&nbsp;</td>\
          <td>\
          </td>\
          <td class='price' id='gift_price_" + giftId +"'>$" + price + "</td>\
        </tr>\
      </tbody>"
    );
    updateTotal(1, price);
    addGiftToSession(info.id, price.toFixed(2), info.qty);
  }
}

function addGiftToSession(id, amount, qty) {
  jQuery('div.loadingCart').show();
  jQuery.manageAjax.add('cartAjaxQueue', { 
    url: "/shopping_carts/addGift/" + id + "/" + amount + '/' + qty,
    success: function(data) {
      updateCartSessionTotals();
    }
  });
}


function removeGift(id, price, dbid){
  var priceId = '#gift_price_' + id;
  var priceHtml = jQuery(priceId).html();
  
  priceHtml = priceHtml.substring(1);
  
  var currentPrice = parseFloat(priceHtml); 
  
  currentPrice = currentPrice * -1;
  updateTotal(1, currentPrice);
  //Remove item from the Cart session
  removeGiftFromSession(dbid, price)
  jQuery('#gift_' + id).remove();
}

function addMealToCart(info) {
  // info:
  //   id:entree id
  //   name:string
  //   image:url
  //   price:number
  //   quantity:number
  //   sides:array
  //     id:side id
  //     name:string
  //     image:url

  // validate info
  var entree = info.id;
  var sides = info.sides;
  var name = info.name;
  var image = info.image;
  var price = info.price;
  var quantity = info.quantity;
  
  if (entree === undefined || sides === undefined) {
    return;// throw error
  } 
  
  var sl = sides.length;
  var missingSide = false;
  for (var i = 0; i < sl; i++) {
    if (sides[i] == null) {
      missingSide = true;
      break;
    }
  }
  if (missingSide) {
    alert("You must select 2 sides.");
    return;
  }
  
  // Check if an equivilent meal exists in Shopping Cart
  var foundMeal = false;
  jQuery(".meal").each(function(index){
    var meal = jQuery(this);
    if (meal.attr("entreeid") == entree) {
      var mealSides = meal.attr("sideids").split(",");
      var sideCount = mealSides.length;
      var mat = true;
      if (sideCount == sides.length) {
        for (var i = 0; i < sideCount; i++) {
          var idx = jQuery.inArray(sides[i].id, mealSides);
          if (idx != -1) {
            mealSides.splice(idx,1);
          } else {
            mat = false;
            break;
          }
        }
      }
      if (mat) {
        foundMeal = meal;
      }
    }
  });
  
  if (foundMeal) {
    increaseMealQuantity(foundMeal.attr("id").split('_')[1], price, parseInt(quantity));
  } else {
    var mid = jQuery('.meal:last').attr('id');
    var mealId = 1;
    if(mid != null){
      mealId = parseInt(mid.split("_")[1]) + 1;
    }
    
    var sidestring = "";
    var firstside = true;
    
    var slen = sides.length;
    for (var i=0;i<slen;i++) {
      var s = sides[i];
      if (firstside) {
         firstside = false;
      } else {
         sidestring += ",";
      }
      sidestring += s.id;
    }
    
    var sidesHtml = "";
    
    for (var i=0; i<slen;i++) {
      var s = sides[i];
      sidesHtml += "<tr class='sideInfo'>\
        <td>\
          <img src='/attachments/photos/small/" + s.image + "' class='meal_side_img'></img>\
        </td>\
        <td colspan='3'>\
          " + s.name + "\
        </td>\
      </tr>";
    }
  
    jQuery("#shopping_cart").append(
      "<tbody id='meal_" + mealId + "' entreeid='" + entree + "' sideids='" + sidestring + "' class='meal'>\
        <tr>\
          <td colspan='4'>\
            <input type='image' src='/img/removeBtn.gif' class='removeBtn' onclick='removeMeal(" + mealId + ");'/>\
            <a class='itemName' href='#'>" + name + "</a>\
          </td>\
        </tr>\
        <tr class='entreeInfo'>\
          <td>\
            <img src='/attachments/photos/small/" + image + "' />\
          </td>\
          <td id='meal_" + mealId + "_qty'>" + quantity + "</td>\
          <td>\
            <input type='image' src='/img/plusBtn.gif' class='' onclick='increaseMealQuantity(" + mealId + ", " + price + ", 1);'/>\
            <input type='image' src='/img/minusBtnActive.png' class='' onclick='decreaseMealQuantity(" + mealId + ", " + price + ", 1);'/>\
          </td>\
          <td class='price' id='meal_" + mealId + "_price'>$" + (price*quantity).toFixed(2) + "</td>\
        </tr>\
        " + sidesHtml + "\
      </tbody>");

    updateTotal(quantity, price*quantity);
    addMealToSession(entree, sidestring, quantity);

  }
}

function removeMeal(id) {
  var qtyId = '#meal_' + id + '_qty';
  var qtyHtml = jQuery(qtyId).html();
  var qty = parseInt(qtyHtml);
  //qty = qty * -1;
  var priceId = '#meal_' + id + '_price';
  var priceHtml = jQuery(priceId).html();
  
  priceHtml = priceHtml.substring(1);
  
  var currentPrice = parseFloat(priceHtml); 
  
  currentPrice = currentPrice * -1;
  updateTotal(qty, currentPrice);

  var meal = jQuery('#meal_' + id);
  var entreeid = meal.attr('entreeid');
  var sides = meal.attr('sideids');
  removeMealFromSession(entreeid, sides);
  meal.remove();
}


function increaseMealQuantity(id, price, byQty) {
  var qtyId = '#meal_' + id + '_qty';
  var qtyHtml = jQuery(qtyId).html();
  
  qtyHtml = parseInt(qtyHtml) + byQty;
  jQuery(qtyId).html(qtyHtml);

  var meal = jQuery('#meal_' + id);
  var entreeid = meal.attr('entreeid');
  var sides = meal.attr('sideids');

  updateMealPrice(id, price);
  updateMealQtySession(entreeid, sides, qtyId);
}

function decreaseMealQuantity(id, price, byQty) {
  var qtyId = '#meal_' + id + '_qty';
  var qtyHtml = jQuery(qtyId).html();
  var qty = parseInt(qtyHtml);
   
  if (qty > 1) {
    qtyHtml = parseInt(qtyHtml) - byQty;
      jQuery(qtyId).html(qtyHtml);
    var negPrice = price * -1;
      updateMealPrice(id, negPrice);
  } else if (qty == 1) { 
    removeMeal(id);
    return;
  }
  
  var meal = jQuery('#meal_' + id);
  var entreeid = meal.attr('entreeid');
  var sides = meal.attr('sideids');

  // need to make ajax call to server and update
  updateMealQtySession(entreeid, sides, qtyId);
}

function updateMealPrice(id, price) {
  var priceId = '#meal_' + id + '_price';
  var priceHtml = jQuery(priceId).html();

  priceHtml = priceHtml.substring(1);

  var curPrice = parseFloat(priceHtml);
  // need to grab this price from server
  curPrice = parseFloat(curPrice) + parseFloat(price);
  curPrice = curPrice.toFixed(2);
  jQuery(priceId).html('$' + curPrice);
   
  //update the total
  updateTotal(1, price);
}

function addMealToSession(entreeid, sides, quantity) {
  // takes the entree id, the comma separated sides, and the price
  // and sends an ajax to the server that adds the meal to the session.

  var sidestring = convertCommasToDashes(sides);
  
  jQuery('div.loadingCart').show();
  jQuery.manageAjax.add('cartAjaxQueue', {
    url: "/shopping_carts/addMeal/" + entreeid + "/" + sidestring + "/" + quantity,
    success: function() {
      updateCartSessionTotals();
    }
  });
}

function removeMealFromSession(entreeid, sides) {
  var sidestring = convertCommasToDashes(sides);
  
  jQuery('div.loadingCart').show();
  jQuery.manageAjax.add('cartAjaxQueue', {
    url: "/shopping_carts/removeMeal/" + entreeid + "/" + sidestring,
    success: function() {
      updateCartSessionTotals();
    }
  });
}

function updateMealQtySession(entreeid, sides, qtyId) {
  var sidestring = convertCommasToDashes(sides);

  var qty = jQuery(qtyId).html();
  jQuery('div.loadingCart').show();
  jQuery.manageAjax.add('cartAjaxQueue', {
    url: "/shopping_carts/updateMealQty/" + entreeid + "/" + sidestring + "/" + qty,
    success: function() {
      updateCartSessionTotals();
    }
  });
}

function convertCommasToDashes(commaString) {
  var result = "";
  var first = true;
  var splitcommas = commaString.split(',');
  var clen = splitcommas.length;
  for (var i=0;i<clen;i++) {
    var s = splitcommas[i];
    if (first) {
       first = false;
    } else {
       result += "-";
    }
    result += s;
  }
  
  return result;
}


function removeGiftFromSession(id, price){
   jQuery('div.loadingCart').show();
   jQuery.manageAjax.add('cartAjaxQueue', { 
     url: "/shopping_carts/removeGift/" + id + "/" + price,
     success: function() {
      updateCartSessionTotals();
    }
   });
}

//Update the cart session after each item updates

function updateCartSessionTotals() {
   var totalHtml = jQuery('#total_quantity').html();
   var qty = totalHtml.substring(7, totalHtml.indexOf(')'));
   var totalPriceHtml = jQuery('#total_price').html();
   var price = totalPriceHtml.substring(1);

   jQuery.ajax({
    type: 'POST',
    url: "/shopping_carts/updateTotal/" + qty + "/" + price
  });
   jQuery(".loadingCart").ajaxStop(function(){
     $(this).hide();
   });

}

//Load shopping cart data

function loadCart(id, price, name, url, qty) {
  jQuery("#shopping_cart").append(
    "<tbody id='item_" + id + "' class='cart_row'>\
      <tr>\
        <td colspan='4'>\
          <input type='image' src='/img/removeBtn.gif' class='removeBtn' onclick='removeItem(" + id + ");'/>\
          <a class='itemName' href='#'>" + name + "</a>\
        </td>\
      </tr>\
      <tr class='itemInfo'>\
        <td>\
          <img src='" + url + "' />\
        </td>\
        <td id='item_qty_" + id + "'>" + qty + "</td>\
        <td>\
          <input type='image' src='/img/plusBtn.gif' class='' onclick='increaseQuantity(" + id + ", " + price + ");'/>\
          <input type='image' src='/img/minusBtnActive.png' class='' onclick='decreaseQuantity(" + id + ", " + price + ");'/>\
        </td>\
        <td class='price' id='item_price_" + id +"'>$" + (price*qty).toFixed(2) + "</td>\
      </tr>\
    </tbody>"
  );
}
