	var dayNames = ['Воскресение', 'Понедельник', 'Вторник', 'Среда', 'Четверг', 'Пятница', 'Суббота'];
	var dayNamesMin = ['Вс', 'Пн', 'Вт', 'Ср', 'Чт', 'Пт', 'Сб'];
	var monthNames = ['Январь', 'Февраль', 'Март', 'Апрель', 'Май', 'Июнь', 'Июль', 'Август', 'Сентябрь', 'Октябрь', 'Ноябрь', 'Декабрь'];
	var monthNamesShort = ['Янв', 'Фев', 'Март', 'Апр', 'Май', 'Июнь', 'Июль', 'Авг', 'Сент', 'Окт', 'Ноя', 'Дек'];
	var groupDiscounts = {10: 5, 20: 10};
	var lastImgShown = 0;
	var timeoutID;
	var initImageTooltip = function()
	{
		$('a.preview').tooltip({delay: 700, 
		    showURL: false, 
		    bodyHandler: function() 
		    { 
				var hotelID = $(this).attr('id').slice(9);
				if (__hotelImage[hotelID])
				{
					$(this).mouseout(function(){
						lastImgShown = 0;
						clearInterval(timeoutID);
					});
					timeoutID = setInterval(function() {
						var img = $('#bigImagePreview');
						if (lastImgShown == __hotelImage[hotelID].length-1) 
							lastImgShown = 0;
						else 
							lastImgShown++;
						img.attr('src', __hotelImage[hotelID][lastImgShown]);
					}, 1300);
		   			return $('<img id="bigImagePreview"/>').attr("src", __hotelImage[hotelID][lastImgShown]);   
				}
				return $('<img id="bigImagePreview"/>');
		    } 
		 });
	}
	
	var initFancy = function()
	{
		$("a.popup").fancybox({
			'transitionIn'		: 'none',
			'transitionOut'		: 'none',
			'titlePosition' 	: 'over',
			'cyclic'			: 'false',
			'titleFormat'		: function(title, currentArray, currentIndex, currentOpts) {
				return '';
			}
		});
		
		$("a.popupIframe").fancybox({
			'transitionIn'		: 'none',
			'transitionOut'		: 'none',
			'titlePosition' 	: 'over',
			'type'              : 'iframe',
			'width'             : 1000,
			'height'            : 800,
			'cyclic'			: 'false',
			'titleFormat'		: function(title, currentArray, currentIndex, currentOpts) {
				return '';
			}
		});
		
		$("a[rel=hoteltumb]").fancybox({
			'transitionIn'		: 'none',
			'transitionOut'		: 'none',
			'titlePosition' 	: 'over',
			'cyclic'			: 'false',
			'titleFormat'		: function(title, currentArray, currentIndex, currentOpts) {
				return '';
			}
		});
		

		$("a.iframe").fancybox({
			'type'				: 'iframe',
			'width'				: '80%',
			'height'				: '80%',
			'transitionIn'		: 'none',
			'transitionOut'		: 'none',
			'titlePosition' 	: 'over',
			'cyclic'			: 'false',
			'titleFormat'		: function(title, currentArray, currentIndex, currentOpts) {
				return '';
			}
		});
	}

	function goToOnline(data)
	{
		sendPostForm('/booking/search/', data);
	}
	
