$(function() {
	$(".progressbar").each(function() {
		$(this).progression({
			Current: $(this).text(),
			Animate: false,
			aBackground: "#EEE",
			BorderColor: "#CCC",
			TextColor: "#333",
			aTextColor: "#333",
			Width: "100%"
		}); 
	});
	
	$("div.catalog_filter select").change(function() {
		uri = document.location.pathname + $.query.set("filter_id", $(this).val()).toString();
		window.open(uri, '_self');
	});

	$("#show_sub_categories").click(function() {
		uri = document.location.pathname + $.query.set("show_sub_categories", $(this).attr("checked") ? "true" : "false").toString();
		window.open(uri, '_self');
	});
	
	$(".favorite_type").click(function() {
		uri = document.location.pathname + $.query.set("type", $(this).val()).toString();
		window.open(uri, '_self');
	});
	
	$(".quickorder_remove").livequery("click", function() {
		var tr = $(this).parent().parent();
		$(".quickorder_quantity", tr).val(0);
		$(".name", tr).toggleClass("crossed");
		$(this).hide();
		quickorder_recalc();
		quickorder_show_change_notification();
		return false;
	});
	
	$(".quickorder_quantity").numeric().livequery("change", function() {
		var tr = $(this).parent().parent();
		
		if (($.trim($(this).val()) == '') || (parseInt($(this).val()) == 0)) {
			$(this).val(0);
			$(".quickorder_remove", tr).click();
			return false;
		} else if ($(".name", tr).hasClass("crossed")) {
			$(".name", tr).toggleClass("crossed");
			$(".quickorder_remove", tr).show();
		}
		quickorder_recalc();
		quickorder_show_change_notification();
		return false;
	});
	
	$(".quickorder_lookup").click(function() {
		quickorder_open_page(0);
		return false;
	});
	
	$(".quickorder_product").keydown(function(e) {
		if (e.keyCode == 13) {
			$(".quickorder_lookup").click();
		}
	});
	
	$(".product_search_cancel").livequery("click", function() {
		$.unblockUI();
		return false;
	});
	
	$("a.quickorder_buy_now").livequery("click", function() {
		$.unblockUI();
		var product_id = $(this).attr("href").substring($(this).attr("href").indexOf("#") + 1);
		if (!quickorder_is_product_purchased(product_id)) {
			quickorder_add_product(product_id);
		}
		$(".quickorder_product").val("");
		return false;
	});
	
	$(".blockUI td.name a").livequery("click", function() {
		$.unblockUI();
		var product_id = $(this).attr("href").split("=")[1];
		if (!quickorder_is_product_purchased(product_id)) {
			quickorder_add_product(product_id);
		}
		$(".quickorder_product").val("");
		return false;
	});
	
	$("p.quickorder_page_nav a").livequery("click", function() {
		$.unblockUI();
		var page = $(this).attr("href").substring($(this).attr("href").indexOf("#") + 1);
		quickorder_open_page(page);
		return false;
	});
	
	$(".quickorder_savecart").click(function() {
		quickorder_savecart(function() {
			document.location.reload();
		});
		return false;
	});
	
	$(".quickorder_checkout").click(function() {
		quickorder_savecart(function() {
			window.open("checkout_shipping.php", '_self');
		});
		return false;
	});
	
	$("p.checkout_selection").hover(function() {
		$(this).toggleClass("checkout_hover");
	}, function() {
		$(this).toggleClass("checkout_hover");
	}).click(function() {
		$("p.checkout_selection").removeClass("checkout_selected");
		$(this).addClass("checkout_selected");
		$(this).find("input").attr("checked", true);
	});
	
	qty_block_hide_all();
});
	
function qty_block_hide_all() {
	$("td.qty_block img").fadeOut("normal", qty_block_show_all);
}

function qty_block_show_all() {
	$("td.qty_block img").fadeIn("normal", qty_block_hide_all);
}

function quickorder_savecart(callback) {
	if ($("input[name='cart_changed']").val() == "yes") {
		$.blockUI({message: "<div class=\"quickorder_savecart\">" + LANG.MSG_CART_SAVING + "</div>"});
		
		var cart = {};
		$("table.product_list input.product_id").each(function(idx) {
			var product_id = $(this).val();
			var tr = $(this).parent().parent();
			var qty = parseInt(tr.find(".quickorder_quantity").val());
			
			cart[product_id] = qty;
		});
		
		$.post("ajax/quickorder_save.php", cart, function(data) {
			$.unblockUI();
			callback();
		});
	} else {
		callback();
	}
}

