//------------------------------------
// QuickOrder v1.2.0 - 20 August 2009
//------------------------------------
// Copyright 2009 ElegantXMods.com
// Please note that this file and
// all QuickOrder files are licenced
// on a per-site basis.
// contact enquiries@elegantxmods.com
// for details or visit our website
// at http://www.elegantxmods.com
//------------------------------------

var $qo = jQuery.noConflict();

$qo(document).ready(function() 
{
	// add hidden categories here - like the following:
	// the category name is in the quotation marks
	// and the category id is after the equal sign
	
 QuickOrder.HiddenCategories["VelaShape"] = 281;
  QuickOrder.HiddenCategories["Skin Rejuvenation"] = 286;
  QuickOrder.HiddenCategories["Skin Tightening"] = 283;
  QuickOrder.HiddenCategories["Laser Hair Removal"] = 289;
  QuickOrder.HiddenCategories["Laser Acne Treatment"] = 282;
	
	// add static links here - top and bottom - same as above - see the two comments below for examples:
	
	// QuickOrder.TopStaticLinks["External Site"] = "http://www.google.com";
	

QuickOrder.BottomStaticLinks["Brochure (Whitestone)"] = "quickmenu.pdf";
QuickOrder.BottomStaticLinks["Brochure (Rego Park)"] = "quickmenu_rp.pdf";
	
	
	
	
	
	QuickOrder.start_cat_id = 252;
	
	if (!QuickOrder.Configuration.show_discounts)
		$qo(".qo_summary_discount_row").css("visibility", "hidden");
	
	if (QuickOrder.Configuration.use_manufacturers)
		$qo("#qo_col_left_linklist").addClass("adjust_for_manufacturers");
	
	$qo("#qo_prevorders").hide();
	$qo("#quickorder_container").css("visibility", "visible");
	QuickOrder.ShowTab("category");
	$qo('#qo_search').AutoComplete('exm_quickorder/ajax_funcs.php?method=autocomplete');
		
	QuickOrder.ShowExistingCart();
	
	if (QuickOrder.Configuration.previous_orders)
		QuickOrder.ShowPreviousOrders();

	QuickOrder.ShowCatsAndManufacturers();
	
	if ((QuickOrder.Configuration.show_featured_products) && (QuickOrder.search_results.length == 0) 
			&& (QuickOrder.start_cat_id == 0) && (QuickOrder.start_manu_id == 0))
		QuickOrder.ShowFeaturedProducts(0);
	else if (QuickOrder.start_cat_id > 0)
		QuickOrder.ShowMainCategory(QuickOrder.start_cat_id);
	else if (QuickOrder.start_manu_id > 0)
		QuickOrder.ShowManufacturer(QuickOrder.start_manu_id);
	
	if (QuickOrder.search_results.length > 0)
		QuickOrder.ShowSearchResults();
});

