// array of items (dish ID) by cart item ID
var cart_items = [];

// array of item prices by cart item ID
var cart_items_prices = [];

// array of item options by cart item ID
var cart_items_options = [];

// array of items (quantity) by cart item ID
var cart_items_qty = [];

// array of items (notes) by cart item ID
var cart_items_notes = [];


// array of items (notes) by cart item ID
var cart_items_errors = [];

var cart_address = "";



function fc_add_item(dish_id, options, quantity, note) {
  var dish = $j("#dish-" + dish_id);
  
  // slide details up, reset dish option choices, notes, quantity back to their defaults
  dish.children(".details").slideUp("normal", function () {
    
    dish.removeClass('selected');
    
    // clearing of options is in a callback so the user doesn't see it
    dish.find("input").each(function () {
      var ids = $j(this).attr("id").split("-");
      if (dishes[ids[0]].options[ids[1]].choices[ids[2]]['default'] === true) {
        $j(this).attr("checked", true);
      } else {
        $j(this).attr("checked", false);
      }
    });
    
    // clear quantity and notes
    $j("#dish-" + dish_id + "_quantity").val("1");
    $j("#dish-" + dish_id + "_notes").val("");
  });
  
  // add up the total price with options
  var price = dishes[dish_id]['price'];
  for (var i in options) {
    var option = options[i];
    price += option.price;
    for (var j in option.choices) {
      var choice = option.choices[j];
      price += choice.price;
    }
  }
  
  // push everything onto arrays
  cart_items.push(dish_id);
  cart_items_prices.push(price);
  cart_items_options.push(options);
  cart_items_qty.push(quantity);
  cart_items_notes.push(note);
  cart_items_errors.push("");

  fc_update_display_cart(true);
  
  $j.post(cobranded_cart_items_path,
    {
      _method: 'post', 
      restaurant_id: restaurant_id, 
      dish_id: dish_id, 
      price: price, 
      options: JSON.stringify(options), 
      quantity: quantity,
      note: note
    },
    function(data) {
      try {
        var obj = JSON.parse(data);
      } catch (err) {
        var obj = data; // under jQuery 1.4, data has already been parsed and the above will fail. in that case, just set obj equal to already-parsed data
      }
      if ("error" in obj){
        cart_items_errors[cart_items.length - 1] = obj.error;
        fc_update_display_cart(false);
      }
    }
  );
}

function fc_del_item(cart_item_id, item) {
  cart_items.splice(cart_item_id, 1);
  cart_items_prices.splice(cart_item_id, 1);
  cart_items_options.splice(cart_item_id, 1);
  cart_items_qty.splice(cart_item_id, 1);
  cart_items_notes.splice(cart_item_id, 1);
  cart_items_errors.splice(cart_item_id, 1);

  item.slideUp("normal", function (){
    fc_update_display_cart(false);
  });

  $j.post(cobranded_cart_items_path + '/' + cart_item_id, { _method: 'delete', id: cart_item_id } );
}