function quickorder_highlight_cart(product_id, text) {
	var name = $("input.product_id[value='" + product_id + "']").parent().parent().find("td.name a");
	name.css("color", "#C00").css("font-weight", "bold");
	if (text != null) alert(text);
	setTimeout(function() {
		name.css("color", "").css("font-weight", "");
	}, 1500);
	$result = true;
}

function quickorder_is_product_purchased(product_id) {
	var cart = JSON.parse($("input[name='cartinfo']").val());
	$result = false;
	$.each(cart, function(i, product) {
		if (parseInt(product.products_id) == product_id) {
			var qty = $("input.product_id[value='" + product_id + "']").parent().parent().find("input.quickorder_quantity");
			if (qty.val() <= 0) qty.val(1).change();
			quickorder_highlight_cart(product_id, LANG.TEXT_PRODUCT_EXISTS_IN_CART);
			$result = true;
		}
	});
	return $result;
}

function quickorder_add_product(product_id) {
	var tr = $(".quickorder_product").parent().parent();
	
	$.getJSON("ajax/product_info.php?p=" + encodeURIComponent(product_id), null, function(data) {
		var cart = JSON.parse($("input[name='cartinfo']").val());
		if (data[0] != false) {
			tr.toggleClass("odd").toggleClass("even").before("<tr class=\"data\"><td class=\"remove\"><input type=\"hidden\" class=\"product_id\" value=\"" + product_id + "\" /><a href=\"#\" class=\"quickorder_remove\"><img src=\"/shop/includes/languages/english/images/buttons/small_delete.gif\" /></a></td><td class=\"image\">" + (data[0].products_image == null ? "&nbsp;" : "<a href=\"/contents/products/" + data[0].products_image + "\" class=\"thickbox-" + product_id + "\"><img src=\"/shop/images/camera.png\" alt=\"\" width=\"18\" height=\"18\" /></a>") + "</td><td class=\"qty_block\">" + (parseInt(data[0].products_qty_blocks) > 1 ? "<img src=\"/shop/images/package.png\" alt=\"\" width=\"18\" height=\"18\" />" : "&nbsp;") + "</td><td class=\"price_break\">" + (parseInt(data[0].products_price1_qty) > 0 ? "<img src=\"/shop/images/currency_dollar.png\" alt=\"\" width=\"18\" height=\"18\" />" : "&nbsp;") + "</td><td class=\"name\"><a href=\"product_info.php?products_id=" + product_id + "\"><small>" + data[0].products_ref_id + "</small><br/>" + data[0].products_name + "</a></td><td class=\"quantity\"><input type=\"text\" size=\"4\" class=\"quickorder_quantity\" value=\"1\" /></td><td class=\"price\">" + quickorder_get_price_string(data[0]) + "</td><td class=\"total\">" + quickorder_get_total_string(data[0]) + "</td></tr>");
			
			tr.prev().addClass(tr.hasClass("odd") ? "even" : "odd");
			tb_init("a.thickbox-" + product_id);
			quickorder_highlight_cart(product_id);
			
			cart.push(data[0]);
			$("input[name='cartinfo']").val(JSON.stringify(cart));
			
			quickorder_recalc();
			quickorder_show_change_notification();
		}
	});
}

function quickorder_get_price_string(product) {
	if (product.products_price == null) {
		return "<a href=\"login.php\" class=\"login_for_price\">" + LANG.TEXT_LOGIN_FOR_PRICE + "</a>";
	} else {
		var price;
		if (isset_currency(product.customers_group_price)) {
			price = format_currency(product.customers_group_price);
		} else {
			price = format_currency(product.products_price);
		}
		
		for (var i = 8; i > 0; i--) {
			if (isset_currency(product["products_price" + i + "_qty"])) {
				price = "<span class=\"product_price_range1\">"  + format_currency(product["products_price" + i]) + "</span>-<span class=\"product_price_range2\">" + price + "</span>";
				break;
			}
		}
		
		if (isset_currency(product.specials_new_products_price)) {
			var specials = format_currency(product.specials_new_products_price);
			price = "<span class=\"product_price_special\"><span>" + price + "</span>" + specials + "</span>";
		}
		
		return price;
	}
}

