$(document).ready(function(){
	
 $('.smallphoto img').click(function(){	 
	 $('#large-photo').attr('src', 'modules/thumb.php?product_image_id=' + $(this).attr('rel'));
	});
	
	$('#tbl-cart a.del').click(function(){
		$(this).parent().parent().remove();
		updateCart();
	});

 $('#tbl-cart input').bind('keyup', function(){
	 updateCart();
	});
	
	$('.btnBuy').click(function(){
	 $.getJSON('modules/_cart.php', 
								{action: 'add', product_id: $(this).attr('rel')},
								function(json){
									$('.basketShop').html(json.cart);
								 alert(json.msg);
								});
		if (typeof show_cart != 'undefined')
		 window.location.reload();
	});
	
	$('#form-cart').ajaxForm({
		url: 'modules/_cart.php',
		dataType: 'json',
		beforeSubmit: function(f, jf, op) {			
			e = $('#form-cart [name="cf[name]"]');
			if (!e.val()) {
				alert('Введите Ваше имя');
				e.focus();
				return false;
			}
			e = $('#form-cart [name="cf[phone]"]');
			if (!e.val()) {
				alert('Введите Ваш телефон');
				e.focus();
				return false;
			}
			
			$('#form-cart').mask('Загрузка...'); 
		},
		success: function (data) {
			$('#form-cart').replaceWith(data.html)
		},
		error: function(req, s, e) {
			alert('Возникла ошибка: ' + req.statusText + ' ' + s + ' ' + e); 
			$('#form-cart').unmask(); 
		}																												
	}); // order product form	
});

function updateCart() {
	var s = 0;
	var cart = {};
	inp = $('#tbl-cart input');
	$.each(inp, function(){
	 e = $(this);
		c = Math.abs(parseInt(e.val()));
		if (c == 0) {
			e.val(1);
			c = 1;
		}
		if (isNaN(c))
		 c = 0;
		x = parseFloat(e.attr('price')) * c;
		$(this).parent().next().html(Math.round(x*100)/100 + ' грн');	
		s += x;
		cart[e.attr('product_id')] = c;
	});
	$.post('modules/_cart.php', {action: 'change', cart: cart});
	
	if (inp.length > 0)
 	$('#tbl-cart .total').html('Итого: <span>' + Math.round(s*100)/100 + ' грн</span>');
	else
	 $('#form-cart').replaceWith('<p>Ваша корзина пуста. Чтобы добавить товар в корзину, выберите его и нажмите кнопку "Заказать".</p>');
}
