function roller(id){
    div = document.getElementById(id);
    
    if (div.style.display == 'block') {
        div.style.display = 'none';
    }
    else {
        div.style.display = 'block';
    }
}

function str_replace(search, replace, subject) {
    return subject.split(search).join(replace);
}

function map_parseLionID(_lid) {
	_lid = parseInt(_lid);
	
	var _cat_name = 'Достопримечательность';
	var _style_type = 'lions';
	
	switch (_lid) {
		case 1:  _cat_name = 'Место';     _style_type = 'place'; break;
		case 2:  _cat_name = 'Аэропорт';  _style_type = 'airport'; break;
		case 3:  _cat_name = 'Вокзал';    _style_type = 'railway'; break;
		case 4:  _cat_name = 'Метро';     _style_type = 'metro'; break;
		case 5:  _cat_name = 'Музей';     _style_type = 'museum'; break;
		case 6:  _cat_name = 'Ресторан';  _style_type = 'restaurant'; break;
		case 7:  _cat_name = 'Театр';     _style_type = 'theater'; break;
		case 8:  _cat_name = 'Памятник';  _style_type = 'monument'; break;
		case 9:  _cat_name = 'Галерея';   _style_type = 'gallerie'; break;
		case 10: _cat_name = 'Кинотеатр'; _style_type = 'theater'; break;
	}
	
	return {name: _cat_name, type: _style_type};
}

function w_open(link) {
	window.open(link, 'Order', 'width=800, height=600');
}

