$(document).ready(function(){
			
	$(".nights").hide();
	//	$4('html, body').animate({scrollTop: $(".response-box").offset().top}, 800);
	
	function	search_block(x,y)
	{
		$(".search-block").hide();
		
		//var pos_x = e.pageX;
		//var pos_y = e.pageY;
		
		$.post("modal/flatscount.php",
				   $("form.fobjects").serialize()+"&"+$("form.fprices").serialize()+"&"+$("form.fguests").serialize()+"&"+$("form.fsearch").serialize()+"",
				   function(date){			
				   		$(".search-block").attr("style","top:"+(y-25)+"px;");
						$(".search-block div").html(date);
						$(".search-block").show();
						
						sb_click();
		});
	}
	
	function	search_flats(page,order)
	{
		var rel=$(".sel .sf-radio").attr("rel");
		var hasorder="";
		
		if (isNaN(page))	page="";
		
		if (order=="")
		{
			order=$(".sorting .act").attr("href");
			hasorder="0";
		}
		else	hasorder="1";
		
		$(".big").fadeOut("slow");
		$(".sorting").fadeOut("slow");
		$(".search").fadeOut("slow",function(){
			$(".preloader").fadeIn("slow");
			
			$(".big").remove();
			$(".sorting").remove();
			
			$.post("modal/flatslist.php",
				   $("form.fobjects").serialize()+"&"+$("form.fprices").serialize()+"&"+$("form.fguests").serialize()+"&"+$("form.fsearch").serialize()+"&page="+page+"&order="+order+"&hasorder="+hasorder,
				   function(date){
						$(".search").html(date);
						
						//$.get("modal/getcnt.php",function(count){$(".big span").html(count)});
						
						$(".preloader").fadeOut("slow",function(){
							//$(".big").fadeIn("slow");
							//$(".sorting").fadeIn("slow");
							$(".search").fadeIn("slow");
							
							lihover();
							//click_pages();
							click_order();
						});
			});
		});
	}
	
	function	search_flats_map()
	{
		var rel=$(".sel .sf-radio").attr("rel");
				
		$(".big").fadeOut("slow");
		$(".sorting").fadeOut("slow");
		$(".search").html("");
		
		$(".search").fadeOut("slow",function(){
			$(".preloader").fadeIn("slow");
			
			$(".big").remove();
			$(".sorting").remove();
			
			$.post("modal/flatslistmap.php",
				   $("form.fobjects").serialize()+"&"+$("form.fprices").serialize()+"&"+$("form.fguests").serialize()+"&"+$("form.fsearch").serialize()+"&rel="+rel+"",
				   function(date){
						$(".search").html(date);
						//$.get("modal/getcnt.php",function(count){$(".big span").html(count)});
						
						$(".preloader").fadeOut("slow",function(){
							
							//$(".big").fadeIn("slow");
							//$(".sorting").fadeIn("slow");
							$(".search").fadeIn("slow",function(){ setupMap(); });
							
							//lihover();
							//click_pages();
							//click_order();
						});
			});
		});
	}
	
	function	click_order()
	{
		$(".sort").click(function(e){
			e.preventDefault();
			
			search_flats("",$(this).attr("href"));
		});
	}
	click_order();
	
	function declOfNum(number, titles) {
	  cases = [2, 0, 1, 1, 1, 2];  
	  return titles[ (number%100>4 && number%100<20)? 2 : cases[(number%10<5)?number%10:5] ];
	}
	
	$('.dates').change(function() {
      date_in = parseInt($("#datein-alt").val());
      date_out = parseInt($("#dateout-alt").val());
	  	  
      if (date_in > 0 && date_out > 0) {
        days_count = ((date_out - date_in)/(86400000));
		
        $(".nights").html(""+parseInt(days_count)+"<span> "+declOfNum(days_count, [' ночь', ' ночи', ' ночей'])+"</span>");
		$(".nights").show();
      }
	  else
	  {
		$(".nights").hide();  
	  }
    });
	
/**************************************************/
	
	$(".l-menu-main a").click(function(e){
		e.preventDefault();
			
		$(".near").attr("value",$(this).attr("href"));
		
		//alert($(".near").attr("value"));
		$(".fsearch").submit();
			
		/*$.post("modal/setnear.php",
				{"id":$(this).attr("href")},
				function(date){
					if (date=="OKAY!")	$(".fsearch").submit();
		});*/
	});
	
/**************************************************/

	$(".catsearch a").click(function(e){
		e.preventDefault();
		
		$(".category").attr("value",$(this).attr("href"));
		$(".fsearch").submit();
		
		/*$.post("modal/setcat.php",
				{"id":$(this).attr("href")},
				function(date){
					alert(date);
					if (date=="OKAY!")	$(".fsearch").submit();
		});*/
	});

/**************************************************/

	$(".search-button").click(function(){
		search_flats("","");
		
		/*$.post("modal/search.php",
			    $(".select-form form").serialize()+"&rel="+rel,
			    function(date){
					$(".select-form form").submit();
		});*/
	});
	
/**************************************************/



/**************************************************/


	$(".tablesrc .filters li input").click(function(e) {										
		//$('html, body').animate({scrollTop: $(".top-l-corner").offset().top}, 800);
		//search_flats("","");
		var offset = $(this).offset();
		
		search_block(offset.left,offset.top);
	});	
	
	$(".mapsrc .filters li input").click(function(e) {
		search_flats_map("","");
	});	
	
	function	sb_click()
	{
		$(".search-block a").click(function(e){
			e.preventDefault();
			
			$(".fsearch").submit();
		});
	}
	
/**************************************************/

	$(".h-menu li:first-child").addClass("li-first");
	$(".h-menu li:last-child").addClass("li-last");
	$(".l-menu .lm-item:last-child").addClass("lm-item-last");
	$(".item-r tr td:first-child").addClass("td-first");
	$(".item-r tr td:last-child").addClass("td-last");
	$(".c-navi li:last-child").addClass("li-last");	
	$(".contacts tr:odd").addClass("tr-odd");	
	$(".fi-c tr:last-child").addClass("tr-last");

/**************************************************/

	$(".captcha-num a").click(function (e) {
		e.preventDefault();
		var img_id = ".captcha-num img";
		var timestamp = new Date().getTime();
		var img_src = $(img_id).attr("src").split("?")[0] + "?" + timestamp;
		$.ajax({
			type: "GET",
			url: img_src,
			success: function(msg){$(img_id).attr('src',img_src);}
		});
	});

/**************************************************/

	$(".excursions tbody tr:odd").addClass("hide-odd").slideUp();
	$(".excursions tbody tr:even").addClass("top");
	$(".excursions tr td:first-child").addClass("td-first");
	$(".excursions tbody tr:last-child").addClass("tr-last");
	$(".excursions tbody tr.top:last").addClass("top-last");

    $(".ex-title").click(function (e) {
      e.preventDefault();
      var base = $(this).parents(".top");
          
      if ($(base).hasClass('open')) {
		$(".hide-odd").hide();
		base.removeClass("open");
		base.next(".hide-odd").hide();
      }
      else {
		$(".hide-odd").hide();
		$(".excursions tr").removeClass("open");
		base.next(".hide-odd").show();
		base.addClass("open");
      }
    });

/**************************************************/

	$(".transport tbody tr:even").addClass("tr-odd");
	$(".transport tr td:first-child").addClass("td-first");
	$(".transport tr td:last-child").addClass("td-last");

/**************************************************/

    $('.photoshow').before('<div id="nav" class="nav">').cycle({
        fx:     'fade',
		speed:  'slow', 
        pager:  '#nav',
        before: function() { if (window.console) console.log(this.src); }
    });

/**************************************************/

	$('select.dropdown').sSelect();

/**************************************************/

	/*$(".sdata").click(function(){
		$(this).addClass("active");
		
		$(".active input").attr("checked",true);
		
		$(".active").removeClass("active");
	});*/

/**************************************************/


	var counter = 200;
	$('.select-form .rel').each(function(i) {
		$(this).attr('style', 'z-index: ' + counter);
		counter -= 1;
    });

/**************************************************/

	//$('.select-form .rel').addClass("pas");

	$(".select-form .rel *").click(function () { 
		$('.select-form .rel').addClass("pas");
		
		$('.select-form .rel .dsbl').attr("disabled","disabled");
		//$('.select-form .rel .selectedTxt').html("");
		
		//$('.select-form .rel .dsbl option').removeAttr("selected");
		//$('.select-form .rel .dsbl option:first').attr("selected","selected");
		
		if ($(".select-form .rel:first").hasClass("sel")==false)	$('.select-form .rel input').attr("value","");
		
		$('.select-form .rel').removeClass("sel");
		
		$(this).parents(".rel").removeClass("pas"); 
		$(this).parents(".rel").addClass("sel"); 
		
		$('.select-form .sel .dsbl').removeAttr("disabled");
		
		$(".relval").attr("value",$(".select-form .sel .sf-radio").attr("rel"));
		//alert($(".select-form .sel .sf-radio").attr("rel"));
    });	

	//$(".select-form .rel:first").removeClass("pas"); 
	//$(".select-form .rel:first").find("input").removeAttr("disabled");

/**************************************************/

	$('.lm-item li').live("click", function(){
		if ($(this).find("input").attr('checked'))
		{
			$(this).addClass("act");
		}
		else
		{
			$(this).removeClass("act");
		}
	});

/**************************************************/

	function	lihover()
	{
		$(".sm-item li").hover(
		  function () {
			if ($(this).hasClass("next"))	$(this).addClass("");
			else	$(this).addClass("hov");
			//$(".search .sm-item li:last-child").removeClass("hov");
		  }, 
		  function () {
			$(this).removeClass("hov");
		  }
		);
	}
	lihover();

/************************************************/

	$(".order a").click(function(e){
	  e.preventDefault();
	  $.post("/modal/order.php",
	  	{"order":$(this).attr("rel")},
	  	function(date)
	  	{
		 	$(".order").submit();
	 	});
	});

/************************************************

$(document).ready(function(){
	$(".cham-1").click(function () { 
		$(this).parent().find("input").attr("value","1");
    });
	$(".cham-2").click(function () { 
		$(this).parent().find("input").attr("value","2");
    });
	$(".cham-3").click(function () { 
		$(this).parent().find("input").attr("value","3");
    });
	$(".cham-4").click(function () { 
		$(this).parent().find("input").attr("value","4");
    });
})
***/

    $(".chambers a").click(function (e) {
      e.preventDefault();	  
      if ($(this).hasClass('act')) {
		$(this).removeClass("act");
		$(this).next("input").attr("value","0");
		$(this).next("input").attr("disabled",true);
      }
      else {
		var cha = $(this).attr('title');
		$(this).addClass("act");
		$(this).next("input").attr("value", cha);
		$(this).next("input").attr("disabled",false);
      }
    });

/**************************************************/


/**************************************************/


	$(".type a:first").addClass("act");
	$(".type-plane").click(function () { 
		$(this).parent().find("input").attr("value","plane");
    });
	$(".type-train").click(function () { 
		$(this).parent().find("input").attr("value","train");
    });
	$(".type a").click(function () { 
		$(".type a").removeClass("act");
		$(this).addClass("act");
    });

/**************************************************/

    $('.rechange-but').click(function (e) {
      e.preventDefault();
      var from = $('#place-from').val();
      var to = $('#place-to').val();
      $('#place-from').val(to);
      $('#place-to').val(from);
    });

/**************************************************/

	var minp=parseInt($(".minp").attr("value"));
	var maxp=parseInt($(".maxp").attr("value"));
	
	$( "#slider-range" ).slider({
		range: true,
		min: minp,
		step: 500,
		max: maxp,
		values: [ minp, maxp ],
		slide: function( event, ui ) {
			//alert(event);
			$( "#amount-l" ).val( ui.values[ 0 ] );
			$( "#amount-r" ).val( ui.values[ 1 ] );
			
			//$( "#amount-r" ).val( ui.values[ 1 ] );
		},
		stop: function ( event, ui ) {
			//search_flats("","");
			//$('html, body').animate({scrollTop: $(".top-l-corner").offset().top}, 800);
			//alert($(".relslide").pageX);
			
			var offset = $(this).offset();
			
			search_block(offset.left,offset.top);
		}
	});
	
	$( "#amount-l" ).val($( "#slider-range" ).slider( "values", 0 ) );
	$( "#amount-r" ).val($( "#slider-range" ).slider( "values", 1 ) );

/**************************************************/

	$('.countone').formCounter({
		min:1,
		max:10
	});
	
	$('.countzero').formCounter({
		min:0,
		max:10
	});
	
/** ************************************************** */

	$('.modal-question form').validate({
		ignore: ":hidden",
		highlight: function(element, errorClass){
			$(element).addClass(errorClass);
			$(element.form).find("label[for=" + element.id + "]").addClass('error-lb');
		},
		unhighlight: function(element, errorClass){
			$(element).removeClass(errorClass);
			$(element.form).find("label[for=" + element.id + "]").removeClass('error-lb');
		},
		errorContainer: '.error-container',
		submitHandler: function(form){
			
			form.submit();			
			return;
			$.post('modal/question_success.html', $(form).serialize(), function(data){
				$('.css-style').html(data);
			});
		}
	});

/** ************************************************** */

	$(".gallery a[rel^='prettyPhoto']").prettyPhoto({
		theme: 'light_rounded'
	});

/** ************************************************** */

	$('.metro-map').click(function (e) {
		e.preventDefault();
		$("#basic-modal-content").load("modal/modal_metromap.html", function()
		{ 
			$('#basic-modal-content').modal(); 
			mapclick();
			
			return false;
		});
		
		//return false;
	});
	
	function	mapclick()
	{
		$('#modal-map div').click(function(){
			//console.log($(this).attr('title'));
			//$('#metros .selectedTxt').html($(this).attr('title'));
			//$('#metros selected').html($(this).attr('title'));
			
			$("#metros .newListSelected").remove();
			$('#metros select option:selected').removeAttr("selected");
			
			var metro_id = $(this).attr('alt');
			$('#metros select').val(metro_id);
			
			$('#metros select').sSelect();
			$.modal.close()
		});
	}
	

/** ************************************************** */


	function equalHeight(el, elTo) {
		el.css('height', 'auto');
		elTo.css('height', 'auto');		
		var tallest = elTo.height();
		var thisHeight = el.height();
		if(thisHeight > tallest) {
			tallest = thisHeight;
		}
		el.height(tallest);
	}	

	$(window).load(function() {
		
		equalHeight($('#sidebar'), $('#main'));	
	});

/*****************************************************************/

        $.datepicker.regional['ru'] = {
                closeText: 'Закрыть',
                prevText: '&#x3c;Пред',
                nextText: 'След&#x3e;',
                currentText: 'Сегодня',
                yearRange: "1911:2012",
                showYearNavigation:true,
                monthNames: ['Январь','Февраль','Март','Апрель','Май','Июнь',
                'Июль','Август','Сентябрь','Октябрь','Ноябрь','Декабрь'],
                monthNamesShort: ['Янв','Фев','Мар','Апр','Май','Июн',
                'Июл','Авг','Сен','Окт','Ноя','Дек'],
                dayNames: ['воскресенье','понедельник','вторник','среда','четверг','пятница','суббота'],
                dayNamesShort: ['Вс','Пн','Вт','Ср','Чт','Пт','Сб'],
                dayNamesMin: ['Вс','Пн','Вт','Ср','Чт','Пт','Сб'],
                dateFormat: 'dd.mm.yy', firstDay: 1,
                changeYear: true,
				readonly:true,
                //minDate: new Date(),
                isRTL: false};
        $.datepicker.setDefaults($.datepicker.regional['ru']);
	$("#date").datepicker({
		minDate: "0"
	  });


    // datapicker
    $('#datein').datepicker({showOn: 'both', buttonImageOnly: true, beforeShow: customRange,altField: '#datein-alt', altFormat: '@'});
    $('#dateout').datepicker({showOn: 'both', buttonImageOnly: true, beforeShow: customRange,altField: '#dateout-alt', altFormat: '@'});
	
    function customRange(input) {
        var input_id = input.id;
				var d = new Date(Date.parse($("#datein").datepicker("getDate"))+(60*60*24));
                if ($("#datein").datepicker("getDate")){
						date=d;
				}
                else    date=new Date();
        if (input_id == "datein"){return {maxDate: $("#dateout").datepicker("getDate"), minDate:new Date()};}
        if (input_id == "dateout"){
			d = new Date(Date.parse(date)+60*60*24*1000);
			return {minDate: d, maxDate: null};
	}
    }

/*****************************************************************/

	$("#pikame").PikaChoose({autoPlay:false, showCaption:false, transition:[0]});
});
/**************************************************/