$(function(){
	initImageTooltip();
	initFancy();
	
	// form autosave
	//$('form').sisyphus();
	
	$('#unknownDateCheckbox').click(function() {
		if(this.checked) 
		{ 
			$('#start, #end').val(''); 
		}
	});
	
	$('#start, #end').click(function() {
		$('#unknownDateCheckbox').attr('checked', false);
	});
	
	$('.tooltip').tooltip({delay: 0, extraClass: 'stylized'});
	
	$('.tipTip').tipTip({defaultPosition: 'bottom', maxWidth: '400px', delay: 0, enter: function() {
			$('#tiptip_content').css('font-size', '12pt').css('padding', '20px');
		}
	});
	
	$('sup.ratingTip').tipTip({keepAlive: true, defaultPosition: 'top', maxWidth: '400px', delay: 0, enter: function() {
		$('#tiptip_content').css('font-size', '12pt').css('padding', '20px');
	}, content: 'Рейтинг основан на оценках клиентов, которые проживали в данном отеле. Чем выше рейтинг у интересующего вас отеля, тем больше положительных отзывов было оставлено клиентами. Вы можете <a href="/files/anketa/anketa.htm" target="_blank">посмотреть образец анкеты</a>, которую получают клиенты после проживания в отеле.'});
	
	$('#groupPeopleCount').keyup(function() {
		var discount = 0;
		var val = parseInt($(this).val());
		for(var i in groupDiscounts)
		{
			if (val >= i) discount = groupDiscounts[i];
		}
		if (discount > 0) $('#groupDiscount').html('&raquo; Скидка '+discount+'% &laquo;');
		else $('#groupDiscount').html('');
	});
	$('#groupPeopleCount').keyup();
	
	
	$('#hideMap').click(switchTopMap);
	$(".datepicker").datepicker({ dateFormat: 'dd-mm-yy', dayNames: dayNames, dayNamesMin: dayNamesMin, numberOfMonths: 1,
		    		dayNamesShort: dayNamesMin, monthNames: monthNames, monthNamesShort: monthNamesShort, 
		    				firstDay: 1, minDate: new Date(),
		    				onSelect: function(dateText, inst)
		    				{ 
									var start = $('#start').datepicker( "getDate");
									var end = $('#end').datepicker( "getDate");
									if (start >= end)
									{
										start.setTime(start.getTime() + 86400000);
										$('#end').datepicker("setDate", start);					
		}}} );
	
	
	$(".groupDatepicker").datepicker({ dateFormat: 'dd-mm-yy', dayNames: dayNames, dayNamesMin: dayNamesMin, numberOfMonths: 1,
		dayNamesShort: dayNamesMin, monthNames: monthNames, monthNamesShort: monthNamesShort, 
				firstDay: 1, minDate: new Date(),
				onSelect: function(dateText, inst)
				{ 
						var start = $('#groupStart').datepicker( "getDate");
						var end = $('#groupEnd').datepicker( "getDate");
						if (start >= end)
						{
							start.setTime(start.getTime() + 86400000);
							$('#groupEnd').datepicker("setDate", start);					
	}}} );
	
	

	$('#showGroupBookingForm').click(function() { 
		$('#groupBookingForm').show();
		$('#bookingForm').hide();
		$.scrollTo('#groupBookingFormAnchor', 300); 
	});
	$('#hideGroupBookingForm').click(function() { 
		$('#groupBookingForm').hide(); $.scrollTo('#bookingFormAnchor', 300); 
		$('#bookingForm').show();
	});
	
	/*
	$('span.peopleSmallButton').click(function(){
		$('span.peoples').append('<em class="smallman" onclick="removePeople(this)"></em>');
	});
	*/
	
	$('#addRoom').click(function()
		{
			addSelectPeople();
			//updatePeopleCount();
		});
	
	

	$('div#subscribe button').click(function() {
		$.post('/ajax/subscribe/', {email: $('div#subscribe input').val()}, function (data) {
			if (data.result) alert(data.message);
			else alert(data.error);
		}, 'json');
	});
		
	
	
	// AUTOSUGGEST
	$.widget( "custom.catcomplete", $.ui.autocomplete, {
		_renderMenu: function( ul, items ) {
			var self = this,
				currentCategory = "";
			$.each( items, function( index, item ) {
				if ( item.category != currentCategory ) {
					ul.append( "<li class='ui-autocomplete-category'>" + item.category + "</li>" );
					currentCategory = item.category;
				}
				self._renderItem( ul, item );
			});
		}
	});
	
	$('#directionInput').catcomplete({
	    source: '/ajax/suggest/',
	    minLength: 3,
	    select: function(event, ui) {
	    	$('input[name=directionType]').val(ui.item.type);
	    	if ($('#start').val() == '') $('#start').focus();

	    	if (ui.item.type == 'hotel')
	    	{
		    	$('#bookingForm').attr('action', '/'+ui.item.url);
	    	}
	    	else if(ui.item.type == 'city')
	    	{
	    		$('#bookingForm').attr('action', '/booking/search/');
	    	}
	    }
	});

	
	$('#directionInput').keyup(function() {
			$('#bookingForm').attr('action', '/booking/go/');
		});
	
	$("#directionInput").focus(function(){

		if($(this).hasClass('empty'))
		{
			$(this).val('');
			$(this).removeClass('empty');
		}
		
	    // Select input field contents
	    this.select();
	});

	$("#directionInput").focusout(function() {
			if ( $(this).val() == '' )
			{
				$(this).addClass('empty');
				$(this).val('Город или название отеля');
			}
		});

	var bookingFormTipAttached = false;
	$('#bookingForm').submit(function() {
			if ( ($('#start').val() == '' || $('#end').val() == '') && !$('#unknownDateCheckbox').attr('checked'))
			{
				if (!bookingFormTipAttached)
				{
					$('#bookingForm').tipTip({activation: 'focus', defaultPosition: 'right', maxWidth: '400px', delay: 0, enter: function() {
						$('#tiptip_content').css('font-size', '12pt').css('padding', '20px');
						$('#tiptip_holder').css('top', -45);
					},
					content: 'Укажите интересующие вас даты, чтобы посмотреть актуальные цены и наличие номеров'
					});
					
					// Скрываем TipTip при клике в произвольном месте
					$(document).bind("click", 
					function()
					{
						$('#bookingForm').blur().$(document).unbind("click");

					});
				
					bookingFormTipAttached = true;
				}
				$('#bookingForm').focus();
				$('#bookingForm').click(function() {$('#bookingForm').blur()});
				return false;
			}
			
			if ($('#directionInput').hasClass('empty')) $('#directionInput').val('');
			$('<input type="hidden" name="formAction" value="" />').val($(this).attr('action')).appendTo($(this));
			
			if($('input#start').val() != '' && $('input#end').val() != '')
			{
				$('<input type="hidden" name="do_show_free_rooms" value="" />').val(1).appendTo($(this));
			}
			
			$.get('/ajax/logSearch/', {search: $('#directionInput').val()});
				
		});
	
});

