//The bulk of the shopping cart logic is contained on this page
/************SETTING UP CONSTANTS*************************/
function trim(str) {
	return str.replace(/^\s+|\s+$/g,"");
}
//COUPON CODE STUFF
var promo = false;

var storeDomain = foxyStoreDomain;

var	uniqueKey = '';
function set_unique_key(key)
{
	uniqueKey = key;
}
function get_unique_key()
{
	return uniqueKey;
}

var edit_id = "";
function get_edit_id()
{
	return edit_id;
}
function set_edit_id(product_id)
{
	edit_id = product_id;
}

var total = 0;
function get_total()
{
	return total;
}
function set_total(amount)
{
	total = amount;
}

var CONST_TaxName = "Sales Tax";
var tax_rate = .0925;
var sales_tax = 0;
function get_sales_tax()
{
	return sales_tax;
}
function set_sales_tax(amount)
{
	sales_tax = amount;
}

var CONST_ShippingItemName = "ModerNash Shipping Cost";
var shipping_cost = 0;
function get_shipping_cost()
{
	return shipping_cost;
}
function set_shipping_cost(amount)
{
	shipping_cost = amount;
}

var subtotal = 0;
function get_subtotal()
{
	return subtotal;
}
function set_subtotal(amount)
{
	subtotal = amount;
}

var delivery_zipcode = "";
function get_delivery_zipcode()
{
	return delivery_zipcode;
}
function set_delivery_zipcode(code)
{
	delivery_zipcode = code;
}

var CONST_DirectDeliveryItemName = "Home Delivery";
var direct_delivery =0;
function get_direct_delivery()
{
	return direct_delivery;
}
function set_direct_delivery(amount)
{
	direct_delivery = amount;
}

var transaction_status = false;
var transaction_type = "";
function get_transaction_status()
{
	return transaction_status;
}
function get_transaction_type()
{
	return transaction_type;
}
function set_transaction_status(status, type){
	if (status === false){
		//UNLOCK THE CART
		$("#cart_busy").fadeOut();
		$("#mn_cart_cover").fadeOut();
		$(".cart_processing").fadeOut(function(){
			$(".submit").show();
		});
	
	//$('#statusProgress').html("<span id='percent'>93.5%</span>"+"<span id='top'>scanning Ikea&hellip;</span>");
			
	 	$('#ProductUrl').val('');
		/*
	 		REMOVE PROGRESS BAR IFRAME
 		*/
 		$('#commentiframe').attr('src', '');
 		$('#commentiframe').remove();
		if (type == "edit")
		{
			edit_id = "";
		}
		transaction_status = false;
		transaction_type = "";
	}
	else if (status === true)
	{
		//LOCK DOWN THE CART
		$("#cart_busy").fadeIn();
 		$("#mn_cart_cover").fadeIn();
		
		transaction_status = true;
		transaction_type = type;
		if (type == "add")
		{
			$('#statusProgressBar').css("width", "0px");
			$('#statusProgress').html("");
			$(".submit").hide(function(){
				//show progress bar and ajax loader
				$(".cart_processing").fadeIn();
			});
			/*
		 		LOAD PROGRESS BAR IFRAME FOR IKEA SCRAPE AND DATABASE ADD
		 	*/
		 	$('#iFrameHolder').append('<iframe id="commentiframe" style="height:1px;width:1px;border:none;"/>'); 
		  	$('#commentiframe').attr('src', '/products/progress/'+uniqueKey);
		}
	}
}

function fc_AddSession(fc_json) {
	fc_json = typeof(fc_json) != 'undefined' ? fc_json : false;
sessionName = "fcsid";
sessionString = "";
fc_regex = /#fcsid=([A-Za-z0-9]*)/;
if (fc_regex.test(window.location.href)) { // check for the session in the URL, overwrite any existing session
fc_match = fc_regex.exec(window.location.href);
// reset the cookie
sessionString = fc_match[1];
fc_CookieSet(sessionName, sessionString);
} else if (document.cookie.indexOf(sessionName + "=") > -1) { // retrieve the session from the cookie
c_start=document.cookie.indexOf(sessionName + "=");
if (c_start != -1) {
c_start = c_start + sessionName.length + 1;
c_end = document.cookie.indexOf(";",c_start);
if (c_end == -1) {
c_end = document.cookie.length;
}
sessionString = unescape(document.cookie.substring(c_start,c_end));
}
} else if (fc_json) { // retrieve the session from the JSON, set a cookie
// set a cookie for next time
sessionString = fc_json.session_id;
fc_CookieSet(sessionName, sessionString);
}
if (sessionString != "") {
return "&fcsid=" + sessionString;
} else {
return "";
}
};
function fc_CookieSet(sessionName, sessionString) {
// get this domain with no subdomain
//alert(sessionName+", "+sessionString);
domain = window.location.href.split('/');
domain = domain[2];
pos1 = domain.lastIndexOf(".");
pos2 = domain.lastIndexOf(".",pos1-1);
if (pos2 > 1) {
	domain = domain.substr(pos2);
} 
else {
	domain = "." + domain;
}
document.cookie = sessionName + "=" + escape(sessionString) + ";path=/;domain="+domain;
return true;
}

function update_checkout_link(sessionString)
{
	couponCode = "&coupon=BLKFRDY";
	checkout_url = $("#checkoutNow a").attr('href');
	checkout_url = checkout_url+sessionString+couponCode;
	$("#checkoutNow a").attr('href', checkout_url);
}

