// JavaScript Document

var basket = '/basket/';
	
$(function() {
	
	recheck();
	
	var page = $("#page").val();
	var subPage = $("#subPage").val();
	
	$('.lightBox').lightBox();
	
	$("#loadingWindow").ajaxStart(function() {
		$(this).modal({
			opacity:35,
			overlayCss: {backgroundColor:"#000"}
		});
    }).ajaxStop(function() {
		if($("#questionForm").is(":visible") || $("#sendBasket").is(":visible")) return; 
		$.modal.close();
    });
		
	// меню --------------------------------------------------
	
	// по умолчанию
	$("#menu div[title='" + page + "']").parent().removeClass('un').addClass('ac').css('background', 'url(/i/menu/' + page + '.png)');
	if(subPage != "") $("div[title='" + page + "'] a[title='" + subPage + "'] img").attr('src', "/i/menu/" + subPage + "A.png");
	
	$("#menu a[href='#']").click(function(event) {
		event.preventDefault();
	});
	
	$("#menu .un").hover(function() {
		var sPage = $(this).attr('title');
		if(sPage != page) $(this).parent().removeClass('un').addClass('ac').css('background', 'url(/i/menu/' + sPage + '.png)');
		if($(this).children().next().length == 1) $(this).children().next().show();
	}, function() {
		var sPage = $(this).attr('title');
		if(sPage != page) $(this).parent().removeClass('ac').addClass('un').css('background', 'none');
		if($(this).children().next().length == 1) $(this).children().next().hide();
	});
	
	$(".subMenu a").hover(function() { 
		var sSubPage = $(this).attr('title');
		var sSubMenuName = $(this).parent().parent().attr('title');
		if((page == 'tyres' || page == 'disks') && subPage == 'articles' && sSubPage == 'articles') {
			if(page != sSubMenuName) 
				$(this).children().attr('src', "/i/menu/" + sSubPage + "A.png")
		} else {
			if(subPage != sSubPage) 
				$(this).children().attr('src', "/i/menu/" + sSubPage + "A.png")	
		}
	}, function() {
		var sSubPage = $(this).attr('title');
		var sSubMenuName = $(this).parent().parent().attr('title');
		if((page == 'tyres' || page == 'disks') && subPage == 'articles' && sSubPage == 'articles') {
			if(page != sSubMenuName) 
				$(this).children().attr('src', "/i/menu/" + sSubPage + ".png")	
		} else {
			if(subPage != sSubPage) 
				$(this).children().attr('src', "/i/menu/" + sSubPage + ".png")
		}
	});
	
	$("#footerFitting").hover(function() { 
		$("#footerSubMenu").toggle();
	});
	
	// меню --------------------------------------------------
	
	
	// поиск -------------------------------------------------
	
	$("#searchField").click(function() {
		$(this).val('');
	}).blur(function() {
		if($(this).val() == '') $(this).val('Поиск по сайту');
	});
	
	$("#searchButton").click(function() {
		var value = $.trim($("#searchField").val());
		if(value != '' && value != 'Поиск по сайту') $(this).parent().submit();		
	});
	
	// поиск -------------------------------------------------
	
	
	// задать вопрос -----------------------------------------

	$("#question").click(function() {		
		$("#questionForm").modal({
			opacity:35,
			overlayCss: {backgroundColor:"#000"}
		});
	});
	
	$("#questionFormClose").click(function() {
		$.modal.close();
		$("#sendQuestion input").val('');
	});
	
	$("#sendQuestionButton").click(function() {
		$.post("/main/sendQuestion", $("#sendQuestion").serialize(), function(data) {
			$(".ef").empty();			
			
			if(data!=null) {
				$.each(data, function(field, error) {
					$("#"+field).parent().parent().find(".ef").text(error);
				});	
			} else 
				$.modal.close();
		}, 'json');
	});
	// задать вопрос -----------------------------------------	
	
	
	// блоки -------------------------------------------------	
	
	$('.scroll-pane-disks, .scroll-pane-tyres, .scroll-pane-actions').jScrollPane({
		showArrows: true,
		bgRun: "jspTrackBig"
	});
	
	$('.scroll-pane-articles').jScrollPane({
		showArrows: true,
		bgRun: "jspTrack"
	});
	
	// блоки -------------------------------------------------
	
	// карусель -------------------------------------------------	
	
	if($("#carousel").length > 0) {
		
		var mouseEnable = true;
		
		if($("#carousel ul li").length < 4) {
			$("#prev, #next").hide();
			mouseEnable = false;
		}
		
		$("#carousel").jCarouselLite({
			mouseWheel: mouseEnable,
			speed: 1000,
			visible: 3,
			vertical: true,
			btnNext: "#next",
			btnPrev: "#prev"
		});
			
		// по умолчанию
		$("#carousel ul li[title='sc']").css('background', 'url(/i/articles/bg-selected.jpg) no-repeat');
		
		$("#carousel ul li").live("mouseover mouseout", function(event) {
		  if($(this).attr('title') == "sc") return;
		  if(event.type == "mouseover")
			$(this).css('background', 'url(/i/articles/bg-selected.jpg) no-repeat');
		  else
			$(this).css('background', 'url(/i/articles/bg-unselected.jpg) no-repeat');
		}).live("click", function () {
			var articleID = $("#articleID").val();
			var id = $(this).attr('value');
			$("#carousel ul li[title='sc']").attr('title', '').css('background', 'url(/i/articles/bg-unselected.jpg) no-repeat');
			$(this).css('background', 'url(/i/articles/bg-selected.jpg) no-repeat').attr('title', 'sc');
			
			if(page == 'articles' || page == 'disks' || page == 'tyres') {	
				$(".lightBox").attr('href', '/data/articles/' + articleID + '/' + id + '-big.jpg')
				.children().attr('src', '/data/articles/' + articleID + '/' + id + '-mid.jpg');
			} else if(page == 'about' || page == 'delivery' || page == 'fitting') {
				$(".lightBox").attr('href', '/data/image/' + id + '-big.jpg')
				.children().attr('src', '/data/image/' + id + '-mid.jpg');
			}
		});
		
	}
	// карусель -------------------------------------------------	
	
	// боковое меню ---------------------------------------------
		
	// по умолчанию
		var filter = $("#filter").val();		
		var brand = $("#brand").val();
		$(".menuTitle[title='" + filter + "']").next().show();
		$(".menuTitle[title='" + filter + "']").parent().find("a[title='" + brand + "']").parent().parent().prop('selected', 'ok')
		.css('background', 'url(/i/blocks/blue/selected.jpg) no-repeat');
				
		$(".menuTitle").click(function() {
			$(".menuLinks").hide();
			$(this).next().show();
		});
		
		$(".subMenuLinks").hover(function() { 
			if($(this).prop('selected') != "ok") $(this).css('background', 'url(/i/blocks/blue/selected.jpg) no-repeat');
		}, function() {
			if($(this).prop('selected') != "ok") $(this).css('background', 'none');
		});
	// боковое меню ---------------------------------------------	
	
	
	// карточка товара ---------------------------------------------	
	
	$(".modelTableItemsSelected").live("mouseover mouseout", function(event) {
		if(event.type == "mouseover") {
			$(this).children().css('background', 'url(/i/item/center.jpg)');
			$(this).children().first().html("<img src='/i/item/left.jpg' alt='' />");
			$(this).children().last().html("<img src='/i/item/right.jpg' alt='' />");
		 } else {
			$(this).children().css('background', 'none');
			$(this).children().first().empty();
			$(this).children().last().empty();
		 }
	});
	
	// изменение кол-ва товара
	$(".changeQ").live('change', function() {
		if($(this).val() == "") return;
		var priceType = $(this).next().next().val();
		var price = (priceType == 'price4') ? parseFloat($(this).parent().prev().find(".newPrice").text()) : parseFloat($(this).parent().prev().text());
		var total = (price * $(this).val()) + " руб.";
		$(this).parent().next().text(total);
	});
	
	// добавление товара в корзину
	$(".addToBasket").live('click', function() {
		var quantity = $(this).parent().prev().prev().children().val();
		if(quantity == "") return;
		var id = $(this).parent().parent().children().find("input").val();
		var restType = $(this).parent().prev().prev().children().next().val();
		var priceType = $(this).parent().prev().prev().children().next().next().val();
		
		if(subPage == 'auto') {
			objectName = ($(this).attr('alt') == 'Положить в корзину шины') ? 'tyres' : 'disks';
		}
	
		var request = {"type" : objectName, "id" : id, "quantity" : quantity, 'restType' : restType, 'priceType' : priceType};
		var position = $(this).position();
		
		$.post(basket + "add", request, function(data) {							  				
			if(data.status == 'ok') {	
				$("#message").text('Товар добавлен в корзину').css({"left": position.left - 150 + "px", "top":position.top + 5 + "px"}).fadeIn('slow', function(){
					$(this).delay(2000).fadeOut();
					recheck();
				});
					
			} else if(data.status == 'error'){ //если ошибка
					$("#message").text(data.text).css({"left":position.left + -150 + "px", "top" : position.top + 5 + "px"}).fadeIn('slow', function(){					
						$(this).delay(2000).fadeOut();
					});
					return;
				}
			}, 'json');			
	});
	
	// карточа товара ---------------------------------------------
	
	
	// бренды авто ---------------------------------------------
	
	$("#brands li").hover(function() {		
		$(this).css('background', 'url(/i/auto/bgA.jpg) no-repeat');
		$(this).find('a').css('color', '#FFF');
	}, function() {
		$(this).css('background', 'url(/i/auto/bg.jpg) no-repeat');
		$(this).find('a').css('color', '#000');
	});
	
	// бренды авто ---------------------------------------------
	
	// показать расширенный поиск
	$("#extB").click(function(event) {
		event.preventDefault();
		$(this).hide();
		$("#ext").show();
	});
	
	
	// если выбираем модель то автоматический переход
	$("#Tmodel").change(function(event) { 
		var modelID = $(this).val();
		var request = {"modelID" : modelID};
		var filter = $("#filter").val();
		$.post('/filters/getNavigate', request, function(data) {
			location.href = "/tyres/car/" + filter +  "/" + data.brand + "/" + data.model + "/";
		}, 'json');
	})
	
});
	
	// модели --------------------------------------

	function loadListModels(path, page, type) { // загрузка списка моделей
		var sort = $("#sort").val();
		var width = $("#standartLayout .center").width();
		var amount = (Math.round(width / 179))*3;
		var request = {"page" : page, "filter" : $("#filter").val(), "amount" : amount, "type" : type, "sort" : sort};
		$.post(path + "loadListModels", request, function(data) {
			$("#ajaxData").html(data);
		});	
	}
	
	$("#listPages a").live('click', function (event) {
		event.preventDefault();
		if($(this).attr('class') != 'selected')
			loadListModels(path, $(this).text(), objectName);
	});
	
	// модели --------------------------------------
	
	
	function createFilters(form, type, pref, size, convert) {	
		dfd = new jQuery.Deferred();
		$.post('/filters/getFilters', form.serialize() + "&type=" + type + "&convert=" + convert, function(data) {	
			 fillFields(data, pref, size);
			 dfd.resolve("ok");		
		}, 'json');
	}
	
	function fillFields(data, pref, size) {
		$.each(data, function (name, value) {	
			if(name == 'pin') {
				$("#Tpin").prop('checked', value.checked);
				$("#Tpin").prop('disabled', value.disabled);
			} else if(name == 'maxPrice' || name == 'minPrice')
				$("#" + name).val(value);
			else if($("#" + pref + name).length > 0 && $("#" + pref + name).attr('type') != 'hidden')
				$("#" + pref + name).html(value).css('width', size);
		});
		
		if(data.minPriceSelected === false || data.minPriceSelected == "") {
			$("#minPrice").val(data.minPrice);
			$("#maxPrice").val(data.maxPrice);
			if($("#page").val() != 'main') priceRange();
		}
		
		
		if(data.minETS === false || data.minETS == "") {
			
			$("#minET").val(data.minET);
			$("#maxET").val(data.maxET);
			etRange();
		}
		
		if(data.minHoleS === false || data.minHoleS == "") {
			$("#minHole").val(data.minHole);
			$("#maxHole").val(data.maxHole);
			holeRange();
		}
	}
	
	function setWidth(obj, need) {
		var width = $(obj).width();
		var times = Math.round(width / need);
		width = (times * need);
		$(obj).width(width);		
		return times;
	}
	
	function recheck() {
		$.post("/basket/recheck", null, function(data) {	
			$("#bq").text(data.quantity);
			$("#bt").text(data.total);
		}, 'json');
	}
