var monthes = new Array();
monthes['01'] = 'января';
monthes['02'] = 'февраля';
monthes['03'] = 'марта';
monthes['04'] = 'апреля';
monthes['05'] = 'мая';
monthes['06'] = 'июня';
monthes['07'] = 'июля';
monthes['08'] = 'августа';
monthes['09'] = 'сентября';
monthes['10'] = 'октября';
monthes['11'] = 'ноября';
monthes['12'] = 'декабря';

var dow = new Array();
dow[0] = 'воскресенье';
dow[1] = 'понедельник';
dow[2] = 'вторник';
dow[3] = 'среда';
dow[4] = 'четверг';
dow[5] = 'пятница';
dow[6] = 'суббота';

var loadingImg = '<img class="loading" src="/s/pic/loading.gif" height="16" width="16" alt="Подождите...">';

$(document).ready( function() {
	// бронирование гостиниц
	$booking = $('#booking');
	if ( $booking.length > 0 ) {
		var dates = $('#from, #to').datepicker({
			buttonImage: '/s/pic/manage/calendar.gif',
			showOtherMonths : true,
			selectOtherMonths: true,
			showOn: 'both',
			buttonImageOnly: true,
			defaultDate: "+1w",
			changeMonth: true,
			numberOfMonths: 3,
			onSelect: function(selectedDate) {
				var option = this.id == "from" ? "minDate" : "maxDate";
				var instance = $(this).data("datepicker");
				var date = $.datepicker.parseDate(instance.settings.dateFormat || $.datepicker._defaults.dateFormat, selectedDate, instance.settings);
				dates.not(this).datepicker("option", option, date);
			}
		});
	}
	
	// настройки
	$(document).bind('keyup', function(e) {
		if ( ( e.target.nodeName == 'INPUT' ) || ( e.target.nodeName == 'TEXTAREA' ) )
			return;

		$ga = $('#global-admin');
		if ( e.keyCode == 89 && $ga.length > 0 ) {
			$.fancybox.showActivity();

			url = window.location.href;
			if ( window.location.hash.length > 0 )
				url = url.split('#')[0];

			if ( window.location.href.indexOf('?') != -1 )
				url = url.split('?')[0];

			$.getJSON( url + '?oh-act=settings', function( data ) {
				$.fancybox('<h2>Настройки</h2>' + data.content );
			});
		}
	});

	// плавные прокрутки
	enableSmoothScroll();

	// FB для маленьких картинок в контенте
	extendPictures()

	// фотогалереи
	$("a.galleryImage").fancybox({
		titlePosition : 'over'
	});

	// красивые псевдо-wysiwyg текстэрии в формах
	var $wysiwyg = $('textarea.wysiwyg');
	if ( $wysiwyg.length > 0 ) {
		$wysiwyg.each( function() {
			extendWysiwygElement( $(this) );
		});
	}

	$('textarea').autogrow();

	$('div.showHiddenGuide a').click( function(){
		$(this).hide();
		$('div.userGuide').removeClass('hidden')
	});

	// карта на главной странице allcafe
	$YMainMapID = $('#YMainMapID');
	if ( $YMainMapID.length > 0 ) {
		var map = new YMaps.Map( $YMainMapID[0] );
		var geodomain = window.location.href.split('.').pop();
		
		var cities = new Array();
		cities['spb'] = { 'name' : 'Санкт-Петербург' , 'longitude' : 30.313497, 'latitude' : 59.938532 };
		cities['msk'] = {'name' : 'Москва' , 'longitude' : 37.609218, 'latitude' : 55.753559 };
		cities['izhevsk'] = {'name' : 'Ижевск', 'longitude' : 53.174075, 'latitude' : 56.856702 };
		cities['kazan'] = {'name' : 'Казань' , 'longitude' : 49.122854, 'latitude' : 55.786764 };
		cities['krasnoyarsk'] = {'name' : 'Красноярск' , 'longitude' : 92.870413, 'latitude' : 56.008712 };
		cities['pskov'] = {'name' : 'Псков' , 'longitude' : 28.332828, 'latitude' : 57.819269 };
		cities['nnov'] = {'name' : 'Нижний Новгород' , 'longitude' : 44.001891, 'latitude' : 56.324461 };
		cities['vnov'] = {'name' : 'Великий Новгород' , 'longitude' : 31.270337, 'latitude' : 58.522711 };
		cities['rnd'] = {'name' : 'Ростов-на-Дону' , 'longitude' : 39.744918, 'latitude' : 47.227164 };
		cities['sochi'] = {'name' : 'Сочи' , 'longitude' : 39.722272, 'latitude' : 43.582795 };
		cities['astrakhan'] = {'name' : 'Астрахань' , 'longitude' : 48.03034, 'latitude' : 46.349636 };
		cities['perm'] = {'name' : 'Пермь' , 'longitude' : 56.241077, 'latitude' : 58.00849 };
		cities['kostroma'] = {'name' : 'Кострома' , 'longitude' : 40.927119, 'latitude' : 57.767279 };
		cities['krasnodar'] = {'name' : 'Краснодар' , 'longitude' : 38.976032, 'latitude' : 45.034942 };
		cities['ufa'] = {'name' : 'Уфа' , 'longitude' : 55.983162, 'latitude' : 54.738437 };
		cities['novosibirsk'] = {'name' : 'Новосибирск' , 'longitude' : 82.919388, 'latitude' : 55.029838 };
		cities['omsk'] = {'name' : 'Омск' , 'longitude' : 73.365364, 'latitude' : 54.990302 };
		cities['vlad'] = {'name' : 'Владивосток' , 'longitude' : 131.928478, 'latitude' : 43.134091 };
		cities['tomsk'] = {'name' : 'Томск' , 'longitude' : 84.962543, 'latitude' : 56.463988 };

		prefix = $('#select-city').children('option:selected').val();
		
		about = cities[prefix]['name'];
		latitude = cities[prefix]['latitude'];
		longitude = cities[prefix]['longitude'];
		delete cities[prefix];

		map.setCenter( new YMaps.GeoPoint( 79.356466, 57.089074 ), map.coordSystem.getMaxZoom() );
		map.setType( YMaps.MapType.MAP );

		var gcb = new YMaps.GeoCollectionBounds();

		// Задает опции метки и отображает метку на карте.
		var placemark = new YMaps.Placemark( new YMaps.GeoPoint(longitude, latitude), {
			hintOptions: {
				maxWidth: 100,
				showTimeout: 200,
				offset: new YMaps.Point(5, 5)
			}, balloonOptions: {
				hasCloseButton: true,
				mapAutoPan: 0
			}
		});

		gcb.add( placemark.getGeoPoint() );

		placemark.setBalloonContent( 'Ваш город: <b>' + about + '</b>' );
		map.addOverlay(placemark);
		placemark.openBalloon();

		// Элементы карты
		map.addControl( new YMaps.TypeControl() );
		map.addControl( new YMaps.ToolBar() );
		map.addControl( new YMaps.Zoom() );

		// Выводим метки для всех городов
		for ( city in cities ) {
			var placemark = new YMaps.Placemark( new YMaps.GeoPoint( cities[ city ]['longitude'], cities[ city ]['latitude'] ), {
				style: 'default#buildingsIcon',
				draggable: 0,
				hintOptions: {
					maxWidth: 100,
					showTimeout: 200,
					offset: new YMaps.Point(5, 5)
				}, balloonOptions: {
					hasCloseButton: true,
					mapAutoPan: 1
				}
			});

			placemark.setBalloonContent( '<a href="http://' + city + '.allcafe.' + geodomain + '">' + cities[ city ]['name'] + '</a>' );
			map.addOverlay( placemark );

			gcb.add( placemark.getGeoPoint() );
		}

		// показываем все метки на карте (подгоняем масштаб)
		map.setBounds( gcb );
	}

	var guide = $('div.main-subblock').html();
	var boris = '';
	var opens = '';

	$('div.title-middle a, div.title-left a, div.title-right a').click( function(){
		tab = $(this).attr('class');
		
		city = $('#select-city').val();
		host = window.location.hostname;
		domain = host.substring( host.lastIndexOf(".") );

		$('div.main-subblock').html(loadingImg);
			
		$('div.main-3cols').removeClass('orange-bg');
		$(this).parent().addClass('orange-bg');

		if ( tab == 'opens' ) {
			if ( opens == '') {
				$.getJSON( 'http://' + city + '.allcafe' + domain + '/news/opennews?callback=?', {'page' : 'opens-on-main'}, function(data) {
					$('div.main-subblock').html(data.content);
					opens = data.content;
				});
			} else {
				$('div.main-subblock').html(opens);
			}
		} else if ( tab == 'boris') {
			if ( boris == '') {
				$.getJSON( 'http://' + city + '.allcafe' + domain + '/news/boris?callback=?', {'page' : 'boris-on-main'}, function(data) {
					$('div.main-subblock').html(data.content);
					boris = data.content;
				});
			} else {
				$('div.main-subblock').html(boris);
			}
		} else if ( tab == 'main-guides' ) {
			if ( guide == '') {
				$.getJSON( 'http://' + city + '.allcafe' + domain + '/restaurants/guide?callback=?', function(data) {
					$('div.main-subblock').html(data.content);
					guide = data.content;
				});
			} else {
				$('div.main-subblock').html(guide);
			}
		}

		return false;
	});

	// datepicker
	$('input.pickdate').datepicker({
		buttonImage: '/s/pic/manage/calendar.gif',
		showOtherMonths : true,
		selectOtherMonths: true,
		showOn: 'both',
		buttonImageOnly: true
	});

	// всплывающее fancybox окно при нажатии на ссылку авторизации
	$('a.authorize').click( function() {
		$.fancybox.showActivity();

		$link = $(this);
		$.getJSON( $link.attr('href') + '?callback=?', function(data) {
			var $content = $(data.content);
			$content.find('input:submit').addClass('disabled').attr('disabled', 'disabled');
			$content.find('input:text').addClass('checkLogin');
			$content.find('input:password').addClass('checkPassword');
			$.fancybox('<h2>Авторизация</h2>' + data.content );
			$('#login_form_ajax').html( $content.html() );
			$('#login_form_ajax input.checkLogin, #login_form_ajax input.checkPassword').keyup( function() {
				buttonAvailable = true;

				if( $('#login_form_ajax input.checkLogin').val().length == 0 )
					buttonAvailable = false;
				if( $('#login_form_ajax input.checkPassword').val().length == 0 )
					buttonAvailable = false;

				if ( buttonAvailable ) {
					$('#login_form_ajax input.submit').removeAttr('disabled').removeClass('disabled');
					return;
				}

				$('#login_form_ajax input.submit').attr('disabled', 'disabled').addClass('disabled');
			});
		});

		return false;
	});

	// всплывающее fancybox окно при отправке письма
	$('a.send-mail').click( function() {
		$.fancybox.showActivity();

		$link = $(this);
		$.getJSON( $link.attr('href'), function(data) {
			$.fancybox( data.content );
		});

		return false;
	});

	// выпадающее меню городов
	var selectedCityName = $('#select-city option:selected').text()
	$('#select-city, #subm-icon, #your-city').addClass('hidden');
	$('#city-select')
		.append( '<span id="town">' + selectedCityName + '</span>' )
		.append( '<a id="this-town" href="javascript:;">другой</a>' )

	$('#this-town').click( function() {
		$dropDownMenu = $('ul.drop-down');
		$selectCity = $('#div-select-city');

		if ( $dropDownMenu.length == 0 ) {
			regions = '';
			host = window.location.hostname;
			domain = host.substring( host.lastIndexOf(".") );

			$('#select-city option').each( function() {
				if ( $(this).text() != selectedCityName ) {
					regions += '<li><a href="http://' + $(this).val() + '.allcafe' + domain + '">' + $(this).text() + '</a></li>';
				}
			});

			$selectCity.append( '<ul class="drop-down">' + regions + '</ul>' );
			bindOutsideClick( $selectCity.children('ul') );
		} else if ( $dropDownMenu.is(":hidden") ) {
			$dropDownMenu.removeClass('hidden');
		} else {
			$dropDownMenu.addClass('hidden');
		}
		
		return false;
	});
	
	/* подсветка значков */
	$('a.manage').live('mouseover', function() {
		img = $(this).css('backgroundImage');
		$(this).css('backgroundImage', img.replace('out', 'over') );
	}).live('mouseout', function() {
		img = $(this).css('backgroundImage');
		$(this).css('backgroundImage', img.replace('over', 'out') );
	});

	$('img.manage').live('mouseover', function() {
		img = $(this).attr('src');
		$(this).attr('src', img.replace('out', 'over') );
	}).live('mouseout', function() {
		img = $(this).attr('src');
		$(this).attr('src', img.replace('over', 'out') );
	});

	$('table.data tr:even').addClass('odd');

	// раскрытие блоков информации
	$('a.more-info').click( function() {
		var $anchor = $(this);
		var $info = $( '#' + $anchor.attr('rel') );

		if ( $info.is(':hidden') ) {
			$info.slideDown('normal', function() {
				$anchor.attr('title', 'скрыть');
			});
		} else {
			$info.slideUp('normal', function() {
				$anchor.attr('title', 'показать');
			});
		}
	});

	// фоловинг человека
	$('#follow-btn').click( function() {
		$btn = $(this);

		if ( $btn.children('img').hasClass('inactive') ) {
			$('#follow-info').fadeOut('fast', function() {
				$('#follow-info').remove();
				$btn.children('img').removeClass('inactive');
			});
		} else {
			$comSep = $('#com-separator');
			$headInfoTbl = $(this).closest('table.head-info');

			newHeight = $headInfoTbl.outerHeight() + 2;
			$('#com-separator').after('<div class="attention" id="follow-info" style="top: ' + newHeight + 'px;">' + loadingImg + '</div>');

			var $followInfo = $('#follow-info');
			$followInfo.css({
				'borderRadius': '0 3px 3px 3px',
				'MozBorderRadius': '0 3px 3px 3px',
				'WebkitBorderRadius': '0 3px 3px 3px'
			});

			$.getJSON('/community/users/' + $headInfoTbl.attr('id'), {act: 'follow'}, function(data) {
				$followInfo.html(data.content);

				followInfoHeight = $followInfo.outerHeight() + newHeight;
				parentHeight = $('#centr-content').outerHeight();
				if ( followInfoHeight > parentHeight )
					$('#centr-content').height( followInfoHeight );

				$btn.children('img').addClass('inactive');

				// навешиваем действие по клику снаружи
				$(document).bind('click', bindOutsideFI );

				// навешиваем действие по нажатию кнопки
				$('#save-follow').click( function() {
					$form = $followInfo.find('form');
					$followInfo.html( loadingImg );

					$.post('/community/users/' + $headInfoTbl.attr('id') + '?act=follow', $form.serialize(), function(data) {
						$followInfo.fadeOut('fast', function() {
							$btn.children('img').removeClass('inactive');
							$followInfo.remove();
						});
					}, 'json');
				});
			});

			
		}

		return false;
	});

	// фоловинг ресторана
	$('#follow-rst-btn').click( function() {
		$btn = $(this);

		if ( $btn.children('img').hasClass('inactive') ) {
			$('#follow-info').fadeOut('fast', function() {
				$('#follow-info').remove();
				$btn.children('img').removeClass('inactive');
			});
		} else {
			$comSep = $('#com-separator');
			$headInfoDiv = $('#common-entity-info');

			newHeight = $headInfoDiv.outerHeight()-5;
			$('#com-separator').after('<div class="attention" id="follow-info" style="top: ' + newHeight + 'px;">' + loadingImg + '</div>');

			var $followInfo = $('#follow-info');
			$followInfo.css({
				'borderRadius': '0 3px 3px 3px',
				'MozBorderRadius': '0 3px 3px 3px',
				'WebkitBorderRadius': '0 3px 3px 3px'
			});
			$link = window.location.href.split('/')[3];

			$.getJSON('/'+$link+'/id-' + $headInfoDiv.attr('rel'), {act: 'follow'}, function(data) {
				$followInfo.html(data.content);

				followInfoHeight = $followInfo.outerHeight() + newHeight;
				parentHeight = $('#centr-content').outerHeight();
				if ( followInfoHeight > parentHeight )
					$('#centr-content').height( followInfoHeight );

				$btn.children('img').addClass('inactive');

				// навешиваем действие по клику снаружи
				$(document).bind('click', bindOutsideFI );

				// навешиваем действие по нажатию кнопки
				$('#save-follow').click( function() {
					$form = $followInfo.find('form');
					$followInfo.html( loadingImg );
					
					$.post('/'+$link+'/id-' + $headInfoDiv.attr('rel') + '?act=follow', $form.serialize(), function(data) {
						$followInfo.fadeOut('fast', function() {
							$btn.children('img').removeClass('inactive');
							$followInfo.remove();
						});
					}, 'json');
				});
			});

		}

		return false;
	});

	// подтверждение удаления
	$('a.del').live('click', function() {
		if ( !$(this).attr('rel') )
			return confirm('Будет удалено без возможности восстановления. Вы подтверждаете данную операцию ?');
		else
			return confirm( $(this).attr('rel') );
	});

	// скрытие/показ левых/правых блоков информации
	$('img.tumblr').click( function() {
		$tumblr = $(this);
		imgID = $tumblr.attr('id');
		$blockLayer = $('#' + imgID.substring(0, imgID.length - 8 ) );
		$topH2 = $tumblr.parent();

		if ( $blockLayer.is(':hidden') ) {
			$blockLayer.slideDown('fast', function() {
				$( '#' + imgID).attr('title', 'свернуть');
				$topH2.removeClass('off');
				$tumblr.removeClass('inactive');

				$.post( '?oh-act=data&act=tumblr', {
					id: imgID.substring(0, imgID.length - 8 ),
					status: 'on'
				});
			});
		} else {
			$blockLayer.slideUp('fast', function() {
				$( '#' + imgID).attr('title', 'развернуть');
				$topH2.addClass('off');
				$tumblr.addClass('inactive');

				$.post( '?oh-act=data&act=tumblr', {
					id: imgID.substring(0, imgID.length - 8 ),
					status: 'off'
				});
			});
		}
	});

	/* скрытие-раскрытие полей в формах через fancybox */
	$('p.form-field.fancy-hide').each( function() {
		processPara( $(this) );
	});

	$('a.fancy-choose').live('click', function() {
		$paraField = $(this).closest('p.form-field');

		$labels = $paraField.find('label');
		$checkedBoxes = $paraField.find('input:checkbox:checked');
		h2 = $paraField.prev().children('b').html();
		blockName = $paraField.children('div.hidden').attr('id').split('-')[1];

		var selectedItems = new Array();
		$checkedBoxes.each( function() {
			selectedItems.push( $(this).attr('id') );
		});

		/* в js нет in_array, потому извращаемся по полной :( */
		var selectedItemsString = '';
		if ( selectedItems.length > 0 )
			selectedItemsString = '#' + selectedItems.join('#') + '#';

		inputs = new Array();
		$labels.each( function() {
			if ( selectedItemsString.indexOf( '#' + $(this).attr('for') + '#' ) != -1 ) {
				selected = ' pushed';
				title = 'Нажмите, чтобы снять выделение';
			} else {
				selected = '';
				title = 'Нажмите, чтобы выделить';
			}

			inputs.push( '<a rel="' + $(this).attr('for') + '" title="' + title + '" href="javascript:;" class="choice' + selected + '"><span>' + $(this).text() + '</span></a>' );
		});

		$.fancybox(
			'<h2>' + h2 + '</h2><div id="elements" rel="' + blockName + '">' + inputs.join('') + '</div><input type="button" id="save-choice" value="Сохранить"> или <input type="button" id="reset-choice" value="Очистить все">', {
				'autoDimensions' : false,
				'width' : 500,
				'height' : 382,
				'transitionIn' : 'none',
				'transitionOut' : 'none'
			}
		);
	});

	/* закрытия popup-окна по клику на кнопке */
	$('#save-choice').live('click', function() {
		hiddenDivName = $('#elements').attr('rel');
		processPara( $('#block-' + hiddenDivName).parent() );

		$.fancybox.close();
	});

	/* deselect */
	$('#reset-choice').live('click', function() {
		$('#elements, #period-elements').find('a.pushed').click();
	});

	/* выделение элеменов-ссылок */
	$('a.choice').live('click', function() {
		$anchor = $(this);
		type = $('#elements').attr('rel');

		if ( $anchor.hasClass('pushed') ) {
			$anchor.removeClass('pushed');
			$anchor.attr('title', 'Нажмите, чтобы выделить');

			$('input[id="' + $anchor.attr('rel') + '"]').removeAttr('checked');
		} else {
			$anchor.addClass('pushed');
			$anchor.attr('title', 'Нажмите, чтобы снять выделение');

			$('input[id="' + $anchor.attr('rel') + '"]').attr('checked', 'checked');
		}
	});

	/* drag'n'drop-сортировка внутренних страниц */
	var innerPagesHtml = '';
	var $sortImg  = $('img.manage.sort');
	var $innerPages = $('#inner-pages');

	if ( $innerPages.length == 0 ) {
		$sortImg.remove();
	} else {
		$sortImg.click( function() {
			if ( innerPagesHtml.length ) {
				$('#sort-cancel').click();
				return;
			}

			$sortImg.addClass('inactive');
			innerPagesHtml = $('#inner-pages').html();

			$innerPages.html('<span class="gray">Подождите...</span>');
			var waitingID = window.setInterval( function() {
				$innerPages.children('span.gray').append('.')
			}, 1000 );

			/* получаем список внутренних страниц включая те, что не показываются */
			$.getJSON( '?oh-act=inner', {pageID: $('#pid').text()}, function( data ) {
				window.clearInterval( waitingID )

				$innerPages.html( data.content );
				$innerPages.append('<input class="btn submit" id="sort-save" type="button" value="Сохранить"> или <input class="btn submit" id="sort-cancel" type="button" value="Отменить">');

				$list = $innerPages.children('ul');
				$list.sortable({placeholder: 'placeholder'});
				$list.disableSelection();
			});
		});
		
		$('#sort-cancel').live('click', function() {
			$innerPages.html( innerPagesHtml );
			innerPagesHtml = '';
			$sortImg.removeClass('inactive');
		});

		$('#sort-save').live('click', function() {
			var sort = new Array();
			var $listItems = $innerPages.find('li');

			$.each( $listItems, function() {
				sort.push( $(this).attr('rel') );
			});

			$innerPages.html('<span class="gray">Подождите...</span>');
			window.setInterval( function() {
				$('#inner-pages span.gray').append('.')
			}, 1000 );

			$.post('?oh-act=inner', {sort: sort}, function() {
				window.location.reload();
			});
		});
	}

	/* Всплывающее fancybox окно при нажатии на ссылку авторизации  */
	$('a.error-report').click( function() {
		$.fancybox.showActivity();

		$link = $(this);
		$.getJSON( $link.attr('href') + '&callback=?', { url: window.location.href }, function(data) {
			$.fancybox('<h2>Ошибка на странице</h2>' + data.content, { 'width' : 500, 'height' : 382 } );
		});

		return false;
	});

	// Лог
	$mngCheckboxes = $('#management').find('input:checkbox');
	$mngCheckboxes.click( function() {
		$('#tweets').html( loadingImg );

		var $form = $(this).closest('form');
		var postData = $form.serialize();
		$mngCheckboxes.attr('disabled', 'disabled');

		$.post( window.location.href, postData, function( data ) {
			$('#tweets').replaceWith( data.content );

			$mngCheckboxes.removeAttr('disabled');
		}, 'json');
	});

	$('a.show-all-repr').click(function(){
			$(this).next().fadeIn();
	});

	// ЗАМЕТКА К СТРАНИЦЕ
	var note = '';
	$('#notes').click(function(){
		if ( $('#edit-note').length == 0 ) {
			var $div = $('<div id="edit-note" class="alignLeft">').css('display', 'none');
			var $textarea = $('<textarea id="note" cols="10" rows="5">');
			var $submit = $('<input type="button" value="Сохранить" id="save-note">').addClass('btn submit');

			$div.append( $textarea ).append( $submit );
			$('#menu').append( $div ).children().fadeIn('fast');

			$('#save-note').click( function() {
				host = window.location.hostname
				domain = host.substring( host.lastIndexOf(".") );

				$('#notes').html( loadingImg );

				getData = {
					text : $('#note').val(),
					url : window.location.href
				};

				$.getJSON( 'http://allcafe' + domain + '/community/note?callback=?', getData, function( data ) {
					$('#edit-note').fadeOut('fast', function() {
						$('#notes').html( $('#note').val() );
						note = $('#note').val();
					});
				});
			});

			note = $('#notes').html();
			$('#note').val( note );
			$(this).html('Ваша заметка к этой странице');
		} else {
			if ( $('#edit-note').is(':hidden') ) {
				$('#edit-note').fadeIn('fast');

				note = $('#notes').html();
				$('#note').val( note );
				$(this).html('Ваша заметка к этой странице:');
			} else {
				$('#edit-note').fadeOut('fast');
				$('#notes').html( note );
			}
		}
	});

	// дебаг-информация
	$('#debug-footer a').click( function() {
		$h2 = $(this).parent();
		$info = $('#debug-info');

		if ( $info.length > 0 ) {
			$info.remove();
		} else {
			$h2.after('<div id="debug-info">' + loadingImg + '</div>');
			$.getJSON('/?oh-act=data', { 'act': 'debug' }, function( data ) {
				$('#debug-info').html( data.content );
			});
		}
	});
});