$(document).ready(function(){
	$.getJSON("http://"+storeDomain+"/cart?output=json&cart=view&callback=?",
	function(fc_json){
		sessionString = fc_AddSession(fc_json);
		update_checkout_link(sessionString);
	});
	key = generate_unique_key(15);
	set_unique_key(key);
	/* ADD TO CART *****************************************************************************/
		//Invoke function when a URL is submitted via the text field and form
	$('#ProductAddForm').submit(function(){
		if (trim($('#ProductUrl').val()).length != 0)
		{
			if (get_transaction_status() == false)			//Make sure no other transactions are in progress
			{
				set_transaction_status(true, "add");		//Begin an add transaction
				var product_url = $('#ProductUrl').val();
				add_to_cart(product_url);
			}
		}
	
		return false;									//Prevents form from submitting via HTML
	});
	/******************************************************************************************/
	
	/* CLICKABLE, TYPEABLE ACTIONS ************************************************************/
	$('.addToCart').live("click", function(){
 		addSelectedProduct($(this).attr("url"));
 	});
 	
 	$('.cancelAdd').live("click", function(){
 		tb_remove();
		type = get_transaction_type();
		set_transaction_status(false, type);
 	});
 	
 	$('.editItem').live("click", function(){
 		var product_id = $(this).attr("product_id");
 		set_edit_id(product_id);
		set_transaction_status(true, "edit");
 		show_variations_select(product_id);
 	});
 	
 	$('.removeFromCart').live("click", function(){
		set_transaction_status(true, "remove");
 		update_quantity($(this).attr("product_id"), 0);
 	});
 	
 	var delayed;
 	$('.quantity_input').live("keyup", function(){
 		clearTimeout(delayed); 
 		var quantity = $(this).val(); 
 		//make sure quantity is numeric
 		if (quantity != "")
 		{
 			if (parseInt(quantity) == quantity)
 			{
 				var product_id = $(this).attr("product_id");
 
 					delayed = setTimeout(function() { 
						set_transaction_status(true, "quantity");
 				  		update_quantity(product_id, quantity);
 						$("#quantity_input_"+product_id).blur();
 				         }, 700); 
 				quantity_entered = false;
 			}
 			else
 			{
 				if (quantity_entered == false)
 				{
 					alert("Please enter a number");
 					quantity_entered = true;
 				}
 			}
 		}
 	});
 	
 	var zipcode_delayed;
 	$('#zipcode').live("keyup", function(){
 		clearTimeout(zipcode_delayed); 
 		var entered_zip = $(this).val(); 
 		//make sure quantity is numeric
 		if (entered_zip != "")
 		{
 			if (parseInt(entered_zip) == entered_zip)
 			{
 				if (entered_zip.length == 5)
 				{
 					zipcode_delayed = setTimeout(function() {
					set_transaction_status(true, "add_DD");
					if (is_valid_zipcode(entered_zip) == true)
					{
						set_delivery_zipcode(entered_zip);
						update_foxy_direct_delivery(entered_zip);
					}
					else
					{
						alert("MN does not ship to that zipcode");
						set_transaction_status(false, "add_DD");
						$("#zipcode").val("");
					}
 					$("#zipcode").blur();
 				    }, 500);	
 				}	
 			}
 			else
 			{
 				set_current_zipcode("");
 				alert("Please enter a valid zipcode");
 			}
 		}
 	});
 	
 	$('#removeDD').live("click", function(){
 		$("#zipcode_input_wrap").show();
 		$("#direct_delivery_display").hide();
		set_transaction_status(true, "remove_DD");
 		set_delivery_zipcode("");
 		update_foxy_direct_delivery();
 	});
 	
 	$('.assembleItem').live("keyup", function(){
 		var product_id = $(this).attr("product_id");
 		add_assembly(product_id);
 	});
	/*******************************************************************************************/

	/*	REBUILD CART BASED ON FOXYCART DATA */
	cart_empty = false;
	$.getJSON("http://"+storeDomain+"/cart?output=json&cart=view&callback=?" + fc_AddSession(),
	function(fc_json)
	{
		if (fc_json.products.length == 0)
		{
			cart_empty = true;
		}
		else
		{
			for (var i=0; i<fc_json.products.length; i++)
	 		{
	 			if (fc_json.products[i].name == CONST_ShippingItemName && fc_json.products.length == 1)//If only shipping is left in the cart
	 			{	
					cart_empty = true;
				}
				if (fc_json.products[i].name == CONST_DirectDeliveryItemName && fc_json.products.length == 2)//Only shipping and direct delivery are left
				{	
					cart_empty = true;
				}
	 		}	
		}
		if (cart_empty == false)
		{
			rebuild_cart();
		}
		else
		{
			empty_foxycart();
			empty_local_cart();
			set_transaction_status(false, "");
		}
	});
	
	/*****************************************************************************************/
	$("#ProductUrl").focus();
});

