var timer = null;

function switchAltText($el) {
	if (!$el.attr("cfg:alt-text"))
		return; 
		
	var buf = $el.attr("cfg:alt-text");
	$el.attr("cfg:alt-text", $el.text());
	$el.text(buf);
}

$(document).ready(function() {

	var post_salt = "KQ46vwTwe2rCkoF";
	$(".post_ticket").attr('value', $(".post_ticket").attr('value') + post_salt);
	
	$("a.show-all").toggle(function() {
		
		switchAltText($(this));
		
		$("#"+$(this).attr("rel")).slideDown();
		$("."+$(this).attr("rel")+"-hide").hide();
	}, function() {
		
		switchAltText($(this));
		
		$("#"+$(this).attr("rel")).slideUp()
		$("."+$(this).attr("rel")+"-hide").show();
	});

	$('#topcatalog a').hover(function() {
		closeAll();
		clearTimeout(timer);
		var item = $(this);
		var smid = $(this).attr('rel');
		$('#sm-' + smid).css({
			top: $(this).offset().top,
			left: $(this).offset().left-223
		});
		$('#sm-' + smid).hover(function () {
			$(item).addClass('on' + smid);
			clearTimeout(timer);
		}, function () {
			closeSmenu(smid, item);
		});
	}, function() {
		var item = $(this);
		var smid = $(this).attr('rel');
		closeSmenu(smid, item);
	});
	
	
	$("#reg-submit").click(function() {
		
		var form = $("#reg-form");
		$("#reg-info").hide();

		$.ajax({
			type: 'post',
			dataType: "html",
			//url: '/ajax/user.php?act=reg',
			url: '/user/register',
			data: form.serialize(),
			beforeSend: function(){
				$("#reg-info").html("<span style='color: gray;'>Отправка запроса..</span>");
				$("#reg-info").fadeIn(500);
			},
			success: function(data){
				if(data == 'ok') {
					$("#reg-info").html("<span style='color: green;'>Вы успешно зарегистрировались.</span>");
					setTimeout(function(){
						$("#reg-close").click();
						window.location = '/';
					}, 500);
					
				}
				else {
					$("#reg-info").html("<span style='color: red;'>" + data + "</span>");
				}
				$("#reg-info").fadeIn(500);
			},
			error: function(){
				$("#reg-info").html("<span style='color: red;'>Ошибка отправки.</span>");
				$("#reg-info").fadeIn(500);
			}
		});
		
		
		return false;
	});
	
	
	$("#login-submit").click(function() {
		
		var form = $("#login-form");
		var info = $("#login-info");
		info.hide();

		$.ajax({
			type: 'post',
			dataType: "html",
			//url: '/ajax/user.php?act=login',
			url: '/user/login',
			data: form.serialize(),
			beforeSend: function(){
				info.html("<span style='color: gray;'>Отправка запроса..</span>");
				info.fadeIn(500);
			},
			success: function(data){
				if(data == 'ok') {
					info.html("<span style='color: green;'>Вы успешно авторизировались.</span>");
					setTimeout(function(){
						$("#login-close").click();
						window.location = '/';
					}, 500);
				}
				else {
					info.html("<span style='color: red;'>" + data + "</span>");
				}
				info.fadeIn(500);
			},
			error: function(){
				info.html("<span style='color: red;'>Ошибка отправки.</span>");
				info.fadeIn(500);
			}
		});
		
		
		return false;
	});
	
	
	
	$("#thumbs img").click(function() {
		$("#mainthumb a").hide();
		$('#mainthumb-' + $(this).attr('rel')).show();
		/*$('#mainthumb img').attr('src', '<?php echo $photoStorage->getPhotoLink($product->getId(), '400x300', $i);?>');
    	$('#mainthumb a').attr('href', '<?php echo $photoStorage->getPhotoLink($product->getId(), '596x447', $i);?>');*/
	});
	
	
	$("#next-step-button").click(function() {
		$("#next-step").submit();
		return false;
	});
	
	$("a.slide-button").each(function(){
		$(this).click(function(){
			$(this).parent().find("div.slide-form").slideToggle(400);
			$(this).parent().toggleClass("active");
			return false;
		});
	});
	
	$("#submit-user-info").click(function() {
		
		var error = '';
		
		if( $("#user_fio").val() == '' )
			error += "Не заполнено поле ФИО\n";
		if( $("#user_phone").val() == '' )
			error += "Не заполнено поле телефон\n";
		if( $("#user_email").val() == '' )
			error += "Не заполнено поле email\n";
			
		if(error != '')
			alert(error);
		else
			$("#form-user-info").submit();
		return false;
	});
	
	$(".compare-new").live('click', function() {
		
		var button = $(this);
		
		$.ajax({
			type: 'post',
			dataType: "html",
			url: '/ajax/compare.php?act=add',
			data: {'id' : button.attr("rel")},
			beforeSend: function(){
				button.addClass("compare-load");
			},
			success: function(data){
				button.removeClass("compare-load");
				if(data == 'ok') {
					button.removeClass("compare-new");
					button.addClass("compare-save");
				}
				else if(data == 'count') {
					alert("Нельзя сравнить больше 3х товаров.");
				}
				else {
					alert("Обнаружена ошибка");
				}
			},
			error: function(){
				alert("Обнаружена ошибка");
			}
		});
		return false;
	});
	
	$(".compare-save").live('click', function() {
		
		var button = $(this);
		
		$.ajax({
			type: 'post',
			dataType: "html",
			url: '/ajax/compare.php?act=del',
			data: {'id' : button.attr("rel")},
			beforeSend: function(){
				button.removeClass("compare-save");
				button.addClass("compare-load");
			},
			success: function(data){
				button.removeClass("compare-load");
				if(data != 'ok') {
					button.addClass("compare-save");
					alert("Обнаружена ошибка");
				}
				else {
					button.addClass("compare-new");
				}
			},
			error: function(){
				alert("Обнаружена ошибка");
			}
		});
		return false;
	});
	
	
	$("#display-hidden-factory").click(function() {
		$("#hidden-factory").slideDown(800);
		$(this).hide();
		return false;
	});
	
	$(".compare-del").click(function() {
		//var tr = $(this).parent().parent();
		var button = $(this);
		
		
		$.ajax({
			type: 'post',
			dataType: "html",
			url: '/ajax/compare.php?act=del',
			data: {'id' : button.attr("rel")},
			beforeSend: function(){
				//alert(tr.html());
			},
			success: function(data){
				if(data == 'ok') {
					window.location = window.location;
				}
				else {
					alert("Обнаружена ошибка");
				}
			},
			error: function(){
				alert("Обнаружена ошибка");
			}
		});
		return false;
	});
	
	
	$("#compare-back").click(function() {
		$.ajax({
			type: 'post',
			dataType: "html",
			url: '/ajax/compare.php?act=clear',
			success: function(data){
				if(data == 'ok') {
					window.history.go(-1);
				}
				else {
					alert("Обнаружена ошибка");
				}
			},
			error: function(){
				alert("Обнаружена ошибка");
			}
		});
		return false;
	});
	
	$("#open-compare").click(function() {
		$.ajax({
			type: 'post',
			dataType: "html",
			url: '/ajax/compare.php?act=open',
			success: function(data){
				if(data == 'ok') {
					window.location.href = '/compare';
				}
				else if(data == 'no') {
					alert("Выберите товары для сравнения");
				}
				else {
					alert("Обнаружена ошибка");
				}
			},
			error: function(){
				alert("Обнаружена ошибка");
			}
		});
		return false;
	});
	
	
	$("#delivery-moscow").click(function() {
		$("#delivery-table .type1").show();
		$("#delivery-table .type2").hide();
		$("#delivery-moscow img").attr("src", "/images/new/moscow.png");
		$("#delivery-other img").attr("src", "/images/new/other-active.png");
		return false;
	});
	
	$("#delivery-other").click(function() {
		calculate();
		$("#delivery-table .type1").hide();
		$("#delivery-table .type2").show();
		$("#delivery-moscow img").attr("src", "/images/new/moscow-active.png");
		$("#delivery-other img").attr("src", "/images/new/other.png");
		return false;
	});
	
	
	$("input[name='delivery']").click(function() {
		$("#delivery_cost").val($(this).attr('title'));
	});
	
	
	// filter ----------------------------------
	$("#select-factory").change(function() {
		var country = factory[$(this).val().toLowerCase() ];
		//alert(country + ' ' + $(this).val().toLowerCase());
		$("#select-country").val(country);
	});
	
	
	
	
	$("#call-form").submit(function() {
		
		var form = $(this);
		
		$.ajax({
			type: 'post',
			dataType: "html",
			url: form.attr('action'),
			data: form.serialize(),
			beforeSend: function(){
				//button.addClass("compare-load");
			},
			success: function(data){
				alert(data);
				if(data == 'Заявка отправлена!') {
					$('#call-block').fadeOut();
					$('#overlay').fadeOut();
				}
			},
			error: function(){
				alert("Обнаружена ошибка");
			}
		});
		return false;
	});
	
	
	
	$("#user-register-status").change(function() {
		if($(this).val() == '1') {
			$(".type-lico-1").fadeIn(300);
		}
		else {
			$(".type-lico-1").fadeOut(300);
		}
	});
	
	
	
	
});