function quickorder_get_total_string(product, quantity) {
	if (typeof(quantity) == "undefined") quantity = 1;
	
	if (product.products_price == null) {
		return "&nbsp;";
	} else {
		var price;
		if (isset_currency(product.customers_group_price)) {
			price = format_currency(product.customers_group_price);
		} else {
			price = format_currency(product.products_price);
		}
		
		for (var i = 8; i > 0; i--) {
			if (isset_currency(product["products_price" + i + "_qty"])) {
				if (quantity >= parseFloat(product["products_price" + i + "_qty"])) {
					price = format_currency(product["products_price" + i]);
				}
			}
		}
		
		if (isset_currency(product.specials_new_products_price)) {
			var specials = format_currency(product.specials_new_products_price);
			price = specials;
		}
		
		return price;
	}
}

function quickorder_select_price(product, quantity) {
	if (typeof(quantity) == "undefined") quantity = 1;
	
	if (product.products_price == null) {
		return 0;
	} else {
		var price;
		if (isset_currency(product.customers_group_price)) {
			price = round_currency(product.customers_group_price);
		} else {
			price = round_currency(product.products_price);
		}
		
		for (var i = 8; i > 0; i--) {
			if (isset_currency(product["products_price" + i + "_qty"])) {
				if (quantity >= parseFloat(product["products_price" + i + "_qty"])) {
					price = round_currency(product["products_price" + i]);
				}
			}
		}
		
		if (isset_currency(product.specials_new_products_price)) {
			var specials = round_currency(product.specials_new_products_price);
			price = specials;
		}
		
		return price;
	}
}

function quickorder_open_page(page) {
	var keyword = $.trim($(".quickorder_product").val());
	if (keyword == "") return false;
	
	$.get("ajax/product_search.php?s=" + encodeURIComponent(keyword) + "&p=" + page, function(data) {
		var search_status = JSON.parse($(data).eq(0).val());
		
		if (search_status[0] == false) {
			alert(LANG.ERROR_PRODUCT_NOT_FOUND);
			$(".quickorder_product").val("");
			return;
		}
		
		if ((search_status[0] == true) && (search_status[1] == 1)) {
			if (!quickorder_is_product_purchased(search_status[2])) {
				quickorder_add_product(search_status[2]);
			}
			$(".quickorder_product").val("");
			return;
		}

		$.blockUI({
			message: data,
			css: { 
				border: "none", 
				padding: "8px", 
				cursor: "default",
				width: "84%",
				left: "8%",
				top: "8%"
			}
		});
	});
}

function quickorder_recalc() {
	var cart = JSON.parse($("input[name='cartinfo']").val());
	var subtotal = 0;
	
	$("table.product_list input.product_id").each(function(idx) {
		var product_id = $(this).val();
		var tr = $(this).parent().parent();
		
		if (tr.find(".price").text() != LANG.TEXT_LOGIN_FOR_PRICE) {
			var qty = parseInt(tr.find(".quickorder_quantity").val());
			var price = quickorder_select_price(cart[idx], qty);
			
			var total = format_currency(price * qty);
			subtotal += price * qty;
			
			tr.find(".total").text(total);
		}
	});
	
	$(".order_total_subtotal").text(format_currency(subtotal));
	
	var percent = parseInt($("input[name='discount_percent']").val());
	var discount = subtotal * percent / 100;
	$(".order_total_discount").text("-" + format_currency(discount));
	$(".order_total_total").text(format_currency(subtotal - discount));
}

function quickorder_show_change_notification() {
	$("input[name='cart_changed']").val("yes");
	$("div.cart_changed").show();
	$(".quickorder_savecart").show();
}

function isset_currency(value) {
	return (value != null) && (value > 0);
}

function round_currency(value) {
	return Math.round(parseFloat(value) * 100) / 100;
}

function format_currency(value) {
	var price = String(Math.round(parseFloat(value) * 100));
	switch (price.length) {
		case 1:
			return "$0.00";
		case 2:
			return "$0." + price;
		default:
			var str = "";
			for (var i = price.length - 2; i >= 0; i -= 3) {
				var pos = i - 3;
				if (pos > 0) {
					str = "," + price.substring(pos, pos + 3) + str;
				} else {
					str = price.substring(0, i) + str;
				}
			}
			return "$" + str + "." + price.substring(price.length - 2);
	}
}