//VALIDATED
function rebuild_cart()
{
	set_transaction_status(true, "loading");
	$.getJSON("http://"+storeDomain+"/cart?output=json&cart=view&callback=?" + fc_AddSession(),
		function(data){
			set_total(data.total_price);
			//update_cart_quantity(data.product_count);
			var j=0;
			for (var i=0; i<data.products.length; i++)
			{
				j = j+1;
				if (data.products[i].name == CONST_DirectDeliveryItemName)
				{
					set_direct_delivery(data.products[i].price);
					set_delivery_zipcode(data.products[i].code);
				}
			
				if (data.products[i].name == CONST_ShippingItemName)
				{
					set_shipping_cost(data.products[i].price);
					//COUPON CODE STUFF
					if (data.products[i].promo == '20%off')
					{
						promo = 'active';
						set_promo_view();
					}
				}
				else
				{
					var product_id = data.products[i].code;
	 				var editable = data.products[i].options.editable;
	 				var assembly = data.products[i].options.hasAssembly;
	 				var assemblyFee = data.products[i].options.assemblyFee; //FIX ME KEVIN
	 				//assemblyFee = typeof(assemblyFee) == 'undefined' ? assemblyFee : false;
	 				// alert(assemblyFee);
	 				var price = data.products[i].price;
	 				var quantity = data.products[i].quantity;

	 				$.ajax({
	 					url: wr+"products/generate_mini_view/",
	 					type: "GET",
	 					data: "product_id="+product_id+"&variations=false&editable="+editable+"&assembly="+assembly+"&remove=true&assemblyFee="+assemblyFee,
	 					dataType: "html",
	 					success: function(html)
	 					{

 						
	 						$("#mn_cart h1").after(html).hide().slideDown();
							//update local view's quantities and prices

	 						if (j==data.products.length)
	 						{
								//once every cart item has returned its ajax call
								//update all quantities and prices for all products
								for (k=0; k<data.products.length; k++)
								{
									var product_name = data.products[k].name;
									if (product_name != CONST_ShippingItemName && 
										product_name != CONST_TaxName &&
										product_name != CONST_DirectDeliveryItemName)
									{
										var product_id = data.products[k].code;
										var price = data.products[k].price;
										var quantity = data.products[k].quantity
										$("#quantity_input_"+product_id).val(quantity);
										$("#cart_item_"+product_id).children(".item-right-side").children(".price").html("$"+price.toFixed(2));
									}
								
									if (product_name == CONST_DirectDeliveryItemName)
									{
										var zipcode = data.products[k].code;
										$("#zipcode").val(zipcode);
										if (zipcode != "")
										{
											show_direct_delivery();
										}
									}
								}
								set_transaction_status(false, "loading");	//loading complete
							}
	 					}
 				});
			}
				
				if (i == (data.products.length-1))
				{
					taxableCost= get_total()-get_direct_delivery();
					set_sales_tax(calculateSalesTax(taxableCost));
					set_total(get_total()+get_sales_tax());
					subT = get_total()-get_sales_tax()-get_shipping_cost();
					if (get_direct_delivery() > 0)
					{
						subT = subT-get_direct_delivery();
					}
					set_subtotal(subT);
					update_totals_view();
				}
			}
		});
		//COUPON CODE STUFF
		if (promo == 'active')
		{
			update_foxy_shipping();
		}
}

 /*
 	ADD FUNCTIONS
 */
//VALIDATED
 function add_to_cart(product_url)
 {
 	 $.ajax(
 	 {	
 	  	url: wr+"products/add_to_cart/",										//call add_to_cart function of products_controller which returns a JSON string
 	 	type: "GET",
 	 	data: "product_url="+product_url+"&uniqueKey="+uniqueKey,
 	 	dataType: "json",
 	 	error: function(error, error2, errorThrown)
 	 	{
 	 		set_transaction_status(false, "add");//Clears field and allows for a new attempt to be made
			$.ajax({
				url: wr+"admin/cart_error_handler/",
				type: "GET",
				data: "product_url="+product_url+"&error=AJAX_ERROR"+error+"."+error2+"."+errorThrown+"&browser="+BrowserDetect.browser+"&version="+BrowserDetect.version+"&os="+BrowserDetect.OS,
				dataType: "html",
				error: function(error, error2, errorThrown)
				{
					alert("Sorry, but an error occurred while adding that item to your cart. Please try again. If the problem continues please contact us.");
				},
				success: function(html)
				{
					alert("Sorry, but an error occurred while adding that item to your cart. Please try again. Technical Support has been notified, but if the problem continues please contact us.");
				} 
			});
 	 	},
 	 	success: function(json)
 	 	{
			if (json.error)
			{
				switch(json.error)
				{
					case "invalid_url":
					alert("The Product Web Address you entered was not valid. Please be sure it starts with:\nhttp://www.ikea.com/us/en");
					break;
					
					case "invalid_key":
					alert("Sorry, but an error occurred while adding that item to your cart. Please try again. If the problem continues please contact us.");
					break;
				}
				set_transaction_status(false, "add");//Clears field and allows for a new attempt to be made
				return false;
			}
 	 		var product_id = encodeURI(json.product_id);
 	 		var variations = encodeURI(json.variations);
 			var assembly = encodeURI(json.assembly);

			//Does the product have variations?
 	 		if (json.variations == true)
 	 		{
 	 			show_variations_select(product_id);
 	 		}
 	 		else
 	 		{
				//Does the product ID already exist in the cart?
				if (check_cart_for_item(product_id) == false)
				{
					var name = decodeURI(json.name);
 					name = str_replace("&#39;", "'", name);
	 	 			var price = encodeURI(json.price);
	 	 			//Add the item to foxycart
					var articleNumbers = encodeURI(json.articleNumbers);
					var options = encodeURI(json.options);
	 	 			add_to_foxycart(name, price, product_id, false, assembly, articleNumbers, options);
	 	 			//Display the item in the local cart
	 	 			prepend_to_local_cart(product_id, variations, false, true, assembly);
				}
 	 			else
				{
					update_quantity_by_one(product_id);
				}
 	 		}
 	 		
 	 	}
 	 });
 }

