/**
 * заказать звонок
 * заказать товар
 * уточнить условия, задать вопрос специалисту, узнать скидку
 */
$(document).ready(function(){
	$('.options a, .order a').click(function () {
		var dialog = $('#' + $(this).attr('rel'));
		simplePopup.moveCenter(dialog);
	});
	
	$('#phone .popupLink, .options .popupLink').click(function () {		
		var target = $(this).attr('rel');
		$('#' + target).find('.form').show().next().hide();
	});

	$(window).resize(function () {
		var dialogList = $('#order-product:visible, #clarify-price:visible, #ask:visible, #sale-size:visible');
		simplePopup.moveCenter(dialogList);
	});

	simplePopup.init({
		onShow : {
			'order-call' : function () {
				$(this).slideDown('slow');
			}
		}
	});

	$('#order-call a.gl-button:eq(0), #order-product a.gl-button:eq(0), #clarify-price a.gl-button:eq(0), #ask a.gl-button:eq(0), #sale-size a.gl-button:eq(0)').click(function () {
		form = $(this).closest('form');

		if (
			form.find('input[name=message\\.name]').val() === ''
			|| form.find('input[name=message\\.phone]').val() === ''
//			|| form.find('textarea[name=message\\.comment]').val() === ''
		) {
			alert('Не заполнено одно из полей Имя, Телефон или Комментарий');
			return false;
		};
		
		$.ajax({
			url: form.attr('action'),
			data: form.serialize(),
			context: this,
			success: function () {
				$(this).parents('.form').hide().next('.thank-you').show();
			},
			error: function () {
				alert('Произошла ошибка при отправке данных. Повторите попытку.');
			}
		});	
		
		return false;
	});
	
	$('#order-product a.gl-button:eq(1), #clarify-price a.gl-button:eq(1), #ask a.gl-button:eq(1), #sale-size a.gl-button:eq(1)').click(function () {
		$(this).closest('.popup').find('.thank-you').hide();
		$(this).closest('.popup').find('.form').show();
		
		$(this).find('.form').show().next().hide();
		simplePopup.hide($(this).parents('.popup'));
		return false;
	});
});

/**
 главное меню
 */
$(document).ready(function () {
	// 
	// Вешаем обработчик на все ссылки
	// По клику скрываем все дроп-дауны 
	$('#main-nav a:not(.none)').click(function () {
		var selector = '#' + $(this).attr('rel');
		var isSelected = $(this).hasClass('selected');
		hideDropDowns();
		if (!isSelected) {
			$(this).addClass('selected');
			$('#top').css('top', $('#top').position()['top']);
			$('#top').addClass('pause');
			$(selector).slideDown('slow');
		} else {
			$(this).removeClass('selected');
		}
		
		return false;
	});

	// который закроет все дропдауны, что только можно если 
	$('*').click(function (event) {
		if (($(this).parents('#main-nav').length == 0)
			&& ($(this).parents('.dropdown').length == 0))
		{
			hideDropDowns();
		} else {
			event.stopPropagation();
		}
	});

	var hideDropDowns = function () {
		$('.dropdown').hide();
		$('#top').removeClass('pause');
		$('#top').css('top', '0');
		$('#main-nav a.selected').removeClass('selected');
	};
	
	$(window).bind('scroll', function() {
		var scroll_top = $(window).scrollTop();

		if ($('#top').hasClass('pause') && scroll_top < $('#top').position()['top']) {
			$('#top').css('top', scroll_top);
		}
		
		if ($('#top').hasClass('pause') && scroll_top > $('#top').position()['top'] + $('#top').height() + $('#top .dropdown:visible').height() - 64) {
			hideDropDowns();
		}
	});
});
/**
 фильтр
 */
