// Requires: overlays.js

String.prototype.trim = function() { return this.replace(/^\s+|\s+$/g,''); };

// When DOM is ready, do ...
$(function() {

	$("button.pr_buy").click(function() {
		//$(this).attr("disabled",true);
		
		// Construct parameters.
		var product = $(this).parents(".product").eq(0);
		if (product.length == 0 || product.attr("id") == undefined)
		{
			// Invalid template!
			return false;
		}
		var id = product.attr("id");

		// Quantity is 1 if there's no quantity field or the value is not an integer > 0.
		var quantity = 1;
		var quantity_field = product.find("input.quantity");
		if (quantity_field.length)
		{
			var quantity_value = parseInt(quantity_field.val());
			if (quantity_value > 0)
			{
				quantity = quantity_value;
			}
		}

		var params = {
			add_to_cart: true,
			product_id: id,
			quantity: quantity
		};

		// Options.
		var menu_group_count = product.find(".product_options_menu_group").length;
		if (menu_group_count > 0)
		{
			params.options = [];
			
			product.find(".product_options_menu_group").each(function() {
				var input = $(this).find(":input");
				// In case of radio buttons, filter to the checked one.
				if (input.length > 1) input = input.filter(":checked");
				params.options.push(input.val());
			});
		}
		
		// Customer text field.
		var customer_text_field = product.find(".customer_text");
		if (customer_text_field.length)
		{
			params.customer_text = customer_text_field.val().trim();
		}
		

		// Add product to cart with Ajax.
		$.post(AJAX_URL + "/add_to_cart_ajax.php", params, function(data) {
			if (data.success)
			{
				if (data.redirect_to_shopping_cart_page)
				{
					window.location = data.shopping_cart_url;
				}
				else
				{
					// Inform with a layer that product has been added to shopping cart.
					if ($(data.overlay).hasClass("modal"))
					{
						ShowModalOverlay(product, data.overlay);
					}
					else
					{
						ShowFadingOverlay(data.overlay);
					}
					
					// Update shopping cart preview if it exists.
					var sc_preview = $("#sc_preview");
					if (sc_preview.length && data.sc_preview)
					{
						sc_preview.replaceWith(data.sc_preview);
					}
				}
			}
			else
			{
				if (data.product_options_overlay)
				{
					var options = {
						onBeforeClose: function(e) {
							var element = e.originalTarget || e.srcElement;
							
							// If overlay is closing by Save click.
							if ($(element).hasClass("add_to_cart"))
							{
								product.find("button.pr_buy").click();
							}
						}
					};
					ShowModalOverlay(product, data.product_options_overlay, options);
				}
				else
				{
					ShowModalOverlay(product, data.overlay);
				}
			}

		}, "json");
	});
	
	
	$(".overlay_close").live("click", function() {
		return false;
	});
});