//VALIDATED
function check_cart_for_item(product_id)
{
	//check to see if product already exists in local cart
 	if ($("#cart_item_"+product_id).html() != null)
	{
		return true;
	}
	else
	{
		return false;
	}
}

//VALIDATED
function calculateSalesTax(cost)
{
	sales_tax = cost*tax_rate;
	set_sales_tax(sales_tax);
	return sales_tax;
}
 
//VALIDATED
function add_foxy_shipping()
{
	var subT = get_subtotal();
	var DDCost = get_direct_delivery();
	var cost = subT-DDCost;
	
	shipping_cost = calculateShipping(cost);
	salesTcost = cost+shipping_cost;
	salesTax = calculateSalesTax(salesTcost);
	//COUPON CODE STUFF
	var promo_info = "";
	if (promo == 'active')
	{
		promo_info = "&1:promo=20%off"
	}
	$.getJSON("http://"+storeDomain+"/cart?output=json&cart=add&1:name="+CONST_ShippingItemName+"&1:price="+shipping_cost+promo_info+"&callback=?" + fc_AddSession(),
		function(add_data)
		{	
			set_total(add_data.total_price+get_sales_tax());				//Update Global TOTAL
			update_foxy_direct_delivery();
		});
}
 
//VALIDATED
function add_foxy_direct_delivery()
{
	var zipcode = get_delivery_zipcode();
	direct_delivery_cost = getDeliveryPriceByZipCode(zipcode);
	$.getJSON("http://"+storeDomain+"/cart?output=json&cart=add&name="+CONST_DirectDeliveryItemName+"&price="+direct_delivery_cost+"&category=mndd&code="+zipcode+"&callback=?" + fc_AddSession(),
	function(add_data)
	{	
		set_total(add_data.total_price+get_sales_tax());
		show_direct_delivery();
		update_totals_view();
	});
}

function show_direct_delivery()
{
	if (get_delivery_zipcode() != "" && get_direct_delivery() != 0)
	{
		$("#zipcode_input_wrap").hide();
		$("#direct_delivery_display").show();
	}
	else
	{
		$("#zipcode_input_wrap").show();
		$("#direct_delivery_display").hide();
	}
}
 
//VALIDATED
function add_to_foxycart(name, price, product_id, editable, hasAssembly, articleNumbers, options)
{
	name = strip_swedish(name);
	name = str_replace("&#39;", "'", name);
 	name = str_replace('&#34;', '"', name);
	name = encodeURI(name);
	options = strip_swedish(decodeURI(options));
	options = str_replace("&#39;", "'", options);
 	options = str_replace('&#34;', '"', options);

	options = encodeURI(options);
 	//This function takes a product's name, price, and product_id, adds the item to foxycart
	//Anytime a product is added the shipping cost will need to be updated
	//console.log("http://"+storeDomain+"/cart?output=json&cart=add&name="+name+"&price="+price+"&code="+product_id+"&hasAssembly="+hasAssembly+"&editable="+editable+"&articleNumbers="+articleNumbers+"&callback=?" + fc_AddSession());
 	$.getJSON("http://"+storeDomain+"/cart?output=json&cart=add&name="+name+"&price="+price+"&code="+product_id+"&hasAssembly="+hasAssembly+"&editable="+editable+"&articleNumbers="+articleNumbers+"&options="+options+"&callback=?" + fc_AddSession(),
 	  function(fc_json){
	//console.log(fc_json);
 			update_foxy_shipping();
         });
}

function strip_swedish(name)
{
	name = decodeURI(name);
	name = str_replace("Å", "A", name);//remove swedish IKEA characters
	name = str_replace("Ä", "A", name);//remove swedish IKEA characters
	name = str_replace("Ö", "O", name);//remove swedish IKEA characters
	name = str_replace("Ø", "O", name);//remove swedish IKEA characters
	name = str_replace("Æ", "E", name);//remove swedish IKEA characters
	name = str_replace("å", "a", name);//remove swedish IKEA characters
	name = str_replace("ä", "a", name);//remove swedish IKEA characters
	name = str_replace("ö", "o", name);//remove swedish IKEA characters
	name = str_replace("ø", "o", name);//remove swedish IKEA characters
	name = str_replace("æ", "e", name);//remove swedish IKEA characters
	name = str_replace("ü", "u", name);//remove swedish IKEA characters
	return name;
}

//VALIDATED 
function addSelectedProduct(product_url)
{
	var addToFoxy = false;
	var incByOne = false;
	var remEdit = false;
	tb_remove();
		$.ajax(
			{ 
		 		url: wr+"products/add_to_cart/",
				type: "GET",
				data: "product_url="+product_url,
				dataType: "json",
				success: function(json)
				{
					//console.log(json);
					var product_id = encodeURI(json.product_id);
					if (get_transaction_type() == "edit")
					{
						var cur_edit_id = get_edit_id();
						if (product_id == cur_edit_id)
						{
							//increment existing quantity by 1
							incByOne = true;
						}
						else
						{
							remEdit = true;
							//remove cur_edit_id from foxy and local carts
						}
					}
					else
					{
						if (check_cart_for_item(product_id) == true)
						{
							//increment existing quantity by 1
							incByOne = true;
						}
						else
						{
							addToFoxy = true;
						}
					}
				
						var name = encodeURI(json.name);
						var price = encodeURI(json.price);
						var assembly = encodeURI(json.assembly);
						var articleNumbers = encodeURI(json.articleNumbers);
						var options = encodeURI(json.options);
						name = str_replace("&#39;", "'", name);

					if (addToFoxy == true)
					{
	 					add_to_foxycart(name, price, product_id, true, assembly, articleNumbers, options);
	 					prepend_to_local_cart(product_id, false, true, true, assembly);
					}
				
					if (remEdit == true)
						{
							swap_products(product_id, cur_edit_id, name, price, assembly, articleNumbers, options);
						}

					if (incByOne == true)
					{
						update_quantity_by_one(product_id);
					}
				}
			});
}