function calculate()
{
	$.each($('.calc_result'), function(key, element) {
		$(element).html('идет расчет...');
		
		if ($('#city').val() == '') {
			$(element).html('Не указан город.');
		}
		else {
			$.post('/cart/calcdelivery', {
				city: $('#city').val(),
				d: $(element).attr('id')
			}, function(data){
				if (data != '0') {
					$("#" + $(element).attr('title') +"-radio").attr('title', data);
					$(element).html(data + ' руб.');
				}
				else {
					$(element).html('ошибка: невозможно расчитать!');
				}
			});
		}
		
	});
}















function closeSmenu(smid, item)
{
	clearTimeout(timer);
	timer = setTimeout(function () {
		$(item).removeClass('on' + smid);
		$('#sm-' + smid).css({
			top: -1000,
			left: -1000
		});
	}, 300);
}
function closeAll()
{
	$('div.sm').css({
		top: -1000,
		left: -1000
	});
}

function Block(name)
{
	var pageScroll = getPageScroll();
    var nHeight = parseInt($('#' + name + '-block').height(),10);
    
    var nTop = pageScroll.yScroll + ($(window).height() - nHeight) / 2.5;
	$('#' + name + '-block').css({
		top:nTop
	});
	$('#' + name + '-block').fadeIn();
	$('#overlay').css({
		height:$(document).height(),
		opacity:.5
	});
	$('#overlay').fadeIn()
}

function getPageScroll() {
    var xScroll, yScroll;
    if (document.documentElement && document.documentElement.scrollTop) {
        yScroll = document.documentElement.scrollTop;
        xScroll = document.documentElement.scrollLeft;
    } 
    else if (document.body) {
        yScroll = document.body.scrollTop;
        xScroll = document.body.scrollLeft;    
    }
    var arrayPageScroll = {'xScroll':xScroll,'yScroll':yScroll};
    return arrayPageScroll;
}

function itemCount(iid, plus)
{
	var count = parseInt($('#item-count-' + iid).val());
	if (plus) {
		count++;
	}
	else {
		count--;
	}
	if (count < 1) {
		return(false);
	}
	$('#item-count-' + iid).val(count);
}
$(document).ready(function(){
	$('#delivery-table tr').click(function(){
		$(this).find('input').attr('checked','checked');
		return false;
	})
});
$(document).ready(function(){
	$('.cart').click(function(){
		href = $(this).attr('href');
		$.getJSON(href, function(data) {
			
			$('#cartCount').html(data.count);
			$('#cartPrice').html(data.sum); 
		});

		if(confirm('Товар успешно добавлен. Перейти в корзину?')){
			window.location.href="/cart";
		}
		return false;
	});
});