function fc_update_display_cart(pulse_last) {
  // note: some of the cart HTML being updated here is originally generated by 
  // views/cobranded/restaurants/_cart.html.erb
  
  var subtotal = fc_calculate_cart_subtotal();
  
  $j('#items_list').html('');
  $j('#errors_list').html('').hide();
  $j('.in_cart').hide();
  
  for (var i in cart_items) {
    var cart_item_options = cart_items_options[i];
    var cart_item_notes = cart_items_notes[i];
    var last_item = (i == cart_items.length-1);
    
    // mark in_cart indicator
    $j('#dish-' + cart_items[i]  + ' .headline .in_cart:first').show();
    
    // build html for the rest of the options
    var options_html = '';
    if (cart_item_options.length > 0 || cart_item_notes.length > 0) {
      var s = [];
      s.push('<ul class="options">');
      for (var j in cart_item_options) {
        var option = cart_item_options[j];
        s.push('<li class="option">');
        s.push('  <span class="name">' + option.name + '</span>:');
        s.push('  <ul class="choices">');
        for (var k in option.choices) {
          var choice = option.choices[k];
          s.push('<li class="choice">' + choice.name + '</li>');
        }
        s.push('  </ul>');
        s.push('</li>');
      }
      if (cart_item_notes.length > 0) {
        s.push('<li class="notes">');
        s.push('  <span class="name">Notes:</span>');
        s.push('  <span class="choices">\"' + cart_item_notes + '\"</span>');
        s.push('</li>');
      }
      s.push('</ul>');
      options_html = s.join('');
    }
    
    // build html for quantity
    var quantity_html = '';
    if (cart_items_qty[i] > 1) {
      var s = [];
      s.push('<span class="quantity">');
      s.push(  ' &times; ');
      s.push(  cart_items_qty[i]);
      s.push('</span>');
      quantity_html = s.join('');
    }
    
    $j('#items_list').append(
      '<li class="item"' + 
          (last_item ? ' id="last_added_cart_item"' :'') + 
        '>' + 
        '<span class="price">$' + 
          (cart_items_qty[i] * cart_items_prices[i] / 100).toFixed(2) + 
        '</span> ' +
        '<a class="remove button" href="#" onclick="fc_del_item('+ i +', $j(this).parent(\'.item\')); return false;">' +
          '<img src="/images/icons/12-em-cross.png" alt="Remove item from order" title="Remove Item" />' +
        '</a> ' + 

        '<span class="name">' + 
          dishes[cart_items[i]]['name'] + 
        '</span> ' +
        quantity_html +
        options_html +
      '</li>'
    );
    
    //show any errors
    if (cart_items_errors[i] != '') {
      $j('#errors_list').append(
        '<li id="cart_item_error_' + i + '" class="count message" style="color: red">' + cart_items_errors[i] + '</li>'
      ).show();
      $j('#cart_item_error_' + i).effect("highlight", {}, 1000);
    }

    if (pulse_last) {
      $j('#last_added_cart_item').effect("highlight", {}, 2000);
    }
  }
  
  var items_count = $j("#items_list > li.item").length;
  
  // checkout allowance conditions, button enabling/disabling, total line addition/removal
  // no items, minimum not met:  show count, show minimum, hide total, disable button
  // items,    minimum not met:  hide count, show minimum, show total, disable button
  // no items, minimum met:      show count, hide minimum, hide total, disable button
  // items,    minimum met:      hide count, hide minimum, show total, enable button
  
  // no items
  if (items_count < 1) {
    $j('#errors_list').append(
      '<li class="count message">There are currently no items. Please add some!</li>'
    ).show();
  } else { // yes items
    $j('#items_list').append(
      '<li class="total"> Subtotal <span class="price">$' + (subtotal/100).toFixed(2) + '</span></li>'
    );
  }
  
  // minimum not met, but yes items
  if (subtotal < cart_minimum && items_count > 0) {
    $j('#errors_list').append(
      '<li class="minimum message">Add $' + ((cart_minimum - subtotal)/100).toFixed(2) + 
      ' more to meet the $' + (cart_minimum/100).toFixed(2) + ' delivery minimum.</li>'
    ).show();
  }
  
  // no items, minimum not met
  if (items_count < 1 || (subtotal < cart_minimum) || (restaurant_force_closed == 'true')) {
    $j('.cart .buttons .check_out').addClass('disabled');
  } else {
    $j('.cart .buttons .check_out').removeClass('disabled');    
  }
  
  // Scroll to the bottom of items list plus workaround for browsers that scroll the entire document
  // TODO make this work for IE
  if ((cart_items.length > 10) && (!$j.browser.msie)) {
    $j('#items_list').after('<a name="bottom_of_items_list"></a>');
    var scroll_back = document.body.scrollTop;
    document.location.hash = '#bottom_of_items_list';
    document.location.hash = '#dish-' + cart_items[cart_items.length-1];
    document.body.scrollTop = scroll_back;
  }
  
  // show or hide address prompt
  if (cart_address.length == 0 && items_count > 0 && ($j('input[name=order_type]:checked').val() == 'delivery')) {
    $j('#address_prompt').show().effect("pulsate", { times: 2 });
  } else {
    $j('#address_prompt').slideUp();
  }
}