//VALIDATED
function swap_products(product_id, cur_edit_id, name, price, assembly, articleNumbers, options)
{
	var editable = true;
	//FC call to set quantity of cur_edit_id to 0 and then add new item product_id
	//ensure the old item is actually in the cart before trying to remove it
 	$.getJSON("http://"+storeDomain+"/cart?output=json&cart=view&callback=?" + fc_AddSession(),
 		function(fc_json)
 		{
 			var noItem = true;
 			for (var i=0; i<fc_json.products.length; i++)
 			{
 				if (fc_json.products[i].code == cur_edit_id)//item found
 				{
 					noItem = false;
 					$.getJSON("http://"+storeDomain+"/cart?output=json&cart=update&1:quantity=0&1:id="+fc_json.products[i].id+"&callback=?" + fc_AddSession(),
 	 				function(data)
 	 				{
						//After the old item has been removed, pass new item on to add_to_foxycart function
						add_to_foxycart(name, price, product_id, true, assembly, articleNumbers, options);
						prepend_to_local_cart(product_id, false, true, true, assembly, true);//last variable is "swap" it's set to true to alter prepend's behavior
 	 				});
 				}
 			}
 			if (noItem == true)
 			{	
				set_transaction_status(false, "");
 				alert("Item swap failed. Original product not found. Prod ID: "+product_id);
 			}
 		});
}

//VALIDATED
function update_quantity_by_one(product_id)
{
	//Local call to grab existing quantity & increment it visually by one
	current_quantity = $("#quantity_input_"+product_id).val();
   	new_quantity = parseInt(current_quantity) +1;
   	update_quantity(product_id, new_quantity);
}
 
//VALIDATED
function prepend_to_local_cart(product_id, variations, editable, remove, assembly, swap)
 {
	//This function makes an AJAX call to the local system which generates and returns an HTML view of the product with the correct options set
	//It then appends that HTML to the modernash cart.
 	editable = typeof(editable) != 'undefined' ? editable : false;
 	remove = typeof(remove) != 'undefined' ? remove : false;
 	assembly = typeof(assembly) != 'undefined' ? assembly : false;
 	swap = typeof(swap) != 'undefined' ? swap : false;
 	$.ajax({
 			url: wr+"products/generate_mini_view/",
 			type: "GET",
 			data: "product_id="+product_id+"&variations="+variations+"&editable="+editable+"&remove="+remove+"&assembly="+assembly,
 			dataType: "html",
 			success: function(html)
 			{
				if (swap == true)
				{
					replace_id = get_edit_id();
					$("#cart_item_"+replace_id).slideUp(function(){
						$(this).remove();
					});
					
				}
				$("#mn_cart h1").after(html).hide().slideDown();
 			}
 	});
}
 
 /*
 	UPDATE FUNCTIONS
 */

function update_cart_items()
{
	cart_status("loading");
	//updates cart item prices and quantities to match current foxycart state
	$(".cart-item").each(function(){
		//update quantity with current, this will set price
		$.getJSON("http://"+storeDomain+"/cart?output=json&cart=view&callback=?" + fc_AddSession(),
			function(fc_json){
				for (i=0; i<fc_json.products.length; i++)
				{
					if (fc_json.products[i].name != CONST_ShippingItemName)
					{
						product_id = fc_json.products[i].code;
						price = fc_json.products[i].price;
						quantity = fc_json.products[i].quantity;
						update_product_price(product_id, price);
						update_product_quantity(product_id, quantity);
					}
				}
				cart_status("done");
			});
	});
}
 
//VALIDATED
function update_foxy_shipping()
{
	//Updating foxy shipping takes place in two phases. The first phase below removes any existing shipping and sales tax items
	//The function then routes to add_foxy_shipping() where new sales tax and shipping amounts are calculated and added to the cart
	var shipping_added = false;
	$.getJSON('http://'+storeDomain+'/cart?output=json&cart=view&callback=?' + fc_AddSession(),
	function(fc_json)
 	{		
		var arrShippingIds = new Array();
	
 		for (var i=0; i<fc_json.products.length; i++)
 		{
 			if (fc_json.products[i].name == CONST_ShippingItemName)
 			{	
				//log any and all id's that are shipping
				arrShippingIds.push(fc_json.products[i].id);
 			}
 		}
		
		if (arrShippingIds.length > 0)
		{
			shipping_added = true;
			//remove shipping from shopping cart
			var JSONString = "http://"+storeDomain+"/cart?output=json&cart=update";
			for (var j=0; j<arrShippingIds.length; j++)
			{
				JSONString += "&"+j+":quantity=0&"+j+":id="+arrShippingIds[j];
			}
			JSONString += "&callback=?" + fc_AddSession();
			$.getJSON(JSONString,
			function(data)
			{
				//Shipping and sales tax have been removed. Update global subtotal
				set_subtotal(data.total_price);
				add_foxy_shipping();
			});
		}
		
		else 
		{
		//no shipping or sales tax items found in the cart. Proceed to add.
			set_subtotal(fc_json.total_price);
			add_foxy_shipping();
		}
 	});
}
 
