var body_tag, ie8 = false, ie6 = false;
(function(){
stopBubble = function(oEvent){
	if(oEvent && oEvent.stopPropagation){
		oEvent.stopPropagation()// для DOM-совместимых браузеров
	}
	else
	{
		window.event.cancelBubble = true;//для IE
	}
}

supportAttr =function(el,attr) {
	if(attr in document.createElement(el))return true;return false
}

var left_pos,	top_pos, el_focus, destination, destination_left, window_pos, posminus, anim_obj, facebox_active = 1, textarea_resize = false, css_trans = false;


if($.browser.msie && $.browser.version < 9){
	ie8 = true
	if($.browser.version < 7){
	ie6 = true
	}
}


for(var i=0,ie_elem=["header","footer","nav","section","article","aside","time"], ie_elem_length=ie_elem.length;i<ie_elem_length;i++){
		document.createElement(ie_elem[i])
}

if ($.browser.webkit){
	anim_obj = "body"
} else {
	anim_obj = document.getElementsByTagName("html")[0]
}

(function(){
var facebox_expr = /\bfacebox\b/, img_expr = /\.(gif|png|jpg|jpeg|bmp)$/i, local_url = location.href.replace(location.hash,"");
$.extend($.expr[':'],
{
	facebox: function(el) {
			var href = el.getAttribute("href") || ""
			if (facebox_expr.test(el.className) && href.length > 0){
			return true
			} else {
				return false;
			}
	}
},
 {
	anchor: function(el) {
		var href=el.href
		if(href.indexOf("#") < 0 || facebox_expr.test(el.className))return false
		href = href.replace(local_url,"")
		if(href.length > 1 && href.charAt(0)== "#"){
			return true
		}
		return false
		}
	}, 

{
		image_link: function(el) {
			var href=el.getAttribute('href') || "";
			if (img_expr.test(href)){
					return true
			} else {return false}

		} 
	}
)
})()




//
// Всплывающие окошки
//

//Закрытие окошка
facebox_close = function(close_time)
{
	var face_time = close_time || 1, facebox_overlay = document.getElementById("facebox_overlay"), facebox_el = document.getElementById("facebox"), facebox_all = document.getElementById("facebox_all")
	 setTimeout(function(){
		$(facebox_overlay).animate({"opacity":"0"},1000)
		$(facebox_el).animate({"opacity":"0","top":"-20","left":facebox_overlay.offsetWidth-facebox_el.offsetWidth+100},1000, function(){
			facebox_all.parentNode.removeChild(facebox_all)
			facebox_active = 1
			facebox_focus()
		})
	}, face_time)
}


//Загрузка окошка
facebox_load = function(html_cont, facebox_loading)
{
	var facebox_old = document.getElementById("facebox_all")
	if(facebox_old)facebox_old.parentNode.removeChild(facebox_old)
	$(body_tag).append('<div id="facebox_all"><div id="facebox_overlay"></div>\
			<div id="facebox" class="facebox_light">\
			<!--[if lte IE 7]><table><tr><td><![endif]--> \
				<span title="Закрыть" onclick="facebox_close()" id="facebox_close_icon"></span>\
								<div id="facebox_content_i">'+html_cont+'</div>\
								<input type="button" value="&nbsp;" id="alert_ok" onclick="facebox_close();">\
			<!--[if lte IE 7]></td></tr></table><![endif]-->\
			</div></div>')
	var facebox_overlay = document.getElementById("facebox_overlay"), facebox_el = document.getElementById("facebox")
	left_pos = (facebox_overlay.offsetWidth - facebox_el.offsetWidth)/2
	top_pos = (facebox_overlay.offsetHeight - facebox_el.offsetHeight)/ 2 - 25
	$(facebox_overlay).animate({"opacity":"0.4"},1000)
	$(facebox_el).animate({"opacity":"1","top":top_pos,"left":left_pos},1000, function(){
			if(ie8){
			 var settings = {
					tl: { radius: 15 },
					tr: { radius: 15 },
					bl: { radius: 15 },
					br: { radius: 15 },
					antiAlias: true
				} 
				curvyCorners(settings, this)
			}
		})
	$(facebox_loading).animate({"opacity":"0"},1000, function(){
		$(this).remove()
	})
	$(facebox_el).draggable({
		cursor: 'crosshair',
		cancel: ':input, option, span, small, img, p, label, ul, ol',
		containment:'parent',
		addClasses: false
	})
	facebox_active = 2
}

//Берем позицию у элемента, для фокуса и стрелки.
get_position = function()
{
	destination = $(el_focus).offset().top;
	destination_left = $(el_focus).offset().left;
	window_pos = $(window).scrollTop();
	posminus = window_pos - destination;
}

arrow = function(){
	var obj = document.createElement("div")
	obj.className = "alert_arrow"
	obj.style.left = destination_left-70+"px"
	obj.style.top = destination-5+"px"
	body_tag.appendChild(obj)
	for(var i=0;i<5;i++){
		$(obj).animate({"left":"+=30"}, "linear").animate({"left":"-=30"}, "linear")
	}
	$(obj).animate({"opacity":0,"left":"+=30"}, 500, "linear", function(){
				obj.parentNode.removeChild(obj)
		})
}

//Фокус
facebox_focus = function(element_focus)
{
	el_focus = element_focus || null
	if(el_focus != null){
		get_position();
		if ((window_pos > destination) || ((window_pos < destination) && posminus < -400)){
				$(anim_obj).animate({scrollTop: destination-250}, 900, function(){
				$(el_focus).focus();
			});
		}else{
		$(el_focus).focus()
		}
		arrow()
	}
}

$.fn.facebox_focus = function(){
facebox_focus(this)
}

facebox_resize = function(){
	if(facebox_active == 2){
			left_pos = ($(window).width() - $("#facebox").width())/2,
			top_pos = ($(window).height() - $('#facebox').height()) / 2 - 50;
			$("#facebox").dequeue().animate({"left":left_pos, "top": top_pos}, "slow", "easeOutBack");
		}
}

facebox_resize_textarea = function(){

		$("#facebox").find("textarea").hover(function(){
			textarea_resize = true
			}, function(){
			textarea_resize = false
			}
		)
		$("#facebox").find("textarea").mouseup(function(){
			if(textarea_resize){
				facebox_resize()
			}
		})
}

//Красивый Алерт
facebox_alert = function(el_text, end_check)
{
	if (end_check == "end" || end_check == null){
	el_focus = null
	} else {
	el_focus = end_check
	};
	facebox_load("<h3 class='alert'>"+el_text+"</h3>");
	$("#facebox").addClass("alert_mes");
	window.setTimeout(function() {
		$("#alert_ok").focus();}, 1500);
}
//Загрузка Аяксом
$.fn.facebox = function()
{
		$(this).click(function(){
			el_focus = null
			var url_load = this.getAttribute("href"), grid_href = url_load.indexOf("#")
			//Если ссылка на страницу, грузим аяксом
			if(grid_href<0){
				var loading_image = new Image()
				loading_image.id = "facebox_loading"
				loading_image.src = "/images/design/lightbox_green/loading.gif"
				$.ajax({
					url: url_load,
					beforeSend: function(){
						body_tag.appendChild(loading_image)
					},
					error:function(){
						facebox_alert("Ошибка, не удается загрузить страницу")
					},
					success: function(html){
						facebox_load(html, loading_image)
						}
					})
			} else {//Если контент находиться на странице href="#id"
				url_load = url_load.substr(grid_href+1)
				var url_load_anchor = document.getElementById(url_load)
				facebox_load(url_load_anchor ? url_load_anchor.innerHTML : "Ошибка, блок с id=\""+url_load+"\" не найден")
			}
			return false
		})
}

//Кешируем элементы в шапке
var header_pic_array = [], header_contats;
function header_cache(){
	for(var i=0;i<15;i++){
		header_pic_array[i] = document.getElementById("blur_back"+i)
	}
}

//Размытие в шапке
function header_blur(){
	for(var blur_pic_width=-header_contats.offsetLeft, i=0,i2=5,i3=10;i<5;i++,i2++,i3++){
		header_pic_array[i].style.left = blur_pic_width+i+"px"
		header_pic_array[i].style.top = header_pic_array[i3].style.top = i+"px"
		header_pic_array[i2].style.left = blur_pic_width-i+"px"
		header_pic_array[i2].style.top = -i+"px"
		header_pic_array[i3].style.left = blur_pic_width+"px"
	}
}

$(document).keydown(function(e){
		 if(e.keyCode == 27){
						facebox_close()
					}
	 })


jQuery(function($){
	$.datepicker.regional['ru'] = {
		closeText: 'Закрыть',
		prevText: '&#x3c;Пред',
		nextText: 'След&#x3e;',
		currentText: 'Сегодня',
		monthNames: ['Январь','Февраль','Март','Апрель','Май','Июнь',
		'Июль','Август','Сентябрь','Октябрь','Ноябрь','Декабрь'],
		monthNamesShort: ['Янв','Фев','Мар','Апр','Май','Июн',
		'Июл','Авг','Сен','Окт','Ноя','Дек'],
		dayNames: ['воскресенье','понедельник','вторник','среда','четверг','пятница','суббота'],
		dayNamesShort: ['вск','пнд','втр','срд','чтв','птн','сбт'],
		dayNamesMin: ['Вс','Пн','Вт','Ср','Чт','Пт','Сб'],
		weekHeader: 'Не',
		dateFormat: 'yy-mm-dd',
		firstDay: 1,
		isRTL: false,
		showMonthAfterYear: false,
		yearSuffix: ''};
	$.datepicker.setDefaults($.datepicker.regional['ru'])
})

//Баннеры
banner_animate = function(el, items){
	$(items[0]).css("opacity","0").animate({"opacity":"1"},1500)
	el.appendChild(items[0])
}

function top_banners(){
	var small_screen = false,
			layout = document.getElementById("layout").getElementsByTagName("header")[0],
			right_block = document.getElementById("ban_right"),
			left_block = document.getElementById("ban_left"),
			ban_left = document.getElementById("ban_left_blocks"),
			//Запоминаем самую крайнюю позицию справа
			right_edge = layout.offsetWidth-right_block.offsetLeft-right_block.offsetWidth,
			left_edge = layout.offsetWidth-left_block.offsetLeft-left_block.offsetWidth,
			width = left_block.offsetWidth+(left_edge-right_edge-16),
			class_test = /\bnot_open\b/
	function banners_position(header_width){
		if(!small_screen && header_width<1120){
			small_screen = true
			var params = class_test.test(left_block.className) ? {"right":right_edge,"top":20} : {"right":right_edge-60,"width":right_block.offsetWidth+44,"height":250,"top":20}
			$(left_block).animate(params, 600, function(){
				$(right_block).animate({"top":160}, 600)
			})
		} else if(small_screen && header_width>=1120){
			small_screen = false
			var params = class_test.test(left_block.className)?{"right":left_edge,"top":95}:{"right":right_edge,"width":width,"height":190,"top":95}
			$(left_block).animate(params, 600, function(){
				$(right_block).animate({"top":95}, 600)
			})
		}
	}
		banners_position(layout.offsetWidth)
		$(window).resize(function(){
			banners_position(layout.offsetWidth)
		})
		$("#header_banners").css("visibility","visible").animate({"opacity":"1"},1000, function(){
			var ban_right = document.getElementById("ban_right_blocks"),
					ban_right_pics = ban_right.getElementsByTagName("span"),
					ban_left_pics = ban_left.getElementsByTagName("span"),
					banners_animate = setInterval(function(){
						banner_animate(ban_right, ban_right_pics)
						banner_animate(ban_left, ban_left_pics)
					}, 3000)
			$(left_block).click(function(){
				if(class_test.test(this.className)){
					clearInterval(banners_animate)
					var params = small_screen ? {"width":"+=60","height":250,"right":right_edge-60} : {"width":width,"height":190,"right":right_edge}
					$("#ban_left_text").show()
					$(this).removeClass("not_open").animate(params, 500)
					ban_left.style.display = "none"
				}
			})
			$("#ban_left_close").click(function(event){
				stopBubble(event)
				var params = {"width":ban_right.offsetWidth,"height":114}
				params["right"] = small_screen ? right_edge : left_edge
				$(ban_left).fadeIn(500)
				$(left_block).addClass("not_open").animate(params, 500, function(){
					$("#ban_left_text").hide()
					left_block.style.right = small_screen ? right_edge+"px" : left_edge+"px"
					this.style.left="auto"
				})
				banners_animate = setInterval(function(){
						banner_animate(ban_right, ban_right_pics)
						banner_animate(ban_left, ban_left_pics)
					}, 3000)
			})
		})
}

/*
function show_tips(event, data){
		var content = document.getElementById(data), content_fly = document.getElementById(data+"_fly")
		if(!el || content_fly)return
		var tip_block = document.createElement("div")
		tip_block.id = data+"_fly"
		tip_block.className = "tips_mes"
		tip_block.style.left = event.clientX+(document.documentElement.scrollLeft || body_tag.scrollLeft)+"px"
		tip_block.style.top = event.clientY+(document.documentElement.scrollTop || body_tag.scrollTop)+"px"
		tip_block.innerHTML = tip_block_cont.innerHTML
		body_tag.appendChild(tip_block)
		$(tip_block).animate({"opacity":1}, "slow")
	}
function close_tips(block){
		if(block && block.getAttribute("data-attach") == null)
		body_tag.removeChild(block)
	}
	*/
$(function(){
	body_tag = document.body
	//setTimeout(top_banners, 1500)
	;(function(){
		var ban_right = $(".ban_title","#ban_right")[0]
		if(ban_right){
			setInterval(function(){
				ban_right.innerHTML = ban_right.innerHTML == "Горящий тур" ? "3-5 февраля" : "Горящий тур"
			}, 2500)
		}
	})()
	
	
	//Для фейсбокса
	$(window).resize(function(){
		facebox_resize()
		header_blur()
	})
	$("a:facebox").facebox()
	$("a:anchor").click(function(){
    var this_href = this.getAttribute("href"), grid_href = this_href.indexOf("#")+1
		this_href = this_href.substr(grid_href)
		el_focus = document.getElementById(this_href) || document.anchors[this_href]
    if(el_focus){
			get_position()
			$(anim_obj).animate({scrollTop: destination-100}, 1500 )
			arrow()
		}
    return false
  });
	/*
	$(".show_title[data-mes]").click(function(event){
		show_tips(event, this.getAttribute("data-mes"))
		return false
	});
	*/
	(function(){
		var left_block = document.getElementById("left_block"), window_height = document.getElementById("window_meter").offsetHeight, layout_height = document.getElementById("layout").offsetHeight
		//Подвал внизу
		if(layout_height-123 < window_height){
			left_block.style.height = window_height-471+"px"
		}
	})();
	//Размытие
	var pic_url = $("header:first").css("background-image").replace(/"|'/g,'').replace("url(","").replace(")","")
	header_contats = document.getElementById("header_contats")
	for(var i=0;i<15;i++){
		var new_img = new Image()
		new_img.src = pic_url
		new_img.id = "blur_back"+i
		header_contats.appendChild(new_img)
	}
	header_cache()
	header_blur()
	$("#content").find(".slider_link").click(function(){
		$(this).toggleClass("slider_link_active").parent().next().toggle("slow").next(".slider_preview").toggle("slow")
		return false
	})
	$(".link_blank").click(function(){
		return !window.open(this.href)
	})
	$(".new_year_tabs").each(function(){
		var block = this, menu = $(block).children(), tabs_contents = $(block).children(".tabs_contents").children()
		menu = $(menu[0]).children()
		menu.each(function(index, item){
			$("strong", item).click(function(){
				if(!/\btab_active\b/.test(item.className)){
					menu.removeClass("tab_active tab_active_sibling")
					$(item).addClass("tab_active").prev().addClass("tab_active_sibling")
					$(tabs_contents).hide("slow").eq(index).show("slow")
				}
			})
		})
		if(!("opacity" in document.createElement("div").style)){
			$(block).append("<i class='article_corner clb'></i><i class='article_corner crb'></i>")
			$(menu).children().append("<i class='article_corner clt'></i><i class='article_corner crt'></i>")
		}
	})

	$(".blink").each(function(){
			var blick_block = this.style
			setInterval(function(){
				blick_block.visibility = blick_block.visibility == "visible"? "hidden": "visible"
			}, 600)
	})
	;(function(){
		var events_block = document.getElementById("events"), events = $(events_block).children("div")
		if(events_block){
			for(var i=events.length;--i>=0;){
					if(i%2!=0)events[i].style.cssFloat = events[i].style.styleFloat = "right"
				}
			function styleHeight(){
				for(var i=events.length;--i>=0;){
					events[i].style.height = ""
				}
				for(var i=events.length;--i>=0;){
					if(i%2!=0)continue
					var el=events[i], next = $(el).next("div")[0]
					if(next){
						var height = [el.offsetHeight,next.offsetHeight]
						el.style.height = next.style.height = height[0]>height[1] ?  height[0]+"px" : height[1]+"px"
					}
				}
			}
			setTimeout(styleHeight, 100)
			$(window).resize(function(){
				styleHeight()
			})
		}
		
	})();
			$('#subscribe').submit(function(){
				var reg = /^[\w_-а-яё\.]+@[\w_-а-яё\.]{2,}\.[\w_-а-яё]{2,}\.?$/i
				var email = this.email
				if (!reg.test(email.value)) {
					alert('Введен неверный e-mail')
					email.focus()
					return false
				}
				$.post(this.action, { 'email': email.value, check_spam: 'nospam95' }, function(data){
					alert(data ? 'E-mail добавлен!' : 'E-mail не добавлен')
				}, 'json')
				return false
			})  
	if(ie8){
				 var r = 4;
				 var settings = {
						tl:{radius:r},
						tr:{radius:r},
						bl:{radius:r},
						br:{radius:r},
						antiAlias: true
					} 
					$("#top_menu li").each(function(){
					curvyCorners(settings, this)
					})
				}
})


//firefox 3.0. :before, :after fix
if($.browser.mozilla && $.browser.version.substr(0,5) == "1.9.0"){
	$(function(){
		$(body_tag).addClass("ff3");
		}
	)
}
})()
