$(document).ready(function(){

	$("#back-top").hide();
 
	// fade in #back-top
	$(function () {
		$(window).scroll(function () {
			if ($(this).scrollTop() > 1800) {
				$('#back-top').fadeIn();
			} else {
				$('#back-top').fadeOut();
			}
		});
 
		// scroll body to 0px on click
		$('#back-top').click(function () {
			$('body,html').animate({
				scrollTop: 0
			}, 500);
			return false;
		});
	});




	$("#overlay").height($("#wrapper").outerHeight());
	
	$("#car-color a").click(function(){
		$("#car-color a").removeClass("active");
		$(this).addClass("active");
		var col = $(this).attr("href");
		$("#car").css('backgroundImage', 'url('+col+')');
		return false;
	});
	
	$("#phones a").click(function(){
		$("#callback p.error").html("");
		$("#overlay").fadeIn().fadeTo(0, 0.9);
		$("#callback").fadeIn();
		return false;
	});
	$("#callback a.close").click(function(){
		$("#callback").fadeOut();
		$("#overlay").fadeOut();
		return false;
	});
	$("#navigator a.close").click(function(){
		$("#navigator").fadeOut();
		$("#overlay").fadeOut();
		return false;
	});
	
	$("#sidebar-navi a").click(function(){
		$("#overlay").fadeIn().fadeTo(0, 0.9);
		$("#navigator").fadeIn();
		map.redraw();
		return false;
	});
	
	$("#navi a").click(function(){
		$("#overlay").fadeIn().fadeTo(0, 0.9);
		$("#navigator").fadeIn();
		map.redraw();
		return false;
	});
	
	// cars event
	
	$('a#ev-lights').hover(
		function(){
			$("#car-lights").fadeIn(200);
		},
		function(){
			$("#car-lights").hide();
	});
	$('a#ev-sale').hover(
		function(){
			$("#car-sale").fadeIn(500);
		},
		function(){
			$("#car-sale").hide();
	});
	$('a#ev-crash').hover(
		function(){
			$("#car-crash").show();
			$("#car-crash").fadeOut(2000);
		},
		function(){
			$("#car-crash").hide();
	});
	$('a#ev-cleavage').hover(
		function(){
			$("#car-cleavage").show();
			$(this).mousemove(function(e){
				var cur_x = e.clientX - $('a#ev-cleavage').offset().left;
				var cur_y = e.clientY - $('a#ev-cleavage').offset().top;
				var car_cur_x = $('#car-cleavage').offset().left;
				var car_cur_y = $('#car-cleavage').offset().top;
				var cur_x_p = Math.floor(300*(cur_x/144)) + car_cur_x;
				var cur_y_p = Math.floor(70*(cur_y/33)) + car_cur_y - 70;
				$("div#pencil").offset({top:cur_y_p, left:cur_x_p});
			});
			setTimeout(function() {$("#cleav-3").fadeOut(1000);}, 500);
			setTimeout(function() {$("#cleav-2").fadeOut(1000);}, 1500);
			setTimeout(function() {$("#cleav-1").fadeOut(1000);}, 2500);
		},
		function(){
			$("#car-cleavage").hide();
			$("#cleav-1").show();
			$("#cleav-2").show();
			$("#cleav-3").show();
	});
	
	
	
	
	YMaps.jQuery(function () {
		// Создает экземпляр карты и привязывает его к созданному контейнеру
		map = new YMaps.Map(YMaps.jQuery("#navigator-wrap")[0]);
		map.addControl(new YMaps.Zoom());
		map.addControl(new YMaps.TypeControl());
		map.addControl(new YMaps.ToolBar());
		// Устанавливает начальные параметры отображения карты: центр карты и коэффициент масштабирования
		map.setCenter(new YMaps.GeoPoint(37.391211, 55.859354), 16);
			
		// Создание стиля для значка метки            
		var s = new YMaps.Style();            
		s.iconStyle = new YMaps.IconStyle();            

		s.iconStyle.href = "/images/navi-icon-ya.png";            
		s.iconStyle.size = new YMaps.Point(66, 72);            
		s.iconStyle.offset = new YMaps.Point(-33, -72);
			
		s.iconStyle.shadow = new YMaps.IconShadowStyle();            
		s.iconStyle.shadow.href = "/images/navi-icon-ya-shadow.png";            
		s.iconStyle.shadow.size = new YMaps.Point(72, 72);            
		s.iconStyle.shadow.offset = new YMaps.Point(-22, -72);
		
		cur_point = new YMaps.GeoPoint(37.396166,55.858252);
		var placemark = new YMaps.Placemark(cur_point, {style: s});
		placemark.name = "Компания S-Glass";
		placemark.description = "г. Москва, МКАД 71й км, ТРЦ «ВэйПарк»";
		map.addOverlay(placemark);
		
		$("#find-button").click(function(){
			if(typeof router != 'undefined')
			{
				map.removeOverlay(router);
			}
			var addr = $("#navigator #address").val();
			router = new YMaps.Router([addr,cur_point], [], { viewAutoApply: true });
			YMaps.Events.observe(router, router.Events.Success, function() {
				router.getWayPoint(0).setIconContent('');
				router.getWayPoint(1).setOptions({style: s});
				map.addOverlay(router);
			});
			
			YMaps.Events.observe(router, router.Events.GeocodeError, function (number) {
				alert('Не удалось найти');
			});
			YMaps.Events.observe(router, router.Events.RouteError, function (number) {
				alert('Не удается проложить маршрут до точки');
			});
			
			map.redraw();			
			return false;
		});
		
	});
	$("#navigator a#find-a").click(function(){
		$(this).hide();
		$("#navigator-find").slideDown();
		return false;
	});
	
	
	$('input.blur').hint();
	
	function onAjaxSuccess(data)
	{
		//alert(data);
		$("#callback p.error").html("Ваш заказ принят, мы свяжемся<br/>с вами в ближайшее время");
		$("#callback").delay(2000).fadeOut();
		$("#overlay").delay(2000).fadeOut();
		$("#overlay").fadeTo(0, 0.9);
	}
	$("#callback a.send").click(function(){
		var reg_phone = /^[\(\)\[\]\s\\\/\-0-9\+]{5,250}$/i;
		var phone = $("#callback-phone").val();
		if (!reg_phone.test(phone))
		{
			$("#callback p.error").html("<span>Проверьте правильность ввода</span>");
		}
		else
		{
			$.post('/_include_areas_/callback.php', { phone:phone }, onAjaxSuccess);
		}
		return false;
	});
});
/* Placeholder */
jQuery.fn.hint = function (blurClass) {
  if (!blurClass) { 
    blurClass = 'blur';
  }

  return this.each(function () {
    // get jQuery version of 'this'
    var $input = jQuery(this),

    // capture the rest of the variable to allow for reuse
      title = $input.attr('title'),
      $form = jQuery(this.form),
      $win = jQuery(window);

    function remove() {
      if ($input.val() === title && $input.hasClass(blurClass)) {
        $input.val('').removeClass(blurClass);
      }
    }

    // only apply logic if the element has the attribute
    if (title) { 
      // on blur, set value to title attr if text is blank
      $input.blur(function () {
        if (this.value === '') {
          $input.val(title).addClass(blurClass);
        }
      }).focus(remove).blur(); // now change all inputs to title

      // clear the pre-defined text when form is submitted
      $form.submit(remove);
      $win.unload(remove); // handles Firefox's autocomplete
    }
  });
};
