var _main_teaser_active = 1;
var _main_teaser_timer = null;

$(document).ready(function() {

	InitLoginForm();
	InitChangeInfoForm();
	InitCart();

	$('.calendar-nav>li>a').click(function() {
		if($(this).parent().is(':not(.opened)')) {
			$('.calendar-nav>li:not(.opened)').show();
			$('.calendar-nav>li.opened').hide();
			$(this).parent().hide().next().show();
		}
		return false;
	});

	// main teaser
	$('.top-vis-i .main-teaser dd:first').show();
	$('.top-vis-i .main-teaser dt:first').addClass('active');

	$('.top-vis-i .main-teaser dt').click(function() {
		if(!$(this).is('.active')) {
			clearInterval(_main_teaser_timer);
			$(this).addClass('active').siblings('dt').removeClass('active');
			var current_active_big_image = $('.top-vis-i .main-teaser dd:eq('+(_main_teaser_active-1)+')');
			_main_teaser_active = $(this).prevAll('dt').length + 1;
			var big_image_to_show = $('.top-vis-i .main-teaser dd:eq('+(_main_teaser_active-1)+')');
			big_image_to_show.css('z-index', current_active_big_image.css('z-index') - 1);
			big_image_to_show.show();
			current_active_big_image.fadeOut(function() {
				big_image_to_show.css('z-index', 99);
				_main_teaser_timer = setInterval(AutoSwitchTeaser, 5000);
			});
		}
		return false;
	});
	_main_teaser_timer = setInterval(AutoSwitchTeaser, 5000);


	//gallery
	$('.b-showgallery .b-linegallery li a').click(function() {
		if($(this).is(':not(.active)')) {
			$(this).parent().parent().find('a.active').removeClass('active');
			$(this).addClass('active').parent().parent().prev().find('img').attr('src', $(this).attr('href'));
		}
		return false;
	});


	if($('#YMapsID').length && $('.b-salons-address li[coords!=""]').length) {
	
		// добавляем ссылку распечатать к заголовку
		$( '.m-title' ).append( '<a class="print-page" href="javascript:window.print();">Распечатать</a>' );

		var map = new YMaps.Map(document.getElementById("YMapsID"));

		map.enableScrollZoom();
		map.addControl(new YMaps.Zoom());

		var bounds = new YMaps.GeoCollectionBounds();

		// Создает стиль
		var s = new YMaps.Style();

		// Создает стиль значка метки
		s.iconStyle = new YMaps.IconStyle();
		s.iconStyle.href = "/_resources/i/home_contacts.png";
		s.iconStyle.size = new YMaps.Point(33, 31);
		s.iconStyle.offset = new YMaps.Point(-16, -31);

		$('.b-salons-address li[coords]').each(function() {
			var coords = $(this).attr('coords').split(",");
			var placemark = new YMaps.Placemark(new YMaps.GeoPoint(parseFloat(coords[1]),parseFloat(coords[0])), {style: s});
			bounds.add( new YMaps.GeoPoint(parseFloat(coords[1]),parseFloat(coords[0])) );

			// Устанавливает содержимое балуна
			placemark.name = $(this).find('h2').html();
			placemark.description = ($(this).find('p.subway').html()?($(this).find('p.subway').html()+"<br />"):'')+$(this).find('p:not(.subway)').html();

			// Добавляет метку на карту
			map.addOverlay(placemark);
		});

		map.setBounds(bounds);

		if(map.getZoom()>13) map.setZoom(13);
		
		
	}

	$(".b-changetheme dd a").click(function() {
		if($(this).is('.active')) {
			$(this).removeClass('active');
			$('body').removeClass('skin-2').removeClass('skin-3').removeClass('skin-1');
			$('#logo_img').attr('src', sHtmlRoot+'_resources/i/skin-1-logo.png')
			Delete_Cookie('skin', '/');
		} else {
			var num = $(this).attr('href').substring(1);
			$(this).addClass('active').parent().siblings().find('a').removeClass('active');
			if(num==1) {
				$('body').removeClass('skin-2').removeClass('skin-3').addClass('skin-1');
				$('#logo_img').attr('src', sHtmlRoot+'_resources/i/skin-1-logo.png')
			} else if(num==2) {
				$('body').removeClass('skin-3').removeClass('skin-1').addClass('skin-2');
				$('#logo_img').attr('src', sHtmlRoot+'_resources/i/skin-1-logo.png')
			} else if(num==3) {
				$('body').removeClass('skin-1').removeClass('skin-2').addClass('skin-3');
				$('#logo_img').attr('src', sHtmlRoot+'_resources/i/skin-3-logo.png')
			}
			Set_Cookie('skin', num, 3600*24*365, '/');
		}
		return false;
	});


	/* constructor */
	$(".constructordrop-select a").click(function() {
		var value1 = $(this).attr('href').substring(1);
		var title = $(this).html();

		var inp = $(this).parents('.constructordrop-select:first').prevAll('input:first');
		var span = inp.nextAll('.constructordrop__link:first').find('span')

		inp.val(value1);
		span.html(title)

		var name = inp.attr('name');
		var another = $('input[name="'+name+'"]').not(inp);
		if(another.length) {
			another.val(inp.val())
			another.nextAll('.constructordrop__link:first').find('span').html(span.html());
		}
	});

	$('.constructor-btn').click(function() {
		$(this).parents('form:first').submit();
	})

	$("input:checkbox.savefilter").click(function() {
		$("input:checkbox.savefilter").not($(this)).attr('checked', $(this).attr('checked'))
	});

	$( "#slider-range" ).slider({
			range: true,
			min: parseInt($('.slider1 .min-val').html()),
			max: parseInt($('.slider1 .max-val').html()),
			values: [ parseInt($('.slider1 .cur-min-val').html()), parseInt($('.slider1 .cur-max-val').html()) ],
			step:1000,

			slide: function( event, ui ) {
				$(".cur-min-val").html(ui.values[ 0 ]);
				$("input[name='C[price-min]']").val(ui.values[ 0 ]);
				$(".cur-max-val").html(ui.values[ 1 ]);
				$("input[name='C[price-max]']").val(ui.values[ 1 ]);

				$( "#slider-range2" ).slider('values', 0, ui.values[ 0 ])
				$( "#slider-range2" ).slider('values', 1, ui.values[ 1 ])

				$('.price-val.min').val(ui.values[ 0 ]);
				$('.price-val.max').val(ui.values[ 1 ]);
			}
	});
	$( "#slider-range2" ).slider({
			range: true,
			min: parseInt($('.slider2 .min-val').html()),
			max: parseInt($('.slider2 .max-val').html()),
			values: [ parseInt($('.slider2 .cur-min-val').html()), parseInt($('.slider2 .cur-max-val').html()) ],
			step:1000,

			slide: function( event, ui ) {
				$(".cur-min-val").html(ui.values[ 0 ]);
				$("input[name='C[price-min]']").val(ui.values[ 0 ]);
				$(".cur-max-val").html(ui.values[ 1 ]);
				$("input[name='C[price-max]']").val(ui.values[ 1 ]);

				$( "#slider-range" ).slider('values', 0, ui.values[ 0 ])
				$( "#slider-range" ).slider('values', 1, ui.values[ 1 ])

				$('.price-val.min').val(ui.values[ 0 ]);
				$('.price-val.max').val(ui.values[ 1 ]);
			}
	});

	//$(".slider1 .cur-min-val").appendTo('.ui-slider-handle:eq(0)');
	//$(".slider1 .cur-max-val").appendTo('.ui-slider-handle:eq(1)');
	$(".slider2 .cur-min-val").appendTo('.ui-slider-handle:eq(0)');
	$(".slider2 .cur-max-val").appendTo('.ui-slider-handle:eq(1)');

	$('.price-val.min').keydown(function(e) {
		$(this).data('prev', $(this).val());
		if( e.keyCode == 8 || e.keyCode == 9 || e.keyCode == 46 || e.keyCode ==13  || e.keyCode ==35 || e.keyCode ==36 || e.keyCode ==16 || e.keyCode ==45 || (e.keyCode>=48 && e.keyCode<=57) || (e.keyCode>=37 && e.keyCode<=40) ) {
			//if( parseInt("" + $(this).val() + e.keyCode-48) )
			return true;
		} else {
			return false;
		}
	}).keyup(function() {
		if($(this).val()!=$(this).data('prev')) {
			$(".cur-min-val").html($(this).val());
			$("input[name='C[price-min]']").val($(this).val());
			$( "#slider-range" ).slider('values', 0, $(this).val())
			$( "#slider-range2" ).slider('values', 0, $(this).val())
		}
	/*}).blur(function() {
		if(parseInt($(this).val())>parseInt($('.price-val.max').val())) {
			$(this).val($('.price-val.max').val());
			$(".cur-min-val").html($(this).val());
			$("input[name='C[price-min]']").val($(this).val());
			$( "#slider-range" ).slider('values', 0, $(this).val())
			$( "#slider-range2" ).slider('values', 0, $(this).val())
		}*/
	});

	$('.price-val.max').keydown(function(e) {
		$(this).data('prev', $(this).val());
		if( e.keyCode == 8 || e.keyCode == 9 || e.keyCode == 46 || e.keyCode ==13  || e.keyCode ==35 || e.keyCode ==36 || e.keyCode ==16 || e.keyCode ==45 || (e.keyCode>=48 && e.keyCode<=57) || (e.keyCode>=37 && e.keyCode<=40) ) {
			return true;
		} else {
			return false;
		}
	}).keyup(function() {
		if($(this).val()!=$(this).data('prev')) {
			$(".cur-max-val").html($(this).val());
			$("input[name='C[price-max]']").val($(this).val());
			$( "#slider-range" ).slider('values', 1, $(this).val())
			$( "#slider-range2" ).slider('values', 1, $(this).val())
		}
	/*}).blur(function() {
		if(parseInt($(this).val())<parseInt($('.price-val.min').val())) {
			$(this).val($('.price-val.min').val());
			$(".cur-max-val").html($(this).val());
			$("input[name='C[price-max]']").val($(this).val());
			$( "#slider-range" ).slider('values', 1, $(this).val())
			$( "#slider-range2" ).slider('values', 1, $(this).val())
		}*/
	});

	$("#pp-sendvacancy form button").click(function() {
		$(this).parents('form:first').submit();
		return false;
	})

	$("#pp-shops .b-shops-regions li a").click(function() {
		if(!$(this).is('.active')) {
			var num = $(this).parent().prevAll().length;
			$(this).addClass('active').parent().siblings().find('a').removeClass('active');
			$("#pp-shops .b-listscroll-i .pp-shops__tbl:eq("+num+")").show().siblings().hide();
		}
		return false;
	});


});