var QuickOrder =
{
	Labels:
	{
		product_name: "Product Name",
		sku: "SKU",
		price: "Price",
		qty: "Qty",
		subtotal: "Subtotal",
		edit: "Edit",
		delete_item: "Delete",
		currency_code: "",
		currency_symbol: "",
		lbl_search: "",
		
		featured_products: "Featured Products",
		choose_previous_order: "Choose a previous order...",
		confirm_overwrite_order: "Are you sure you want to bring back this order? Your current cart will be deleted to make way for this order.",
		loading_elips: "Loading...",
		loading_cart_elips: "Loading your cart...",
		product: "product",
		products: "products",
		could_not_find_product: "Sorry, we could not find that product. Please try again.",
		must_order_at_least: "Sorry, you must order at least ###QTY### of this product",
		insufficient_stock: "Sorry, there is not enough in stock. At present, we only have a maximum of ###QTY### to sell.",
		updating_cart_elips: "Updating cart...",
		qty_must_above_zero: "You must enter a quantity higher than zero.",
		clearing_cart_elips: "Clearing cart...",
		checkout_elips: "Checking out...",
		choose_product_options: "Choose Options",
		lbl_continue: "Continue",
		lbl_cancel: "Cancel"
	},
	
	Configuration:
	{
		number_format: "2.",
		
		// MultiCurrency support
		multi_currency_active: false,
		exchange_rate: 1,

		// AJAX MiniCart support
		ajax_minicart_active: false,
	
		// default configuration settings
		use_manufacturers: false,
		show_featured_products: false,
		color_theme: "default",
		use_phpthumb: false,
		display_sku: false,
		show_discounts: true,
		allow_backorders: false,
		previous_orders: true
	},
	
	HiddenCategories: new Array(),
	TopStaticLinks: new Array(),
	BottomStaticLinks: new Array(),

	// internal objects
	search_results: new Array(),
	cart: new Array(),
	cart_totals: {"subtotal":0, "shipping":0, "taxes":0, "discount":0, "total":0},
	start_cat_id: 0,
	start_manu_id: 0,
	version: "1.2.0",
	
	// functions
	ShowExistingCart: function()
	{
		QuickOrder.cart.length = 0;
		QuickOrder.LoadingPanel.Show(QuickOrder.Labels.loading_cart_elips);
		$qo.getJSON("exm_quickorder/ajax_funcs.php?method=current_cart_contents",
			function(json) {
				$qo.each(json.cart.products, function(i,item)
				{
					QuickOrder.cart.push({
						"productid": item.id,
						"productcode": item.code,
						"productname": item.name,
						"price": item.price,
						"quantity": item.qty,
						"thumbnail": item.thmb,
						"option_count": item.opts,
						"cartid": item.cid,
						"min_amount": item.minam,
						"avail": item.avail,
						"product_options": item.optstext
					});
				});
				
				QuickOrder.UpdateCartTotals(
					json.cart.subtotal,
					json.cart.shipping,
					json.cart.taxes,
					json.cart.discount,
					json.cart.total
				);
				QuickOrder.UpdateCartDisplay();
				QuickOrder.LoadingPanel.Hide();
			}
		);
	},
	
	UpdateCartTotals: function(subtotal, shipping, taxes, discount, total)
	{
		QuickOrder.cart_totals["subtotal"] = subtotal;
		QuickOrder.cart_totals["shipping"] = shipping;
		QuickOrder.cart_totals["taxes"] = taxes;
		QuickOrder.cart_totals["discount"] = discount;
		QuickOrder.cart_totals["total"] = total;
	},
	
	ShowPreviousOrders: function()
	{
		var order_count = 0;
		$qo("#qo_ddl_orders").html("<option value=''>" + QuickOrder.Labels.choose_previous_order + "</option>");
		$qo.getJSON("exm_quickorder/ajax_funcs.php?method=previous_orders",
			function(json) {
				$qo.each(json.orders, function(i,item){
					$qo('#qo_ddl_orders').append(
        		$qo('<option></option').val(item.order_id).html("#" + item.order_id + " - " +
					QuickOrder.Labels.currency_symbol + item.total + " - " + item.date)
    			);
					order_count++;
				});
				if (order_count > 0)
				{
					$qo("#qo_col_left_linklist").css("height", 
						($qo("#qo_col_left_linklist").css("height").replace("px", "") - 35) + "px");
					$qo("#qo_prevorders").fadeIn("slow");
				}
		});
	},
	
	ShowOrder: function()
	{
		if (confirm(QuickOrder.Labels.confirm_overwrite_order))
		{
			var order_id = $qo("#qo_ddl_orders").val();
			QuickOrder.Clear();
			$qo.get("exm_quickorder/ajax_funcs.php?method=order_to_cart&order_id=" + order_id,
				function(data) {
					$qo.get("cart.php?mode=checkout", function(data) {
						QuickOrder.ShowExistingCart();
					});
			});
		}
	},
	
	ShowSearchResults: function()
	{
		var url = "exm_quickorder/ajax_funcs.php?method=search_results_list&products=";
		for (var i = 0; i < QuickOrder.search_results.length; i++)
		{
			if (i > 0)
				url += "," + QuickOrder.search_results[i];
			else
				url += QuickOrder.search_results[i];
		}
		
		$qo.getJSON(url, function(json) {
			var sHtml = "";
			sHtml = sHtml + "<div class='qopg_catheading'>Search Results</div>";
				
			$qo.each(json.search_results, function(i,product)
			{
				var sAlt = "";
				if (i % 2 == 1)
					sAlt = " qogr_alt";
				
				sHtml = sHtml + 
				"<div class='qo_product_gridrow" + sAlt + "'>" +
				"<div class='qogr_qty'><input type='text' size='3' maxlength='4' value='" + product.min_amount + "' id='qty_" + 
					product.productid + "' /> <input type='button' onclick='AddToCartFromProdList(" + 
					product.productid + ")', class='plus_button' value=' + ' />" +
					"<input type='hidden' id='optcount_" + product.productid + "' value='" + product.option_count + "' />" +
					"<input type='hidden' id='min_qty_" + product.productid + "' value='" + product.min_amount + "' />" +
					"<input type='hidden' id='avail_" + product.productid + "' value='" + product.avail + "' /></div>" +
				"<div class='qogr_price'>" + AdaptCurrency(product.price) + "</div>" + 
				"<div class='qogr_img'>" + Thumbnail(product.thumbnail, product.main_image, 25, 25) + "</div>" +
				"<div class='qogr_prodname'>" + FormatProduct(product.productcode, product.productname) + "</div>" + 
				"</div>";
			});
			$qo("#qo_product_grid").html(sHtml);
			QuickOrder.EnableProductBox();
		});
	},
	
	ShowCatsAndManufacturers: function()
	{
		$qo.getJSON("exm_quickorder/ajax_funcs.php?method=categories_and_manufacturers",
			function(json) {
				sHtml = "";
				
				// and any static links
				var stlnk = QuickOrder.TopStaticLinks;
				for (var lnkname in stlnk) 
				{
					sHtml = sHtml + "<li><a id='ll_category_" + stlnk[lnkname] + "' ";
					sHtml = sHtml + "href='" + stlnk[lnkname] + "' >" + lnkname + "</a></li>";
				}
				
				$qo.each(json.categories, function(i,item){
					sHtml = sHtml + "<li><a id='ll_category_" + item.i + "' ";
					
					if (item.s > 0)
						sHtml = sHtml + "class='has_subcats' ";
					
					sHtml = sHtml + "href='javascript:QuickOrder.ShowMainCategory(" + item.i + 
						", 1);' >" + item.n + "</a></li>"+
						"<li id='li_subcats_" + item.i + "' class='left_subcats_list'>&nbsp;</li>";
				});
				
				// now show hidden categories
				var hidcat = QuickOrder.HiddenCategories;
				for (var catname in hidcat) 
				{
					sHtml = sHtml + "<li><a id='ll_category_" + hidcat[catname] + "' ";
					sHtml = sHtml + "href='javascript:QuickOrder.ShowMainCategory(" + hidcat[catname] + 
						", 1);' >" + catname + "</a></li>";
				}
				
				// and any static links
				stlnk = QuickOrder.BottomStaticLinks;
				for (var lnkname in stlnk) 
				{
					sHtml = sHtml + "<li><a id='ll_category_" + stlnk[lnkname] + "' ";
					sHtml = sHtml + "href='" + stlnk[lnkname] + "' >" + lnkname + "</a></li>";
				}
				
				$qo("#qo_category_list").html(sHtml);
				
				var sHtml = "";
				if (QuickOrder.Configuration.use_manufacturers)
				{
					$qo.each(json.manufacturers, function(i,item){
						var sAlt = "";
						if (i % 2 == 0) {sAlt = "class='alt'";}
						sHtml = sHtml + "<li><a id='ll_manufacturer_" + item.i + 
							"' href='javascript:QuickOrder.ShowManufacturer(" + item.i + 
							");' " + sAlt + ">" + item.n + "</a></li>";
					});
					$qo("#qo_manufacturer_list").html(sHtml);
				}
			}
		);
	},
	
	ShowTab: function(list_type)
	{
		var id = "";
		switch(list_type)
		{
			case "manufacturer":
				$qo("#qo_manufacturer_list").show();
				$qo("#qo_category_list").hide();
				$qo("#qo_manulist_link").addClass("active");
				$qo("#qo_catlist_link").removeClass("active");
				$qo("#hdn_list_type").value = "manufacturer";
				break;
			case "category":
				$qo("#qo_manufacturer_list").hide();
				$qo("#qo_category_list").show();
				$qo("#qo_manulist_link").removeClass("active");
				$qo("#qo_catlist_link").addClass("active");
				$qo("#hdn_list_type").value = "category";
				break;
		}
	},
	
	ShowFeaturedProducts: function(cat_id)
	{
		$qo.getJSON("exm_quickorder/ajax_funcs.php?method=featured_products&cat_id=" + cat_id,
			function(json) {
				var sHtml = "";
				sHtml = sHtml + "<div class='qopg_catheading'>Featured Products</div>";
				
				$qo.each(json.featured_products, function(i,product)
				{
					var sAlt = "";
					if (i % 2 == 1)
						sAlt = " qogr_alt";
					
					sHtml = sHtml + 
					"<div class='qo_product_gridrow" + sAlt + "'>" +
					"<div class='qogr_qty'><input type='text' size='3' maxlength='4' value='" + product.minam + "' id='qty_" + 
						product.id + "' /> <input type='button' onclick='QuickOrder.AddToCartFromProductList(" + 
						product.id + ")', class='plus_button' value=' + ' />" +
						"<input type='hidden' id='optcount_" + product.id + "' value='" + product.opts + "' />" +
						"<input type='hidden' id='min_qty_" + product.id + "' value='" + product.minam + "' />" +
						"<input type='hidden' id='avail_" + product.id + "' value='" + product.avail + "' /></div>" +
					"<div class='qogr_price'>" + QuickOrder.DisplayCurrency(product.price) + "</div>" + 
					"<div class='qogr_img'>" + QuickOrder.Thumbnail(product.thmb, product.id, 25, 25) + "</div>" +
					"<div class='qogr_prodname'>" + QuickOrder.DisplayProductName(product.id, product.code, product.name) + "</div>" + 
					"</div>";
				});
				$qo("#qo_product_grid").html(sHtml);
				QuickOrder.EnableProductBox();
			}
		);
	},
	
	// main interaction functions
	ShowMainCategory: function(id, page_no)
	{
		QuickOrder.MainPanelMessage(QuickOrder.Labels.loading_elips);
		if (page_no == 1)
		{
			$qo("#qo_category_list a").removeClass("selected");
			$qo("#ll_category_" + id).addClass("selected");
			$qo("li.left_subcats_list").hide();

			// first get all sub-categories
			$qo.getJSON("exm_quickorder/ajax_funcs.php?method=sub_categories&cat_id=" + id,
				function(json) {
					var sHtml = "<ul>";
					var subcat_count = 0;
					$qo.each(json.subcategories, function(i, subcat)
					{
						sHtml = sHtml + "<li><a href='javascript:QuickOrder.ShowSubcategory(" + 
							subcat.categoryid + ", " + subcat.parentid + ");'>" + 
							subcat.categoryname + "</a></li>";
							
						subcat_count++;
					});
					sHtml = sHtml + "</ul>";
					$qo("#li_subcats_" + id).html(sHtml);
					$qo("#li_subcats_" + id).show();
					
					if (subcat_count > 0)
						$qo("#ll_category_" + id).addClass("open_category");
				}
			);
		}
		
		$qo.getJSON("exm_quickorder/ajax_funcs.php?method=products_by_category&cat_id=" + id + "&page_no=" + page_no,
			function(json) {
				var sHtml = "";
				
				if (json.products.length > 0)
				{
				
					// allowing for singular and plural 'product' in subcategory heading
					var subcat_prod_count = "";
					if (json.product_count > 1)
						subcat_prod_count = json.product_count.toString() + " " + QuickOrder.Labels.products;
					else
						subcat_prod_count = json.product_count.toString() + " " + QuickOrder.Labels.product;
					
					// writing HTML for subcategory headings
					sHtml = sHtml + "<div class='qopg_catheading'>" +
						json.category_name + " - (" + subcat_prod_count + ")</div>";
				
					$qo.each(json.products, function(i,product)
					{
						var sAlt = "";
						if (i % 2 == 1)
							sAlt = " qogr_alt";
					
						sHtml = sHtml + 
							"<div class='qo_product_gridrow" + sAlt + "'>" +
							"<div class='qogr_qty'><input type='text' size='3' maxlength='4' value='" + product.minam + "' id='qty_" + 
								product.id + "' /> <input type='button' onclick='QuickOrder.AddToCartFromProductList(" + 
								product.id + ")', class='plus_button' value=' + ' />" +
								"<input type='hidden' id='optcount_" + product.id + "' value='" + product.opts + "' />" +
								"<input type='hidden' id='min_qty_" + product.id + "' value='" + product.minam + "' />" +
								"<input type='hidden' id='avail_" + product.id + "' value='" + product.avail + "' /></div>" +
							"<div class='qogr_price'>" + QuickOrder.DisplayCurrency(product.price) + "</div>" + 
							"<div class='qogr_img'>" + QuickOrder.Thumbnail(product.thmb, product.id, 25, 25) + "</div>" +
							"<div class='qogr_prodname'>" + QuickOrder.DisplayProductName(product.id, product.code, product.name) + "</div>" + 
							"</div>";
					});
				
					if (json.pagination_required == "Y")
					{
						sHtml = sHtml + "<div class='qo_prod_pagination'>";
					
						if (json.page_no > 1)
							sHtml = sHtml + "<a href='javascript:QuickOrder.ShowMainCategory(" + id + ", " + (page_no-1) + ");'>Previous</a>";
						
						for (var k = 1; k <= (json.product_count / 500); k++)
						{
							sHtml = sHtml + "<a href='javascript:QuickOrder.ShowMainCategory(" + id + ", " + k + ");'";
						
							if (k == page_no)
								sHtml = sHtml + " class='selected'";
						
							sHtml = sHtml + ">" + k + "</a>";
						}
					
						if ((json.product_count / 500) > json.page_no)
							sHtml = sHtml + "<a href='javascript:QuickOrder.ShowMainCategory(" + id + ", " + (page_no+1) + ");'>Next</a>";

						sHtml = sHtml + "</div>";
					}
					$qo("#qo_product_grid").html(sHtml);
					QuickOrder.EnableProductBox();
				}
				else // no products found, show subcategories instead
				{
					// first get all sub-categories
					$qo.getJSON("exm_quickorder/ajax_funcs.php?method=sub_categories&cat_id=" + id,
					function(json2) {
						sHtml = sHtml + "<ul class='show_subcat'>";
						$qo.each(json2.subcategories, function(i, subcat)
						{
							sHtml = sHtml + "<li>";
							sHtml = sHtml + "<a href='javascript:QuickOrder.ShowSubcategory(" + 
								subcat.categoryid + ", " + subcat.parentid + ");'>" + 
								subcat.categoryname + "</a>";
							sHtml = sHtml + "</li>";
						});
						sHtml = sHtml + "</ul>";
						$qo("#qo_product_grid").html(sHtml);
						QuickOrder.EnableProductBox();
					});
				}
			}
		);
	},
	
	MainPanelMessage: function(msg)
	{
		$qo("#qo_product_grid").html("<div class='mainpanel_loading'><img src='exm_quickorder/images/spinner.gif' /><h1>" + 
			msg + "</h1></div>");
	},
	
	ShowSubcategory: function(id, parentid)
	{
		QuickOrder.MainPanelMessage(QuickOrder.Labels.loading_elips);
	
		$qo("#qo_category_list a").removeClass("selected");
		$qo("#ll_category_" + parentid).addClass("selected");
		$qo("#li_subcats_" + parentid).show();

		$qo.getJSON("exm_quickorder/ajax_funcs.php?method=products_by_subcategory&cat_id=" + id,
			function(json) {
				var sHtml = "";
				$qo.each(json.categories, function(i,subcat)
				{
					var subcat_prod_count = "";
					if (subcat.product_count > 1)
						subcat_prod_count = subcat.product_count.toString() + " " + QuickOrder.Labels.products;
					else
						subcat_prod_count = subcat.product_count.toString() + " " + QuickOrder.Labels.product;

					// writing HTML for subcategory headings
					sHtml = sHtml + "<div class='qopg_catheading'>" +
						subcat.category_name + " - (" + subcat_prod_count + ")</div>";

					// writing HTML for product listings
					$qo.each(subcat.products, function(j,product)
					{
						var sAlt = "";
						if (j % 2 == 1)
							sAlt = " qogr_alt";

						sHtml = sHtml + 
						"<div class='qo_product_gridrow" + sAlt + "'>" +
						"<div class='qogr_qty'><input type='text' size='3' maxlength='4' value='" + product.minam + "' id='qty_" + 
							product.id + "' /> <input type='button' onclick='QuickOrder.AddToCartFromProductList(" + 
							product.id + ")', class='plus_button' value=' + ' />" +
							"<input type='hidden' id='optcount_" + product.id + "' value='" + product.opts + "' />" +
							"<input type='hidden' id='min_qty_" + product.id + "' value='" + product.minam + "' />" +
							"<input type='hidden' id='avail_" + product.id + "' value='" + product.avail + "' /></div>" +
						"<div class='qogr_price'>" + QuickOrder.DisplayCurrency(product.price) + "</div>" + 
						"<div class='qogr_img'>" + QuickOrder.Thumbnail(product.thmb, product.id, 25, 25) + "</div>" +
						"<div class='qogr_prodname'>" + QuickOrder.DisplayProductName(product.id, product.code, product.name) + "</div>" + 
						"</div>";
					});
				});

				$qo("#qo_product_grid").html(sHtml);
				QuickOrder.EnableProductBox();
			}
		);
	},
	
	ShowManufacturer: function(id)
	{
		$qo("#qo_manufacturer_list a").removeClass("selected");
		$qo("#ll_manufacturer_" + id).addClass("selected");
		$qo.getJSON("exm_quickorder/ajax_funcs.php?method=products_by_manufacturer&manufacturer_id=" + id,
			function(json) {
				var sHtml = "";
				$qo.each(json.categories, function(i,subcat)
				{
					var subcat_prod_count = "";
					if (subcat.product_count > 1)
						subcat_prod_count = subcat.product_count.toString() + " " + QuickOrder.Labels.products;
					else
						subcat_prod_count = subcat.product_count.toString() + " " + QuickOrder.Labels.product;
					
					// writing HTML for subcategory headings
					sHtml = sHtml + "<div class='qopg_catheading'>" +
						subcat.category_name + " - (" + subcat_prod_count + ")</div>";

					// writing HTML for product listings
					$qo.each(subcat.products, function(j,product)
					{
						var sAlt = "";
						if (j % 2 == 1)
							sAlt = " qogr_alt";
					
						sHtml = sHtml + 
						"<div class='qo_product_gridrow" + sAlt + "'>" +
						"<div class='qogr_qty'><input type='text' size='3' maxlength='4' value='" + product.minam + "' id='qty_" + 
							product.id + "' /> <input type='button' onclick='QuickOrder.AddToCartFromProductList(" + 
							product.id + ")', class='plus_button' value=' + ' />" +
							"<input type='hidden' id='optcount_" + product.id + "' value='" + product.opts + "' />" +
							"<input type='hidden' id='min_qty_" + product.id + "' value='" + product.minam + "' />" +
							"<input type='hidden' id='avail_" + product.id + "' value='" + product.avail + "' /></div>" +
						"<div class='qogr_price'>" + QuickOrder.DisplayCurrency(product.price) + "</div>" + 
						"<div class='qogr_img'>" + QuickOrder.Thumbnail(product.thmb, product.id, 25, 25) + "</div>" +
						"<div class='qogr_prodname'>" + QuickOrder.DisplayProductName(product.id, product.code, product.name) + "</div>" + 
						"</div>";
					});
					
				});
				
				$qo("#qo_product_grid").html(sHtml);
				QuickOrder.EnableProductBox();
			}
		);
	},

	AddToCartFromProductList: function(productid)
	{
		var qty = parseInt($qo("#qty_" + productid).val());
		var minqty = parseInt($qo("#min_qty_" + productid).val());
		var maxqty = parseInt($qo("#avail_" + productid).val());
		var optcount = parseInt($qo("#optcount_" + productid).val());
		var tot_qty = qty;
		
		// we need to check that this won't go over maximum quantity...
		for (var i = 0; i < QuickOrder.cart.length; i++)
		{
			if (productid == QuickOrder.cart[i]["productid"])
			{
				tot_qty = qty + parseInt(QuickOrder.cart[i]["quantity"]);
			}
		}
		
		if (!QuickOrder.Configuration.allow_backorders)
		{
			if ((qty >= minqty) && (tot_qty <= maxqty))
			{
				QuickOrder.AddToCart(productid, qty, optcount);
			}
			else
			{
				if (qty < minqty)
				{
					alert("Sorry, you must order at least " + minqty + " of this product");
					$qo("#qty_" + productid).val(minqty); document.getElementById("qty_" + productid).focus();
				}
				else if (tot_qty > maxqty)
				{
					alert("Sorry, there is not enough in stock. At present, we only have a maximum of " + maxqty + " to sell.");
					$qo("#qty_" + productid).val(maxqty); document.getElementById("qty_" + productid).focus();
				}
			}
		}
		else
		{
			QuickOrder.AddToCart(productid, qty, optcount);
		}
	},
	
	AddToCartFromSearchBar: function()
	{
		var productid = $qo("#hdn_qo_searchboxselected").val();
		var qty = parseInt($qo("#qo_search_qty").val());
		var tot_qty = qty;
		
		if (productid.length > 0)
		{
			$qo.getJSON("exm_quickorder/ajax_funcs.php?method=product_from_id&productid=" + productid, 
				function(json)
			{
				// we need to check that this won't go over maximum quantity...
				for (var i = 0; i < QuickOrder.cart.length; i++)
				{
					if (productid == QuickOrder.cart[i]["productid"])
					{
						tot_qty = qty + parseInt(QuickOrder.cart[i]["quantity"]);
					}
				}
				
				if (productid > 0)
				{
					var maxqty = parseInt(json.avail);
					var minqty = parseInt(json.minam);
					var optcount = parseInt(json.opts);
				
					if (!QuickOrder.Configuration.allow_backorders)
					{
						if ((qty >= minqty) && (tot_qty <= maxqty))
						{
							QuickOrder.AddToCart(productid, qty, optcount);
							$qo("#qo_search, #QuickOrder.search_qty").removeClass("searchbox_selected");
							if (QuickOrder.searchbox_filter == "SKU")
								$qo("#qo_search").val(QuickOrder.Labels.sku);
							else
								$qo("#qo_search").val(QuickOrder.Labels.product_name);
					
							$qo("#qo_search_qty").val(QuickOrder.Labels.qty);
						}
						else
						{
							if (qty < minqty)
							{
								alert(QuickOrder.Labels.must_order_at_least.replace('###QTY###', minqty));;
								$qo("#qo_search").val(""); $qo("#QuickOrder.search_qty").val(""); document.getElementById("qo_search").focus();
							}
							else if (tot_qty > maxqty)
							{
								alert(QuickOrder.Labels.insufficient_stock.replace('###QTY###', maxqty));
								$qo("#qo_search").val(""); $qo("#QuickOrder.search_qty").val(""); document.getElementById("qo_search").focus();
							}
						}
					}
					else
					{
						QuickOrder.AddToCart(productid, qty, optcount);
						$qo("#qo_search, #QuickOrder.search_qty").removeClass("searchbox_selected");
						if (QuickOrder.searchbox_filter == "SKU")
							$qo("#qo_search").val(QuickOrder.Labels.sku);
						else
							$qo("#qo_search").val(QuickOrder.Labels.product_name);
					
						$qo("#qo_search_qty").val(QuickOrder.Labels.qty);
					}
				}
				else
				{
					alert(QuickOrder.Labels.could_not_find_product);
					$qo("#qo_search").val(""); $qo("#QuickOrder.search_qty").val(""); document.getElementById("qo_search").focus();
				}
			});
		}
		else
		{
			alert(QuickOrder.Labels.could_not_find_product);
			$qo("#qo_search").val(""); $qo("#QuickOrder.search_qty").val(""); document.getElementById("qo_search").focus();
		}
	},
	
	AddToCart: function(productid, qty, optcount)
	{
		$qo.getJSON("exm_quickorder/ajax_funcs.php?method=set_cart_contents&productid="+productid+"&qty="+qty+"&mode=add", 
			function(json){
			
			if (parseInt(optcount) > 0)
			{
				//$qo.get("cart.php");
				QuickOrder.ProductOptions.Edit(productid);
			}
			else
			{
				QuickOrder.cart.length = 0;
				$qo.each(json.cart.products, function(i,item)
				{
					QuickOrder.cart.push({
						"productid": item.id,
						"productcode": item.code,
						"productname": item.name,
						"price": item.price,
						"quantity": item.qty,
						"thumbnail": item.thmb,
						"option_count": item.opts,
						"cartid": item.cid,
						"min_amount": item.minam,
						"avail": item.avail,
						"product_options": item.optstext
					});
				});
				
				QuickOrder.UpdateCartTotals(
					json.cart.subtotal,
					json.cart.shipping,
					json.cart.taxes,
					json.cart.discount,
					json.cart.total
				);
				QuickOrder.UpdateCartDisplay();
			}
		});
	},
	
	UpdateCart: function(productid, qty, json)
	{
		// does the product already exist in the cart? if so, update its quantity
		var isnewproduct = 1;
		for (var i = 0; i < QuickOrder.cart.length; i++)
		{
			if (QuickOrder.cart[i]["productid"] == productid)
			{
				// update product's quantity
				QuickOrder.cart[i]["quantity"] = parseInt(QuickOrder.cart[i]["quantity"]) + parseInt(qty);
				QuickOrder.UpdateAjaxMiniCartMod();
			}
		}
	},
	
	
	// right-hand cart section
	
	EditQuantity: function(productid)
	{
		var quantity = 0;
		for (var i = 0; i < QuickOrder.cart.length; i++)
		{
			if (QuickOrder.cart[i]["productid"] == productid)
			{
				quantity = QuickOrder.cart[i]["quantity"];
			}
		}
		sHtml = QuickOrder.Labels.qty + ": <input type='text' value='" + quantity + "' id='txtQtyEdit_" + productid + "' class='txtEditQty' /> - <a href='javascript:QuickOrder.SaveQuantity(" + productid + ");'>Save</a>";
		$qo("#lblQuantityBox_" + productid).html(sHtml);
	},
	
	SaveQuantity: function(productid)
	{
		var qty = parseInt($qo("#txtQtyEdit_" + productid).val());
		if (qty > 0)
		{
			var minqty = parseInt($qo("#cart_minqty_" + productid).val());
			var maxqty = parseInt($qo("#cart_maxqty_" + productid).val());

			if (!QuickOrder.Configuration.allow_backorders)
			{
				if ((qty >= minqty) && (qty <= maxqty))
				{
					for (var i = 0; i < QuickOrder.cart.length; i++)
					{
						if (QuickOrder.cart[i]["productid"] == productid)
						{
							QuickOrder.cart[i]["quantity"] = qty;
						}
					}
					QuickOrder.LoadingPanel.Show(QuickOrder.Labels.updating_cart_elips);
					var page="exm_quickorder/ajax_funcs.php?method=set_cart_contents&productid="+productid+"&qty="+qty+"&mode=modify";	
					$qo.get(page, function(data){
						$qo.get("cart.php", function(data){
							QuickOrder.ShowExistingCart();
						});
					});
				}
				else
				{
					if (qty < minqty)
					{
						alert(QuickOrder.Labels.must_order_at_least.replace('###QTY###', minqty));
						$qo("#txtQtyEdit_" + productid).val(minqty); document.getElementById("txtQtyEdit_" + productid).focus();
					}
					else if (qty > maxqty)
					{
						alert(QuickOrder.Labels.insufficient_stock.replace('###QTY###', maxqty));
						$qo("#txtQtyEdit_" + productid).val(maxqty); document.getElementById("txtQtyEdit_" + productid).focus();
					}
				}
			}
			else
			{
				for (var i = 0; i < QuickOrder.cart.length; i++)
				{
					if (QuickOrder.cart[i]["productid"] == productid)
					{
						QuickOrder.cart[i]["quantity"] = qty;
					}
				}
				QuickOrder.LoadingPanel.Show(QuickOrder.Labels.updating_cart_elips);
				var page="exm_quickorder/ajax_funcs.php?method=set_cart_contents&productid="+productid+"&qty="+qty+"&mode=modify";	
				$qo.get(page, function(data){
					$qo.get("cart.php", function(data){
						QuickOrder.ShowExistingCart();
					});
				});
			}
		} else {
			alert(QuickOrder.Labels.qty_must_above_zero);
		}
	},
	
	DeleteItem: function(productid)
	{
		for (var i = 0; i < QuickOrder.cart.length; i++)
		{
			if (QuickOrder.cart[i]["productid"] == productid)
			{
				QuickOrder.cart.splice(i, 1);
			}
		}
		QuickOrder.LoadingPanel.Show(QuickOrder.Labels.updating_cart_elips);
		var page="exm_quickorder/ajax_funcs.php?method=set_cart_contents&productid="+productid+"&mode=delete";	
		$qo.get(page, function(data){
  			QuickOrder.ShowExistingCart();
		});
	},
	
	Clear: function()
	{
		QuickOrder.cart.length = 0;
		QuickOrder.LoadingPanel.Show(QuickOrder.Labels.clearing_cart_elips);
		$qo.get("cart.php?mode=clear_cart", function(data){
  			QuickOrder.ShowExistingCart();
		});
	},
	
	Checkout: function()
	{
		QuickOrder.LoadingPanel.Show(QuickOrder.Labels.checkout_elips);
		window.location.href = "cart.php";
	},
	
	UpdateCartDisplay: function()
	{
		var sHtml = "";
		for (i=0; i < QuickOrder.cart.length; i++)
		{
			sHtml += '<div class="productinfo">';
			sHtml += QuickOrder.Thumbnail(QuickOrder.cart[i]["thumbnail"], QuickOrder.cart[i]["productid"], 60, 60);
			sHtml += '<p><b>' + QuickOrder.cart[i]["productname"] + '</b><br />';
			if (QuickOrder.cart[i]["product_options"].length > 4)
			{
				sHtml += "<i>" + QuickOrder.cart[i]["product_options"] + "</i><br />";
			}
			sHtml += '<input type="hidden" id="cart_minqty_' + QuickOrder.cart[i]["productid"] + '" value="' + QuickOrder.cart[i]["min_amount"] + '" />';
			sHtml += '<input type="hidden" id="cart_maxqty_' + QuickOrder.cart[i]["productid"] + '" value="' + QuickOrder.cart[i]["avail"] + '" />';
			sHtml += '<span id="lblQuantityBox_' + QuickOrder.cart[i]["productid"] + '">Qty: <b>' + QuickOrder.cart[i]["quantity"] + '</b> - ';
			sHtml += '<a href="javascript:QuickOrder.EditQuantity(' + QuickOrder.cart[i]["productid"] + ');">' + QuickOrder.Labels.edit + '</a> - ';
			sHtml += '<a href="javascript:QuickOrder.DeleteItem(' + QuickOrder.cart[i]["productid"] + ');">' + QuickOrder.Labels.delete_item + '</a>';
			if (QuickOrder.cart[i]["option_count"] > 0)
			{
				sHtml += ' - <a href="javascript:QuickOrder.ProductOptions.Edit(' + QuickOrder.cart[i]["productid"] + ');">Options</a>';
			}
			var subtotal = parseFloat(QuickOrder.cart[i]["price"]) * parseInt(QuickOrder.cart[i]["quantity"]).toFixed(2);
			
			sHtml += '</span><br />Subtotal: <b>' + QuickOrder.Labels.currency_symbol + QuickOrder.FormatNumber(subtotal) + '</b></p>';
			sHtml += '</div>';
		}
		$qo("#qo_col_right_cart").html(sHtml);
		QuickOrder.EnableProductBox();
		
		// populate summary panel	
		$qo("#lblNoItemsBasket").html(QuickOrder.cart.length);

		$qo("#lblSubtotal").html(QuickOrder.FormatNumber(QuickOrder.cart_totals["subtotal"]));
		$qo("#lblDiscount").html(QuickOrder.FormatNumber(QuickOrder.cart_totals["discount"]));
		$qo("#lblTotal").html(QuickOrder.FormatNumber(QuickOrder.cart_totals["total"]));

		document.getElementById("qo_col_right_cart").scrollTop = document.getElementById("qo_col_right_cart").scrollHeight;
	},
	
	// helper functions
	DisplayProductName: function(productid, pcode, pname)
	{
		if (QuickOrder.Configuration.display_sku)
			return "<a href='exm_quickorder/product_details.php?iframe&pid=" + productid + "' class='zoom'>" + pcode + " - " + pname + "</a>";
		else
			return "<a href='exm_quickorder/product_details.php?iframe&pid=" + productid + "' class='zoom'>" + pname + "</a>";
		
	},

	Thumbnail: function(sThumb, productid, nWidth, nHeight)
	{
		if (QuickOrder.Configuration.use_phpthumb)
			return "<a href='exm_quickorder/product_details.php?iframe&pid=" + productid + "' class='zoom'><img src='exm_quickorder/thumbnail/phpthumb.php?src=" + sThumb + "&q=80&w=" + nWidth + "&h=" + nHeight + "' /></a>";
		else
			return "<a href='exm_quickorder/product_details.php?iframe&pid=" + productid + "' class='zoom'><img src='" + sThumb + "' width='" + nWidth + "' height='" + nHeight + "' /></a>";
	},
	
	EnableProductBox: function()
	{
		$qo("a.zoom").fancybox({ 'frameWidth': 650, 'overlayShow': true }); 
	},
	
	PrintCart: function()
	{
		window.frames['qo_printframe'].src = "exm_quickorder/print_cart.php";
		if ($qo.browser.msie)
		{
			document.qo_printframe.focus();
			document.qo_printframe.print();
		}
		else
		{
			window.frames['qo_printframe'].focus();
			window.frames['qo_printframe'].print();
		} 
	},
	
	// third-party mod compatibility
	DisplayCurrency: function(price)
	{
		if (QuickOrder.Configuration.multi_currency_active)
			return QuickOrder.FormatNumber(QuickOrder.RoundNumToTwoDecimalPlaces(price * QuickOrder.exchange_rate));
		else
			return QuickOrder.FormatNumber(price);
	},
	
	UpdateAjaxMiniCartMod: function()
	{
		if (QuickOrder.Configuration.ajax_minicart_active)
		{
			var post_vars = "action=update&charset=iso-8859-1";
			for (var i = 0; i < QuickOrder.cart.length; i++)
			{
				post_vars += "&productindexes[" + (i+1) + "]=" + QuickOrder.cart[i]["quantity"];
			}
			$qo.post("minicart_content.php", post_vars);
		}
	},
	
	// math and number functions
	IsInteger: function(n)
   	{
    	if(typeof(n)=='number' && /^\d*$qo/.test(n.toString(10)))
			return true;
		else
			return false;
   	},
   	
   	RoundNumToTwoDecimalPlaces: function(n) {
		var s = "" + Math.round(n * 100) / 100;
		var i = s.indexOf('.');
		if (i < 0)
			return s + ".00";
		
		var t = s.substring(0, i + 1) + s.substring(i + 1, i + 3);
		if (i + 2 == s.length) 
			t += "0";
			
		return t;
	},
	
	FormatNumber: function(n)
	{
		n = parseFloat(n).toFixed(2);
		switch(QuickOrder.Configuration.number_format)
		{
			case "2.,":
				n += '';
				var x = n.split('.');
				var x1 = x[0];
				var x2 = x.length > 1 ? '.' + x[1] : '';
				var rgx = /(\d+)(\d{3})/;
				while (rgx.test(x1)) {
					x1 = x1.replace(rgx, '$1' + ',' + '$2');
				}
				return x1 + x2;
				break;
			case "2, ":
				n += '';
				var x = n.split(',');
				var x1 = x[0];
				var x2 = x.length > 1 ? ',' + x[1] : '';
				var rgx = /(\d+)(\d{3})/;
				while (rgx.test(x1)) {
					x1 = x1.replace(rgx, '$1' + ' ' + '$2');
				}
				return x1 + x2;
				break;
			case "2,.":
				n += '';
				var x = n.split(',');
				var x1 = x[0];
				var x2 = x.length > 1 ? ',' + x[1] : '';
				var rgx = /(\d+)(\d{3})/;
				while (rgx.test(x1)) {
					x1 = x1.replace(rgx, '$1' + '.' + '$2');
				}
				return x1 + x2;
				break;
			default:
				return n;
				break;
		}
	},
	
	LoadingPanel:
	{
		Show: function(msg)
		{
			$qo(".plus_button").each( function() { this.disabled = true } );
			$qo("#loading_message").html(msg);
			$qo("#loading_panel").fadeIn('fast');
		},
	
		Hide: function()
		{
			QuickOrder.UpdateCartDisplay();
			$qo("#loading_panel").fadeOut('normal');
			$qo(".plus_button").each( function() { this.disabled = false } );
		}
	},
	
	ProductOptions:
	{
		Edit: function(productid)
		{
			if ($qo.browser.msie)
				$qo("#qo_canvas").show();
			else
				$qo("#qo_canvas").fadeIn("fast");
				
			$qo.getJSON("exm_quickorder/ajax_funcs.php?method=product_options&productid="+productid, 
				function(data) {
				
					// first get default / chosen options
					var aDefOpts = new Array();
					for (var i = 0; i < data.default_options.length; i++)
					{
						aDefOpts.push ({
							"classid":data.default_options[i].classid,
							"optionvalue":data.default_options[i].optionvalue
						});
					}

					// build options dropdowns and text boxes
					var sHtml = "";
					for (var i = 0; i < data.product_options.length; i++)
					{
						var opt = data.product_options[i];
					
						// find the corresponding default/selected option
						var def_option = "";
						for (var d = 0; d < aDefOpts.length; d++)
						{
							if (aDefOpts[d]["classid"] == opt.classid)
								def_option = aDefOpts[d]["optionvalue"];
						}
					
						if (((opt.classtype == "variant") || (opt.classtype == "price_modifier"))
							&& (opt.option_types.length > 1))
						{
							sHtml += "<div><label>" + opt.classtext + "</label>";
							sHtml += "<select id='product_options[" + opt.classid + "]'>";
							for (var j = 0; j < opt.option_types.length; j++)
							{
								var opttype = opt.option_types[j];
								var sSelected = "";
							
								if (opttype.optionid == def_option)
									sSelected = " selected='selected'";
							
								sHtml += "<option value='" + opttype.optionid + "'" + sSelected +
									">" + opttype.option_name + "</option>";
							}
							sHtml += "</select>";
						}
						else if ((opt.classtype == "variant") && (opt.option_types.length == 1))
						{
							sHtml += "<div><label>" + opt.classtext + "</label>";
							sHtml += "<select id='product_options[" + opt.classid + "]'>";
							for (var j = 0; j < opt.option_types.length; j++)
							{
								var opttype = opt.option_types[j];
								var sSelected = "";
							
								if (opttype.optionid == def_option)
									sSelected = " selected='selected'";
							
								sHtml += "<option value='" + opttype.optionid + "'" + sSelected +
									">" + opttype.option_name + "</option>";
							}
							sHtml += "</select>";
						}
						else if (opt.classtype == "text_field")
						{
							sHtml += "<div><label>" + opt.classtext + "</label>";
							sHtml += "<input type='text' value='" + def_option + "' id='product_options[" + opt.classid + "]' />"
						}
					
						sHtml += "</div>";
					}
					
					$qo("#qo_optpop_options").html(sHtml);
					
					// add buttons
					sHtml = "<div><label>&nbsp;</label>" +
								"<input type='button' value='" + QuickOrder.Labels.lbl_continue + 
								" &raquo;' onclick='QuickOrder.ProductOptions.Save(" + productid + ")' />" +
								"</div>";
					$qo("#qo_optpop_buttons").html(sHtml);
	            	
					// now display product information
					var prod = data.product_details;
					sHtml = "<div>" + QuickOrder.Thumbnail(prod.thmb, prod.id, 160, 160) + "</div>";
					sHtml += "<div><b>" + prod.name + "</b></div>";
					sHtml += "<div>" + QuickOrder.Labels.sku + ": " + prod.code + "</div>";
					sHtml += "<div>" + QuickOrder.Labels.price + ": " +
						QuickOrder.Labels.currency_symbol + prod.price + "</div>";
					$qo("#qo_optpop_proddesc").html(sHtml); 
					
					$qo("#qo_optionspopup_outer").show();
			});	
		},
	
		Save: function(productid)
		{
			var cart_id = 0;
			$qo.getJSON("exm_quickorder/ajax_funcs.php?method=get_cart_id&productid="+productid, 
				function(data) {
					var cart_id = data.cartid;
					var sData = "mode=update&id=" + cart_id + "&target=cart&eventid=0";
					
					var aClasses = $qo("#qo_optionspopup select, #qo_optionspopup input");
					for (var i = 0; i < aClasses.length; i++)
					{
						var selId = aClasses[i].id;
						var selOption = $qo(aClasses[i]).val();
						sData += "&" + selId + "=" + selOption;
					}

					$qo.ajax({
   						type: "POST",
   						url: "popup_poptions.php",
   						data: sData,
   						success: function(msg){
							
							$qo.get("cart.php", function(nomatter)
							{
   								$qo("#qo_optionspopup_outer").hide();
   								$qo("#qo_optpop_options").html("");
   								$qo("#qo_canvas").hide();
     							QuickOrder.ShowExistingCart();
							});
   						}
 					});
			});
		}
	},
	
	SearchBar:
	{
		Selected: function(pcode)
		{
			$qo("#hdn_qo_searchboxselected").val(pcode);
			QuickOrder.SearchBar.Clear("qty");
			document.getElementById("qo_search_qty").focus();
			document.getElementById("qo_search_qty").select();
		},
		
		Clear: function(box)
		{
			if (box == "qty")
			{
				$qo("#qo_search_qty").addClass("searchbox_selected");
				$qo("#qo_search_qty").val("1");
			}
			else if (box == "search")
			{
				$qo("#qo_search").addClass("searchbox_selected");
				$qo("#qo_search").val("");
			}
		}
	}
};
	


	
	

