
function do_cart_add(json){
  if (json[0].success) {
    cart_flyout = $("#cart-flyout");
    cart_flyout.html(json[0].html);
    
    options = 
    {
      overlay: ($.browser.opera) ? 0 : 40,
      onShow: function(h){
        $(".modal").jqm().jqmHide();
        h.w.fadeIn("fast");
      },
      onHide: function(h){
        h.o.remove();
        h.w.fadeOut('500');
      }
    };
    cart_flyout.jqm(options).jqmShow();
    
    if (json[0].target == 'cart_page') {
      if (json[0].newitem_html) {
        $("#cartmain").append(json[0].newitem_html);
        refresh_cart(json[0]);
      } else {
        do_cart_save(json);
      }

    } else {
    	//$("#num_cart_items").html(json[0].num_items);
    	$("#cart").html(json[0].num_items);
	 }
    
    
  } else {
    alert('Error adding item to the cart');
  }
}


function cart_freight(){
  var zip = $("#zip").val();
  //alert("updating cart");
  //var zipc = Number(zip);
  //if (typeof zipc != 'number' || zip != '') {
  //  return;
  //}
  var url = 'cart-process.php?action=freight&zip=' + zip;
  $('#freight_cost').html('Loading <img src="http://media.hertzfurniture.com/js/grey-loading.gif"/>');
  $.getJSON(url, {}, function(json){
    refresh_cart(json[0]);
  });
}

//passed a model_form
function check_quantity(mf,do_alert){
  //do_alert = (do_alert);
  var error = '';
  if (mf.quantity < mf.lowqty) {
    var itemtext = (mf.lowqty > 1) ? ' units' : ' unit';
    error = "There is a minimum order of " + mf.lowqty + " " + itemtext + ".\n";
  }else if (mf.quantity % mf.quantityunit != 0) {
    error = "The quantity must be a multiple of " + mf.quantityunit + ".\n"; 
  }
  
  if ( typeof is_model_page  != 'undefined' && is_model_page && !do_alert) {
    var earrow = ($("#quantity-earrow-"+mf.form_ref).length) ? $("#quantity-earrow-"+mf.form_ref) : $($("#errorarrow").html()).appendTo('body').attr('id', 'quantity-earrow-'+mf.form_ref);
    if (error) {
      earrow.children('p').text(error);
      earrow.css(
      {
        top: $("#purchaseqty").offset().top,
        left: $("#purchase").offset().left - earrow.width() + 10
      }).fadeIn(150);
    } else {
      earrow.fadeOut(150,function(){$(this).remove()});
    }
  }
  
  return error;
}

function check_swatches(mf, do_alert){
	//alert("Ready to check swatches");
  var error = '', allselected = 1,earrow_id, earrow,cont,zindex,is_acc,ieadjust;
  mf.swatches.each(function(){
		 if (!do_alert) {
    	  earrow_id = this.name.replace(/[\[\]]/g,'')+'-earrow-'+mf.form_ref;
		//  alert("Checking " + earrow_id + " val=[" + this.value + "]");
		 }
		 if (do_alert) {
		 	if (this.value == '') {
      	  allselected = 0;
			}

		} else if (this.value == '') {
			//alert("Missing value for swatch" + earrow_id);
      cont = $(this).parents('.swatchsection');
      earrow =  ($("#"+earrow_id).length>0)?$("#"+earrow_id):$($("#errorarrow").html()).appendTo("body").attr('id',earrow_id);
      
      allselected = 0;
      earrow.children('p').text('Please select swatch');
      is_acc = (mf.local_form.children('div.accessoryviewer').length>0) ? 1 : 0;
      zindex = (is_acc)?5000:10;
      //ieadjust = ($.browser.msie)?10:0;
      ieadjust = 0;
      
      earrow.css(
      {
        top: cont.offset().top -.5*earrow.height() +7,
    left:  cont.parents('.swatches').offset().left - earrow.width(),

        "z-index": zindex
      }).fadeIn(150);
      if(is_acc) earrow.addClass('acc-arrow');
      
    } 
  });
  if (!allselected) {
    error = "Selecting all options for this item is required.";
    //error += "Please select all swatches.\n";
  }
  return error;
}


