$(function () {
	
	{	// обработка формы заказа
		$('.datepicker').datePicker();
		
		$('#order_form').submit(function () {
			if (
				this.company.value 
				&& this.fio.value 
				&& this.phone.value 
				&& this.email.value
				&& this.plan_date.value
				) {
					$('.datepicker').removeAttr('disabled');
				}
			else {
				alert('Пожалуйста, заполните все обязательные поля');
				return false;
			}
		});
		
		/*
		$('#rb2').click(function () {
			if ($(this).is(':checked')) {
				$('.plan_date').show();
			}
		})
		
		$('#rb1').click(function () {
			if ($(this).is(':checked')) {
				$('.plan_date').hide();
			}
		});
		*/
		
		$('#order_btn').click(function () {
			$(this).hide();
			$('#order_div').slideDown(1000);

			return false;
		});
		
		
	}
	
	
	{	// обработка корзины
			
		if ($('.auth_exit').length) {
			bindCart();
			toggleCart();
		}

	}

	{ // обработка клавишь в корзине
		
		$('#recalc').click(function () {
			
			$('.count').each(function () {
				
				var count = parseInt($(this).val())
				cart.del(parseInt($(this).attr('rel')));
				
				if (count > 0 && !isNaN(count)) {
					cart.add(parseInt($(this).attr('rel')), count, true);
				}
				

			});
				
			return false;
		});
		
		$('#delete').click(function () {

			$('.checkbox:checked').each(function () {
				cart.del($(this).val());
			});
			
			return false;
			
		});
		
		$('#clear').click(function () {

			cart.clear();
			
			return false;
		});

		$('#recalc, #delete, #clear').click(function () {
			
			cart._write();

			//toggleCart();
			document.location = document.location;

			return false;
		});
		
	}
	
	
});


var cart = {

	cart : [],
	
	
	add : function (id, count, no_write) {
		
		
		if (this.cart[id]) {
			this.cart[id] += count;
		}
		else {
			this.cart[id] = count;
		}

		if (!no_write) {
			this._write();
		}
		
	},

	get : function () {

		this.cart = this._read();
		return this.cart;
				
	},

	del : function (id) {
		
		this.cart = this._read();
		delete(this.cart[id]); 
		
		//this._write();
		
	},

	clear : function () {

		this.cart = [];
		//$.userData('galanteya_cart', '');
		//$.cookie('galanteya_cart', null, {path : '/'});
		
	},

	_read : function () {
		
		if (this.cart.length) {
			return this.cart;
		}
		//$.userData('galanteya_cart');
		
		if ($.userData('galanteya_cart')) {
			var ret = unserialize($.userData('galanteya_cart'));
		}
		else {
			var ret = {};
		}
		
		ret.length = function () {
			var i = -1;
			for (var id in this) {
				i++;
			}
			
			return i;
		};
		
		this.cart = ret;

		return ret;
		
	},

	_write : function () {
		$.userData('galanteya_cart', serialize(this.cart));
	}

}

/**
 * Юнит тест для корзины
 */

$(function () {

	return false;
	cart.clear();
	
	alert(cart.get().toSource());	// должно вывести [10, 25, 100]
	
	for(var i = 100000; i < 100200; i++) {
		cart.add(i, 1);
	}
	
	alert(cart.get().toSource());	// должно вывести [10, 25, 100]
	
	
});


var bindCart = function (parents) {
			
	$('.kol', parents).each(function () {

		$('.cart_link', this).click(function () {
			
			var count = $('input', $(this).parents('.kol:first')).val();
			if (parseInt(count) > 0) {
				cart.add($(this).attr('rel'), parseInt(count));
				toggleCart();
				alert('Товар помещен в корзину.\nКоличество: ' + count + ' шт.\nВсего продуктов в корзине: ' + $('.counter_bags').html());

			}
			
			return false;
		});
		
	});
}

var toggleCart = function () {

	if (cart.get().length()) {
		
		var items = cart.get();
		count = 0;
		for (var id in items) {
			if (parseInt(id) == id) {
				count += items[id];
			}
		}

		$('.counter_bags').html(count);
		$('#cart_placeholder').show();
		$('#cart_placeholder_empty').hide();
	}
	else {
		$('#cart_placeholder_empty').show();
		$('#cart_placeholder').hide();
	}

}


jQuery.userData = function (name, value) {
	
	var _url = _root + 'include/user_data.php4';
	
	if (typeof value != 'undefined') { // setter
		
		var response = $.ajax({
			url: _url,
			type: "POST",
			data: {key: name, data: value},
			async: false
		});
		
		return response;
		
	}
	else {	// getter
		var response = $.ajax({
			url: _url,
			type: "GET",
			data: {key: name},
			async: false
			}).responseText;
		
		return response;

	}
	
}