$(document).ready(function() {
	$('.addItem').live("click",addItem);
	$('.removeItem').live("click",removeItem);
	$('input.change').live("keyup",change);
	$('.toggleBasket').live("click",toggleBasket);
	$('#basket div.basket').css('display','none');
	$('.sendOrder').live("click",sendOrder);
	$('.hideOrderForm').live('click',hideOrderForm);
	$('.captchaCode').live('click',refreshCaptcha);
});

function refreshCaptcha(){
	var img = $('#basket a.captchaCode img');
	var rnd = Math.random() * 100000;
	img.attr('src',"/getpic.php?rnd=" + rnd);
	return false;
}

function addItem() {
	var productID = $(this).attr("productID");
	var show = $("#basket div.basket").css("display") == 'block' ? true : false;
	$.post(
		'/basket/add/' + productID,
		'',
		function(data) {
			$("#basket").remove();
			$('body').append(data);
			if (!show) {
				$('#basket div.basket').css('display','none');
			}
			getLabel();
		}
	);
}

function removeItem() {
	var productID = $(this).attr("productID");
	$.post(
		'/basket/remove/' + productID,
		'',
		function(data) {
			$("#basket").remove();
			$('body').append(data);
			getLabel();
		}
	);
}

var timers = {};

function change() {
	var productID = $(this).attr("productID");
	var qty = $(this).val();
	if (qty <= 0) {
		$(this).val(1);
		qty = 1;
	}

	if (timers[productID]){
        clearTimeout(timers[productID]);
    }

	timers[productID] = setTimeout(function() {
		$.post(
			'/basket/change/' + productID,
			{'qty' : qty },
			function(data) {
				$("#basket").remove();
				$('body').append(data);
				getLabel();
			}
		);
	},1000);
}

function toggleBasket() {
	if ($("#basket div.basket").css("display") == 'block') {
		$("#basket div.basket").slideUp(1000,function() {
			getLabel()
		});
	} else {
		$("#basket div.basket").slideDown(1000,function() {
			getLabel()
		});
	}
	return false;
}

function getLabel() {
	if ($("#basket div.basket").css("display") == 'block') {
		$("#basket a.toggleBasket").html("скрыть");
	} else {
		$("#basket a.toggleBasket").html("показать");
	}
}

function renderBasket() {
	$.post(
		'/basket/render/',
		'',
		function(data) {
			$("#basket").remove();
			$('body').append(data);
			getLabel();
		}
	);
}

function sendOrder() {
	$.post(
		'/basket/showorderform/',
		'',
		function(data) {
			$("#basket .orderForm").remove();
			$('#basket').append(data);
			$("#basket div.orderForm form").submit(sendOrderForm);
		}
	);
	return false;
}

function hideOrderForm() {
	$('#basket div.orderForm').remove();
	return false;
}


function validateOrderForm() {
	$("#basket div.orderForm form select,#basket div.orderForm form input[type=text]").each(function() {
		if ($(this).attr("required") && !(/[\d\wа-я]{3,50}/.test($(this).val()))) {
			var label = $(this).attr('lbl');
			emptyFields.push($("#"+label+":not(span.redstar)").text());
		}
	});
	return (emptyFields.length > 0) ? false : true;
}

var emptyFields = [];

function sendOrderForm() {
	if (validateOrderForm()) {
		var url = $("#basket div.orderForm form").attr("action");
		var fData = {};
		$("#basket div.orderForm form select,#basket div.orderForm form input, #basket div.orderForm form textarea").each(function() {
			if ($(this).find("option").length > 0 || $(this).attr("type") == "text" || $(this).attr("type") == "textarea" || $(this).attr("type") == "hidden") {
				fData[$(this).attr("name")] = $(this).val();
			} else {
				if ($(this).attr("checked")) {
					fData[$(this).attr("name")] = $(this).val();
				}
			}
		});
		$.post(
			url,
			fData,
			function(response) {
				refreshCaptcha();
				if (response.status == 'OK') {
					$("#basket div.orderForm").html("<h4>" + response.msg + "</h4>");
					setTimeout(function(){
						$("#basket div.orderForm").remove();
                        renderBasket();
					},5000);
				} else {
					$("#basket div.orderForm div.errors").html(response.msg);
				}
			},
			'json'
		);
	} else {
		var fields = emptyFields.join("<br/>");
		$('#basket div.orderForm div.errors').html("Необходимо заполнить следующие поля: <br/>" + fields);
		emptyFields = [];
	}
	return false;
}