$(function() {
	$.datepicker.regional['ru'] = {
		closeText : 'Закрыть',
		prevText : '&#x3c;Пред',
		nextText : 'След&#x3e;',
		currentText : 'Сегодня',
		monthNames : [ 'Январь', 'Февраль', 'Март', 'Апрель', 'Май', 'Июнь', 'Июль', 'Август', 'Сентябрь', 'Октябрь', 'Ноябрь', 'Декабрь' ],
		monthNamesShort : [ 'Янв', 'Фев', 'Мар', 'Апр', 'Май', 'Июн', 'Июл', 'Авг', 'Сен', 'Окт', 'Ноя', 'Дек' ],
		dayNames : [ 'воскресенье', 'понедельник', 'вторник', 'среда', 'четверг', 'пятница', 'суббота' ],
		dayNamesShort : [ 'вск', 'пнд', 'втр', 'срд', 'чтв', 'птн', 'сбт' ],
		dayNamesMin : [ 'Вс', 'Пн', 'Вт', 'Ср', 'Чт', 'Пт', 'Сб' ],
		dateFormat : 'dd.mm.yy',
		firstDay : 1,
		minDate: new Date(),
		isRTL : false
	};
		
	$.datepicker.setDefaults($.datepicker.regional['ru']);
	
	var dates = $("#date_arrive, #date_departure").datepicker({
		numberOfMonths: 2,
		duration: 1,
		onSelect: function(selectedDate) {
			if (this.id == "date_arrive") {
				var d = new Date();
				var arrive = Date.parse($(this).datepicker("getDate"));
				var departure = Date.parse(dates.not(this).datepicker("getDate"));
				var _day = 86400000;
				
				if (arrive >= departure) {
					d.setTime(arrive+_day);
					dates.not(this).datepicker("setDate", d.getDate() + "." + (d.getMonth()+1) + "." + d.getFullYear());
				}
			}
		}
	});

	 $("#head_logo").bind("mouseenter",function() {
		 $("#head_logo_wrapper").addClass('head__logo-wrapper_hover');
	 }).bind("mouseleave",function(){
		 $("#head_logo_wrapper").removeClass('head__logo-wrapper_hover');
	 });
	
	$("#overview_overlay").css({opacity:0.8});	
	
	jQuery.fn.tooltip = function(id, str) {
		var id = $(id);
		
		id.bind("mouseenter",function(){
			$("body").append('<div id="tooltip">' + str + '</div>');
			
			var offset = $(this).offset();
			
			$("#tooltip").css({ top:offset.top-11, left:offset.left-138});

		}).bind("mouseleave",function(){
			$("#tooltip").remove();
		});
	}
	
    jQuery.fn.center = function(id) {
		var w = $(window);
		var id = $("#" + id);
		
		var h = (w.height() - id.height()) / 2 + w.scrollTop();
		
		if (h < 10)
		{
			h = 10;	
		}
		
		id.css("top", h + "px");		
		id.css("left", (w.width() - id.width()) / 2 + w.scrollLeft() + "px");
		
		return id;
	}

	jQuery.fn.overview_show = function(btn_close) {
		$("#overview_overlay").height($(document).height());
		$("#overview").height($(window).height());
		$().center('overview_overlay_loader');
		$("#overview, #overview_overlay").show();
		
		if (btn_close == 1) {
			$("#overview_btn_close").show();
		}
	}
	
	jQuery.fn.overview_hide = function() {
		$("#overview, #overview_overlay, #overview_btn_close").hide();
		$("#overview_content").empty();
	}
	
	$(".popup__close-btn").click(function() {
		$().popup_close();
	});
	
    jQuery.fn.popup_close = function() {
		try{
			popup_close_callback();
			popup_close_callback = null;
		}
		catch(e){}
		
   	 	$("#overview_p").hide();
   	 	$().overview_hide();
		$("#overview_p_content").empty();
		
		$("#overview_p").css({'width':600, 'height':''});
    }
    
	jQuery.fn.popup_show = function(data) {
		$("#overview_p_content").html(data);
		
		$().center("overview_p");
   	 	
		$("#overview_p").show();
		$('#overview_p').focus();
		
		$("#overview_i").hide();
		
		$(window).keydown(function( e ) {
			if ( e.keyCode == 27 ) {
				$().popup_close();
				$("body").keydown( function(){} );
			}
		});
		
		$('#overview').click($().popup_close );
    }
	
    jQuery.fn.right_list = function(name, id, reducer) {
		$.ajax({
			url : '/hotels/rightlist/' + name + '/',
			global : false,
			type : "POST",
			data : ( {
				parent_link : P_uri.parent_link,
				hotel_id : id,
				reducer : reducer,
				name : name
			}),
			dataType : 'html',
			async : false,
			success : function(data) {
				$('#content_' + name).html(data);				
				$().tooltip(".ic8", "Удалить из списка");
				
				$(".ic8").click(function(){
					$().right_list($(this).parents('div[id^=content_]').attr('id').substr(8), $(this).attr("id").substr(5), name + '_delete');
					$("#tooltip").remove();
				});
			}
		});
    }
    
    $('.columns-content .column-right .tabs a').click(function () {
    	var this_id = $(this);
		
    	$('.columns-content .column-right a').removeClass('selected');
    	this_id.addClass('selected');
    	
    	$('.columns-content .column-right div[id^=content_]').hide();
    	$('#content_' + this_id.attr('href').substr(1)).show();
		
		$('.columns-content .column-right a[href=#lions]').addClass('selected');
		$('#content_lions').show();
    });
	
	$("#auth_block .auth__btn-close").click(function () {
		$('#auth_block').slideUp(500);
	});
    
	$("#auth_signin").click(function () {
		$("html,body").stop().animate({ scrollTop: 0 }, 500, function() {
			$('#auth_block:hidden').slideDown(500);
		});
	});
	
	$("#auth_right span").click(function () {
		var _index = $("#auth_right span").index(this);
		
		$("#auth_right li").removeClass();
		$("#auth_right li").eq(_index).addClass('auth__item_selected');
		
		$("#auth_left table").hide();
		$("#auth_left table").eq(_index).show();
	});
	
	jQuery.fn.auth_block_login_submit = function() {
		var _email = $("#auth_block_login_content [name=email]").val();
		var _password = $("#auth_block_login_content [name=password]").val();
		var _message;
		
		$("#auth_message").empty().hide();
		
		if ( _email == '') {
			$("#auth_block_registration_content [name=email]").focus();
			_message = 'Укажите электронную почту';
		} else if (_password == '') {
			$("#auth_block_registration_content [name=password]").focus();
			_message = 'Введите пароль';
		}
		
		if ( _message != null) {
			$('#auth_message').text(_message).show();

			return false;
		}
		
		$.post("/profile/login/", { email: _email, password: _password }, function(data) {
			if (data.reducer == false) {
				$('#auth_message').html(data.message).show();
			} else {
				//document.location.reload(true);
				document.location.href = document.location.href;
			}
		}, 'json');
		
		return false;
	}
	
	jQuery.fn.auth_block_registration_submit = function() {
		var _email = $("#auth_block_registration_content [name=email]").val();
		var _password = $("#auth_block_registration_content [name=password]").val();
		var _password_re  = $("#auth_block_registration_content [name=password_re]").val();
		var _message;
		
		$("#auth_message").empty().hide();
		
		if ( _email == '') {
			$("#auth_block_registration_content [name=email]").focus();
			_message = 'Укажите электронную почту';
		} else if (_password == '') {
			$("#auth_block_registration_content [name=password]").focus();
			_message = 'Введите пароль';
		} else if (_password_re == '') {
			$("#auth_block_registration_content [name=password_re]").focus();
			_message = 'Повторите пароль';
		} else if ( _password != _password_re) {
			$("#auth_block_registration_content [name=password]").focus();
			_message = 'Пароли не совпадают';
		}
		
		if ( _message != null) {
			$('#auth_message').text(_message).show();

			return false;
		}
		
		$.post("/profile/registration/", { email: _email, password: _password }, function(data) {
			if (data.reducer == false) {
				$('#auth_message').html(data.message).show();
			} else {
				//document.location.reload(true);
				document.location.href = document.location.href;
			}
		}, 'json');
	}
	
	jQuery.fn.auth_block_password_reset_submit = function() {
		var _email = $("#auth_block_password_reset_content [name=email]").val();
		
		$("#auth_message").empty().hide();
		
		if ( _email == '' ) {
			$('#auth_message').text('Укажите электронную почту').show();
			
			$("#auth_block_password_reset_content [name=email]").focus();
			return false;
		}
		
		$.post("/profile/password_reset/", { email: _email }, function(data) {
			if (data.reducer == false) {
				$('#auth_message').html(data.message).show();
			} else {
				$("#auth_block_password_reset_content").hide();
				$("#auth_block_login_content").show();
				$("#auth_right li").removeClass();
				$("#auth_right li").eq(0).addClass('auth__item_selected');
				$('#auth_message').text('Новый пароль отправлен на ' + _email);
			}
			
			$("#auth_message").show();
		}, 'json');
	}
	
	/* OAuth */
	var _popup_oauth_interval = null;
	var _popup_oauth_window = null;
	var _oauth_type = null;
	var _oauth_func = null;
	var _oauth_param = '';
	
	function oauth_popup() {
		$.cookie('oauth_'+_oauth_type, null);
		
        var _width = 750;
		var _height = 500;
        var _left = (screen.width / 2) - (_width / 2);
		var _top = (screen.height / 2) - (_height / 2);
		var url = "/profile/oauth/" + _oauth_type;
		
		if ( _oauth_param != '' ) {
			url += '?' + _oauth_param;
		}
		
        _popup_oauth_window = window.open(url, "hotelshop_popup",
				"left=" + _left + "," +
				"top=" + _top + "," +
				"width=" + _width + "," +
				"height=" + _height + "," +
				"location=1,toolbar=0,menubar=0,status=0,scrollbars=0,resizable=1");
        
        if (_popup_oauth_window == null) {
            alert('Please unlock popup window!')
        } else {
			//$('.auth-block img[oauth='+_oauth_type+']').attr('src', '/i/ajax-loader-w.gif');
			_darkenScreen();
			_popup_oauth_interval = window.setInterval(waitForPopupClose_, 80);
            _popup_oauth_window.focus();
        }
	}
	
	function waitForPopupClose_() {
		if ( !_popup_oauth_window || _popup_oauth_window.closed ) {
			//$('.auth-block img[oauth=' + _oauth_type + ']').attr('src', '/i/oauth/s/' + _oauth_type + '.png');
			
			var _div_dark = window.document.getElementById('_popup_dark_bg');
			
			if ( _div_dark ) {
				_div_dark.style.visibility = 'hidden';
			}
			
			_popup_oauth_window = null;
			
			if ( _popup_oauth_interval !== null ) {
				window.clearInterval(_popup_oauth_interval);
				_popup_oauth_interval = null;
			}
			
			if ( $.cookie('oauth_'+_oauth_type) !== null ) {
				$.cookie('oauth_'+_oauth_type, null);
				if ( _oauth_func != null ) {
					_oauth_func();
				}
			}
		}
	}
	
	function _darkenScreen() {
			var _div_dark = window.document.getElementById('_popup_dark_bg');
			
			if (!_div_dark) {
				_div_dark = window.document.createElement('div');
				_div_dark['id'] = '_popup_dark_bg';
				_div_dark.setAttribute('style', 
						[ 'z-index:10000;',
						  'border:none;',
						  'margin: 0px',
						  'padding: 0px;',
						  'position:fixed;',//absolute
						  'top:0px;',
						  'left:0px;',
						  'background-color:rgb(0,0,0);',
						  'opacity:0.7;',
						  '-moz-opacity:0.7;',
						  'filter:alpha(opacity=0.7);',
						  'width:100%;',
						  'height:100%;'
						].join('')
				);
				window.document.body.appendChild(_div_dark);
			}
			_div_dark.style.visibility = 'visible';
	}
	/* OAuth end */
	
	/* OAuth login */
	$("#auth_block > .auth__oauth > img").click(function () {
		if ( _popup_oauth_window !== null ) {
			return _popup_oauth_window.focus();
		}
		
		var oauth_type = $(this).attr('oauth');
		_oauth_type = oauth_type;
		
		_oauth_func = oauth_login;
		
		_oauth_param = '';
		oauth_popup();
	});
	
	function oauth_login() {
		window.location.reload();
	}
	/* OAuth login end */
	
	/* OAuth register */
	$(".register-block #oauth").click(function () {
		if (_popup_oauth_window !== null) {
			return _popup_oauth_window.focus();
		}
		
		var oauth_type = $(this).attr('oauth');
		_oauth_type = oauth_type;
		
		_oauth_func = oauth_register;
		
		$.cookie('registration', 'true');
		
		_oauth_param = 'registration';
		oauth_popup();
	});
	
	function oauth_register() {
		document.location = '/profile/registration/';
		//window.location.reload();
	}
	/* OAuth register end */
	
	$("#b_faq .g-link").click(function() {
		$("#b_faq .g-hide").eq($("#b_faq .g-link").index(this)).toggle();
	});
	
	$("#feedback_label").click(function() {
		$('#overview_content').html($('#feedback').html());
		$().center('overview_content .feedback');
		$().overview_show();
		$('#overview_content .feedback').show();
		
		$("#overview_content h1 .g-link").click(function() {
			$.post("/feedback/", { email: $('#overview_content [name=feedback_email]').val(), phone: $('#overview_content [name=feedback_phone]').val(), content: $('#overview_content [name=feedback_content]').val() }, function(data) {
				$('#overview_content .feedback__content').html('<p>Ваше сообщение отправленно администрации сайта.</p>');
				setTimeout("$().overview_hide()", 3000);
			}, 'json');
		});
	});
});

