function naturalNumberInput(el, length)
{
	var test = new RegExp('^[1-9]+[0-9]{0,' + length + '}$');
	var value = test.exec($(el).val());
	if (value == null)
	{
		value = 1;
		$(el).val('1');
	}
	return Number(value);
}

function updateSumPrice(multiplier, product)
{
	var price = $('.price', product);
	var currency_format = $('.currency_format', product);
	var currency_sign = $('.currency_sign', product);
	var value = price.text() * multiplier;
	if (price.length && currency_format.length && currency_sign.length)
	{
		$('.sum', product).html($.sprintf(currency_format.text(), value, currency_sign.text()));
		$('.sum_value', product).text($.sprintf('%1.2f', value));
		var cart = $(product).closest('.cart');
		if (cart.length)
		{
			var total = 0;
			$('.sum_value', cart).each(function(){
				total += Number($(this).text());
			});
			$('.total', cart).html($.sprintf(currency_format.text(), total, currency_sign.text()));
		}
	}
}

var loadingImage = '<img class="loading" style="border: 0px; margin: auto;" src="/images/loading.gif" alt="" />';
var errorImage = '<img class="error" style="border: 0px; margin: auto;" src="/images/cross.gif" alt="&#215;" />';

jQuery.fn.catalogJumps = function()
{
	var jumps = $(this);
	$('a', this).click(function(){
		var el = jumps.clone(true);
		jumps.replaceWith(loadingImage);
		var page = $(this).attr('href').substr(1);
		$.ajax({
			type: 'POST',
			url: '/req/',
			data: 'go=catalog&action=show&catalog_page=' + page,
			success: function(data){
				$('#catalog_list').html(data);
				$('#catalog_list .jumps').catalogJumps();
			},
			complete: function(){
				$('img.loading', jumps.parent()).replaceWith(el);
			}
		});
	});
	return false;
};

function ping()
{
	var d = new Date();
	$.get('/ping/', { ie: d.getTime() });
	setTimeout('ping()', 900000);
}

