﻿var am_w = new am_window();

$(document).ready(function (){
	$.ajaxSetup({
		timeout: 5000,
		type: "POST",
		cache: false,
		async: true,
		contentType: "application/x-www-form-urlencoded"
	});

	//	Список представительств
	$('div.h-offices span, div.h-offices div').hover(
		function(){$('div.h-offices div').show();},
		function(){$('div.h-offices div').hide();}
	);
	//	Список магазинов
	$('div.h-shops-container').hover(
		function(){$('div.h-shops-container div').addClass('h-shops-open');},
		function(){$('div.h-shops-container div').removeClass('h-shops-open');}
	);
	//	Заказ звонка
	$('.h-get-call').live('click', function(){
		switch($(this).attr('name'))
		{
			case 'get':
				$.getJSON('/ajax/call/get/', function(answer)
				{
					if (answer && answer.result == 'ok')
					{
						am_w.open(answer);
					}
				});
				break;
			case 'set':
				$.post('/ajax/call/set/', $('#call-form').serialize(), function(answer)
				{
					if (answer.message)
					{
						$('.am-w-comment td.message').html(answer.message);
					}
					if (answer && answer.result == 'ok')
					{
						setTimeout(function(){ am_w.close($('#call-form').closest('.am-window-container').attr('id')); }, 2000);
					}
				}, 'json');
		}
	});
	//	Функции пользователя
	$('.user').live('click', function(){
		var p = $(this).attr('name');
		$.post('/ajax/user/'+p+'/', $('#auth-form').serialize(), function(answer){
			if (!answer)
			{
				return;
			}
			
			switch (p)
			{
				case 'loginform':
				case 'regform':
				case 'restoreform':
				case 'feedbackform':
					if (answer.result == 'ok')
					{
						am_w.open(answer);
					}
					break;
				case 'feedbacksend':
					if (answer.result == 'ok')
					{
						setTimeout(function(){ am_w.close(); }, 2000);
					}
					break;
				case 'login':
				case 'logout':
					if (answer.result == 'ok')
					{
						document.location.reload();
					}
					break;
				case 'reg':
				case 'restore':
					if (answer.result == 'ok')
					{
						setTimeout(function(){ document.location.reload(); }, 2000);
					}
					break;
			}
			if (answer && answer.message)
			{
				$('#auth-form .message').html(answer.message).show();
			}
		}, 'json');
	});
	$('.am-w-auth input').live('keyup', function(e){
		if (e.keyCode == 13)
		{
			$('.am-w-auth a.auth').click();
		}
	});
	//	Вкладки меню
	$('.h-menu-pad').each(function(){
		var w = $(this).width();
		$(this).width(w);
		$(this).find('.h-menu-container').width(w-2);
		$(this).find('.h-menu-pad-button').width(w - 6);
		$(this).find('a.h-menu-link').width(w - 40);
	});
	$('.h-menu-container').hover(
		function(){
			$(this).parent('td').addClass('hover');
			//	Выпадающее меню
			var m = $(this).find('.h-sub-menu');
			var sh = $(this).find('.h-sub-menu-shadow');
			m.show();
//			if(typeof(sh.attr('style')) == 'undefined' || sh.attr('style') == '')
			{
				var w = parseInt(m.width());
				var l = parseInt($(this).position().left + ($(this).width() - w) / 2);
				if (l < 0)
				{
					l = 0;
				}
				if (l + w > 950)
				{
					l = 950 - w;
				}
				m.css({'left':l+'px'});
				$(this).find('.h-sub-menu-shadow').css({
					'width':(parseInt(m.outerWidth()) + 12)+'px',
					'height':(parseInt(m.outerHeight()) + 6)+'px',
					'left':(l - 6)+'px',
					'opacity':0.3
				});
			}
			sh.show();
		},
		function(){
			$(this).parent('td').removeClass('hover');
			//	Выпадающее меню
			$(this).find('.h-sub-menu').hide();
			$(this).find('.h-sub-menu-shadow').hide();
		}
	);
	//	Поиск
	$('.search input.q').focus(function(){
		if ($(this).val() == 'поиск по сайту')
		{
			$(this).val('');
		}
	});
	var search_string = $('.search input.q').val();
	var search_timer;
	$('.search input.q').bind('keyup change click', function(e){
		var val = $(this).val();
		if (val == search_string)
		{
			return;
		}
		clearTimeout(search_timer);
		search_string = val;
		if (val == '')
		{
			$('.search-loader').hide();
			return;
		}

		search_timer = setTimeout(function(){
			var url = '/ajax/search/'+$('.search input.q').val()+'/';
			var order = window.location.href.match(/order=(\w+)/g);
			if (order && order.length)
			{
				url += order+'/';
			}
			$.get(url, function(answer){
				if (answer.length)
				{
					$('.search-loader').html(answer).show();
				}
				else
				{
					$('.search-loader').hide();
				}
			});
		}, 200);
	});
	$('.search input.q').blur(function(){
		if ($(this).val() == '')
		{
			$(this).val('поиск по сайту');
		}
		$('.search-loader').hide();
	});
	$('.search-loader').hover(function(){ $(this).addClass('hover'); }, function(){ $(this).removeClass('hover'); });
	//	Товары по названию
	$('.alfa-open').click(function(){
		$(this).closest('div.alfa-list').toggleClass('open');
		$('a.alfa').removeClass('sel');
		$('div.alfa-content').html('');
	});
	$('.alfa-close').live('click', function(){
		$(this).closest('div.alfa-list').removeClass('open');
		$('a.alfa').removeClass('sel');
		$('div.alfa-content').html('');
	});
	$('.alfa').live('click', function(){
		$('a.alfa').removeClass('sel');
		$(this).addClass('sel');
		$.get('/ajax/alfa/'+$(this).attr('name')+'/', function(answer)
		{
			if (answer)
			{
				$('div.alfa-content').html(answer);
			}
		});
	});
	//	Раскрытие описания рубрики
	$('.rub-about div.hider a').click(function(){
		$(this).parent('div').siblings('div.hided').slideToggle(300);
		$(this).parent().find('a').toggleClass('hide');
	});
	$('.descr .text').hover(function(){ $(this).addClass('hover'); }, function(){ $(this).removeClass('hover'); });
	$('.descr .full-text-content').each(function(){
		var h = $(this).height();
		$(this).css({'height':'auto'});
		var ha = $(this).height();
		if (ha > h)
		{
			$(this).removeAttr('style');
		}
	});
	//	Скроллинг фотографий товара
	$('.other-images .other-up').click(function(){
		$('.other-scroll').scrollTo('-=76px', 300);
	});
	$('.other-images .other-down').click(function(){
		if ($('.other-scroll div').height() - ($('.other-scroll').scrollTop() + $('.other-scroll').height()) > 70)
		{
			$('.other-scroll').scrollTo('+=76px', 300);
		}
	});
	//	Доставка и гарантия в окне
	$('a.w-doc').click(function(){
		$.getJSON('/ajax/doc/'+$(this).attr('name')+'/', function(answer)
		{
			if (answer && answer.result == 'ok')
			{
				am_w.open(answer);
			}
		});
	});
	//	Вкладки товара
	$('.prod-pads td').hover(
		function(){ $(this).addClass('hover'); },
		function(){ $(this).removeClass('hover'); }
	);
	$('.prod-order-container').hover(
		function(){ $(this).addClass('hover'); },
		function(){ $(this).removeClass('hover'); }
	);
	//	Переключение вкладок товара
	$('.prod-pads a').click(function(){
		$('.prod-pads td').removeClass('sel');
		$(this).parent().parent().addClass('sel');
		var name = $(this).attr('name');
		$('div.prod-pads-content > div.prod-pad').removeClass('open all');
		if (name == 'all')
		{
			$('div.prod-pads-content > div.prod-pad').not('#pad-howbuy').addClass('all');
		}
		else
		{
			$('#pad-'+name).addClass('open');
		}
		if (name == 'howbuy' && !$(this).hasClass('loaded'))
		{
			if (typeof load_map_data == 'function')
			{
				load_map_data();
			}
		}
		if ($(this).attr('ecommerce').length)
		{
			_gaq.push(['_trackPageview', $(this).attr('ecommerce')]);
		}
	});
	$('.prod-pads td:first-child').addClass('sel');
	//	Изменение размера шрифта
	$('.font-size-text').jfontsize();
	//	Форматирование таблиц параметров
	if ($('#pad-har > table').length)
	{
		$('#pad-har div tr').each(function(){
			if ($.trim($(this).html()) == '')
			{
				$(this).remove()
			}
			else
			{
				$(this).children('td').wrapInner('<p/>');
			}
		});
		$('#pad-har > table').append($('#pad-har div tr'));
		$('#pad-har > div').remove();
		$('#pad-har > table tr td:first-child').addClass('name');
	}
	//	Отзывы
	$('a.comment').live('click', function(){
		var _this = $(this);
		var p = _this.attr('name').split('|');
		if (p.length < 2)
		{
			return;
		}
		switch (p[0])
		{
			case 'get':
				$.getJSON('/ajax/comment/'+p[0]+'/'+p[1]+'/', function(answer)
				{
					if (answer && answer.result == 'ok')
					{
						am_w.open(answer);
					}
				});
				break;
			case 'set':
				$.post('/ajax/comment/'+p[0]+'/'+p[1]+'/', $('#comment-form').serialize(), function(answer)
				{
					if (answer.message)
					{
						$('.am-w-comment td.message').html(answer.message);
					}
					if (answer && answer.result == 'ok')
					{
						setTimeout(function(){
							am_w.close($('#comment-form').closest('.am-window-container').attr('id'));
							setTimeout(function(){document.location.reload()}, 800);
						}, 2000);
					}
				}, 'json');
		}
	});
	$('.order-arj a.prod-list').click(function(){
		$('.order-arj a.prod-list').not(this).removeClass('open');
		$(this).addClass('open');
		var prod = $(this).closest('.order-arj').find('div.products');
		$('.order-arj div.products').not(prod).slideUp();
		prod.slideDown();
	});
	//	Акционный ротатор
	var rotator_tm = setTimeout(rotator, 3000);
	function rotator(direct)
	{
		var scroller = $('div.rotator-scroll');
		var table = scroller.children('table');
		clearTimeout(rotator_tm);
		scroller.stop();
		if (direct == 'down')
		{
			table.find('tr.rotator-row:last-child').insertBefore(table.find('tr.rotator-row:first-child'));
			scroller.scrollTo('+=304px', 0);
			scroller.scrollTo(table.find('tr.rotator-row:eq(1)'), 800);
		}
		else
		{
			if (scroller.scrollTop() > 304)
			{
				table.find('tr.rotator-row:first-child').insertAfter(table.find('tr.rotator-row:last-child'));
				scroller.scrollTo('-=304px', 0);
			}
			scroller.scrollTo(table.find('tr.rotator-row:eq(1)'), 800);
		}
		rotator_tm = setTimeout(rotator, 3000);
	}
	$('.rotator-up').click(function(){ rotator('up'); });
	$('.rotator-down').click(function(){ rotator('down'); });
	
	//	Просмотренные товары
	$('.seen-left').click(function(){ $('div.prod-seen-content').scrollTo('-=110px', 800); });
	$('.seen-right').click(function(){ $('div.prod-seen-content').scrollTo('+=110px', 800); });
	
	//	Вызов окна акции
	$('a.action').click(function(){
		var _this = $(this);
		$.getJSON('/ajax/action/'+_this.attr('name')+'/', function(answer)
		{
			if (answer && answer.result == 'ok')
			{
				var o = _this.offset();
				answer.params.left = 'center';
				answer.params.top = o.top + _this.height() + 10;
				var id = am_w.open(answer);
			}
		});
	});

	//	Покупка
	$('a.buy, input.buy').live('click change keyup', function(e)
	{
		var _this = $(this);
		if(e.type == 'click' && $(this).is('input'))
		{
			return;
		}
		var p = $(this).attr('name').split('|');
		var count = 1;
		if (p[0] == 'set')
		{
			if (e.type == 'click')
			{
				return;
			}
			count = parseInt($(this).val());
			if (count <= 0)
			{
				return;
			}
		}
		if (p[0] == 'add')
		{
			_gaq.push(['_trackPageview', '/addToCart']);
		}
		$.getJSON('/ajax/backet/'+p[0]+'/'+p[1]+'/'+count+'/', function(answer)
		{
			if (answer && answer.result == 'ok')
			{
				$('.i-c').html(answer.count);
				$('.i-p').html(answer.cost);
				$('a.i-u').attr('href', answer.url);
				$('a.backet-refresh').addClass('active');
				if (parseInt(answer.count) > 0)
				{
					$('.h-backet').removeClass('empty')
				}
				else
				{
					$('.h-backet').addClass('empty')
				}
				if (p[0] == 'set' && answer.cur_cost)
				{
					_this.closest('tr').find('.i-cc').html(answer.cur_cost);
				}
				if (p[0] == 'del' && _this.hasClass('window') == false)
				{
					document.location.href = answer.url;
				}
				if (p[0] == 'add' || p[0] == 'get' || p[0] == 'edit' || (p[0] == 'del' && _this.hasClass('window') == true))
				{
					var id = am_w.open(answer);
				}
				switch (p[0])
				{
					case 'add':
						$('#buy'+p[1]).removeClass('buy').addClass('incart');
						break;
					case 'del':
						$('#buy'+p[1]).removeClass('incart').addClass('buy');
						break;
				}
			}
		});
	});
	$('a.incart').live('click', function(){
		$('.h-backet a.buy').click();
	});

	//	Уведомить о наличии
	$('a.out').live('click', function(){
		var p = $(this).attr('name').split('|');
		
		switch (p[0])
		{
			case 'add':
				$.getJSON('/ajax/alert/'+p[0]+'/'+p[1]+'/', function(answer)
				{
					if (answer && answer.result == 'ok')
					{
						am_w.open(answer);
					}
				});
				break;
			case 'set':
				$.post('/ajax/alert/'+p[0]+'/'+p[1]+'/', $('#alert-form').serialize(), function(answer)
				{
					if (answer.message)
					{
						$('.am-w-comment td.message').html(answer.message);
					}
					if (answer && answer.result == 'ok')
					{
						setTimeout(function(){
							am_w.close($('#alert-form').closest('.am-window-container').attr('id'));
						}, 2000);
					}
				}, 'json');
		}
	});

	//	Сравнение
	$('.compare').live('click', function(e)
	{
		var _this = $(this);
		var p = $(this).attr('name').split('|');
		if (p.length < 2)
		{
			p[1] = '';
		}
		$.getJSON('/ajax/compare/'+p[0]+'/'+p[1]+'/', function(answer)
		{
			if (answer && answer.result == 'ok')
			{
				if (typeof answer.button != 'undefined')
				{
					$('#compare-button-'+p[1]).html(answer.button);
				}
				if (typeof answer.list != 'undefined')
				{
					$('#compare-list').html(answer.list);
				}
				else
				{
					$('#compare-list').html('');
				}
				if (_this.hasClass('reload'))
				{
					document.location.reload();
				}
			}
		});
	});
	$('table.compare-table tr.param:odd').addClass('odd');
	$.getJSON('/ajax/compare/get/', function(answer)
	{
		if (answer && answer.result == 'ok' && typeof answer.list != 'undefined')
		{
			$('#compare-list').html(answer.list);
		}
	});
	//	Подсказки в оформлении заказа
	$('.field-help').click(function(){
		var _this = $(this);
		$.getJSON('/ajax/help/'+$(this).attr('name')+'/', function(answer)
		{
			if (answer && answer.result == 'ok')
			{
				var o = _this.offset()
				answer.params.left = o.left;
				answer.params.top = o.top - answer.params.height - 10;
				var id = am_w.open(answer);
				$('.am-w-help .name a').click(function(){
					var sel = $('select[name="'+$(this).attr('name')+'"]');
					sel.find('option').removeAttr('selected');
					sel.find('option[value="'+$(this).attr('value')+'"]').attr('selected', 'selected');
					am_w.close($(this).closest('.am-window-container').attr('id'));
				});
			}
		});
	});
	//	Убираю ссылки с неактивных галочек фильтра
	$('.filter-value a.disabled').removeAttr('href').parent('span').siblings('input').removeAttr('onclick');
	//	Переключение типа оплаты (нал/безнал)
	$('.currency input[name=currency]').click(function(){
		$.getJSON('/ajax/currency/'+$(this).val()+'/', function(answer)
		{
			if (answer.result)
			{
				document.location.reload();
			}
		});
	});
	//	Переключение баннеров
	$('div.l-banner-pager a').click(function(){
		var id = $(this).attr('name');
		$('div.l-banner-one').not('#bn'+id).removeClass('sel');
		$('div#bn'+id+'.l-banner-one').addClass('sel');
		$('div.l-banner-pager a').not(this).removeClass('sel');
		$(this).addClass('sel');
	});
	function bn_change()
	{
		if ($('div.l-banner-pager a.sel').next().length)
		{
			$('div.l-banner-pager a.sel').next().click();
		}
		else
		{
			$('div.l-banner-pager a:first-child').click();
		}
		setTimeout(bn_change, 4000);
	}
	//setTimeout(bn_change, 4000);
	//	Очистка списка просмотренных товаров
	$('a.seen-clear').click(function(){
		$.get('/ajax/seen/clear/', function(answer){
			if (answer.result == 'ok')
			{
				$('div.prod-seen').slideUp(1000, function(){ $('div.prod-seen').remove(); });
			}
		}, 'json')
	});
	//	Просмотр фото
	$("a.preview").fancybox({
		'overlayShow': true,
		'overlayOpacity': 0.8,
		'autoScale': false,
		'hideOnContentClick': true,
		'titleShow': false,
		'transitionIn': 'elastic',
		'transitionOut': 'elastic'
	});
});