function addSelectPeople()
{
	var count = $('select.sf_peoples').length;
	var html = '<div id="sf_room_select' + (count + 1) + '">Номер ' + (count + 1)+ ': ';
	html += '<select name="peoples[]" class="sf_peoples">';
	html += '<option value="1">1 человек</option>';
	html += '<option value="2">2 человека</option>';
	html += '<option value="3">3 человека</option>';
	html += '</select><div class="removeRoom"  onclick="$(this).parent().remove()" alt="">&nbsp;</div></div>';
	$('#sf_roomContainer').append(html);
}

function removeSelectPeople()
{
	var x = $('select.sf_peoples');
	var count = x.length;
	$('#sf_room_select'+(count)).remove();
}

function addDrawedPeople()
{
	$('span.peoples').append('<em class="sf_man man" onclick="removeDrawedPeople(this)"></em>');
	updatePeopleSelectCount();
}

function removeDrawedPeople()
{
	var x = $('div#sf_peopleContainer > span.peoples > em.sf_man.man');
	if (x.length > 1)
	{
		$(x[x.length - 1]).remove();
		updatePeopleSelectCount();
	}
}

function updatePeopleCount()
{
	var selectPeopleCount = 0;
	$('select.sf_peoples').each(function(item, obj){
		selectPeopleCount += parseInt($(obj).val());
	});
	var drawedPeople = $('div#sf_peopleContainer > span.peoples > em.sf_man.man').length;
	
	if (drawedPeople > selectPeopleCount)
		while (drawedPeople > selectPeopleCount)	
		{
			removeDrawedPeople();
			drawedPeople--;
		}
	
	if (drawedPeople < selectPeopleCount)
		while (drawedPeople < selectPeopleCount)	
		{
			addDrawedPeople();
			drawedPeople++;
		}		
}

function updatePeopleSelectCount()
{
	var x = $('select.sf_peoples');
	var selectPeopleCount = 0;
	x.each(function(item, obj){
		selectPeopleCount += parseInt($(obj).val());
	});
	var count = x.length;
	
	// отрисованные человечки
	var drawedPeople = $('div#sf_peopleContainer > span.peoples > em.sf_man.man').length;
	
	if (drawedPeople > selectPeopleCount)
	{
		var lastVal = parseInt($(x[count-1]).val());
		if (lastVal == 3)
		{
			addSelectPeople();	
		}
		else
		{
			$(x[count-1]).val(lastVal + 1);			
		}
	}
	
	if (drawedPeople < selectPeopleCount)
	{
		var lastVal = parseInt($(x[count-1]).val());
		if (lastVal == 1)
		{
			removeSelectPeople();	
		}
		else
		{
			$(x[count-1]).val(lastVal - 1);			
		}		
	}
}
	


function switchTopMap()
{
	if ($('#topMap').height() == 5)
	{
		$('#topMap').animate({
			height: 400
		}, 700, function(){
			if ( $('#mapIframe').attr('ref') != 'OK') {
				$('#mapIframe').attr('src', $('#mapIframe').attr('ref') );
				$('#mapIframe').attr('ref', 'OK')
			}
		});
		$('#hideMap').html('Скрыть карту &uarr;');
	}
	else
	{
		$('#topMap').animate({
			height: 5
		}, 700);
		$('#hideMap').html('Показать карту &darr;');
	}
}


function removeLatestHotel(pageID)
{
	$.ajax({url:'/ajax/removeLatestHotel/'+pageID});
	$('#latestHotel'+pageID).remove();
}

function removeAllLatestHotel()
{
	$.ajax({url:'/ajax/removeAllLatestHotel/'});
	$('div#latestHotels').hide(400);
}

function sendPostForm(action, object, target)
{
	if (target == undefined || target == null) target = '_self';
	var a = $('<form action="'+action+'" method="get" target="'+target+'"></form>');
	
	for (var i in object)
	{
		if (typeof object[i] == 'object') appendObject(a, i, object[i]);
		else a.append($('<input type="hidden" name="'+i+'" value="'+object[i]+'"/>'));
	}
	
	$('body').append(a);
	a.submit();
}


function appendObject(form, name, object)
{
	for (var i in object)
	{
		if (typeof object[i] == 'object') appendObject(form, name+'['+i+']', object[i]);
		form.append($('<input type="hidden" name="'+name+'['+i+']" value="'+object[i]+'"/>'));
	}
}

function checkGroupBookingForm()
{
	if ($('#groupPeopleCount').val() == '')
	{
		alert('Не заполнено поле "Количество человек"');
		return false;
	}
	
	if ($('#groupClientPhone').val() == '')
	{
		alert('Не заполнено поле "Телефон"');
		return false;
	}
	
	if ($('#groupClientEmail').val() == '')
	{
		alert('Не заполнено поле "E-mail"');
		return false;
	}

	return true;
}