//VALIDATED
function update_foxy_direct_delivery()
{
	//Updating foxy DD takes place in two phases. The first phase below removes any existing DD
	$.getJSON('http://'+storeDomain+'/cart?output=json&cart=view&callback=?' + fc_AddSession(),
	function(fc_json)
 	{	
		var arrDDIds = new Array();
	
 		for (var i=0; i<fc_json.products.length; i++)
 		{
 			if (fc_json.products[i].name == CONST_DirectDeliveryItemName)
 			{	
				//log any and all id's that are dd
				arrDDIds.push(fc_json.products[i].id);
 			}
 		}
		
		if (arrDDIds.length > 0)
		{
			//remove DD item(s)
			var JSONString = "http://"+storeDomain+"/cart?output=json&cart=update";
			for (var j=0; j<arrDDIds.length; j++)
			{
				JSONString += "&"+j+":quantity=0&"+j+":id="+arrDDIds[j];
			}
			JSONString += "&callback=?" + fc_AddSession();
			$.getJSON(JSONString,
			function(data)
			{
			if (get_transaction_type() == "remove_DD")//We want to just remove the DD, the update is finished, no need to add
			{
				set_direct_delivery(0);
				set_delivery_zipcode("");
				set_total(data.total_price+get_sales_tax());
				update_totals_view();
			}
			else
			{
				add_foxy_direct_delivery();
			}
			});
		}
		
		else //DD didn't already exist, check to see if we're adding it
		{
		if (get_transaction_type() == "add_DD")
		{
			add_foxy_direct_delivery();
		}
		else
		{
			update_totals_view();
		}
		}
 	});
}

function update_totals_view()
{
	var tax = get_sales_tax();
	var cart_total = get_total();
	var cart_subtotal = get_subtotal();
	var shipping = get_shipping_cost();
	//COUPON CODE STUFF - FIX THIS LATER QUICK AND DIRTY FIX

	var dd_cost = get_direct_delivery();
	var zipcode = get_delivery_zipcode();
	$("#foxy_total").html(cart_total.toFixed(2));
	$("#shipping_cost_span").html(shipping.toFixed(2));
	$("#sales_tax_span").html(tax.toFixed(2));
	$("#cart_subtotal").html(cart_subtotal.toFixed(2));
	$("#direct_delivery_cost_span").html(dd_cost.toFixed(2));
	$("#zipcode").val(zipcode);
	//UPDATE visuals of local cart here
	//alert("BUILD update_local_cart() function!");
	$(".mn_totals").slideDown();
	transaction_type = get_transaction_type();
	set_transaction_status(false, transaction_type);
}

//VALIDATED
function update_quantity(product_id, quantity)
{
//reset transaction_status to remove if quantity = 0
	if (quantity == 0)
	{
		set_transaction_status(true, "remove");
		$("#cart_item_"+product_id).css("background", "red");
	}

//update local quantity field (irrelevant if quantity was typed, but shouldn't hurt anything)
$("#quantity_input_"+product_id).val(quantity);

//update local product price display
	price_each = $("#cart_item_"+product_id).children(".item-right-side").children(".price_each_wrapper").children(".price_each").html();
  	product_price = quantity*price_each;
	$("#cart_item_"+product_id).children(".item-right-side").children(".price").html("$"+product_price.toFixed(2));

	//update foxycart quantity
	update_foxycart_quantity(product_id, quantity);
}
 
//VALIDATED
function empty_foxycart()
{
	$.getJSON("http://"+storeDomain+"/cart?output=json&cart=empty&callback=?" + fc_AddSession(),
	function(empty)
	{
		return true;
	});
}

//VALIDATED
function update_foxycart_quantity(product_id, quantity)
{
 	//ensure the item is actually in the cart before trying to update it
 	$.getJSON("http://"+storeDomain+"/cart?output=json&cart=view&callback=?" + fc_AddSession(),
 		function(fc_json)
 		{
 			var noItem = true;
 			for (var i=0; i<fc_json.products.length; i++)
 			{
 				if (fc_json.products[i].code == product_id){
					//item found
 					noItem = false;
 					$.getJSON("http://"+storeDomain+"/cart?output=json&cart=update&1:quantity="+quantity+"&1:id="+fc_json.products[i].id+"&callback=?" + fc_AddSession(),
 	 				function(data)
 	 				{
						cart_empty = false;
 						if (get_transaction_type() == "remove" && quantity == 0)//If we just removed an item
						{
							for (var i=0; i<data.products.length; i++)
					 		{
					 			if (data.products[i].name == CONST_ShippingItemName && data.products.length == 1)//If only shipping is left in the cart
					 			{	
									cart_empty = true;
								}
								if (data.products[i].name == CONST_DirectDeliveryItemName && data.products.length == 2)//Only shipping and direct delivery are left
								{	
									cart_empty = true;
								}
					 		}
						
							if (cart_empty === true)
							{
								empty_foxycart();
								set_transaction_status(false, "remove");
								empty_local_cart();
							}
							else
							{
								remove_from_local_cart(product_id);
								update_foxy_shipping();
							}
						}
						else
						{
							update_foxy_shipping();
						}
 	 				});
 				}
 			}
 			if (noItem == true){	
				type = get_transaction_type();
				set_transaction_status(false, type);
 				alert("Quantity Update Failed: Product Not Found: "+product_id);
 			}
 		});
}
 
