
var countdownCounterRunning = 0;


$(document).ready(function() {
	
	var itemImages = $("a.imgGallery");
	if (itemImages.length) {
		itemImages.fancybox({
			'transitionIn'	:	'elastic',
			'transitionOut'	:	'elastic',
 			'speedIn'		:	200, 
			'speedOut'		:	200, 
			'overlayShow'	:	true
		});
	}
	
	$("a[href*=#]:not([href=#])").click(function() {
		var thisHash = this.hash;
		var offset = $(thisHash).offset();
		if (offset) {
			var targetOffset = offset.top;
			$("html:not(:animated),body:not(:animated)").animate( {
				scrollTop : targetOffset
			}, 1100);
			// location.hash = this.hash;
			return false;
		}
	});
	
	var mainmenu = $('#mainmenu');
	mainmenu.find('.closed > ul').hide();

	var fxspeed = 200;

	var menu_timeout = 500;
	
	mainmenu.find('.openable > a').bind('click', function () {
		var parent = $(this).parent();
		parent.siblings('.openable').each(function() {
			if ($(this).hasClass('closed')) {
				return;
			}
			$(this).addClass('closed').children('ul').hide("blind", { direction: "vertical" }, fxspeed);
		});

		if (parent.hasClass('closed')) {
			parent.removeClass('closed').children('ul').show("blind", { direction: "vertical" }, fxspeed, function () { blockHeightSync(); });
		} else {
			parent.addClass('closed').children('ul').hide("blind", { direction: "vertical" }, fxspeed);
		}
		return false;
	});

	var bodymenu = $('#body-menu');
	bodymenu.find('li.nojs').removeClass('nojs');
	
	var bodymenu_li = bodymenu.find('li.has-submenu');
	
	bodymenu_li.each(function() {
		var hovered = $(this);

		var closefn = function () {
			hovered.children('ul').stop(true, true).hide(fxspeed, function() {
				hovered.removeClass('hovered');
			});
		};

		var openfn = function () {
			// сбросим таймаут на себе, чтобы не закрыться
			clearTimeout(hovered.data('timeout'));
			hovered.children('ul').stop(true, true).show(fxspeed).end().addClass('hovered');
			
			bodymenu.children('li.hovered').not(hovered).each(function() {
				clearTimeout($(this).data('timeout'));
				$(this).data('closefn')();
			});
		};
		
		hovered.data('closefn', closefn).data('openfn', openfn);
		

		hovered.children('a').click(function() {
			if (hovered.hasClass('hovered')) {
				closefn();
			} else {
				openfn();
			}
			return false;
		});

	}).hover(function () {
		// откроемся
		$(this).data('openfn')();
	}, function () {
		//запустим закрытие по таймауту
		$(this).data('timeout', setTimeout($(this).data('closefn'), 500));
	});
	
	
	
	
	/* Всплывающие окна перехода в автокаталог */
	
	$('.acatPopupCell').each(function (index) {
		var hovered = $(this);
		var link = hovered.children('a');
		var box = hovered.children('div');
		
		link.click(function() {
			return false;
		});
		
		
		var openfn = function () {
			clearTimeout(box.data('timeout'));
			if (! box.hasClass('opened')) {
				offset = link.position();
				box.css('top', offset.top - 16);
				box.css('left', offset.left + 20);
				box.stop().addClass('opened').slideDown(500);// css('width','0px').css('display','block').animate({width: "300px" }, 500);
//				box.stop().addClass('opened').css('width','0px').css('display','block').animate({width: "300px" }, 500);
				
				$('.acatPopupCell div.opened').not(box).data('closefn')();
			}
		};
		
		var closefn = function () {
			box.fadeOut(10);
			box.removeClass('opened');
		};
		
		box.data('closefn', closefn).data('openfn', openfn);
		
		hovered.children().mouseleave(function() {
			box.data('timeout', setTimeout(box.data('closefn'), 500));
		}).mouseenter(function() {
			box.data('openfn')();
		});
		
	});
	// подсветка строк
	$('.acatPopupRow').each(function (index) {
		var hovered = $(this);
		hovered.children('td').each(function (index) {
			$(this).mouseleave(function() {
				hovered.removeClass('hover');
			}).mouseenter(function() {
				hovered.addClass('hover');
			});
		});
		
	});
	
	
	/* Алфавитный поиск */
	
	var char_fxspeed = 200;
	var $alphaHolder = $('#alphaHolder');

	$('#alphaHolder a.alphaChar').unbind().each(function() {
		var $alpha = $(this);
		var $related = $(document.getElementById($alpha.attr('id').substring(4)));
		var $alphabetList = $alpha.next('div.alphabetList');
		
		//var needs_shift = $alpha.hasClass('shiftCharMenu');
		
		// alphabetSubList
		
		$alpha.hover(function () {
			clearTimeout($alpha.data('timeout'));
			$alpha.data('openfn')();
		}, function () {
			$alpha.data('timeout', setTimeout($alpha.data('closefn'), menu_timeout));
		}).click(false);
		
		$related.detach().appendTo('body');
		
		
		$alpha.data('closefn', function () {
			// скроем меню
			$related.stop(true, true).hide();
			// уберем пометку об открытии
			$alpha.removeClass('alphaChar-shown');
			
			// закроем все подменю
			$('#alphaHolder a.alphabetList-element-shown').each(function() {
				$(this).data('related').stop(true, true).hide();
				clearTimeout($(this).data('timeout'));
				$(this).data('closefn')();
			});
			
		}).data('openfn', function () {
			if ($alpha.hasClass('alphaChar-shown')) {
				// мы уже открыты, ничего не делаем
				return;
			}
			// закроем все остальные открытые
			$('a.alphaChar-shown').each(function() {
				clearTimeout($(this).data('timeout'));
				$(this).data('closefn')();
			});
			// пометим себя как отрытое
			$alpha.addClass('alphaChar-shown');
			
			$related.fadeIn(char_fxspeed);
			$related.position({
				//my: "center top",
				my: "left top",
				at: "right bottom",
				of: $alpha,
				collision: "fit",
				offset: '-100 0'
			});
			
			
			/*
			if (needs_shift) {
				$related.position({
					my: "center top",
					at: "right bottom",
					of: $alpha,
					collision: "fit",
					//offset: '100 0',
				});
			}
			*/
		});
		
		$related.hover(function() {
			// захватим колесо мышки
			$(document).unbind('mousewheel');
			$(document).bind('mousewheel', function(event, delta) {
				$related.scrollTop($related.scrollTop() - 30 * delta);
				return false;
			});
			
			// перенесем событие уровнем выше
			$alpha.trigger('mouseenter');
			
		}, function() {
			// отпустим колесо мышки
			$(document).unbind('mousewheel');
			
			// перенесем событие уровнем выше
			$alpha.trigger('mouseleave');
		});

		
		
		$alphabetList.find('a.alphabetList-element').each(function() {
			var $entry = $(this);
			var $related = $(document.getElementById($entry.attr('id').substring(4)));
			if ($related.length == 0) {
				$entry.bind('mouseenter', function() {
					$alphabetList.find('a.alphabetList-element-shown').each(function() {
						$(this).data('related').stop(true, true).hide();
						clearTimeout($(this).data('timeout'));
						$(this).data('closefn')();
					});
				});
				return;
			}
			// пометим себя как раскрывающийся
			$entry.addClass('alphabetList-element-showable');
			
			$related.detach().appendTo('body');
			  
			
			$entry.data('related', $related).data('closefn', function () {
				// уберем признак раскрытости
				$entry.removeClass('alphabetList-element-shown');
				// скроем субменю
				$related.hide();
			}).data('openfn', function () {
				if ($entry.hasClass('alphabetList-element-shown')) {
					// мы уже открыты, ничего не делаем
					return;
				}
				// пометим себя как открытое
				$entry.addClass('alphabetList-element-shown');
				
				// уберем всех показанных соседей
				$alphabetList.find('a.alphabetList-element-shown').not($entry).each(function() {
					$(this).data('related').stop(true, true).hide();
					clearTimeout($(this).data('timeout'));
					$(this).data('closefn')();
				});
				
				// покажем субменю
				$related.fadeIn(char_fxspeed);
				$related.position({
					 //my: "left top",
					 //at: "left bottom",
					// offset: '50 0',
					 my: "left top",
					 at: "right top",
					 of: $entry,
					 collision: "fit"
				});
			});

			$entry.hover(function () {
				clearTimeout($entry.data('timeout'));
				$entry.data('openfn')();
			}, function () {
				$entry.data('timeout', setTimeout($entry.data('closefn'), 500));
			});
	
			$related.hover(function() {
				clearTimeout($entry.data('timeout'));
	
				$(document).unbind('mousewheel');
				$(document).bind('mousewheel', function(event, delta) {
					$related.scrollTop($related.scrollTop() - 30 * delta);
					return false;
				});
				// перенесем событие уровнем выше
				$alpha.trigger('mouseenter');
				
			}, function() {
				$(document).unbind('mousewheel');
				$entry.data('timeout', setTimeout($entry.data('closefn'), 500));
				
				// перенесем событие уровнем выше
				$alpha.trigger('mouseleave');
			});

			
		});
		
	});
	
	
	
	
	/* Оформление заказа */

	$('input[name|="deliveryId"]').click(function() {
		
		if ($(this).val() == 600) {
			$('#distance').attr('disabled', '');
		} else {
			$('#distance').attr('disabled', 'disabled');
		}
		
		if ($(this).val() == 700) {
			$('#paymentStandart').hide();
			$('#paymentIndividual').show();
		} else {
			$('#paymentIndividual').hide();
			$('#paymentStandart').show();
		}		
		
	});
	
	$('input[name|="paymentMethodId"]').click(function() {
		if ($(this).val() == 300) {
			$('#deliverySchemes2').hide();
			$('#deliverySchemes1').show();
			$('input[name|="deliveryId"]').val(['500']);
		} else if ($(this).val() == 400) {
			$('#deliverySchemes1').hide();
			$('#deliverySchemes2').show();
			$('input[name|="deliveryId"]').val(['400']);
		}			
	});
	
	/* Фильтр */
	$('div.filter-item').each(function() {
		var itemDiv = $(this);
		var link = itemDiv.children('a.selector');
		var box = itemDiv.children('div.filter-values');
		
		var openfn = function() {
			$('div.filterOpen').each(function() {
				$(this).data('closefn')();
			});
			itemDiv.addClass('filterOpen');
			link.addClass('open');
			box.height(0).show().animate({'height':200}, 300);
		};
		var closefn = function() {
			itemDiv.removeClass('filterOpen');
			box.animate({'height':0}, 300, null, function(){ box.hide(); link.removeClass('open'); });
		};
		
		itemDiv.data('closefn', closefn).data('openfn', openfn);
		
		
		link.click(function() {
			if (link.hasClass('open')) {
				closefn();
			} else {
				openfn();
			}
			return false;
		});
		
		box.hover(function() {
			$(document).unbind('mousewheel');
			$(document).bind('mousewheel', function(event, delta) {
				box.scrollTop(box.scrollTop() - 30 * delta);
				return false;
			});
			// перенесем событие уровнем выше
			//link.trigger('mouseenter');
			
		}, function() {
			$(document).unbind('mousewheel');
			// перенесем событие уровнем выше
			//link.trigger('mouseleave');
		});
		
	});
	
	
	$('#countdown-counter').each(function() {
		var timer = $(this);
		
		if (countdownCounterRunning) return;
		else countdownCounterRunning = 1;
		
		var update = function() {
			var curval = parseInt(timer.text());
			if (!curval) return;
			if (curval > 1) {
				timer.text(curval - 1);
				setTimeout(update, 1000);
			} else {
				//history.go(0);
				window.location.reload(true);
			}
		};
		
		update();
	});
	
	
	// запуск загрузки баннеров
	loadAdPlaces();
	
	// выравнивание высоты левого и центрального дивов
	blockHeightSync();
	
	/*
	// настрока меню
    $("ul.sf-menu").supersubs({ 
        minWidth:    12,   // minimum width of sub-menus in em units 
        maxWidth:    27,   // maximum width of sub-menus in em units 
        extraWidth:  1     // extra width can ensure lines don't sometimes turn over 
                           // due to slight rounding differences and font-family 
    }).superfish({
    	animation:   {opacity:'show', height:'show'},  // fade-in and slide-down animation 
        speed:       'normal',
        delay: 500
    	
    });
    */
//	$("a.horMenu").each(function (index) {
//		$(this).mouseenter(function() {
//			var submenu = $("#" + this.id + 'sub');
//		});
//	})
	
});

function blockHeightSync()
{
	var lColDiv = $("#leftpart");
	var contentDiv = $("#content-body");
	
	if (lColDiv.height() > contentDiv.height() + 40) {
		contentDiv.css('height', lColDiv.height() + 40);
	}
	
}