/**
 * Обработка всех элементов внутри параграфа
 * @param jQuery $para парагра с элементами
 * @return void
 */
function processPara( $para ) {
	$checkbox = $para.find('input:checkbox');
	$hiddenBlock = $para.children('div.hidden');

	var block = '';
	var selected = new Array();
	$checkbox.each( function() {
		if ( block == '' ) {
			block = $(this).attr('id').split('_').slice(0,-1);
			if ( block.length > 1 )
				block = block.join('_');
		}

		if ( $(this).attr('checked') )
			selected.push( '<a href="javascript:;" class="fancy-choose">' + $(this).parent().text() + '</a>' );
	});

	if ( selected.length == 0 ) {
		text = 'Ничего не выбрано.';
		if ( $checkbox.length > 0 )
			text += ' <a class="fancy-choose" href="javascript:;">Выбрать</a>';
	} else {
		last = selected.pop();
		if ( selected.length == 0 ) {
			text = last;
		} else if ( selected.length == 1 ) {
			text = selected[0] + ' и ' + last;
		} else {
			text = selected.join(', ') + ' и ' + last;
		}
	}

	text = '<span class="txt">' + text + '</span>';
	if ( $hiddenBlock.length == 0 ) {
		if ( block == '' )
			$para.html( text );
		else
			$para.html( text + '<div id="block-' + block + '" class="hidden">' + $para.html() + '</div>');
	} else {
		$para
			.children(':not(div.hidden)')
			.remove()
				.end()
			.prepend( text );
	}
}