//VALIDATED
function empty_local_cart()
{
	//hide all the totals, reset all the global totals to 0
	set_subtotal(0);
	set_shipping_cost(0);
	set_sales_tax(0);
	set_total(0);
	set_direct_delivery(0);
	set_edit_id("");
	set_delivery_zipcode("");
	total = get_total();
	$("#foxy_total").html(total.toFixed(2));
	$(".cart-item").slideUp(function(){
		$(this).remove();
	});
	$(".mn_totals").slideUp(); 
}
 /*
 	REMOVE FUNCTIONS
 */
 
//VALIDATED
function remove_from_local_cart(product_id)
{
 	$("#cart_item_"+product_id).slideUp(function(){
		$(this).remove();
	});
}

//VALIDATED
function updateStatus(status, c, t, type)
{
	//console.log('updateStatus called: '+status+', '+c+', '+t+', '+type); DEBUGGING
	/* 
		UPDATES THE VISUAL DISPLAY OF THE PROGRESS BAR
	*/
	var progressBarWidth;
	var totalPBWidth = 220;
	var message;
	var percent = 0;
	
	if (type=="scan")
	{
		message = "scanning Ikea&hellip;";
	}
	else if (type=="add")
	{
		message = "adding to system&hellip;";
	}
	else if (type="update")
	{
		message = "updating price information&hellip;";
	}
	else
	{
		message ="Loading&hellip;";
	}
	
	if(status == 'initializing') 
	{
		$('#statusProgressBar').css("width", "0px");
		message = 'Initializing';
	} 
	else if(status == 'canceled') 
	{
		$('#statusProgressBar').css("width", "0px" );
		message = 'Canceled';
		percent = number_format(c / t * 100, 2)+'%';
	} 
	else if(status == 'complete')
	{
		$('#statusProgressBar').css("width", totalPBWidth+"px");
		message = 'Completed';
	}
	else 
	{
		$('#dropZoneCover p').html(type);
		if(t) 
		{
			percent = number_format(c / t * 100, 2)+'%';
		} 
		else 
		{
			//statusHTML = '<span id="top">0 result(s)</span>';
		}
		progressBarWidth = Math.floor(totalPBWidth * (c / t));
			$('#statusProgressBar').animate({
				width: progressBarWidth+"px"
			}, 500);
	}
	$('#statusPercent').html(percent);
	$('#statusMessage').html(message);
}
 
//VALIDATED
function show_variations_select(product_id)
{
	//If the item has multiple variations, show a thickbox forcing a variation choice
	tb_show('caption', wr+"products/generate_mini_view/?product_id="+product_id+"&modal=true&height=205");
}
 
//VALIDATED
function check_valid_combination(productIds){
	var matchLength = productIds.length;//the number of select boxes on the product page
	for (var i in masterVariations){
		var theseVariations = masterVariations[i].variations;
		var thisProductId = masterVariations[i].product_id;
		var matches = 0;
		for (j=0; j<productIds.length; j++){
			product_id = productIds[j];
			product_id = str_replace('"', '&#34;', product_id);
			for (k in theseVariations){
				if (theseVariations[k] == product_id){
					matches++;
					if (matches == matchLength){
						tb_show('caption', wr+"products/generate_mini_view/?product_id="+thisProductId+"&height=205");
						var matchfound = true;
					}				
				}
			}		
		}			
	}	
	if (matchfound != true){
		alert("That combination of options does not exist.");
	}
}
 
//ASSEMBLY ADDITION - DISABLED FOR NOW 7.25.09
function add_assembly(product_id)
{
	var assembly_cost = 25;
	//ensure the item is actually in the cart before trying to add assembly
	$.getJSON("http://"+storeDomain+"/cart?output=json&cart=view&callback=?" + fc_AddSession(),
		function(fc_json)
		{
			var noItem = true;
			for (var i=0; i<fc_json.products.length; i++)
			{
				if (fc_json.products[i].code == product_id)//item found
				{
					if (typeof(fc_json.products[i].options.assemblyFee)=='undefined')
					{
						noItem = false;
						var name = fc_json.products[i].name;
						name = strip_swedish(name);
						var price = fc_json.products[i].price;
						var quantity = fc_json.products[i].quantity;
						var editable = fc_json.products[i].options.editable;
						var hasAssembly = fc_json.products[i].options.hasAssembly;
						var assemblyFee = assembly_cost+'{p+'+assembly_cost+'}';
						$.getJSON('http://'+storeDomain+'/cart?output=json&cart=update&1:quantity=0&1:id='+fc_json.products[i].id+'&callback=?' + fc_AddSession(),
							function(fc_post_remove)
							{
								
								$.getJSON("http://"+storeDomain+"/cart?output=json&cart=add&name="+name+"&price="+price+"&code="+product_id+"&x:hasAssembly="+hasAssembly+"&x:editable="+editable+"&assemblyFee="+assemblyFee+"&quantity="+quantity+"&callback=?" + fc_AddSession(),
								function(fc_post_add)
								{
									//update visuals here
									// alert(assembly_cost+"ASSEMB COST");
									show_assembly(product_id, assembly_cost);
									var new_product_price = price+assembly_cost;
									update_product_price(product_id, new_product_price);
									update_foxy_shipping();
								});
							});
					}
					else
					{
						noItem = false;
						alert("assembly already added");
					}	
				}
					
			}
			if (noItem == true)
			{	
				type = get_transaction_type();
			set_transaction_status(false, type);
				alert("Assembly Update Failed: Product Not Found: "+product_id);
			}
		});
}
//ASSEMBLY ADDITION - DISABLED FOR NOW 7.25.09
function show_assembly(product_id, assemblyFee)
{
	// alert(assemblyFee+"ASSEMBLY"+product_id);
	$("#cart_item_"+product_id).children(".item-right-side").children(".assembly_fee_holder").html("Assembly: $"+assemblyFee.toFixed(2));
}
 
