var apiID = ( geoDomain == '.ru' ) ? 2132666 : 2132661; // vk.api.id

var mailruAppID = ( geoDomain == '.ru' ) ? 583456 : 580985; // mailru app_id
var mailruPrivateKey = ( geoDomain == '.ru' ) ? '1cba7115840fc16b40b2a8d6bd8ffa63' : '14bdce70a550ae2acd4532e9f981d19e'; // mailru private key

$(document).ready( function() {
	// бронирование гостиниц
	$booking = $('#booking');
	if ( $booking.length > 0 ) {
		var dates = $('#from, #to').datepicker({
			buttonImage: assetsDomain + '/pic/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);
			}
		});
	}

	// подключаем api mail.ru
	initMailRu( mailruAppID, mailruPrivateKey );
	
	// показать-скрыть архивные акции
	$('#show-archive').click( function() {
		$archiveOffers = $('#archive-offers');
		$link = $(this);

		if ( $archiveOffers.length == 0 ) {
			$.getJSON( window.location.href, { act: 'archive' }, function( data ) {
				$link.parent().after( data.content );
				$('#archive-offers').fadeIn().find('tr.mnths:even').addClass('odd');
			});
		} else if ( $archiveOffers.is(':hidden') ) {
			$archiveOffers.fadeIn()
		} else {
			$archiveOffers.fadeOut()
		}
	});
	
	$('div.showHiddenGuide a').click( function(){
		$(this).hide();
		$('div.userGuide').removeClass('hidden')
	});

	$YMainMapID = $('#YMainMapID');
	if ( $YMainMapID.length > 0 )
		indexMap( citiesList, 68.961965, 55.965108, 3 );

	// скрыть дополнительные возможности заказа для банкетов
	if ( $('#hide_additional').length > 0 )
		$('#banquetAdditional').hide();
	else
		$('#showBanquetAdditional').hide();

	$('#showBanquetAdditional').click( function() {
		$('#banquetAdditional').fadeIn('fast');
		$(this).hide();
	});

	if ( $('#hide_additional').length > 0 )
		$('#banquetAdditional').hide();
	else
		$('#showBanquetAdditional').hide();

	$('#showBanquetAdditional').click( function() {
		$('#banquetAdditional').fadeIn('fast');
		$(this).hide();
	});

	// переключаемые вкладки
	var $main3cols = $('div.main-3cols');
	if ( $main3cols.length > 0 ) {
		// кэш-массив данных
		var tabsContent = new Array();
		$main3cols.each( function() {
			key = $(this).children().attr('class');
			tabsContent[ key ] = $(this).hasClass('open')
				? $('#main-subblock').html()
				: '';
		});

		$main3cols.children('a').click( function() {
			if ( $(this).parent().hasClass('open') )
				return false;

			$main3cols.removeClass('orange-bg').removeClass('open');
			$(this).parent().addClass('orange-bg open');

			var tab = $(this).attr('class');
			$('#main-subblock').html( loadingImg );

			if ( tabsContent[ tab ] != '' ) {
				$('#main-subblock').html( tabsContent[ tab ] );
				return false;
			}

			url = $(this).attr('href') + '?callback=?';
			$.getJSON( url, function( data ) {
				tabsContent[ tab ] = data.content;
				$('#main-subblock').html( data.content );
			});

			return false;
		});

		// если данных по умолчанию нет, подгружаем
		if ( $.trim( $('#main-subblock').html() ) == '' )
			$main3cols.children('a:first').click();
	}

	// фоловинг человека
	$('#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;
	});

	// Лог
	$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();
	});

	//
	$('#empty-entity').live('click', function() {
		var $input = $(this).prev().prev();

		$input.val('');
		$input.next().val('0');
		$(this).addClass('hidden');
	});
});

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 для поиска ресторанов
 */
$.fn.searchRestaurantAutocomplete = function( redirectAfterSelect ) {
	// кэш результатов поиска
	var cache = {};

	// добавляем скрытый input с постфиксом "_id" после видимого
	if ( !redirectAfterSelect ) {
		// ID ресторана
		name = this.attr('name');
		if ( name.substr(-2) == '[]' )
			this.after('<input type="hidden" name="' + name.substr(0, name.length - 2) + '_id[]" value="0">');
		else {
			if ( this.next('input[name="' + name + '_id"]').length == 0 )
				this.after('<input type="hidden" name="' + name + '_id" value="0">');
		}

		var $resultInput = this.next();

		$resultInput.after('<a class="xhr" href="javascript:;" id="empty-entity">очистить</a>');
		var $emptyAnchor = $resultInput.next();
		if ( $resultInput.val() == '0' )
			$emptyAnchor.addClass('hidden');
	}

	this.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 );
				$emptyAnchor.removeClass('hidden');
			} else {
				window.location.href = '/restaurants/id-' + ui.item.id;
			}
		}
	});
};

/**
 * Autocomplete для поиска мед. учреждений
 */
function searchHealthAutocomplete( $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('/health/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 = '/health/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;
		}
	});
}

/**
 * Autocomplete для поиска поставщиков
 */
function searchSupplierAutocomplete( $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('/profy/suppliers?callback=?', {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 = 'suppliers/id-' + ui.item.id;
		}
	});
}

/**
 * Autocomplete для поиска товаров в маркете
 */
function searchProductAutocomplete( $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('?callback=?', {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 = 'market/id-' + ui.item.id;
		}
	});
}

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 );
	});
}