function getAwesomeString( arrayInput ) {
	initialLength = arrayInput.length;

	last = arrayInput.pop();
	if ( initialLength == 1 )
		return last;

	if ( initialLength == 2 )
		return arrayInput.pop() + ' или ' + last;

	return arrayInput.join(', ') + ' или ' + last;
}

/**
 * Autocomplete для поиска ресторанов
 */
function searchRestaurantAutocomplete( $input, redirectAfterSelect ) {
	// кэш результатов поиска
	var cache = {};

	if ( !redirectAfterSelect ) {
		// ID ресторана
		name = $input.attr('name');
		if ( name.substr(-2) == '[]' )
			$input.after('<input type="hidden" name="' + name.substr(0, name.length - 2) + '_id[]" value="0">');
		else {
			if ( $input.next('input[name="' + name + '_id"]').length == 0 )
				$input.after('<input type="hidden" name="' + name + '_id" value="0">');
		}

		var $resultInput = $input.next();
	}

	$input.autocomplete({
		minLength: 2,
		html: true,
		source: function(request, response) {
			if ( request.term in cache ) {
				response( cache[ request.term ] );
				return;
			}

			$.getJSON('/restaurants/catalogue', {title: request.term, autocomplete: true}, function(data) {
				cache[ request.term ] = data.content;
				response( data.content );
			});
		}, select: function(event, ui) {
			if ( !redirectAfterSelect )
				$resultInput.val( ui.item.id );
			else
				window.location.href = '/restaurants/id-' + ui.item.id;
		}
	});
}