$(function () {
	var scope = null;
	var currentLink = null;
	
	// На клик вешаем 
	$('div.col div.select a').click(function () {
		scope = $(this).parents('div.col');
		currentLink = $(this);
		// Скрыть другие попапы
		hideOtherPopups();
		// Устанавливаем значения
		setupValues();
		scope.addClass('selected');
		return false;
	});

		// 
	// На применить вешаем 
	$('div.col a.gl-button').click(function () {
		var result = [];
		var title = '';
		// сохранение данных
		if ($('input[type=checkbox]:checked',scope).length == $('input[type=checkbox]',scope).length)
		{
			// снять выбор со всех, т.к. это действие по-умолчанию
			$('input[type=checkbox]:checked').each(function (i, input) {
				$(input).removeProp('checked');
			})
			
			// Тогда тайтл это первый элемент
			result.push(0);
			title = $('input[type=checkbox]:eq(0)',scope).next().html();
		} else {
			var titleList = [];
			$('input[type=checkbox]',scope).each(function (i) {
				if (i != 0) {
					var checkbox = $(this);

					if (this.checked)
					{
						result.push(i);
						titleList.push(checkbox.next().text());
					}
				}
			});
			title = createTitle(titleList)
			
		}
		if (result.length == 0)
		{
			result = [0];
			title = $('input[type=checkbox]:eq(0)',scope).next().html();
		}
		currentLink.attr('rel',result.join(',')).html(title);
		
		scope.find('form').submit();
		
		// скрытие попапа
		hideOtherPopups();
		// для хорошего стиля сбрасываем их
		currentLink = null;
		scope = null;
		return false;
	});
	// Обрабатываем клика за пределами
	$('*').live('click',function (event) {
		if (event.currentTarget == event.target) {
			
			var isFilterParent = $(this).parents('#filter').length == 0;
			var condition = isFilterParent ;
			if (condition)
			{
				$('div.col a.cancel:visible').click();
				return ;
			}
		}
	});
	// На отменть вешаем 
	$('div.col a.cancel').click(function () {
		// скрытие попапа
		hideOtherPopups();
		// Сбрасываем на начальные
		setupValues();
		// для хорошего стиля сбрасываем их
		currentLink = null;
		scrope = null;
		return false;
	});
	// На чекбокс-все 
		// Вешаем все селектед
	// На остальные чекбоксы 
	$('div.col input[type=checkbox]').click(function () {
		
		var self = $(this);
		self.next().removeClass('checked');
		if (this.checked)
		{
			self.next().addClass('checked');
		} 
		var isAllClicked = self.parent('form').length == 1;
		if (isAllClicked)
		{
			if (this.checked)
			{
				setupAll(true);
			} else {
				setupAll(false);
			}
		} else {
			var checkAll = false;
			if (this.checked)
			{
				var all = true;
				$('input[type=checkbox]:gt(0)',scope).each(function () {
					if (!this.checked)
					{
						if ($(this).attr('disabled') === undefined)
						{
							all = false;
							//return false;
						}					
					}
				});
				checkAll = all;
			} else {
				checkAll = false;
			}
			$('input[type=checkbox]:eq(0)',scope).get(0).checked = checkAll;
		}
		
		// Обновляем класc selected
		// Если все остальные тоже selected
		// То чекбокс "все" активируется
	});
	var setupValues = function () {
		setupAll(false);
		// Загружаем данные
		var values = currentLink.attr('rel');
		if (!values)
		{
			values = [0];
		} else {
			values = values.split(',');
		}
		$(values).each(function (i,row) {
			row = parseInt(row);
			if (row == 0)
			{
				setupAll(true);
			}
			$('input[type=checkbox]:eq(' + row +')',scope).get(0).checked = true;
			$('input[type=checkbox]:eq(' + row +')',scope).next('label').addClass('checked');
		});
	}
	var hideOtherPopups = function () {
		$('div.col').removeClass('selected');
	}
	var setupAll = function (active) {
		$('input[type=checkbox]', scope).each(function () {
			if ($(this).attr('disabled') !== undefined)
			{
				return;
			}
			if (active)
			{
				this.checked = true;
				$(this).next().addClass('checked');
			} else {
				this.checked = false;
				$(this).next().removeClass('checked');
			}
			
		});
	}
	var createTitle = function (titleList) {
		var title = titleList.join(', ');
		if (title.length > 27)
		{
			title = title.substring(0,24) + ' ...';
		}
		return title;
	}
	// Вызов первоначальной инициализации 
	// Если у ссылки уже заполнено rel, то формируем его
	$('div.select a').each(function () {
		var scope = $(this).parents('div.col');
		//currentLink = $(this);
		/*
		var rel = $(this).attr('rel');
		if (rel !== undefined) {
			var list = rel.split(',');
			var titleList = [];
			// Поиск лабела, формируем тайтл
			$(list).each(function (key,row) {
				var label = $('input[type=checkbox]:eq(' + row +')',scope).next().find('a').html();
				if (label) {
					titleList.push(label);
				}
			});
			
			title = createTitle(titleList);
			$(this).html(title);
		}
		*/
		
		list = $('input[type=checkbox]', scope);

		if (list.length > 0) {
			var titleList = [];
			var result = [];
			
			list.each(function (i, v) {
				var label = $(v).closest('.c').find('label a').html();
				
				if ($(v).is(':checked') && label) {
					result.push(i);
					titleList.push(label);
				};
			});

			if (titleList.length > 0 && titleList.length != list.length - 1) {
				title = createTitle(titleList);
				rel = result.join(',');
				$(this).attr('rel', rel).html(title);
			}
		};
	});
	
	$('div.cnt .c label a').click(function () {
		checkbox = $(this).closest('.c').find('input[type=checkbox]');
	
		if (checkbox.is(':checked')) {
			checkbox.removeProp('checked');
			checkbox.addClass('checked');			
		} else {
			checkbox.prop('checked', true);
			checkbox.removeClass('checked');
		}

		return false;
	});
	
/*
	$('div.cnt .c label').click(function () {
		return false;
	});
*/
})
/**
прокрутка промо-галереи (#promo)
*/

$(function () {
	var slider = $('#slideshow').bxSlider({
		controls: false,
		auto: true,
		pager: true,
		pagerSelector: '#promo-pager',
		speed: 500,
    	pause: 4500
	});

	$('div.prev').click(function() {
		slider.goToPreviousSlide();
		return false;
	});
        
    $('div.next').click(function() {
		slider.goToNextSlide();
        return false;
    });       
});

$(document).ready(function(){
	$('#slideshow .desc').each(function(i){
  		var ah = $('#slideshow .desc').eq(i).height();
  		var mh = ah / 2;
  		$('#slideshow .desc').eq(i).css('margin-top', -mh);
	});
  $('#promo-pager').each(function(i){
  		var ah = $('#promo-pager').eq(i).width();
  		var mh = ah / 2;
  		$('#promo-pager').eq(i).css('margin-left', -mh);
	});
});