$(document).ready(function(){

	// Make ready my ping, general!
	setTimeout('ping()', 900000);

	// Update price on page load
	var updateTotalPrice = function(){
		$('.cart .product input.quantity').each(function(){
			updateSumPrice($(this).val(), $(this).closest('.product'));
		});
	};
	updateTotalPrice();

	// Add to cart
	$('a.add_to_cart').click(function(){
		var parent = $(this).parent();
		var el = $(this).clone(true);
		$(this).replaceWith(loadingImage);
		$('#cart').load(
			'/req/ #cart > *', {
				go: 'cart_info',
				action: 'add',
				prod_id: $('.prod_id', parent).val(),
				site_lng: $('.site_lng', parent).val()
			},
			function(){
				parent.find('img.loading').replaceWith(el);
			}
		);
		return false;
	});

	// Remove from cart
	$('.cart .product .remove').click(function(){
		var product = $(this).closest('.product');
		var el = $(this).clone(true);
		$(this).replaceWith(loadingImage);
		$('#cart').load(
			'/req/ #cart > *', {
				go: 'cart_info',
				action: 'delete',
				prod_id: $('.prod_id', product).text(),
				site_lng: $('.site_lng', product).text(),
				reset: $('.quantity', product).val()
			},
			function(response, status){
				if (status == 'success')
				{
					product.remove();
					updateTotalPrice();
				}
				else
					$('img.loading', product).replaceWith(el);
			}
		);
		return false;
	});

	// Update price on quantity change
	$('.cart .product input.quantity').change(function(){
		var multiplier = naturalNumberInput(this, 4);
		var product = $(this).closest('.product');
		var quantity = $('input.quantity', product);
		if (quantity.length)
		{
			var buttons = product.find('button');
			buttons.attr('disabled', 'disabled');
			$('#cart').load(
				'/req/ #cart > *', {
					go: 'cart_info',
					action: 'add',
					prod_id: $('.prod_id', product).text(),
					site_lng: $('.site_lng', product).text(),
					reset: $('.quantity', product).val()
				},
				function(){
					buttons.removeAttr('disabled');
					updateSumPrice(multiplier, product);
				}
			);
		}
	});
	$('.cart .product .inc').click(function(){
		var product = $(this).closest('.product');
		var quantity = $('input.quantity', product);
		if (quantity.length)
		{
			var el = $(this);
			el.attr('disabled', 'disabled');
			$('#cart').load(
				'/req/ #cart > *', {
					go: 'cart_info',
					action: 'add',
					prod_id: $('.prod_id', product).text(),
					site_lng: $('.site_lng', product).text()
				},
				function(response, status){
					if (status == 'success')
					{
						quantity.val(naturalNumberInput(quantity, 4) + 1);
						updateSumPrice(quantity.val(), product);
					}
					el.removeAttr('disabled');
				}
			);
		}
		return false;
	});
	$('.cart .product .dec').click(function(){
		var product = $(this).closest('.product');
		var quantity = $('input.quantity', product);
		if (quantity.length)
		{
			var oldQuantity = naturalNumberInput(quantity, 4);
			if (oldQuantity > 1)
			{
				var el = $(this);
				el.attr('disabled', 'disabled');
				$('#cart').load(
					'/req/ #cart > *', {
						go: 'cart_info',
						action: 'delete',
						prod_id: $('.prod_id', product).text(),
						site_lng: $('.site_lng', product).text()
					},
					function(response, status){
						if (status == 'success')
						{
							quantity.val(oldQuantity - 1);
							updateSumPrice(quantity.val(), product);
						}
						el.removeAttr('disabled');
					}
				);
			}
			else
				quantity.val(1);
		}
		return false;
	});

	// Place order
	$('button.order').click(function(){
		var markErrors = new Array();
		$('table.buyer tbody tr').each(function(){
			var input = $(':input', this);
			if (input.hasClass('phone'))
			{
				var regexp = /^[0-9\s\(\)+\-]+$/i;
				if (!regexp.test(input.val()))
					markErrors.push($('td.check', this).get(0));
			}
			else if (input.hasClass('email'))
			{
				var regexp = /^[\s]*[a-z0-9&_\.\-]+?@[\w\-]+\.(?:[\w\.\-]+\.)?[\w]+[\s]*$/i;
				if (!regexp.test(input.val()))
					markErrors.push($('td.check', this).get(0));
			}
			else if (input.val().length < 1)
				markErrors.push($('td.check', this).get(0));

		});
		$('table.buyer tr').css('background-color', 'transparent');
		$('table.buyer tr td.check').html('');
		if (markErrors.length)
		{
			$(markErrors).each(function(){
				$(this).html(errorImage).parent().css('background-color', '#fcc');
			});
			return false;
		}
		var products = $('#products');
		var productsClone = products.clone(true);
		var addressValue = $('#buyer_address', products).val();
		var parent = $(this).parent();
		var order =
			'go=place_order&action=show&catalog_page=1&' +
			$(this).closest('.order_form').serialize();
		var el = $(this).clone(true);
		$(this).replaceWith(loadingImage);
		$.ajax({
			type: 'POST',
			url: '/req/',
			data: order,
			success: function(data){
				products.html(data);
				$('button.confirm', products).click(function(){
					var parent = $(this).parent();
					var parentClone = parent.clone(true);
					parent.html(loadingImage);
					$(products).load(
						'/req/',
						{ go: 'place_order', action: 'add' },
						function(responseText, textStatus){
							if (textStatus == 'success')
							{
								$('#cart').load(
									'/req/ #cart > *', {
										go: 'cart_info',
										action: 'show',
										site_lng: $('.site_lng').text()
									}
								);
							}
							else
								parent.replaceWith(parentClone);
						}
					);
				});
				$('button.cancel', products).click(function(){
					products.replaceWith(productsClone);
					$('#buyer_address', productsClone).val(addressValue);
				});
			},
			error: function(data){
				$('img.loading', parent).replaceWith(el);
			}
		});
		return false;
	});

	// Page switching
	$('#catalog_list .jumps').catalogJumps();

	// Catalog search
	$('form.catalog_form button.find').click(function(){
		var parent = $(this).parent();
		var form = $(this).closest('.catalog_form');
		var search = 'go=catalog&action=show&' + form.removeInputHints().serialize();
		form.addInputHints();
		var el = $(this).clone(true);
		$(this).replaceWith(loadingImage);
		$.ajax({
			type: 'POST',
			url: '/req/',
			data: search,
			success: function(data){
				$('#catalog_list').html(data);
				$('#catalog_list .jumps').catalogJumps();
			},
			complete: function(){
				$('img.loading', parent).replaceWith(el);
			}
		});
		return false;
	});

	// Catalog key search
	$('form.catalog_form input, select').keydown(function(event){
		if (event.keyCode == 13)
			$('form.catalog_form button.find').click();
	});
});