/**
 * Autocomplete для поиска компаний по доставке еды
 */
function searchDeliveryAutocomplete( $input, redirectAfterSelect ) {
	// кэш результатов поиска
	var cache = {};

	if ( !redirectAfterSelect ) {
		// ID компании
		name = $input.attr('name');
		if ( name.substr(-2) == '[]' )
			$input.after('<input type="hidden" name="' + name.substr(0, name.length - 2) + '_id[]" value="0">');
		else {
			if ( $input.next('input[name="' + name + '_id"]').length == 0 )
				$input.after('<input type="hidden" name="' + name + '_id" value="0">');
		}

		var $resultInput = $input.next();
	}

	$input.autocomplete({
		minLength: 2,
		html: true,
		source: function(request, response) {
			if ( request.term in cache ) {
				response( cache[ request.term ] );
				return;
			}

			$.getJSON('/restaurants/delivery', {title: request.term, autocomplete: true}, function(data) {
				cache[ request.term ] = data.content;
				response( data.content );
			});
		}, select: function(event, ui) {
			if ( !redirectAfterSelect )
				$resultInput.val( ui.item.id );
			else
				window.location.href = '/restaurants/delivery/id-' + ui.item.id;
		}
	});
}

/**
 * Autocomplete для поиска ресторанов
 */