/*
	MISC PHP-JS FUNCTIONS
*/
function str_replace(search, replace, subject, count) {
    var i = 0, j = 0, temp = '', repl = '', sl = 0, fl = 0,
            f = [].concat(search),
            r = [].concat(replace),
            s = subject,
            ra = r instanceof Array, sa = s instanceof Array;
    s = [].concat(s);
    if (count) {
        this.window[count] = 0;
    }
 
    for (i=0, sl=s.length; i < sl; i++) {
        if (s[i] == '') {
            continue;
        }
        for (j=0, fl=f.length; j < fl; j++) {
            temp = s[i]+'';
            repl = ra ? (r[j] !== undefined ? r[j] : '') : r[0];
            s[i] = (temp).split(f[j]).join(repl);
            if (count && s[i] !== temp) {
                this.window[count] += (temp.length-s[i].length)/f[j].length;}
        }
    }
    return sa ? s : s[0];
}
 
function number_format( number, decimals, dec_point, thousands_sep ) {
    var n = number, c = isNaN(decimals = Math.abs(decimals)) ? 2 : decimals;
    var d = dec_point == undefined ? "." : dec_point;
    var t = thousands_sep == undefined ? "," : thousands_sep, s = n < 0 ? "-" : "";
    var i = parseInt(n = Math.abs(+n || 0).toFixed(c)) + "", j = (j = i.length) > 3 ? j % 3 : 0;

    return s + (j ? i.substr(0, j) + t : "") + i.substr(j).replace(/(\d{3})(?=\d)/g, "$1" + t) + (c ? d + Math.abs(n - i).toFixed(c).slice(2) : "");
}

function generate_unique_key(length)
{
	chars = "abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ1234567890";
	  pass = "";
	  for(x=0;x<length;x++)
	  {
	    i = Math.floor(Math.random() * 62);
	    pass += chars.charAt(i);
	  }
	return pass;
}

var BrowserDetect = {
	init: function () {
		this.browser = this.searchString(this.dataBrowser) || "An unknown browser";
		this.version = this.searchVersion(navigator.userAgent)
			|| this.searchVersion(navigator.appVersion)
			|| "an unknown version";
		this.OS = this.searchString(this.dataOS) || "an unknown OS";
	},
	searchString: function (data) {
		for (var i=0;i<data.length;i++)	{
			var dataString = data[i].string;
			var dataProp = data[i].prop;
			this.versionSearchString = data[i].versionSearch || data[i].identity;
			if (dataString) {
				if (dataString.indexOf(data[i].subString) != -1)
					return data[i].identity;
			}
			else if (dataProp)
				return data[i].identity;
		}
	},
	searchVersion: function (dataString) {
		var index = dataString.indexOf(this.versionSearchString);
		if (index == -1) return;
		return parseFloat(dataString.substring(index+this.versionSearchString.length+1));
	},
	dataBrowser: [
		{
			string: navigator.userAgent,
			subString: "Chrome",
			identity: "Chrome"
		},
		{ 	string: navigator.userAgent,
			subString: "OmniWeb",
			versionSearch: "OmniWeb/",
			identity: "OmniWeb"
		},
		{
			string: navigator.vendor,
			subString: "Apple",
			identity: "Safari",
			versionSearch: "Version"
		},
		{
			prop: window.opera,
			identity: "Opera"
		},
		{
			string: navigator.vendor,
			subString: "iCab",
			identity: "iCab"
		},
		{
			string: navigator.vendor,
			subString: "KDE",
			identity: "Konqueror"
		},
		{
			string: navigator.userAgent,
			subString: "Firefox",
			identity: "Firefox"
		},
		{
			string: navigator.vendor,
			subString: "Camino",
			identity: "Camino"
		},
		{		// for newer Netscapes (6+)
			string: navigator.userAgent,
			subString: "Netscape",
			identity: "Netscape"
		},
		{
			string: navigator.userAgent,
			subString: "MSIE",
			identity: "Explorer",
			versionSearch: "MSIE"
		},
		{
			string: navigator.userAgent,
			subString: "Gecko",
			identity: "Mozilla",
			versionSearch: "rv"
		},
		{ 		// for older Netscapes (4-)
			string: navigator.userAgent,
			subString: "Mozilla",
			identity: "Netscape",
			versionSearch: "Mozilla"
		}
	],
	dataOS : [
		{
			string: navigator.platform,
			subString: "Win",
			identity: "Windows"
		},
		{
			string: navigator.platform,
			subString: "Mac",
			identity: "Mac"
		},
		{
			   string: navigator.userAgent,
			   subString: "iPhone",
			   identity: "iPhone/iPod"
	    },
		{
			string: navigator.platform,
			subString: "Linux",
			identity: "Linux"
		}
	]

};
BrowserDetect.init();