
normalizePrice = function(t){
	t = String(t);
	var ln = t.length;
	return t.substring(0, ln - 3) + ' ' + t.substring(ln - 3, ln);
}

ctoggleClass = function(s) {
	s.toggleClass("inactive");
	s.toggleClass("active");
}

$(document).ready(function(){
	
// Корзина: обработчики кнопок +/- товаров
	$('#showcase .inc, #showcase .dec').unbind('click');
	$('#showcase .quantity').unbind('focusout');


	$('#showcase .inc').click(
		function() {
			var id = $(this).parent().parent().attr('id').substring(5);
			var quantity = $(this).parent().find('.quantity');
			var t = Number(quantity.val()) + 1;
			quantity.val(t);			

			setQuantity(id);
			if (1 == t) 
				gritterNotify(id, 'add');
			return false;
		}
	);

	$('#showcase .dec').click(
		function() {
			var id = $(this).parent().parent().attr('id').substring(5);
			var quantity = $(this).parent().find('.quantity');
			var t = Number(quantity.val()) - 1;
			
			if (t < 1)
				quantity.val('');
			else
				quantity.val(t);		
			
			setQuantity(id);
			if ('' == t) 
				gritterNotify(id, 'dec');

			return false;
		}
	);

	$('#showcase .submit-item').click(
		function() {
			return false;
		}
	);

	$('#showcase .del').click(
		function() {
			var id = $(this).parent().parent().attr('id').substring(5);
			var quantity = $(this).parent().find('.quantity');
			var item = $(this).parent().parent();

			quantity.val('');
			
			item.fadeTo('fast', 0, function(){
				item.parent().slideUp('fast');
			});

			setQuantity(id);
			gritterNotify(id, 'dec');

			return false;
		}
	);

	$('#showcase .quantity').focusout(
		function() {
			var id = $(this).parent().parent().attr('id').substring(5);
			var quantity = $(this).parent().find('.quantity');
			var t  = $(this).parent().find('.quantity').val();
			setQuantity(id);
			if (1 == t) 
				gritterNotify(id, 'add');
			if ('' == t || 0 == t) {
				quantity.val('');
				gritterNotify(id, 'dec');	
			}
			return false;
		}
	);


// Установка кол-ва товара на сервере
	var setQuantity = function(id) {
		var quantity = $("#item_" + id + " .add .quantity").val();
		var item = $("#item_" + id);
		$.ajax ({
			type: "POST",
			url: "/cart-set.html",
			dataType: "json",
			data: 
			{
				action: 'setQuantity',
				item_id: id,
				item_quantity: quantity
			},
			success: function(data) {
				if (data.msg === 'ok') {
					// Удалить элемент из корзины, если кол-во 0;
					if (0 >= quantity.length && $("#showcase .items").hasClass('is-cart'))
						item.fadeTo('fast', 0, function(){
							item.parent().slideUp('fast');
						});
					updateCartInfo(data.total);
				}
			}
		})
		
		return false;
	}

	
// Пересчет общей суммы заказа
	var updateCartInfo = function(total) {
		if (0 < total ) {
			if ($("#cart-info .full").hasClass('no-display')) {
				$("#cart-info .full").removeClass('no-display');
				$("#cart-info .empty").addClass('no-display');
			}
			// $("#cart-info .full .value").html(normalizePrice(total));
			$("#cart-info .full .value").html(total);
			$("#cart-total").html(total);
		}
		else if ($("#cart-info .empty").hasClass('no-display')) {
			$("#cart-info .full").addClass('no-display');
			$("#cart-info .empty").removeClass('no-display');
			$("#cart-info .text .value").html('пустая');
			$("#cart-total").html(total);

			if ('/cart.html' == window.location.pathname)
				window.location.reload();
		}
		
		return false;
	}



// Проверка полей формы заказа
	$("#person_name").focusin(function() {
		s = $("#person_name");
		if (s.val() == "Введите ваши имя и фамилию") {
			s.val("");
			ctoggleClass(s);
		}	
	})
	$("#person_name").focusout(function() {
		s = $("#person_name");
		if (s.val() == "") {
			s.val("Введите ваши имя и фамилию");
			ctoggleClass(s);
		}
	})
	$("#person_address").focusin(function() {
		s = $("#person_address");
		if (s.val() == "Адрес доставки") {
			s.val("");
			ctoggleClass(s);
		}
	})
	$("#person_address").focusout(function() {
		s = $("#person_address");
		if (s.val() == "") {
			s.val("Адрес доставки");
			ctoggleClass(s);
		}
	})
	$("#person_phone").focusin(function() {
		s = $("#person_phone");
		if (s.val() == "Номер контактного телефона") {
			s.val("");
			ctoggleClass(s);
		}
	})

	$("#person_phone").focusout(function() {
		s = $("#person_phone");
		if (s.val() == "") { 
			s.val("Номер контактного телефона");
			ctoggleClass(s);
		}
	})
	$("#delivery_date").focusin(function() {
		s = $("#delivery_date");
		if (s.val() == "25 января, 16:00") {
			s.val("");
			ctoggleClass(s);
		}
	})
	$("#delivery_date").focusout(function() {
		s = $("#delivery_date");
		if (s.val() == "") {
			s.val("25 января, 16:00");
			ctoggleClass(s);
		}
	})
	$("#delivery_comment").focusin(function() {
		s = $("#delivery_comment");
		if (s.val() == "Напишите, что вы еще хотели сказать оператору по доставке") {
			s.val("");
			ctoggleClass(s);
		}
	})
	$("#delivery_comment").focusout(function() {
		s = $("#delivery_comment");
		if (0 >= s.val().length) {
			s.val("Напишите, что вы еще хотели сказать оператору по доставке");
			ctoggleClass(s);
		}
	})
	

// Разворачивание скрытых блоков при клике
	$(".card-pay a").click(function() {
		$("#card-pay").css("display", "block");
		return false;		
	})

	$(".delivery-date a").click(function() {
		$("#delivery-date").css("display", "block");
		return false;		
	})
	
	$(".delivery-comment a").click(function() {
		$("#delivery-comment").css("display", "block");
		return false;		
	})


// Показ корзины всегда вверху экрана
	var shareBar = $("#cart-info");
	var menuGoods = $("#menu-goods");
	var menuGoodsPos = $("#menu-goods").position();
	var above = 141;
	var position = $("#cart-info").position();
	

	$(window).scroll(function(){
		if (0 < shareBar.length) {
			var headerStop = $(".content").height();
			var absolutePos = self.pageYOffset || (document.documentElement && document.documentElement.scrollTop) || (document.body && document.body.scrollTop);
			var upTop = $(this).scrollTop();
			var barPos = shareBar.css('position');

			if (upTop > above){
				if (upTop - 10 > headerStop){
					if (barPos != 'absolute') shareBar.css({'position':'absolute', 'top':absolutePos});
					menuGoods.css({'position':'absolute', 'top':150, 'left':'0'});
				} else 
				if (barPos != 'fixed'){
					shareBar.css({'position':'fixed', 'top':'10px', 'left':position.left});
					menuGoods.css({'position':'fixed', 'top':'68px'});
				}
			}
			else if (barPos != 'static'){
				shareBar.css("position","static");
				menuGoods.css("position","static");
			}
		}
	});


// Всплывающее уведомление
	var gritterNotify = function(id, token) {
		var title = $("#item_" + id + " h3").html();
		var t = $("#item_" + id + " .preview img").attr('src');

		var image = '/images/goods/preview/item' + id + '.png';
		var text = ('dec' == token) ? 'Удалено' : 'Добавлено в корзину';

		$.ajax({
			url: image,
			type: 'HEAD',
			error: function(){
					$.gritter.add({
						title: title,
						text: text,
						image: t,
						sticky: false,
						time: '2000'
					});
			},
			success: function(){
				$.gritter.add({
						title: title,
						text: text,
						image: image,
						sticky: false,
						time: '2000'
					});
			}
		});
	}
			
		
// Превью картинок каталога
	$("a[rel=gallery]").fancybox({
		'transitionIn'	: 'elastic',
		'transitionOut'	: 'elastic',
		'overlayOpacity': '0.6',
		'titlePosition' : 'over'
	});


// Обратбока клика по всей корзине
	$("#cart-info").click(function() {
		 window.location = '/cart.html';
	});


// Бонуснуя карта - получить
	$(".bonuscard .get").click(function() {
		 show_register_popup();
	});

// Бонуснуя карта - проверить балланс
	$(".bonuscard .check").click(function() {
		 show_card_info_popup();
	});

});