function searchHotelsAutocomplete( $input, redirectAfterSelect ) {
	// кэш результатов поиска
	var cache = {};

	if ( !redirectAfterSelect ) {
		// ID ресторана
		name = $input.attr('name');
		if ( name.substr(-2) == '[]' )
			$input.after('<input type="hidden" name="' + name.substr(0, name.length - 2) + '_id[]" value="0">');
		else
			$input.after('<input type="hidden" name="' + name + '_id" value="0">');

		var $resultInput = $input.next();
	}

	$input.autocomplete({
		minLength: 2,
		html: true,
		source: function(request, response) {
			if ( request.term in cache ) {
				response( cache[ request.term ] );
				return;
			}

			$.getJSON('/hotels/catalogue', {title: request.term, autocomplete: true}, function(data) {
				cache[ request.term ] = data.content;
				response( data.content );
			});
		}, select: function(event, ui) {
			if ( !redirectAfterSelect )
				$resultInput.val( ui.item.id );
			else
				window.location.href = '/hotels/id-' + ui.item.id;
		}
	});
}

function bindOutsideClick( $element ) {
	var elementOffset = $element.offset();

	$(document).click( function(e) {
		if ( e.pageX >= elementOffset.left && e.pageX <= $element.width() + elementOffset.left && e.pageY >= elementOffset.top && e.pageY <= $element.height() + elementOffset.top )
			return;

		$element.remove();
	});
}