function photogallery_show(path, files_row) {
	var html_photogallery = '<div class="overview-photogallery" id="photogallery"><img src="" alt="" class="overview-photogallery__img" id="photogallery_img" /><div class="overview-photogallery__alt"></div><div class="overview-photogallery__left"></div><div class="overview-photogallery__right"></div><div class="overview-photogallery__list"><div class="overview-photogallery__list-reducer"></div><div class="g-clear"></div></div></div>';
	var overview = $('#overview_content');
	
	overview.html(html_photogallery);
	
	var width_list = 0, html_list = '';
	
	for (var files_key in files_row) {
		if (files_key == 0) {
			html_list += '<div class="selected" _k="' + files_key + '">';
		} else {
			html_list += '<div _k="' + files_key + '">';
		}
		
		html_list += '<img src="' + path + 's/' + files_row[files_key].id + '.' + files_row[files_key].ext + '" alt="' + files_row[files_key].alt + '" />';
		html_list += '</div>';
		
		width_list += 66;
	}
	
	$().overview_show(1);
	
	overview.find('.overview-photogallery__list-reducer').html(html_list);
	overview.find('.overview-photogallery__list-reducer').css("width", width_list);
	
	if (width_list < overview.width()) {
		overview.find('.overview-photogallery__list-reducer').css("margin-left", ((overview.width() - width_list) / 2));
	}
	
	var img = $("#photogallery_img");
	
	img.attr('src', path + 'b/' + files_row[0].id + '.' + files_row[0].ext);
	img.load(function() {
	    $(this).removeAttr("width").removeAttr("height").css({width: "", height: ""});
	    
	    var img_width  = ($(this).width() + 40);
	    var img_height = ($(this).height() + 140);
	    
	    if (img_width > overview.width()) {
	    	$(this).width(overview.width() -40);
	    } 
	    
	    if (img_height > overview.height()) {
	    	$(this).height(overview.height() -140);
		}
	    
	    $(this).css({"left": ((overview.width() - $(this).width()) / 2),"top": ((overview.height() - $(this).height())/2)-50});
	    $(this).show();
	});
	
	overview.find('.overview-photogallery__list-reducer > div').click(function() {
		overview.find('.overview-photogallery__list-reducer > div').removeClass();
		$(this).addClass('selected');
		img.attr('src', path + 'b/' + files_row[$(this).attr('_k')].id + '.' + files_row[$(this).attr('_k')].ext);
	});
	
	overview.find('.overview-photogallery__left, .overview-photogallery__right').click(function() {
		var i = overview.find('.overview-photogallery__list-reducer > div.selected').index();
		var i_all = overview.find('.overview-photogallery__list-reducer > div:last').index();
		
		overview.find('.overview-photogallery__list-reducer > div').removeClass();
		
		if ($(this).hasClass('overview-photogallery__left') == true) {
			if (i == 0) {
				var div = overview.find('.overview-photogallery__list-reducer > div:last');
			} else {
				var div = overview.find('.overview-photogallery__list-reducer > div').eq(i-1);
			}
		} else {
			if (i == i_all) {
				var div = overview.find('.overview-photogallery__list-reducer > div:first');
			} else {
				var div = overview.find('.overview-photogallery__list-reducer > div').eq(i+1);
			}
		}
		
		div.addClass('selected');
		img.attr('src', path + 'b/' + files_row[div.attr('_k')].id + '.' + files_row[div.attr('_k')].ext);
	});
}

