﻿var _pp = new popup();

$(document).ready(function (){
	//	Наведение мыши на дерево
	$('.trees td').hover(
		function(){ $(this).addClass('t-sel'); $(this).find('.t-long-list').addClass('t-open'); },
		function(){ $(this).removeClass('t-sel'); $(this).find('.t-open').removeClass('t-open'); }
	);
	//	Раскрытие ветки дерева
	$('div.tree li p').click(function(){
		var li = $(this).parent('li');
		var ul = li.parent('ul');
		var cur_class = li.attr('class');
		var next_class = li.next().attr('class');

		$(this).toggleClass('o');
		if ($(this).hasClass('o'))
		{
			li.nextUntil('li.'+cur_class).filter('.'+next_class).show();
		}
		else
		{
			li.nextUntil('li.'+cur_class).hide().find('p.o').removeClass('o');
		}

		if (ul.height() > 250)
		{
			ul.parent('div.t-rub-list').addClass('t-long-list').addClass('t-open').siblings('div.t-more-arr').addClass('t-more');
		}
		else
		{
			ul.parent('div.t-rub-list').removeClass('t-long-list').removeClass('t-open').siblings('div.t-more-arr').removeClass('t-more');
		}

		if (ul.closest('td').find('p.o').length)
		{
			ul.closest('td').addClass('t-hold-open');
		}
		else
		{
			ul.closest('td').removeClass('t-hold-open');
		}
	});
	//	Расстановка стрелок раскрытия под деревьями, которые не помещяются в 250px
	$('div.tree').each(function(){
		if($(this).find('div.t-rub-list ul').height() > 250)
		{
			$(this).find('div.t-rub-list').addClass('t-long-list').siblings('div.t-more-arr').addClass('t-more');
		}
	});
	//	Авторизация
	$('a.enter').click(function(){
		if ($('#auth-form').css('display') == 'none')
		{
			$('#auth-form').slideDown(300);
		}
		else
		{
			$('#auth-form').slideUp(300);
		}
	});
	$('a.a-close').click(function(){
		$('#auth-form').slideUp(300);
	});
	$('input.a-input').focus(function(){
		if ($(this).attr('name') == 'login' && $(this).val() == 'Введите логин (e-mail)')
		{
			$(this).val('');
		}
		if ($(this).attr('name') == 'password' && $(this).val() == 'Введите пароль')
		{
			$(this).val('');
		}
		$(this).addClass('active');
	});
	$('input.a-input').blur(function(){
		if ($(this).attr('name') == 'login' && $(this).val() == '')
		{
			$(this).val('Введите логин (e-mail)');
		}
		if ($(this).attr('name') == 'password' && $(this).val() == '')
		{
			$(this).val('Введите пароль');
		}
		$(this).removeClass('active');
	});
	$('a.a-enter').click(function(){
		$.post('/ajax/user/login/', $('#auth-form').serialize(), function(answer){
			if (answer && answer.result == 'OK')
			{
				document.location.reload();
			}
			else
			{
				var message = 'Ошибка';
				if (answer && answer.message)
				{
					message = answer.message;
				}
				$('#auth-form .a-message').html(message).show();
			}
		}, 'json');
	});
	$('input.a-input').keyup(function(e){
		if (e.keyCode == 13)
		{
			$('a.a-enter').click();
		}
	});
	$('a.a-exit').click(function(){
		$.get('/ajax/user/logout/', function(answer){
			if (answer && answer.result == 'OK')
			{
				document.location.reload();
			}
		}, 'json');
	});

	//	Поиск
	$('.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'); });

	//	Переключение рубрикатор/фильтр в левой колонке
	$('.rb-switch a').click(function(){
		$(this).siblings('a').removeClass('sel');
		$(this).addClass('sel');
		$('.rb-switch-contents > *').removeClass('sel');
		$('#rb-'+$(this).attr('name')).addClass('sel');
	});
	//	Убираю ссылки с неактивных галочек фильтра
	$('.filter-value a.disabled').removeAttr('href').parent('span').siblings('input').removeAttr('onclick');
	//	Последняя вкладка должна быть закруглена
	$('div.prod-pads a:last-child').addClass('last').wrapInner('<span>');
	//	Переключение вкладок товара
	$('div.prod-pads a').click(function(){
		$(this).siblings('a').removeClass('sel');
		$(this).addClass('sel');
		var name = $(this).attr('name');
		if (name == 'all')
		{
			$('div.prod-pads-content > div.prod-pad').show();
		}
		else
		{
			$('div.prod-pads-content > div.prod-pad').hide();
			$('#pad-'+name).show();
		}
	});
	//	Покупка
	$('.buy').live('click change keyup', function(e)
	{
		var _this = $(this);
		if (_this.hasClass('out'))
		{
			return;
		}
		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;
			}
		}
		$.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 (p[0] == 'del' && _this.hasClass('window') == false)
				{
					document.location.href = answer.url;
				}
				if (typeof(answer.html) != 'undefined' && answer.html.length)
				{
					if (p[0] == 'add' || p[0] == 'get' || (p[0] == 'del' && _this.hasClass('window') == true))
					{
						_pp.open({content:answer.html});
					}
				}
			}
		});
	});
	//	Покупка списком
	$('.buy-pack').click(function()
	{
		var pack = $('#backet-pack').val();
		$.post('/ajax/backet/pack/', 'pack='+pack, 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');
				$('#backet-pack-done').attr('action', answer.url).submit();
				//document.location.href = answer.url;
			}
		}, 'json');
	});
	//	Показать пакетную загрузку товаров в корзину
	$('a.backet-more-toggle').click(function(){
		if ($('div.backet-more').css('display') == 'none')
		{
			$('div.backet-more').slideDown(300);
			$(this).html('- <u>Скрыть</u>');
		}
		else
		{
			$('div.backet-more').slideUp(300);
			$(this).html('+ <u>Дополнение корзины по списку кодов</u>');
		}
	});
	//	Вывод дополнительных полей в заказе
	$('.backet-pay input').change(function(){
		if ($(this).attr('name') == 'legacy')
		{
			if ($(this).val() == 2)
			{
				$('#legacy-fields').slideDown(300);
			}
			else
			{
				$('#legacy-fields').slideUp(300);
			}
		}
		if ($(this).attr('name') == 'delivery')
		{
			if ($(this).val() == '   AAQ')
			{
				$('#delivery-fields').slideDown(300);
			}
			else
			{
				$('#delivery-fields').slideUp(300);
			}
		}
	});
	//	Функция "Перезвоните мне"
	$('.call').live('click', function(e)
	{
		var _this = $(this);
		var p = $(this).attr('name').split('|');
		$.post('/ajax/call/'+p[0]+'/'+p[1]+'/', $('.pp-form').serialize(), function(answer)
		{
			if (answer && answer.result == 'ok')
			{
				if (typeof(answer.html) != 'undefined' && answer.html.length)
				{
					_pp.open({content:answer.html});
				}
				if (p[0] == 'set')
				{
					_pp.close(2000);
				}
			}
			if (typeof(answer.message) != 'undefined' && answer.message.length)
			{
				_pp.message(answer.message);
			}
		}, 'json');
	});
	//	Переключение вида отображения товаров (прайс/блоки)
	$('.show-type').click(function(){
		$.getJSON('/ajax/show_type/'+$(this).attr('name')+'/', function(answer)
		{
			if (answer.result && answer.result == 'ok')
			{
				document.location.reload();
			}
		});
	});
	//	Переключение типа оплаты (нал/безнал)
	$('.currency input[name=currency]').click(function(){
		$.getJSON('/ajax/currency/'+$(this).val()+'/', function(answer)
		{
			if (answer.result)
			{
				document.location.reload();
			}
		});
	});
	//	Переключение типов отображения по складам
	$('#wh_mode').change(function(){
		$.getJSON('/ajax/wh_mode/'+$(this).val()+'/', function(answer)
		{
			if (answer.result && answer.result == 'ok')
			{
				document.location.reload();
			}
		});
	});
	//	Раскрытие списка сортировки
	$('.prod-order').hover(function(){ $(this).addClass('open'); }, function(){ $(this).removeClass('open'); });
	
	$("a.preview").fancybox({
		'overlayShow': true,
		'overlayOpacity': 0.8,
		'autoScale': false,
		'hideOnContentClick': true,
		'titleShow': false,
		'transitionIn': 'elastic',
		'transitionOut': 'elastic'
	});
	
	$('div.prod-image div.i').click(function(){
		$('div.prod-image div.mi td:first-child a').click();
	});
});