function fc_check_minimum() {
  //display warnings (in the future, this shouldn't be in this function)
  for (var i=0; i < cart_items_errors.length; i++) {
    if (cart_items_errors[i] != "") {
      var fix = confirm("You have errors in your cart.\n\nTo continue without correcting press 'OK'");
      if (fix == false) {
        return false;
      }
      break;
    }
  }
  
  if (cart_items.length == 0) {
    alert(
      'You have no items in your cart. Please add some!'
    );
    return false;
  }
  
  var subtotal = fc_calculate_cart_subtotal();
  
  if (subtotal < cart_minimum) {
    alert(
      'Please add $' + ((cart_minimum - subtotal)/100).toFixed(2) + 
      ' more to meet the $' + (cart_minimum/100).toFixed(2) + ' minimum'
    );
    return false;
  } else {
    return true;
  }
}

function fc_calculate_cart_subtotal() {
  subtotal = 0;
  for (var i in cart_items_prices) {
    subtotal += cart_items_prices[i] * cart_items_qty[i];
  }
  return subtotal;
}

function fc_collect_options(dish_id) {
  var options = new Array();

  // find all this dish option sets for this dish
  $j("#dish-"+dish_id).find(".dish_option").each(function () {
    if($j(this).css('display') != 'none'){ //make sure the dish option is visible.
      option_id = $j(this).attr("id").split("-")[1];
      var option = new Object();

      option['id'] = option_id;
      option.name = dishes[dish_id].options[option_id]['name'];
      option.price = dishes[dish_id].options[option_id].price;
      option.choices = new Object();

      // find all the selected option choices for this set of options
      selected_choices = $j(this).find("input:checked");
      if (selected_choices.length > 0) {
        selected_choices.each(function () {
          choice_id = $j(this).attr("id").split("-")[2];
          option.choices[choice_id] = new Object();
          option.choices[choice_id]['name'] = dishes[dish_id].options[option_id].choices[choice_id]['name'];
          option.choices[choice_id].price = dishes[dish_id].options[option_id].choices[choice_id].price;
        });
        options.push(option);
      }
    }
  });
  return options;
}

function fc_set_address(address) {
  cart_address = address;
  $j.post(cobranded_carts_path + '/' + cart_uuid, { _method: 'put', 'cart[address]': address });
  fc_update_display_cart(false);
}

var cart_orig_left = 0;

// order placement checks and tasks
$j(document).ready(function() {
  // minimum gets checked by onclick handler written into button anchor tag
  // append selected order_type to the query string
  var checkout_button = $j('.cart .buttons .check_out');
  $j('.cart .buttons .check_out, input[name=order_type]').click(function() {
    
    var order_type = $j('input[name=order_type]:checked').val();
    
    // return without doing anything if for some reason order type is not what we expect
    if (order_type != 'delivery' && order_type != 'takeout') { return; }
    
    // TODO: handle params manipulation with jquery bbq
    if (checkout_button.attr("href").match(/&order_type=(\w+)/g) === null) {
      // append cart order type
      checkout_button.attr("href", checkout_button.attr("href") + '&order_type=' + order_type);
    } else {
      // replace cart order type
      checkout_button.attr("href", checkout_button.attr("href").replace(/&order_type=(\w+)/g, '&order_type=' + order_type));
    }
  });
  
  // Enforce correct minimum amount when order type is toggled
  $j('input[name=order_type]').click(function() {
    // Set the right minimum order amount based on order type
    if ($j('input[name=order_type]:checked').val() == 'delivery') {
      cart_minimum = delivery_minimum;
    } else {
      cart_minimum = takeout_minimum;
    }
    
    fc_update_display_cart(false);
  });
});

// cart scrolly
$j(document).ready(function(){
  cart_orig_left = parseInt($j('.cart').css("left"));
});

$j(window).scroll(function(){ 
  if (cart_orig_left > 0 && $j('.cart').css('position') == "fixed") {
    if ($j.browser.msie) {
      var x = document.documentElement.scrollLeft + document.body.scrollLeft;
      $j('.cart').css("left",cart_orig_left - x + "px");
    } else {
      $j('.cart').css("left",cart_orig_left - document.body.scrollLeft + "px");
    }
  }
});