function AutoSwitchTeaser() {
	var next = $('.top-vis-i .main-teaser dt.active').nextAll('dt:first');
	if(!next.length) next = $('.top-vis-i .main-teaser dt:first');
	next.trigger('click');
}

function InitLoginForm() {
	$('.login-block-popup').submit(function() {
		$(".login-error").hide();
		$.getJSON('/_services/auth/login/', $(this).serialize(), function(result) {
			if(result.result == "1") {
				document.location.href='/cabinet/';
			} else {
				$(".login-error").show();
			}
		});
		return false;
	});
	$('.remind-block-popup').submit(function() {
		$(".login-error").hide();
		$.getJSON('/_services/auth/password/', $(this).serialize(), function(result) {
			$('.remind-block-info .login-remind').html(result.result)
			$('.remind-block-form').slideUp('slow');
			$('.remind-block-info').slideDown('slow');
			return false;
		});
		return false;
	});

}

function InitChangeInfoForm() {
	$('.pp-sendmail-form:not(.merge-wishlist)').submit(function() {
		$.post('/_services/auth/changerequest/', $(this).serialize(), function(result) {
			alert('Сообщение отправлено');
			$('#pp-sendclientinfo').hide();

		});
		return false;
	});

}

function InitCart() {
	$(".bskg-count input[name*=QTY]").blur(function() {
		var el = $(this);
		$.post("./", $(this).attr('name')+"="+$(this).val(), function(result) {
			el.parents('.bskg-count').next().find('strong').html(result.local+'<span class="rur">Р</span>')
			$('.summmm').html(result.total);
		}, 'json')
	})

	$(".bskg-cost select").change(function() {
		var el = $(this);
		$.post("./", $(this).attr('name')+"="+$(this).val(), function(result) {
			el.nextAll('strong').html(result.per_one+'<span class="rur">Р</span>');
			el.nextAll('strike').html(result.per_one_old+'<span class="rur">Р</span>');
			el.parents('.bskg-cost').next().next().find('strong').html(result.local+'<span class="rur">Р</span>')
			$('.summmm').html(result.total);
		}, 'json')
	})
}

