(function($){
	$.fn.attachAsyncCart = function(options){
		var settings = {
			url: '/cart',
			successMessage: 'Selected product has been added to your cart',
			showCart: 'Show shopping cart',
			errorMessage: 'An error has occured while adding the product to your cart. We aplogize for any inconvenince.',
			invalidItemCount: 'Please enter correct number of items'
		};
		
		if (options)
		{
			$.extend(settings, options);
		}
		
		return this.each(function(){
			$(this).bind('click', function(event){
				var productId = $(this).parent().find("input[name=product]").val();
				var qty = $(this).parent().find("input[name=qty]").val();
				var op = $(this).parent().find("input[name=op]").val();
				var step = $(this).parent().find("input[name=step]").val();
				
				var responseCode = null;
				
				$.ajax({
					async: false,
					type: 'POST',
					url: settings.url,
					data:
					{
						product: productId,
						qty: qty,
						async: 1,
						op: op,
						step: step
					},
					success: function(data, textStatus, xhr)
					{
						responseCode = xhr.status;
					},
					error: function(xhr, textStatus, errorThrown)
					{
						responseCode = xhr.status;
					}
				});
				
				if (200 == responseCode)
				{
					var message = $('<div class="asyncCartOk">'
						+ '<p>' + settings.successMessage + '</p>'
						+ '<a href="' + settings.url + '">' + settings.showCart + '</a>'
						+ '</div>');
					$('body').append(message);
					
					message.fadeIn();
					message.offset({top: $(window).scrollTop() + ($(window).height() / 3), left: $(window).width() / 2 - message.width() / 2});
					message.delay(1700).fadeOut();
					window.setTimeout( (function() { message.remove(); }), 2000 );
				}
				else
				{
					var message = $('<div class="asyncCartError">' + (412 == responseCode ? settings.invalidItemCount : settings.errorMessage ) + '</div>');
					$('body').append(message);
					message.fadeIn();
					message.offset({top: $(window).scrollTop() + ($(window).height() / 3), left: $(window).width() / 2 - message.width() / 2});
					message.delay(1500).fadeOut();
					window.setTimeout( (function() { message.remove(); }), 3000 );
				}
				
				return false;
			});
		});
	};
})(jQuery);
