$(document).ready( function() {
	// написание отзыва
	$('#publish').attr('disabled', 'disabled').addClass('disabled');
	$('input[name="gentle[]"]').click( function() { checkForm(); });
	$('#guide-form').find('input[name="author_name"]').keyup( function() { checkForm(); });
	$('#guide-form').find('input[name="author_city"]').keyup( function() { checkForm(); });
	$('#guide-form').find('input[name="author_email"]').keyup( function() { checkForm(); });
	$('#guide-form').find('input[name="visit_date"]').keyup( function() { checkForm(); });
	$('#guide-form').find('textarea[name="content"]').keyup( function() {
		checkForm();

		tareaContent = $(this).val();
		if ( tareaContent.length == 0 ) {
			$('#res-150').html('не менее 150 символов, а то что это за отзыв?');
			return;
		}

		if ( tareaContent.length >= 150 ) {
			$('#res-150').html('ура! вы преодолели планку в 150 символов!');
			return;
		}

		remain = 150 - tareaContent.length;
		$('#res-150').html('не менее 150 символов, а то что это за отзыв? (осталось ' + remain + ')');
	});
	
	// редактирование отзыва
	$('a.edit-guide').click( function() {
		var $responseLayer = $(this).closest('div.response'); // глобальный слой с отзывом
		var $contentLayer = $responseLayer.children('div.response-content'); // слой с текстом отзыва
		var $conversationLayer = $responseLayer.find('div.conversation'); // слой с 2 ссылками на комментарии
		var $img = $(this).children(); // изображение карандаша
		var $responseAddForm = $('#response-add-form'); // форма оставления отзыва

		var resetDefaults = function() {
			$img.removeClass('inactive');
			$contentLayer.html( $contentLayer.data('initial') );

			if ( $responseAddForm.length > 0 )
				$responseAddForm.fadeIn();

			return false;
		};

		if ( $img.hasClass('inactive') )
			return resetDefaults();

		$img.addClass('inactive');
		$contentLayer.data('initial', $contentLayer.html() );
		$contentLayer.html( loadingImg );
		if ( $responseAddForm.length > 0 )
			$responseAddForm.fadeOut();

		var url = $conversationLayer.children('a').attr('href');
		$.getJSON( url, function( data ) {
			$contentLayer.html( data.response );

			var $saveBtn = $contentLayer.find('input[name="save"]');
			var $resetBtn = $contentLayer.find('input[name="reset"]');

			var $wysiwygElement = $contentLayer.find('textarea.wysiwyg');
			$wysiwygElement.extendWysiwygElement();

			if ( $wysiwygElement.val().length < 150 )
				$saveBtn.attr('disabled', 'disabled').addClass('disabled');
			else
				$('#temp-res-150').html('ура! вы преодолели планку в 150 символов!');

			// обработчик ввода текста отзыва
			$wysiwygElement.keyup( function() {
				tareaContent = $(this).val();
				if ( tareaContent.length == 0 ) {
					$('#temp-res-150').html('не менее 150 символов, а то что это за отзыв?');
					$saveBtn.attr('disabled', 'disabled').addClass('disabled');

					return;
				}

				if ( tareaContent.length >= 150 ) {
					$('#temp-res-150').html('ура! вы преодолели планку в 150 символов!');
					$saveBtn.removeAttr('disabled').removeClass('disabled');

					return;
				}

				remain = 150 - tareaContent.length;
				$('#temp-res-150').html('не менее 150 символов, а то что это за отзыв? (осталось ' + remain + ')');
				$saveBtn.attr('disabled', 'disabled').addClass('disabled');
			});

			// обработчик нажатия "сохранить"
			$saveBtn.bind('click', function() {
				var postData = { content: $wysiwygElement.val() };
				$contentLayer.html( loadingImg );

				$.post( url, postData, function( data ) {
					$contentLayer.html( data.response );
					$img.removeClass('inactive');

					if ( $responseAddForm.length > 0 )
						$responseAddForm.fadeIn();

					// FB для маленьких картинок
					// TODO стоит ли делать для всех?
					$('img[src$="_XS.jpeg"], img[src$="_XS.jpg"]').extendPictures();
				}, 'json');
			});

			// обработчик нажатия "оставить как было"
			$resetBtn.bind('click', function() {
				return resetDefaults();
			});
		});

		return false;
	});

	// редактирование ресторанов и гостиниц
	var $editForm = $('#entity-edit');
	var active_value = 0;

	if ( $editForm.length > 0 ) {
		$statusField = $editForm.find('input[name="status"]');

		$statusField.each( function() {
			if ( $(this).attr('checked') ) {
				active_value = $(this).val();
				return false;
			}
		});

		// скрываем поля для открытых ресторанов и рекламодателей
		if ( active_value != 3 )
			$('#for-closed').hide();

		// скрываем поля для открытых ресторанов и закрытых ресторанов
		if ( active_value != 1 )
			$('#for-advert').hide();

		$statusField.click( function() {

			if ( $(this).val() == 3 )
				$('#for-closed').show();
			else
				$('#for-closed').hide();

			if ( $(this).val() == 1 )
				$('#for-advert').show();
			else
				$('#for-advert').hide();
		});
	}

	// карта у заведений
	$yMapDiv = $('#YMapsID');
	if ( $yMapDiv.length > 0 ) {
		// ID текущего заведения
		eid = window.location.href.split('-')[1];
		
		var map = new YMaps.Map( $yMapDiv[0] );
		map.setType( YMaps.MapType.MAP );
		map.disableDblClickZoom();

		// Создание изображения, говорящего о загрузке
		var loadingControl = new loadingObject();
		
		// максимальный и минимальный зум
		if ( typeof isAdministrator != 'boolean' ) {
			map.setMinZoom(15);
			map.setMaxZoom(17);
		}
		
		// элементы карты
		map.addControl( new YMaps.TypeControl() );
		map.addControl( new YMaps.ToolBar() );
		map.addControl( new YMaps.Zoom() );
		map.addControl( new YMaps.ScaleLine() );

		var about = '<b>' + $('#entity-head').find('h1.title').find('a').html() + '</b>';
		about += '<div style="margin-top: 6px"><small><b>Адрес:</b> ' + $('#address').html()+'<br>';
		if ( $('#phone').length != 0 )
			about += '<b>Телефон:</b> ' + $('#phone').html() + '</small></div><div class="clear"></div>';
		about += '<div style="margin-left: 2px;"></div>';

		// создаем плэйсмарк заведения и вешаем на него observer
		var longitude =  $('#coordinates').html().split(',')[0];
		var latitude = $('#coordinates').html().split(',')[1];
		draggableOption = ( $('#entityID').length > 0 ) ? 1 : 0;

		// устанавливаем центр карты с максимальным зумом
		map.setCenter( new YMaps.GeoPoint( longitude, latitude ), map.coordSystem.getMaxZoom() );

		var placemark = new YMaps.Placemark( new YMaps.GeoPoint( longitude, latitude ), { draggable: draggableOption,
			hintOptions: {
				maxWidth: 100,
				showTimeout: 2000,
				offset: new YMaps.Point(5, 5)
			}, balloonOptions: {
				hasCloseButton: true,
				mapAutoPan: 1
			}
		});

		placemark.setBalloonContent( about );
		map.addOverlay( placemark );
		placemark.openBalloon();

		style = ( window.location.href.indexOf('restaurants') == -1 ) ? 'default#houseIcon' : 'default#restaurauntIcon';

		var placemarks = new Array();

		// Вывести на карту все видимые точки
		function drawNearItems() {
			for ( var i=0; i<placemarks.length; i++ ) {
				map.removeOverlay( placemarks[ i ] );
				delete placemarks[i];
			}

			// Создание шаблона для значка метки
            var template = new YMaps.Template("\
				<div>\n\
				<div style=\"margin-top: 10px; background-color: white; border: solid 1px;white-space: nowrap; font-size: 10px; padding: 2px; margin: 0px\">$[description|0]</div>\n\
				<img alt=\"123\" style=\"position:relative; top:-3px; left:0px; padding: 0px; margin: 0px !important; padding: 0px; height:$[style.iconStyle.size.y];width:$[style.iconStyle.size.x]\" src=\"$[style.iconStyle.href]\">\n\
				</div>");

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

			// Создает стиль значка метки
			s.iconStyle = new YMaps.IconStyle();

			s.iconStyle.href = "/s/pic/mark.png";
			s.iconStyle.size = new YMaps.Point(18, 29);
			s.iconStyle.offset = new YMaps.Point(-9, -29);

			// Создание стиля для значка метки с использованием шаблона
            var s = new YMaps.Style();
            s.iconStyle = new YMaps.IconStyle(template);
            s.iconStyle.offset = new YMaps.Point(-10, -24);
            s.iconStyle.href = "/s/pic/mark.png";
            s.iconStyle.size = new YMaps.Point(10, 10);
			s.iconStyle.shadow = new YMaps.IconShadowStyle();
            s.iconStyle.shadow.offset = new YMaps.Point(0, -25);
            s.iconStyle.shadow.href = "/s/pic/shadow.png";
            s.iconStyle.shadow.size = new YMaps.Point(25, 23);
			YMaps.Styles.add("example#customPoint", s);
			
			$.each( $('small.showOnMap'), function() {
				attributes = $(this).prev().attr('rel').split('#');
				
				var placemark = new YMaps.Placemark( new YMaps.GeoPoint( attributes[1], attributes[0] ), {
					style: style,// тестовый стиль иконок style: "example#customPoint",
					draggable: 0,
					hintOptions: {
						maxWidth: 100,
						showTimeout: 200,
						offset: new YMaps.Point(5, 5)
					}, balloonOptions: {
						hasCloseButton: true,
						mapAutoPan: 0
					}
				});
				
				title = $(this).prev().prev().html()+' '+$(this).prev().html();

				var about = '<b>' + title + '</b>';
				about += '<div style="margin-top: 6px"><small><b>Адрес:</b> ' + attributes[2]+'<br>';

				if ( $('#phone').length != 0 )
					about += '<b>Телефон:</b> ' + attributes[3] + '';

				about += '<div style="margin-top: 6px;"></small><a href="'+$(this).prev().attr('href')+'">Страница заведения на AllCafe</a></div>';
				about += '</div><div class="clear"></div>';
				about += '<div style="margin-left: 2px;">';
				about += '</div>';
				placemark.description = $(this).prev().html();
				placemark.setBalloonContent( about );

				//placemark.setIconContent( title );
				
				map.addOverlay( placemark );

				placemarks.push( placemark );
			});
		}
		
		// Создаем невидимый элемент управления
		map.addControl( loadingControl );
		
		// Загрузка соседних заведений
		function loadNearItems() {
			size = map.getBounds();
			loadingControl.container.css({ 'opacity': '0.7' });

			$('#near_items').html( loadingImg );
			$.getJSON( '?getitems', { longitude: longitude, latitude: latitude,left: size._left, right: size._right, top: size._top, bottom: size._bottom }, function( data ) {
				$('#near_items').html('');
				$.each( data.content, function(i, item) {
					if ( item.entity_id != eid ) {
						if ( $('#near_items').html().length != 0)
							$('#near_items').append(', ');
						$('#near_items').append('<span>'+item.type+'</span> <a href="/restaurants/id-'+item.entity_id+'" rel="'+item.latitude+'#'+item.longitude+'#'+item.address+'#'+item.phone+'">&laquo;'+item.title+'&raquo;</a> <small class="showOnMap">('+item.distance+')</small>');
					}
				});
				loadingControl.container.css({ 'opacity': '0' });
				drawNearItems();
			});
		}
		
		// загружаем соседние заведения на карте при первоначлаьной загрузке страницы
		loadNearItems();
		
		// Обработчик изменения границ видимой области карты
		if ( typeof isAdministrator != 'boolean' ) {
			YMaps.Events.observe( map, map.Events.BoundsChange, function () {
				loadNearItems();
			});
		}
		
		// observer изменения координат
		YMaps.Events.observe( placemark, placemark.Events.DragEnd, function( map ) {
				new_longitude = placemark.getGeoPoint().getLng();
				new_latitude = placemark.getGeoPoint().getLat();

				placemark.setBalloonContent( loadingImg );
				placemark.openBalloon();

				$.post( window.location.href, { 'longitude' : new_longitude, 'latitude' : new_latitude }, function( data ) {
						placemark.setBalloonContent( about );
				}, 'json');
		});
		
		// загружаем ближайшие станции метро
//		YMaps.load( "metro", function(){
//			// Поиск ближайших станций метро
//			var metro = new YMaps.Metro.Closest(new YMaps.GeoPoint( longitude, latitude), { results : 3, span: new YMaps.Size(10, 10) } )
//
//			// Обработчик успешного завершения
//			YMaps.Events.observe(metro, metro.Events.Load, function (metro) {
//				if (metro.length()) {
//					metro.setStyle("default#greenSmallPoint");
//					console.log(metro);
//				} else {
//					console.log("Поблизости не найдено станций метро");
//				}
//			});
//
//			YMaps.Events.observe(metro, metro.Events.Fault, function (metro, error) {
//				console.log("При выполнении запроса произошла ошибка: " + error);
//			});
//		} );

	}

	// Управляющий элемент 'Идет загрузка меркеров...'
	function loadingObject () {
		// Добавление на карту
		this.onAddToMap = function (map) {
			this.container = YMaps.jQuery("<p>Идет загрузка маркеров...</p>")
			this.position = new YMaps.ControlPosition( YMaps.ControlPosition.TOP_LEFT, new YMaps.Size(240, 5) );

			// Выставление необходимых CSS-свойств
			this.container.css({
				position: "absolute",
				zIndex: YMaps.ZIndex.CONTROL,
				background: '#fff',
				listStyle: 'none',
				padding: '8px',
				'font-weight': 'bold',
				'opacity': '0.7',
				margin: 0
			});

			// Применение позиции к управляющему элементу
			this.position.apply( this.container );

			// Добавление на карту
			this.container.appendTo( map.getContainer() );
		}

		// Удаление с карты
		this.onRemoveFromMap = function () {
			this.container.remove();
			this.container = this.map = null;
		};
	}

	// открытие карты в попап-окне
	$('a.wtf').live('click', function() {
		$link = $(this);
		coords = $link.attr('rel');

		$head = $link.closest('div.entity').children('p.head').children('a');
		var baloonText = $head.html();

		$.fancybox('<div id="map-popup" style="width: 650px; height: 450px;">' + loadingImg + '</div>', {
			'autoDimensions' : false,
			'width' : 650,
			'height' : 450,
			'transitionIn' : 'none',
			'transitionOut' : 'none'
		});

		YMaps.jQuery(function () {
			longitude = coords.split(':')[0];
			latitude = coords.split(':')[1];

			var map = new YMaps.Map(YMaps.jQuery("#map-popup")[0]);
			map.setCenter(new YMaps.GeoPoint(longitude, latitude), map.coordSystem.getMaxZoom());
			map.setType(YMaps.MapType.MAP);
			map.openBalloon(new YMaps.GeoPoint(longitude, latitude), baloonText);
			map.addControl(new YMaps.ToolBar());
			map.addControl(new YMaps.Zoom());
		});

		return false;
	});

	// удаление логотипа ресторана
	$('#del-logo').click( function() {
		var entityID = window.location.pathname.split('-')[1];

		$('#uploadLogo').attr('src', assetsDomain + 'pic/blank.gif').css('background', 'url(/s/pic/loading.gif) 50% 50% no-repeat');
		$('#del-logo').addClass('hidden');
		$.getJSON( '/?oh-act=del-logo&entity-id=' + entityID,  function(data) {
			$('#uploadLogo').attr('src', assetsDomain + 'pic/add-logo.jpg');
		});
	});

	// сочная загрузка аватарок для ресторанов
	$uploadLogo = $('#uploadLogo');
	if ( $uploadLogo.length > 0 ) {
		var entityID = window.location.pathname.split('-')[1];

		new AjaxUpload( $('#uploadLogo'), {
			action: '/?oh-act=upload&type=entity-logo&entity-id=' + entityID,
			responseType: 'json',
			onSubmit: function(file, ext) {
				$('#uploadLogo').attr('src', assetsDomain + 'pic/blank.gif').css('background', 'url(/s/pic/loading.gif) 50% 50% no-repeat');
				if (!ext || !/^(jpg|png|jpeg|gif)$/i.test(ext)) {
					alert('Вы можете загружать только изображения');
					$('#uploadLogo').attr('src', assetsDomain + 'pic/add-logo.jpg');
					return false;
				}

			}, onComplete: function(file, response) {
				if ( response.error.length > 0 ) {
					alert( response.error );
				} else {
					$('#uploadLogo').attr('src', response.text + '?' + Math.random());
					$('#del-logo').removeClass('hidden');
				}
			}
		});
	}

	// вырезание отзывов
	$('a.cut').click(function(){
		if ( !$(this).hasClass('inactive') ){
			// анхайдим кнопку
			$('div.response.inactive').find('a.cut').show();

			// снимание выделение с прошлого выбранного отзыва
			$('div.response.inactive').removeClass('inactive');

			// убираем кнопку "вырезать"
			$(this).hide();
			$(this).closest('div.response').addClass('inactive');

			var link = $(this).closest('div.response').find('div.conversation a').attr('href');
			var guideID = link.split('post-')[1];

			if ( link.indexOf('net') == -1 ){
				var entityID = link.split('id-')[1].split('/')[0];
				var networkID = 0;
			} else {
				var entityID = 0;
				var networkID = link.split('net-')[1].split('/')[0];
			}

			var prefix = window.location.href.split('.')[0].split('//')[1];
			var domain = window.location.href.split('.')[2].split('/')[0];
			var module = window.location.href.split('.')[2].split('/')[1];

			$.post('http://' + prefix + '.allcafe.' + domain + '/' + module + '/cut', {
				'entityID' : entityID,
				'networkID' : networkID,
				'guideID' : guideID
			}, function() {}, 'json');
		}
	});

	// вставка отзыва
	canPaste = ( window.location.pathname.indexOf('/restaurants/') != -1 || window.location.pathname.indexOf('/hotels/') != -1 || window.location.pathname.indexOf('/health/') != -1 );
	$('a.add-comment.insert').click( function() {
		if ( !canPaste ) {
			alert('Вы можете вставить отзыв только в комментарии к ресторанам или гостиницам');
			return false;
		}

		p = window.location.href.split('/');
		address = p[0] + '//' + p[2] + '/' + p[3] + '/paste';

		var commentID = ( $(this).attr('id') != 'addLastComment' ) ? $(this).closest('div.comment').attr('id').split('-')[1] : 0;
		var guideID = window.location.href.split('post-')[1].split('?')[0].split('#')[0];

		$.post( address, { 'commentID' : commentID, 'guideID' : guideID }, function() {
			window.location.reload();
		}, 'json');
	});
});

var checkForm = function() {
	canPublish = true;

	$authorName = $('#guide-form').find('input[name="author_name"]');
	$authorCity = $('#guide-form').find('input[name="author_city"]');
	$authorEmail = $('#guide-form').find('input[name="author_email"]');

	if( $authorName.length == 1 && $authorName.val() == '' )
		canPublish = false;

	if( $authorCity.length == 1 && $authorCity.val() == '' )
		canPublish = false;

	if( $authorEmail.length == 1 && $authorEmail.val() == '' )
		canPublish = false;
	
	if ( $('#guide-form').find('input[name="visit_date"]').val() == '' )
		canPublish = false;

	if ( $('#guide-form').find('textarea[name="content"]').val().length < 150 )
		canPublish = false;

	// "я обязуюсь не постить глупости на олкафе"
	if ( !$('input[name="gentle[]"]').attr('checked') )
		canPublish = false;

	// если не может писать, то увы и ах
	if ( !canPublish ) {
		$('#publish').attr('disabled', 'disabled').addClass('disabled');
		return;
	}

	// няка-няка!
	$('#publish').removeAttr('disabled').removeClass('disabled');
}