function bindOutsideFI( e ) {
	var $followInfo = $('#follow-info');
	var offset = $followInfo.offset();
	if ( $('#common-entity-info').length == 0 )
		var $btn = $('#follow-btn');
	else
		var $btn = $('#follow-rst-btn');
	
	if ( e.pageX >= offset.left && e.pageX <= $followInfo.width() + offset.left && e.pageY >= offset.top && e.pageY <= $followInfo.height() + offset.top )
		return;

	$followInfo.fadeOut('fast', function() {
		$followInfo.remove();
		$btn.children('img').removeClass('inactive');

		$(document).unbind('click', bindOutsideFI );
	});
}

function extendWysiwygElement( $wysiwygElement ) {
	$wysiwygElement.hide();

	// корректируем padding
	outerLayerWidth = $wysiwygElement.parent().width() - 8;
	$wysiwygElement.css({
		width: outerLayerWidth + 'px',
		padding: '3px'
	}).show();

	// добавляем элементы управления
	$paraField = $wysiwygElement.parent();
	wysiwygArea = '';
	wysiwygArea += '<a title="жирный" href="javascript:;"><img class="b" alt="жирный" width="24" height="24" src="/s/pic/blank.gif"></a>';
	wysiwygArea += ' <a title="курсив" href="javascript:;"><img class="i" alt="курсив" width="24" height="24" src="/s/pic/blank.gif"></a>';
	wysiwygArea += ' <a title="подчеркнутый" href="javascript:;"><img class="u" alt="подчеркнутый" width="24" height="24" src="/s/pic/blank.gif"></a>';
	wysiwygArea += ' &nbsp; ';
	wysiwygArea += '<a title="добавить фотографию" href="javascript:;"><img class="upload-photo" alt="добавить изображение" width="24" height="24" src="/s/pic/icons/24/photo.png"></a>';

	$paraField.prepend('<div class="wysi-area">' + wysiwygArea + '</div>');

	// навешиваем обработчик загрузки фотографий
	$imgUpload = $paraField.find('img.upload-photo');
	new AjaxUpload( $imgUpload, {
		action: '/?oh-act=upload&type=user-image',
		responseType: 'json',
		onSubmit: function(file, ext) {
			if (!ext || !/^(jpg|png|jpeg|gif)$/i.test(ext)) {
				alert('Вы можете загружать только изображения');
				return false;
			}

			$imgUpload.parent().after( loadingImg );
		}, onComplete: function(file, response) {
			if ( response.error.length > 0 ) {
				alert( response.error );
			} else {
				if ( document.selection ) {
					$wysiwygElement.focus();
					slc = document.selection.createRange();

					if ( slc.text )
						slc.text = '[IMG]' + response.text + '[/IMG]';
					else
						slc.text += '[IMG]' + response.text + '[/IMG]';
				} else if ( document.getSelection ) {
					mVal = $wysiwygElement.val();
					sPos = $wysiwygElement[0].selectionStart;
					ePos = $wysiwygElement[0].selectionEnd;

					sTxt = mVal.substring( 0, sPos );
					cTxt = mVal.substring( sPos, ePos );
					eTxt = mVal.substring( ePos, mVal.length );

					$wysiwygElement.val( sTxt + '[IMG]' + response.text + '[/IMG]' + eTxt );
				}

				$wysiwygElement.focus();
			}

			$imgUpload.parent().next().remove();
		}
	});

	// навешиваем обработчики
	$wysi = $paraField.find('div.wysi-area');
	$wysi.find('img.b, img.i, img.u').click( function() {
		$btn = $(this);

		if ( $btn.hasClass('b') )
			tag = 'B';
		else if ( $btn.hasClass('i') )
			tag = 'I';
		else if ( $btn.hasClass('u') )
			tag = 'U';

		if ( document.selection ) {
			$wysiwyg.focus();
			slc = document.selection.createRange();

			if ( slc.text )
				slc.text = '[' +tag+ ']' +slc.text+ '[/' +tag+ ']';
			else
				slc.text += '[' +tag+ '][/' +tag+ ']';
		} else if ( document.getSelection ) {
			mVal = $wysiwygElement.val();
			sPos = $wysiwygElement[0].selectionStart;
			ePos = $wysiwygElement[0].selectionEnd;

			sTxt = mVal.substring( 0, sPos );
			cTxt = mVal.substring( sPos, ePos );
			eTxt = mVal.substring( ePos, mVal.length );

			if ( cTxt.length >= 1 )
				$wysiwygElement.val( sTxt+ '[' +tag+ ']' +cTxt+ '[/' +tag+ ']' +eTxt );
			else
				$wysiwygElement.val( sTxt+ '[' +tag+ '][/' +tag+ ']' +eTxt );
		}

		$wysiwygElement.focus();
	});
}