function get_model_form(form_ref){
	var model_details;
	var local_form;
	var q_ele;
  if (form_ref.indexOf('model_') > -1) {
    local_form = $("#" + form_ref), target = 'cart_page', action = 'add';
  	 if (form_ref.indexOf('acc_model_') > -1) {
	 	model_details = local_form;
    } else {
	 	model_details = $("#model_details");
	 }

  } else {
    local_form = $('#cart_item_' + form_ref), action = 'save';
	 model_details = local_form;
  }

  if (form_ref.indexOf('ship_model_') > -1) {
    q_ele = $("input[name='freightqty']", local_form);
  } else {
    q_ele = $("input[name='quantity']", local_form);
  }
  
  return {
    local_form: local_form,
    form_ref: form_ref,
    action: action,
    model_no: $("input[name='model_no']", model_details).val(),
    target: $("input[name='target']", local_form).val(),
    quantity: parseInt(q_ele.val()),
    swatches: $("[name^='swid']", local_form),
    quantityunit: parseInt($("input[name='quantityunit']", model_details).val()),
    lowqty: parseInt($("input[name='lowqty']", model_details).val()),
    stid: $("input[name='stid']", model_details).fieldValue(),
    referid: $("input[name='referid']", model_details).val()
  }
}

// general function for adding and edit/saving items
function save_cart_item(form_ref, do_alert){
  var error = '';
  do_alert = (do_alert);
  if (!do_alert) { do_alert = 0; }
  var mf = get_model_form(form_ref);
  error = check_quantity(mf, do_alert);
  error += check_swatches(mf, do_alert);
  
  if (error != '') {
    if (!is_model_page) {
      alert(error);
    }
    return;
  }
  
  swatch_str = '';
  mf.swatches.each(function(){
    swatch_str += this.name + "=" + this.value + "&";
  });
  
  var url = "/cart-process.php?action=" + mf.action;
  url += (mf.action == 'save') ? "&cart_item_id=" + form_ref : "&model_no=" + mf.model_no;
  url += "&" + swatch_str + "quantity=" + mf.quantity + "&stid=" + mf.stid;
  url += (mf.target == 'cart_page') ? '&target=cart_page' : '';
  if (typeof mf.referid != 'undefined') {
  		url += "&referid=" + mf.referid;
	}
		  //alert("url= " + url);
  
  $.getJSON(url, {}, function(json){
    if (mf.action == 'save') {
      do_cart_save(json);
    } else {
      do_cart_add(json);
    }
  });
}

// - until here - general page - after here checkout
function do_cart_save(json){
  if (json[0].success) {
    // if the cart_item was changed to match a different cart item
    if (json[0].duplicate > 0) {
      $("#cartitem_" + json[0].cart_item_id).fadeOut();
      load_cart_item(json[0].duplicate, 1);
    } else {
      $("#cartitem_" + json[0].cart_item_id).replaceWith(json[0].html);
    }
    refresh_cart(json[0]);

  } else {
    alert('Error saving item in cart.');
  }
}


function reset_cart_item(cart_item_id){
  load_cart_item(cart_item_id, 1);
}

function load_cart_item(cart_item_id, reset){
  var edit = (reset == 1) ? '&edit=0' : '';
  var cart_item = $("#cartitem_" + cart_item_id);
  
  var url = '/cart-process.php?action=load&cart_item_id=' + cart_item_id + edit;
  
  $.getJSON(url, {}, function(json){
    if (json[0].success) {
      cart_item.replaceWith(json[0].html);
    } else {
      success = false;
      alert('Error loading item.');
    }
  });
}

function confirm_delete(cart_item_id, delete_item_text){

  $("#delete_item_text").html(delete_item_text);
  $('#do_remove_cart_item').unbind('click').click(function(){
    delete_from_cart(cart_item_id);
    $('#deleteprompt').jqmHide();
    return false;
  });
  
  $('#deleteprompt').jqm().jqmShow();
}

function delete_from_cart(cart_item_id){
  var cart_item = $("#cartitem_" + cart_item_id);
  var url = '/cart-process.php?action=delete&cart_item_id=' + cart_item_id;
  $.getJSON(url, {}, function(json){
    if (json[0].success) {
      cart_item.css(
      {
        border: "1px solid red",
        background: "#FBE6F2"
      }).fadeOut(1000);
      refresh_cart(json[0]);
    } else {
      success = false;
      alert('Error deleting item from cart.');
    }
  });
}

function refresh_cart(json){
  
  if (json.freight_text) {
    $("#calculatefreight").html(json.freight_text);
  }

  if (json.subtotal_text) {
    $("#sub_total").html(json.subtotal_text);
  }
  if (! json.success) {
	  return;
  }

  if (typeof json.num_items != 'undefined') {
    $("#cart").html(json.num_items);
  }

  $("#googlecart").load("/gcart.php");
}

$(function(){
   $("h3.accessory_expand").livequery('click', function(){
    if ($(this).hasClass('activeaccessory')) {
      $(this).removeClass('activeaccessory').text('Click here to show accessories for this product').next(".cartitemaccessories").slideUp();
    } else {
      $(this).addClass('activeaccessory').text('Click here to hide accessories for this product').next(".cartitemaccessories").slideToggle();
    }
  });
});

