/* JQuery common file, Kirill Aristov, upd 0:03 11.07.2011 */
// charset utf-8

$(function() {
	new Image().src = '/theme/mine/loading.png';
	body = $("body");
	overlay = $('<div id="overlay"></div>').appendTo(body);
	loadingDiv = $('<div id="loading"></div>').appendTo(body);

// Тултип ------------------------------
$.fn.easyTooltip = function(options){
	var defaults = {xOffset:10,yOffset:25}; 
	var options = $.extend(defaults, options);  
	var content;
	this.each(function() {
		$(this).attr('tooltip', $(this).attr('title'));
		$(this).removeAttr('title');
		$(this).bind("mouseover", function(e) {
				content = $(this).attr('tooltip');
				if (content != "" && content != undefined){			
					$("body").append('<div id="tooltip">' + content + '</div>');		
					$("#tooltip")
						.css("top",(e.pageY - options.yOffset) + "px")
						.css("left",(e.pageX + options.xOffset) + "px")						
						.css("display","none")
						.fadeIn("fast");}});
		$(this).bind("mouseout", function(){
				$("#tooltip").remove();
		});
			
		$(this).bind("mousemove", function(e){
			$("#tooltip")
				.css("top", (e.pageY - options.yOffset) + "px")
				.css("left", (e.pageX + options.xOffset) + "px")
				.css("z-index","2000")
		});	
	});
};



	// Карусель --------------------------------------------------------
$.fn.jCarouselLite = function(o) {
	o = $.extend({mouseWheel:true,speed:300,circular:true,visible:15,start:0,scroll:2}, o || {});
	return $(this).each(function() {
		var running = false,
			animCss="left",
			sizeCss="width";
		var div = $(this),
			ul = div.children('ul'),
			tLi = ul.children('li'),
			tl = tLi.length,
			v = o.visible;

	if (tLi.width()*tl > $(window).width()) {
			ul.prepend(tLi.slice(tl - v - 1 + 1).clone(true))
			  .append(tLi.slice(0, v).clone(true));
			o.start += v;
		
		var li = $("li", ul),
			itemLength = li.size(),
			curr = o.start;
		var liSize = width(li);
		var ulSize = liSize * itemLength;
		var divSize = liSize * v;
		li.css({width: li.width(), height: li.height()});
		ul.css(sizeCss, ulSize + "px").css(animCss, - (curr*liSize));
		var hover_and_rotate = 0;
		div.hover(
			function () {
				if (hover_and_rotate == 0) {
					hover_and_rotate = 1;
					return go(curr - 1);
					}
				},
			 function () {}
		);
		if(o.mouseWheel && div.mousewheel) {
			div.mousewheel(function(event, delta) {
				event.preventDefault();
				return delta > 0 ? go(curr - o.scroll) : go(curr + o.scroll);
			});
			}
		function vis() {
			return li.slice(curr).slice(0,v);
		};
		function go(to) {
			if(!running) {
				if(o.beforeStart)
					o.beforeStart.call(this, vis());
				if(o.circular) {
					if(to<=o.start - v - 1) {
						ul.css(animCss, - ((itemLength - (v * 2)) * liSize) + "px");
						curr = to == o.start - v - 1 ? itemLength - (v * 2) - 1 : itemLength-(v * 2) - o.scroll;
					} else if(to >= itemLength - v + 1) {
						ul.css(animCss, - ((v) * liSize ) + "px");
						curr = to == itemLength - v + 1 ? v + 1 : v + o.scroll;
					} else curr = to;
				} else {
					if(to < 0 || to > itemLength - v) return;
					else curr = to;
				}
				running = true;
				ul.animate(
					animCss == "left" ? { left: - (curr * liSize) } : { top: - (curr * liSize) } , o.speed, o.easing,
					function() {
						if(o.afterEnd) o.afterEnd.call(this, vis());
						running = false;
					}
				);
			}
			return false;
		};
		}
	});
function width(el) {return  el[0].offsetWidth + css(el, 'marginLeft') + css(el, 'marginRight');};
function css(el, prop) {return parseInt($.css(el[0], prop)) || 0;};
};

// Анимация загрузки
var loadingInterval;
function loading (state) {
	top2 = 0;
	clearInterval(loadingInterval);
	if (state == 'show') {
		loadingDiv.show();
		loadingInterval = setInterval(function () {
			top2 -= 40;
			loadingDiv.css('background-position', '0 ' + top2 + 'px');
			if (top2 == - 40 * 11) top2 = 0;
		}, 100);}
	if (state == 'hide') {
		clearInterval(loadingInterval);
		top2 = 0;
		loadingDiv.hide();
	}
	loadingDiv.click(function () {$(this).hide();});
};

// Всплывающие изображения
// old version
/*$.fn.popImage = function () {
	$(this).bind('click', function(event) {
		event.preventDefault();
		loading('show');
		var src = $(this).attr('href');
		aloneImageContainer = $('<div class="alone-image-container"></div>').appendTo(body);
		overlay.show();
		$("<img />").attr({'src' : src}).appendTo(aloneImageContainer);
		
		var imgW,imgH;
		
		$.ajax({
			url: '/theme/mine/dimensions.php?file=' + src,
			success: function(data) {
				var imgSizes = /w(\d+)h(\d+)/.exec(data);
				imgW = imgSizes[1];
				imgH = imgSizes[2];
				pos();
				aloneImageContainer.show();
			}
		});
		
		aloneImageContainer.children('img').load(function () {
			loading('hide');
		});

		if ($(this).children('img').attr('alt')) {
			var title = $(this).children('img').attr('alt');
			$('<div class="alone-image-title">').text(title).appendTo(aloneImageContainer);
		}
		else if ($(this).attr('tooltip') && ($(this).children('img').length == 0)) {
			var title = $(this).attr('tooltip');
			$('<div class="alone-image-title">').text(title).appendTo(aloneImageContainer);
		}
		
		function pos () {
			var border = 20;

			var winW = $(window).width();
			var winH = $(window).height();
			var maxW = winW - border*2;
			var maxH = winH - border*2;

			var left,top;
			
			if ((imgH > maxH) || (imgW > maxW))
				if (maxH/maxW < imgH/imgW)
					{top = border;
					var imgWidthNew = parseInt(imgW/(imgH/maxH));
					left = parseInt((winW - imgWidthNew)/2);
					aloneImageContainer.children('img').css({'height':maxH+'px', 'width':imgWidthNew+'px'});}
				else
					{left = border;
					var imgHeightNew = parseInt(imgH/(imgW/maxW));
					top = parseInt((winH - imgHeightNew)/2);
					aloneImageContainer.children('img').css({'height':imgHeightNew+'px', 'width':maxW+'px'});}
			else
				{top = parseInt((winH - imgH)/2);
				left = parseInt((winW - imgW)/2);
				aloneImageContainer.children('img').css({'height':imgH+'px', 'width':imgW+'px'});}

			aloneImageContainer.css({'top':top+'px', 'left':left+'px'});
		}
		$(window).resize(function () {pos();});
	});
};*/

// !!!new version!!!
// ------------------------------------- photos vidget ---------------------------------
	// всплывающие изображения для альбома фотографий
	var imgClass = '.aloneimage';
	$.fn.jpopimg = function () {
		$(this).live('click', function(event) {
			event.preventDefault();
			loading('show');
			//alert ($(imgClass).index($(this)));
			currPos = $(imgClass).index($(this));
			showImg(currPos);
		});
	};
	
	var nextjpopimage = '';
	var slideInterval = 'undefined';

	function showImg (pos) {
		currPos = pos;
		if ($('#jpopimgcontainer').length == 0)
			var jpopimgcontainer = $('<div id="jpopimgcontainer"><h1 id="img-title" /><div id="slide-and-counter"><div id="img-counter" /><div id="slideshow" tooltip="click or press spacebar (5sec delay)" /></div></div>')
			.appendTo(body);
		else {
			jpopimgcontainer = $('#jpopimgcontainer');
			jpopimgcontainer.children('.theimage').remove();
		}
		
		if ($('#jpopimgcontainer').is(':visible')) {
			document.title = document.title.replace(/^[^|]+\|\s(.*)$/, "$1");
		}
			
		var currImgUrl = $(imgClass).eq(pos).attr('href');
		var nextImgUrl = $(imgClass).eq(nextPos(pos)).attr('href');
		//var currImgSrc = $(imgClass).eq(pos).children('img').attr('src').replace('/tn_','/');
		//var nextImgSrc = $(imgClass).eq(nextPos(pos)).children('img').attr('src').replace('/tn_','/');

		if ($(imgClass).eq(pos).children('img').attr('alt')) {
			var currImgAlt = $(imgClass).eq(pos).children('img').attr('alt');
			$('#img-title').removeClass('empty');
			var currImgTitle = currImgAlt
		}
		else {
			var currImgAlt = 'Фото ' + (pos + 1);
			$('#img-title').addClass('empty');
			var currImgTitle = '';
		}
		$('#img-title').text(currImgTitle);
		
		
		document.title = currImgAlt + ' | ' + document.title;

// -------------
		function getImagePlusDimensions (currImgUrl) {
				$.ajax({
				url: '/theme/mine/dimensions.php?file=' + currImgUrl,
				success: function(data) {
					var imgSizes = /w(\d+)h(\d+)/.exec(data);
					var imgW = imgSizes[1];
					var imgH = imgSizes[2];
					$('<img class="theimage"/>').attr({'src':currImgUrl, 'width':imgW, 'height':imgH}).insertAfter(jpopimgcontainer.children('h1'));
					//return creatingImg;
				}
			});
		}
// -------------
		
		
		//если изображение в кеше
		if (nextjpopimage.length != 0 && nextjpopimage.attr('src') == currImgUrl) {
			nextjpopimage.insertAfter(jpopimgcontainer.children('h1'));
			//$('<img class="theimage" style="display:none;" />').attr('src', nextImgUrl);
			doingAfterLoad();
			}
		//если нет в кеше, первая загрузка
		else {
			$.ajax({
				url: '/theme/mine/dimensions.php?file=' + currImgUrl,
				success: function(data) {
					var imgSizes = /w(\d+)h(\d+)/.exec(data);
					var imgW = imgSizes[1];
					var imgH = imgSizes[2];
					$('<img class="theimage"/>').attr({'src':currImgUrl, 'width':imgW, 'height':imgH}).insertAfter(jpopimgcontainer.children('h1'));
					doingAfterLoad()
				}
			});
		}
		
		function doingAfterLoad() {
			jpopimgcontainer.placing();
			$('.theimage').load(function () {
				loading('hide');
			});
			$.ajax({
				url: '/theme/mine/dimensions.php?file=' + nextImgUrl,
				success: function(data) {
					var imgSizes = /w(\d+)h(\d+)/.exec(data);
					var imgW = imgSizes[1];
					var imgH = imgSizes[2];
					nextjpopimage = $('<img class="theimage"/>').attr({'src':nextImgUrl, 'width':imgW, 'height':imgH});
				}
			});
		}
		
		overlay.show();
		
		if (slideInterval == 'undefined') slideText = 'slideshow –';
		else slideText = 'slideshow +';
		$('#slideshow').text(slideText);
		$('#img-counter').text(pos + 1 + '/' + $(imgClass).length);
		
		jpopimgcontainer.show();
	}

	function nextPos (val) {
		if (val != $(imgClass).length -1) val++;
		else val = 0;
		return val;
	}
	function prevPos (val) {
		if (val != 0) val--;
		else val =  $(imgClass).length - 1;
		return val;
	}

	$.fn.placing = function () {
			overlay.show();
			var border = 20;
			var winW = $(window).width();
			var winH = $(window).height();
			var maxW = winW - border*2;
			var maxH = winH - border*2;
			var imgW = $(this).children('img').attr('width');
			var imgH = $(this).children('img').attr('height');
			//alert (imgW);
			//alert (imgH);
			var left,top;
			
			if ((imgH > maxH) || (imgW > maxW))
				if (maxH/maxW < imgH/imgW)
					{top = border;
					var imgWidthNew = parseInt(imgW/(imgH/maxH));
					left = parseInt((winW - imgWidthNew)/2);
					$(this).children('img').css({'height':maxH+'px', 'width':imgWidthNew+'px'});}
				else
					{left = border;
					var imgHeightNew = parseInt(imgH/(imgW/maxW));
					top = parseInt((winH - imgHeightNew)/2);
					$(this).children('img').css({'height':imgHeightNew+'px', 'width':maxW+'px'});}
			else
				{top = parseInt((winH - imgH)/2);
				left = parseInt((winW - imgW)/2);
				$(this).children('img').css({'height':imgH+'px', 'width':imgW+'px'});}

			$(this).css({'top':top+'px', 'left':left+'px'});
	};
	
	//позиционирование фотогрфии при изменении размеров окна
	$(window).resize(function () {
		if ($('#jpopimgcontainer').is(':visible')) $('#jpopimgcontainer').placing();
	});
	
	//влево-вправо с клавиатуры
	$(document).bind('keydown', function(e) {
		if ($('#jpopimgcontainer').is(':visible')) {
			if (e.keyCode == 37) {e.preventDefault(); showImg(prevPos(currPos));} //влево
			else if (e.keyCode == 39) {e.preventDefault(); showImg(nextPos(currPos));}//вправо
		}
	});
	
	//slideshow
	$(document).bind('keydown', function(e) {
		if (e.keyCode == 32 && $('#jpopimgcontainer').is(':visible')) { // 32 - spacebar
			e.preventDefault();
			slideshow();
		}
	});
	$('#slideshow').live('click', function (e) {
		slideshow();
	});
	
	var slideInterval = 'undefined';
	function slideshow () {
		if (slideInterval == 'undefined') {
			$('#slideshow').text('slideshow +');
			
			setTimeout(function() {
				slideInterval = 'bla-bla :-)';
				showImg(nextPos(currPos));
				slideInterval = setInterval(function() {
					showImg(nextPos(currPos));
				}, 5000);
			}, 500);
		}
		else {
			clearInterval(slideInterval);
			slideInterval = 'undefined';
			$('#slideshow').text('slideshow –');
		}
	}
	
	
// ---------------------------------------  end photos vidget -----------------------------

// По клику на оверлее всё открытое скрыть
overlay.bind('click', function () {
	if ($('#modalwindow').length != 0 && $('.alone-image-container').length != 0) {
		$('#jpopimgcontainer').hide();
		loading('hide');}
	else {
		overlay.hide();
		document.title = document.title.replace(/^[^|]+\|\s(.*)$/, "$1");
		$('#jpopimgcontainer').hide();
		clearInterval(loadingInterval); //анимация загрузки
		clearInterval(slideInterval); //slideshow
		slideInterval = 'undefined';
		loading('hide');
		$(".modal-window-open").hide();
		$('#modalwindow').remove();

	}
});

// По клавише Esc всё открытое скрыть
$(document).bind('keydown', function(e) {
	if (e.keyCode == 27) {
		if ($('#modalwindow').length != 0 && $('.alone-image-container').length != 0) {
			$('#jpopimgcontainer').hide();
			loading('hide');}
		else {
			overlay.hide();
			document.title = document.title.replace(/^[^|]+\|\s(.*)$/, "$1");
			$('#jpopimgcontainer').hide();
			clearInterval(loadingInterval); //анимация загрузки
			clearInterval(slideInterval); //slideshow
			slideInterval = 'undefined';
			loading('hide');
			$(".modal-window-open").hide();
			$('#modalwindow').remove();

		}
	}
});

// -------------------------------------------------------------------------------

// инициализация карусели
	$(".carousel").jCarouselLite();
	
// добавление тултипа
	$("*[title]:not(.value)").easyTooltip();
	
// всплывающие изображения
	$('a.aloneimage').jpopimg();

// открытие форм
	$(".form").click(function (event) {
		event.preventDefault();
		overlay.show();
		//$('body').css('overflow','hidden');
		var formHandler = $('#form-' + $(this).children('.value').attr('title'));
		formHandler.show().addClass('modal-window-open');
		
		formPlacing();
		
		function formPlacing () {
			formHandler.css('margin-top', 0 - formHandler.outerHeight()/2 + 'px');
		}
		
		$(window).resize(function() {formPlacing();});
		
		
		
		
	});

// внешние ссылки в новом окне
	$('.external').each(function() {
		$(this).attr("target", "_blank");
	});
	
// перещёлкивание с кол-ва подписчиков на поясняющую надпись
	$("#w-subscribe").hover(
		function() {
			var height = $(this).children('div').height();
			$(this).children('span').css('visibility', 'hidden');
			$(this).children('div').css({'visibility' : 'visible', 'line-height' : height + 'px'});
		},
		function(){
			$(this).children('div').css('visibility', 'hidden');
			$(this).children('span').css('visibility', 'visible');
		}
	);

// обработка событий формы подписки
	$("#form-w-subscribe").submit(function() {
		if ($("#form-w-subscribe .name").val().length < 2 || $("#form-w-subscribe .email").val().length < 8 || $("#form-w-subscribe .website").val().length < 8) {
			if ($("#form-w-subscribe .name").val().length < 2) {
				$("#form-w-subscribe .name").addClass('error');
			}
			else $("#form-w-subscribe .name").removeClass('error');
			
			if ($("#form-w-subscribe .email").val().length < 8) {
				$("#form-w-subscribe .email").addClass('error');
			}
			else $("#form-w-subscribe .email").removeClass('error');
			
			if ($("#form-w-subscribe .website").val().length < 8) {
				$("#form-w-subscribe .website").addClass('error');
			}
			else $("#form-w-subscribe .website").removeClass('error');
			
			return false;
		}
		else {
			$("#form-w-subscribe .name").removeClass('error');
			$("#form-w-subscribe .email").removeClass('error');
			$("#form-w-subscribe .website").removeClass('error');
			$("#form-w-subscribe :submit").attr("disabled","disabled"); //блокировка формы при отправке
			loading('show');
			$.ajax({
				type	: "POST",
				cache	: false,
				url		: "/interactive/subscribe.php",
				data	: $(this).serializeArray(),
				success: function() {
					loading('hide');
					alert('Successfully! Your confirmation link has been sent to your email');
					$(".modal-window-open").hide();
					overlay.hide();
				}
			});
		}
	return false;
	});
	
// обработка событий формы сообщения
	$("#form-w-message").bind("submit", function() {
		if ($("#form-w-message .name").val().length < 2 || $("#form-w-message .email").val().length < 8 || $("#message").val().length < 15) {
			if ($("#form-w-message .name").val().length < 2) {
				$("#form-w-message .name").addClass('error');
			}
			else $("#form-w-message .name").removeClass('error');
			
			if ($("#form-w-message .email").val().length < 8) {
				$("#form-w-message .email").addClass('error');
			}
			else $("#form-w-message .email").removeClass('error');
			
			if ($("#message").val().length < 15) {
				$("#message").addClass('error');
			}
			else $("#message").removeClass('error');

			return false;
		}
		else {

			$("#form-w-message .name").removeClass('error');
			$("#form-w-message .email").removeClass('error');
			$("#message").removeClass('error');
			$("#form-w-message input:submit").attr("disabled","disabled"); //блокировка формы при отправке
			loading('show');
			$.ajax({
				type	: "POST",
				cache	: false,
				url		: "/interactive/message.php",
				data	: $(this).serializeArray(),
				success: function() {
					loading('hide');
					alert ('Succesfully! Wait for the reply to email');
					$(".modal-window-open").hide();
					overlay.hide();
				}
			});
		}
	return false;
	});
	
// при клике на rss в форме подписки и заполненных полях - подтверждение ухода
	$('#form-w-subscribe a').click(function () {
	if ($('#form-w-subscribe .email').val().length > 0 || $('#form-w-subscribe .website').val().length > 0 || $('#form-w-subscribe .name').val().length > 0) {
		if (!(confirm('Want to get away from this page?'))) return false;}
	});

//перелистывание избранных записей дневника
	var favnext = 1;
	$('#fav-changer').click(function () {
		$('#fav-changer').html('● следующие 5');
		$('#fav-block').fadeTo(250, 0.1, function() {
			$('#fav-block').html($('#fav' + favnext).html());
		});
		$('#fav-block').fadeTo(250,1);
		favnext++;
		if ($('#fav' + favnext).length == 0) {
			favnext = 0;
			$('#fav-changer').html('» заново');
		}
	});

//история статуса
	$("#hidden_status_trigger").click(function () {
		$("#hidden_status").slideToggle('slow');
		if ($("#hidden_status_trigger").attr('tooltip') != 'hide') {
			$("#hidden_status_trigger").attr('tooltip', 'show');
			$('#tooltip').text('hide'); }
		else {
			$("#hidden_status_trigger").attr('tooltip', 'show history');
			$('#tooltip').text('show history'); }
	});

//перелистывание записей из Лена 2011-2012
	$('.blog-pages').click(function (event) {
		event.preventDefault();
		$('.blog-pages').css('background-color','#fff');
		$(this).css('background-color','#ccc');
		$.get("/blog/returnpages.php?page=" + $(this).children('.value').attr('title'), function(data) {
			$("#allmessages03").html(data);
			$("*[title]:not(.value)").easyTooltip();
			// внешние ссылки в новом окне
			$('.external').each(function() {
				$(this).attr("target", "_blank");
			});
			// всплывающие изображения
			$('a.aloneimage').popImage();
		});
	});
	//прелоадер при загрузке новых страниц с сообщениями
	$('#allmessages03').ajaxStart(function() {
		loading('show');
		}).ajaxStop(function() {
			loading('hide');
	});

//обновление лого-картинки
	var logoImageLen = $(".logoimage").length;
	var logoImagePosition = 0;
	var logoImageChangerStopped = "true";
	for (var j = 0; j <= logoImageLen; j++) {
		var i = logoImageLen - j;
		$(".logoimage").eq(j).css({"z-index":i});
	}
	function logoImageChanger () {
		function changerBody () {
			$(".logoimage").eq(logoImagePosition).animate({opacity:'hide'},1500, function () {
				$(".logoimage").each(function () {
					var index = $(this).css("z-index"); index = index * 1;
					if (index + 1 <= logoImageLen) {index++;}
					else {index = 1;}
					$(this).css({"z-index":index});
				});
			});
			if (logoImagePosition < logoImageLen - 1) logoImagePosition++;
			else logoImagePosition = 0;
			$(".logoimage").eq(logoImagePosition).css({"display":"block"});
		}
		setTimeout(function () {changerBody();}, 100);
		logoImageChangerInterval = setInterval(function () {changerBody();}, 4000);
	}
	$("#logo span").click(function () {
		$("#logo span").toggleClass("hover");
		if (logoImageChangerStopped == "true") {
			logoImageChangerStopped = "false";
			logoImageChanger();
		}
		else {
			logoImageChangerStopped = "true";
			clearInterval(logoImageChangerInterval);
		}
	});
	
//всплывающие изображения из карусели
	/*var position1;
	function popImageNextPosition (position1) {
		if (position1 != $(".carousel li").length -1) position1++;
		else position1 = 0;
		return position1;
	}
	function popImagePrevPosition (position1) {
		if (position1 != 0) position1--;
		else position1 =  $(".carousel li").length - 1;
		return position1;
	}
	$(document).bind('keydown', function(e) {
		if (e.keyCode == 37 && $(".popimage-container").length > 0 && $('#new-title').length == 0) {
			position1 = popImagePrevPosition(position1)
			showImageFromCarousel(position1);
			 }
		else if (e.keyCode == 39 && $(".popimage-container").length > 0 && $('#new-title').length == 0) {
			position1 = popImageNextPosition(position1);
			showImageFromCarousel(position1);
			}
	});
	$('.popimage-container').live('click', function () { $(this).remove(); });
	function showImageFromCarousel(position1) {
		loading('show');
		var title = $('.carousel li:eq(' + position1 + ') a img').attr('alt');
		var src = $('.carousel li:eq(' + position1 + ') a').attr('href');
		container = $('<div class="popimage-container"></div>').appendTo(body);
		$("<img />").attr({'src':src}).appendTo(container);
		
		function temp500() {
			$(".popimage-container img").css('max-width', $('.carousel').width() - 15 + 'px');}
		temp500();
		$(window).resize(function () {temp500();});
		
		$(".popimage-container img").load(function () {
			if (title.length > 0)
				$('<div class="popimage-title">').text(title).appendTo(container);
			loading('hide');
		});
		if ($(".popimage-container").length > 1)
			$(".popimage-container:first").remove();
		var uploadImage = new Image();
		var newpos = popImageNextPosition(position1);
		uploadImage.src = $('.carousel li:eq(' + newpos + ') a').attr('href');
	}
	$(".carousel li").live('click', function () {
		position1 = $(this).index();
		showImageFromCarousel(position1);
		return false;
	});*/
	
// управление колонкой с записями из дневника для страниц экспедиций
	$.fn.favtripposition = function () {
		var text1 = 'move to the end';
		var text2 = 'move to the top';
		var text3 = 'unfold';
		var name = $(this).children('h2').text();
		
		var column = $(this);
		column.children("h2").after('<span class="jlink" id="favtripwindow">' + text3 + '</span>');
		column.children("h2").after('<span class="jlink" id="favtriplist">' + text1 + '</span>');
	// в отдельном окне
		$('#favtripwindow').click(function(event) {
			event.preventDefault();
			overlay.show();
			body.append('<div id="modalwindow"><div id="temp58" class="block-border"><h2 style="padding-bottom:10px;">' + name + '</h2></div></div>');
			column.children('ul').clone().appendTo('#modalwindow #temp58');
			$('a.aloneimage').popImage();
		});
		
	// выставляю высоту колонки с записями
		var centerHeight,posFav,heightColumn;
		function heightfavcolumn() {
			centerHeight = $("#super-center").height();
			posFav = Math.round(column.position().top);
			heightColumn = centerHeight - posFav - 35;
			column.css({"height":heightColumn});}
		heightfavcolumn();
		$(window).resize(function () {heightfavcolumn();});
		
	//обрабатываю перетаскивание мышкой
		var startMargin,startCoords;
		column.children("ul").mousedown(function(event1) {
			event1.preventDefault();
			startCoords = event1.pageY;
			startMargin = column.children("ul").css("margin-top").replace("px","")*1;
			$(this).bind("mousemove", function(event2) {
				event2.preventDefault();
				var newMargin = startMargin + event2.pageY - startCoords;
				if (newMargin > 0) newMargin = 0;
				$(this).css({"margin-top" : newMargin + "px"});
				
			});
		});
		column.children("ul").bind("mouseup mouseleave", function() {
			$(this).unbind("mousemove");
		});
		
	//промотка в конец и начало
		var finish = false;
		$("#favtriplist").click(function (event) {
			event.preventDefault();
			var heightList = column.children("ul").height();
			
			if (!finish)
				column.children("ul").animate({marginTop : 0 - heightList + heightColumn - 90}, 1000,
					function() { $("#favtriplist").text(text2); finish = true;  });
			else
				column.children("ul").animate({marginTop : 0}, 500, 
					function () { $("#favtriplist").text(text1); finish = false; });
		});
	};

	if ($("#fav-from-trip").length) { $("#fav-from-trip").favtripposition(); }
	
	$('.false').click(function(event){
		event.preventDefault();
	});
	
	
	$('.backup').click(function() {
		$('div.backup').toggle();
	});
	
	//добавление пунктирной линии ко всем j-ссылкам, не содержащим jpg
	$('a.aloneimage:not(:has(img))').addClass('border-dashed');
	
	
});