function extendPictures() {
	// FB для маленьких картинок в контенте
	$('img[src$="_XS.jpeg"], img[src$="_XS.jpg"]').each( function() {
		$img = $(this);
		if ( $img.hasClass('parsed') )
			return true;

		smallPicSrc = $img.addClass('parsed').attr('src');
		bigPicSrc = smallPicSrc.replace('_XS', '_XL');

		imgHTML = $('<div>').append( $img.eq(0).clone() ).html();
		$img.replaceWith('<a class="fb" title="увеличить" href="' + bigPicSrc + '">' + imgHTML + '</a>');
	});

	$('a.fb').fancybox({
		titleShow : false
	});
}

function smoothScroll( targetName, onLoad ) {
	var $link = $( '#' + targetName );

	if ( $link.length == 0 ) {
		$link = $( 'a[name="' + targetName + '"]' );
		if ( $link.length == 0 )
			return false;
	}

	starty = !onLoad ? $(window).scrollTop() : 0;
	stopy = $link.offset().top - starty;

	if ( stopy <= 0 )
		return false;

	section = true;
	startTime = new Date().getTime();

	timer = setInterval( function() {
		var x = ( new Date().getTime() - startTime ) / 500;
		if ( x > 1 )
			x = 1;

		var y = ( -Math.cos( x*Math.PI ) / 2 ) + 0.5;
		cy = Math.round( starty + stopy*y );
		$(document).scrollTop( cy );

		if ( x == 1 ) {
		  clearInterval( timer );
		  section = false;
		  window.location.hash = '#' + targetName;
		}
	}, 15);

	return false;
}

// функция обработки и вызова плавного скролла
function enableSmoothScroll() {
	// сперва орабатываем текущую страницу
	if ( window.location.hash.length > 0 ) {
		hash = window.location.hash.substr(1);
		smoothScroll( hash, true );
	}

	// текущая страница - адрес и адрес с протоколом
	var currentPage = window.location.pathname;
	var currentPageWP = window.location.protocol + '//' + window.location.hostname + currentPage;

	$('a[href*=#]').each(function() {
		$anchor = $(this);
		href = $anchor.attr('href');

		if ( href == '#' )
			return true;
		
		if ( href.substr(0, 1) != '#' ) {
			hrefPath = href.substr(0, href.indexOf('#') );
			if ( hrefPath != currentPage && hrefPath != currentPageWP )
				return true;
		}

		// победитель всех проверок по клику вызывает плавный скролл
		var target = href.substr( href.indexOf('#') + 1 );
		$anchor.click( function() {
			return smoothScroll( target );
		});
	});
}