function valid_email(email) {
	var _regexp_email = /^((([a-z]|\d|[!#\$%&'\*\+\-\/=\?\^_`{\|}~]|[\u00A0-\uD7FF\uF900-\uFDCF\uFDF0-\uFFEF])+(\.([a-z]|\d|[!#\$%&'\*\+\-\/=\?\^_`{\|}~]|[\u00A0-\uD7FF\uF900-\uFDCF\uFDF0-\uFFEF])+)*)|((\x22)((((\x20|\x09)*(\x0d\x0a))?(\x20|\x09)+)?(([\x01-\x08\x0b\x0c\x0e-\x1f\x7f]|\x21|[\x23-\x5b]|[\x5d-\x7e]|[\u00A0-\uD7FF\uF900-\uFDCF\uFDF0-\uFFEF])|(\\([\x01-\x09\x0b\x0c\x0d-\x7f]|[\u00A0-\uD7FF\uF900-\uFDCF\uFDF0-\uFFEF]))))*(((\x20|\x09)*(\x0d\x0a))?(\x20|\x09)+)?(\x22)))@((([a-z]|\d|[\u00A0-\uD7FF\uF900-\uFDCF\uFDF0-\uFFEF])|(([a-z]|\d|[\u00A0-\uD7FF\uF900-\uFDCF\uFDF0-\uFFEF])([a-z]|\d|-|\.|_|~|[\u00A0-\uD7FF\uF900-\uFDCF\uFDF0-\uFFEF])*([a-z]|\d|[\u00A0-\uD7FF\uF900-\uFDCF\uFDF0-\uFFEF])))\.)+(([a-z]|[\u00A0-\uD7FF\uF900-\uFDCF\uFDF0-\uFFEF])|(([a-z]|[\u00A0-\uD7FF\uF900-\uFDCF\uFDF0-\uFFEF])([a-z]|\d|-|\.|_|~|[\u00A0-\uD7FF\uF900-\uFDCF\uFDF0-\uFFEF])*([a-z]|[\u00A0-\uD7FF\uF900-\uFDCF\uFDF0-\uFFEF])))\.?$/;
	
	return ( email.match(_regexp_email) );
}

function tooltip_show(id, text) {
	var tooltip = $("#tooltip");
	
	tooltip.find('.tooltip__reducer').html(text);
	tooltip.css({top:id.offset().top-tooltip.height(), left:id.offset().left-((tooltip.width()/2)-12)});
	tooltip.show();
}

function tooltip_hide() {
	$("#tooltip").hide();
	$("#tooltip .tooltip__reducer").empty();
}

function el_incorrect(el, focus) {
	if (focus != undefined && focus == true) {
		$("html:not(:animated),body:not(:animated)").animate({scrollTop: ($(el).offset().top - 20) }, 500 , function() {
			$(el).focus().val($(el).val());
		});
	}
	
	$(el).css({ 'background-color': '#FFFFFF'});
	
	var _a_speed = 100;
	$(el)
		.animate({ 'background-color': '#FFD9D8'}, _a_speed )
		.animate({ 'background-color': '#FFFFFF'}, _a_speed )
		.animate({ 'background-color': '#FFD9D8'}, _a_speed )
		.animate({ 'background-color': '#FFFFFF'}, _a_speed )
		.animate({ 'background-color': '#FFD9D8'}, _a_speed );
	
	return false;
}

function el_correct(el) {
	// $(el).unbind('click');
	
	$(el).removeClass('error');
	$(el).animate({ 'background-color': '#FFFFFF'}, 100);
	
	return true;
}
