loadComment = function(id) {
	jQuery.get("/threadedcomments/comment_body/"+id,"",function(data){
		//alert($("#fcomment_"+id));
		$("#fcomment_"+id).html(data);
		return false;
	});
}

$.fn.openPopup = function(params){
	// Проверяем, вызывался ли попап раньше. Если не вызывался - инициализируем его
	if(!$(this).hasClass('ispopup')){
		if(typeof params == 'undefined' ){
			params={};
		}

		if(typeof params.marginBottom != 'undefined' ){
			marginBottom = params.marginBottom;
		} else {
			marginBottom = 0;
		}
		// Настраиваем подложку
		if(!$('.backlight').length){
			var backlight = $(document.createElement('DIV'));
			backlight.addClass('backlight');
			if(typeof params.bgColor != 'undefined' ){
				backlight.css({'background':params.bgColor});
			}
			backlight.appendTo('#upyachka');
			backlight.fadeTo(1, 0.9);
			//$('#upyachka').height($(document).height());
			backlight.height($(document).height());
			backlight.width($(document).width());
			$('.backlight').click(function(){
				$(this).closePopup();
				if($("#gallery-line").length)
					$("#gallery-line").hide();
				return false;
			});

			// Вставляем пояснительный текст
		//	var helptext = $(document.createElement('P'));
		//	helptext.addClass('helptext');
		//	helptext.html('Кликните в любом месте, чтобы закрыть окно');
		//	helptext.appendTo('#upyachka');
		}

		// Настраиваем сам попап. Копируем в него классы элемента, который окажется у него внутри
		if(!$('.popup').length){
			var bubble = $(document.createElement('DIV'));
			bubble.addClass('popup');
			if(typeof params.popupClass != 'undefined' ){
				bubble.addClass(params.popupClass);
			}
			bubble.appendTo('#upyachka');
		}

		// Прикручиваем закрывалку
		$('#upyachka .popup').html('<div class="popupcloser"></div>');
		$('#upyachka .popup').append($(this));

		if((typeof params.showCloser!='undefined')&&(params.showCloser==false)){
			$('#upyachka .popupcloser').hide();
		}

		// Вешаем обработчики на закрытие попапа
		$('.popupcloser').click(function(){
			$(this).closePopup();
			if($("#gallery-line").length)
				$("#gallery-line").hide();
			return false;
		});
		$(this).find('.cancel').click(function(){
			$(this).closePopup();
			if($("#gallery-line").length)
				$("#gallery-line").hide();
			return false;
		});

		// Внимательно слушаем клавишу Esc
		$(document).keydown(function(e) {
			if(e.which==27) $(this).closePopup();
			if($("#gallery-line").length)
				$("#gallery-line").hide();
		});


		// Говорим попапу, что он попап и показываем его
		$(this).addClass('ispopup');
		$(this).show();

	//	if($("object").length)
	//		$("object").append('<param name="wmode" value="opaque">').css({"display":"block","z-index":1});
	}

	// Закрываем предыдущий попап и открывам текущий
	//$(this).parent('.popup:visible').closePopup();
	//$(this).parent('.popup').show();

	// Эта хрень должна исчезнуть, когда сделаем предзагрузку
	if ($('#upyachka .popup').width()) {
		var popupWidth = $('#upyachka .popup').width();
	}

	if ($('#upyachka .popup').height()) {
		var popupHeight = $('#upyachka .popup').height();
	}

	// Настраиваем размеры окна попапа в соотвествии с тем, что будет у него внутри
	$(this).parent('.popup').css({marginTop:-popupHeight/2+$(document).scrollTop()-marginBottom,marginLeft:-popupWidth/2,top:"50%",left:"50%"});

	if(jQuery.browser.opera){
		$(document).oneTime(1,"hideDropdown",function(){
			$('.popup').show();
		});
	} else {
		$('.popup').show();
	}

	$('.backlight').css({left:'0px'}).show();
	$('.helptext').css({top:$(document).scrollTop()}).show();

	// Костыли - скрываем селекты в эксплорере, чтобы они не просвечивали через подложку
	if(jQuery.browser.msie){
		$('.supportblock select').hide();
	}
}

// Обрабатываем закрытие попапа
$.fn.closePopup = function() {
    el = $('.popup .ispopup');
	$('.backlight').css({left:'-100000px'});
	$('.popup').css({marginTop:-$('.popup').height()/2+$(document).scrollTop(),marginLeft:-$('.popup').width()/2,top:"50%",left:"50%",display:"none"});
	$('.helptext').hide();
	if(jQuery.browser.msie){
		$('.supportblock select').show();
	}
    $(el).appendTo('#front');
    $(el).hide();
    $(el).removeClass('ispopup');
}

function toggleKeyboardScroll() {
	var k = $(this).data("scrollable").getConf().keyboard;
    $(this).data("scrollable").getConf().keyboard = !k;
    if (k) {
        $('#dummy-scrollable').data('scrollable').focus();
    } else {    
        $(this).data('scrollable').focus();
    }
}

$(document).ready(function(){
    $('#dummy-scrollable').scrollable({keyboard: false});    
    
	$(".media .illustration").mouseenter(function(){
		$(this).find(".meta").css({'display':'block'});
	});

	$(".media .illustration").mouseleave(function(){
		$(this).find(".meta").css({'display':'none'});
	});

	 // для показа и скрытия выпадающих списков подпунктов главного меню
    $('.dropdown-link').hover(
        function () {
            // прячем все другие такие же выпадающие списки
            $('.blogs-dropdown-box').stopTime("hideDropdown");
            $('.blogs-dropdown-box').hide();
            $('.dropdown-link').removeClass("blogs-dropdown-overlink");

            $(this).children('.blogs-dropdown-box').show();
            $(this).children('.blogs-dropdown-box').stopTime("hideDropdown");
            $(this).addClass("blogs-dropdown-overlink");
        },
        function () {
            $(this).children('.blogs-dropdown-box').oneTime(500, "hideDropdown", function(){
                $(this).hide();
                $(this).parent().removeClass("blogs-dropdown-overlink");
            });
        }
    );

	$(".show-all-tags").hover(
		function(){
			$(this).find('.all-tags').show();
			$(this).find('.all-tags').stopTime("hideTags");
		},
		function(){
			$(this).find('.all-tags').oneTime(500,"hideTags",function(){$(this).hide()});
		}
	);

	//Старый код для вывода блока опций у комментов. Заменяем новыми оверлеями.
	//$(".comment .chead").hover(
	//	function(){
	//		$(this).find(".controls").show();
	//	},
	//	function(){
	//		$(this).find(".controls").hide();
	//	}
	//);



	if($(".mail-link")[0]){
		$(".mail-link").click(function() {
			var comment = $(document.createElement('DIV'));
			$(comment).load(this.href+" .popup-wrap");
			$(comment).openPopup();

			return false;
		});
	}

	if($(".playlist .clips a span")[0]){
		$(".playlist .clips a span").click(function() {
			$('#playlist-blocker').show();
			document.location.href=$(this).parent().find("em").html();
			return false;
		});
	}


	var mainplayer_settings = {
		key: '#@a38baa27b1f0d15312e',

		logo: {
			url: 'http://kanobu.ru/img/fp_logo.png',
			fullscreenOnly: false,
			top: 6,
			right:5,
			linkUrl: 'http://kanobu.ru'
		},

		//onMouseOver: function() {
		//	var sclip = this.getClip();
		//		if(sclip.isInStream){
		//			return this.getPlugin("content").css({backgroundImage: 'http://kanobu.ru/media/kanobu/modern/images/partners/logo_lava.png'}).fadeIn(1000);
		//		}	
    	//	}, 
				
		//onMouseOut: function() { 
		//	this.getPlugin("content").fadeOut(1000)
    	//	},

		clip: {
			
			tags: ['kanobu'],
			
			scaling:'fit',
			
			//provider: 'rtmp',
			
			onStart: function(clip) {
				pageTracker._trackEvent("Videos", "Play", clip.url);
				$('#embedTab').removeClass("inactive");
			},

			onFinish: function(clip) {
				pageTracker._trackEvent("Videos", "Finish", clip.url);
			}
		},				

		canvas: {
			backgroundColor: '#000000',
			backgroundGradient: 'none'
		},

		play: {
			opacity: 1,
			label: null,
			replayLabel: 'Ещё раз'
		},

		plugins: {
			
			videoplaza: { 
                url: 'http://service.cdn.videoplaza.com/resources/as3_bridge_flowplayer.swf', 

                vpid:'9f03e736-81c3-4943-8bc4-fabbf4593f73' 
            },
			
			//vn:  { 
           //		url: 'http://poligon.videonow.ru/players/plugins/vn_flowplayer_plugin.swf',
			//	vn_profile_id: 92613, //id профиля
			//	vn_category_id: 7, //id категории видео 
			//	top: 0, 
            //	left: 0 
        	//},
			
			//rtmp: {
			//	url: 'http://kanobu.ru/flowplayer/flowplayer.rtmp-3.2.1.swf',
			//	proxyType: 'best',
			//	netConnectionUrl: 'rtmp://video.kanobu.ru:1935/flowplayer',
			//	durationFunc: 'getStreamLength'
			//},
			
			controls: {
				//url: 'http://kanobu.ru/flowplayer/flowplayer.controls-skinless-3.1.5.swf',
				//skin: 'customskin',
				url: 'http://kanobu.ru/flowplayer/flowplayer.controls-3.2.1.swf',
				
				backgroundColor: "transparent",
				backgroundGradient: "none",				

				height: 30,
				
				border: 'none',
				
				hideDelay: 1000,

				all:false,
				
				enabled: {scrubber: true},
				
				scrubber:true,
				volume:true,
				play:true,
				mute:true,
				playlist:false,
				fullscreen: true,
				time: false,
				
				scrubberHeightRatio: 0.4,
				volumeSliderHeightRatio: 0.4,
				
				progressColor: '#47ff91',
				volumeColor: '#47ff91',				
				bufferColor: 'rgba(163, 163, 163, 0.4)',
				volumeSliderColor: 'rgba(50, 50, 50, 1)',
				//buttonColor: "#000000",
				buttonOverColor: '#47ff91',
				tooltipColor: '#ffffff',
				tooltipTextColor: '#000000',
				
				autoHide: 'always',
				bottom: 5,
				left: '50%'
			}//,

			//customskin: {
			//	url: "http://kanobu.ru/flowplayer/gameslife_buttons.swf",
			//	type: "classLibrary"
			//}			
			
		}

	};

	var player_settings = {
		key: '#@a38baa27b1f0d15312e',

		logo: {
			url: 'http://kanobu.ru/img/fp_logo.png',
			fullscreenOnly: false,
			top: 6,
			right:5,
			linkUrl: 'http://kanobu.ru'
		},

		clip: {
			
			tags: ['kanobu'],
			
			scaling:'fit',
			autoPlay: true,
			autoBuffering: false,
			
			//provider: 'rtmp',
			
			onStart: function(clip) {
				$('#embedTab').removeClass("inactive");
				pageTracker._trackEvent("Videos", "Play", clip.url);
				$('#embedTab').removeClass("inactive");
			},
			onFinish: function(clip) {
				pageTracker._trackEvent("Videos", "Finish", clip.url);
            }
			//,
			
			//,
			//onFinish: function() {
            //    this.unload();
            //},
			
			//playlist: 
			//	[ 				 
        	//		{
			//			url: 'http://static.kanobu.ru/images/partners/parcel.flv', 
			//	 		position: 0,
			//			autoBuffering: true,
						
			//			controls: { 
			//				scrubber:true,
            //       			enabled: {scrubber: false}
            //   			}
			//		}
		    //   	]
		},

		canvas: {
			backgroundColor: '#000000',
			backgroundGradient: 'none'
		},

		play: {
			opacity: 1,
			label: null,
			replayLabel: 'Ещё раз'
		},

		plugins:  {
			
			videoplaza: { 
                url: 'http://service.cdn.videoplaza.com/resources/as3_bridge_flowplayer.swf',                 
                vpid:'9f03e736-81c3-4943-8bc4-fabbf4593f73' 
            },
			
			//vn:  { 
            //	url: 'http://poligon.videonow.ru/players/plugins/vn_flowplayer_plugin.swf',
			//	vn_profile_id: 92613, //id профиля
			//	vn_category_id: 7, //id категории видео 
			//	top: 0, 
            //	left: 0 
        	//},
			
			//rtmp: {
			//	url: 'http://kanobu.ru/flowplayer/flowplayer.rtmp-3.2.1.swf',
			//	proxyType: 'best',
			//	netConnectionUrl: 'rtmp://video.kanobu.ru:1935/flowplayer',
			//	durationFunc: 'getStreamLength'
			//},
			
			controls: {

				//url: 'http://kanobu.ru/flowplayer/flowplayer.controls-skinless-3.1.5.swf',
				//skin: 'customskin',
				url: 'http://kanobu.ru/flowplayer/flowplayer.controls-3.2.1.swf',
				
				backgroundColor: "transparent",
				backgroundGradient: "none",				

				height: 30,
				
				border: 'none',
				
				hideDelay: 1000,

				all:false,
				
				enabled: {scrubber: true},
				
				scrubber:true,
				volume:true,
				play:true,
				mute:true,
				playlist:false,
				fullscreen: true,
				time: false,
				
				scrubberHeightRatio: 0.4,
				volumeSliderHeightRatio: 0.4,
				
				progressColor: '#47ff91',
				volumeColor: '#47ff91',				
				bufferColor: 'rgba(163, 163, 163, 0.4)',
				volumeSliderColor: 'rgba(50, 50, 50, 1)',
				//buttonColor: "#000000",
				buttonOverColor: '#47ff91',
				tooltipColor: '#ffffff',
				tooltipTextColor: '#000000',
				
				autoHide: 'always',
				bottom: 5,
				left: '50%'
			}//,
			//customskin: {
			//	url: "http://kanobu.ru/flowplayer/gameslife_buttons.swf",
			//	type: "classLibrary"
			//}//,	
			
		}
	};
	
	var mainaudio_settings = {
		key: '#@a38baa27b1f0d15312e',

		clip: {
			
			autoPlay: true,
			
			scaling:'fit',
			
			//provider: 'rtmp',
			
			onStart: function(clip) {
				pageTracker._trackEvent("Music", "Play", clip.url);
			},

			onFinish: function(clip) {
				pageTracker._trackEvent("Music", "Finish", clip.url);
			}
		},				

		canvas: {
			backgroundColor: '#f1f1f1',
			backgroundGradient: 'none'
		},

		play: {
			opacity: 0,
			label: null,
			replayLabel: null
		},
		
		plugins: {	
		
			audio: { 
            	url: 'http://kanobu.ru/flowplayer/flowplayer.audio-3.2.0.swf'
			},
			
			//rtmp: {
			//	url: 'http://kanobu.ru/flowplayer/flowplayer.rtmp-3.2.1.swf',
			//	proxyType: 'best',
			//	netConnectionUrl: 'rtmp://audio.kanobu.ru:1935/flowplayer',
			//	durationFunc: 'getStreamLength'
			//},
						
			controls: {
				//url: 'http://kanobu.ru/flowplayer/flowplayer.controls-skinless-3.1.5.swf',
				//skin: 'customskin',
				url: 'http://kanobu.ru/flowplayer/flowplayer.controls-3.2.1.swf',
				
				backgroundGradient: 'none',
				backgroundColor: 'transparent',
				background: '#114455 url(http://static.kanobu.ru/kanobu/modern/skin/kanobu-ver_0.4/img/mainaudio_playlist3.jpg) no-repeat top center',
				height: 30,
				
				border: 'none',
				
				hideDelay: 1000,

				all:false,
				
				enabled: {scrubber: true},
				
				scrubber:true,
				volume:true,
				play:true,

				mute:true,
				playlist:false,
				fullscreen: false,
				time: false,
				
				scrubberHeightRatio: 0.4,
				volumeSliderHeightRatio: 0.4,
				
				progressColor: '#47ff91',
				volumeColor: '#47ff91',				
				bufferColor: 'rgba(163, 163, 163, 0.4)',
				volumeSliderColor: 'rgba(50, 50, 50, 1)',
				//buttonColor: "#000000",
				buttonOverColor: '#47ff91',
				tooltipColor: '#ffffff',
				tooltipTextColor: '#000000',

				autoHide: 'never',
				bottom: 0,
				left: '50%'
			}//,

			//customskin: {
			//	url: "http://kanobu.ru/flowplayer/gameslife_buttons.swf",
			//	type: "classLibrary"
			//}
		}

	};
	
	var audio_settings = {
		key: '#@a38baa27b1f0d15312e',

		clip: {
			
			autoPlay: true,
			
			scaling:'fit',
			
			//provider: 'rtmp',
			
			onStart: function(clip) {
				pageTracker._trackEvent("Music", "Play", clip.url);
			},

			onFinish: function(clip) {
				pageTracker._trackEvent("Music", "Finish", clip.url);
			}
		},				

		canvas: {
			backgroundColor: '#000',
			backgroundGradient: 'none'
		},

		play: {
			opacity: 0,
			label: null,
			replayLabel: null
		},
		
		plugins: {	
		
			audio: { 
            	url: 'http://kanobu.ru/flowplayer/flowplayer.audio-3.2.0.swf'
			},
			
			//rtmp: {
			//	url: 'http://kanobu.ru/flowplayer/flowplayer.rtmp-3.2.1.swf',
			//	proxyType: 'best',
			//	netConnectionUrl: 'rtmp://audio.kanobu.ru:1935/flowplayer',
			//	durationFunc: 'getStreamLength'
			//},
						

			controls: {
				//url: 'http://kanobu.ru/flowplayer/flowplayer.controls-skinless-3.1.5.swf',
				//skin: 'customskin',
				url: 'http://kanobu.ru/flowplayer/flowplayer.controls-3.2.1.swf',
				
				backgroundGradient: 'none',
				backgroundColor: 'transparent',
				background: '#114455 url(http://static.kanobu.ru/kanobu/modern/skin/kanobu-ver_0.4/img/audio_bg.jpg) no-repeat top center',
				height: 30,
				
				border: 'none',
				
				hideDelay: 1000,

				all:false,
				
				enabled: {scrubber: true},
				
				scrubber:true,
				volume:true,
				play:true,
				mute:true,
				playlist:false,
				fullscreen: false,
				time: true,
				
				scrubberHeightRatio: 0.4,
				volumeSliderHeightRatio: 0.4,
				
				progressColor: '#47ff91',
				volumeColor: '#47ff91',				
				bufferColor: 'rgba(163, 163, 163, 0.4)',
				volumeSliderColor: 'rgba(50, 50, 50, 1)',
				buttonOverColor: '#47ff91',
				tooltipColor: '#ffffff',
				tooltipTextColor: '#000000',

				autoHide: 'never',
				bottom: 0,
				left: '50%'
			}//,

			//customskin: {
			//	url: "http://kanobu.ru/flowplayer/gameslife_buttons.swf",
			//	type: "classLibrary"
			//}
		}

	};

	if($("a.player_centered")[0]){
		$f("a.player_centered", {src: "http://kanobu.ru/flowplayer/flowplayer.commercial-3.2.2.swf", wmode: 'opaque'}, player_settings);
		$(".player_centered").show();
	}	
	
	if($("a.audio_single")[0]){
		$f("a.audio_single", {src: "http://kanobu.ru/flowplayer/flowplayer.commercial-3.2.2.swf", wmode: 'opaque'}, audio_settings);
		//$(".audio_single").show();
	}
	
	if($("a.audio_playlist")[0]){
		$("a.audio_playlist").each(function () {

			$theScroller = $($(".musiclist", $(this).parent())).scrollable({size: 5,vertical:true,next:'a.next',prev:'a.prev', mousewheel: true});
            $theScroller.mouseenter(toggleKeyboardScroll).mouseleave(toggleKeyboardScroll).data("scrollable").getConf().keyboard = false;
			strm= "#" + $("div.musicplayer", $(this).parent()).attr("id");

			$f(this, {src: "http://kanobu.ru/flowplayer/flowplayer.commercial-3.2.2.swf", wmode: 'opaque'}, {
		key: '#@a38baa27b1f0d15312e',

		clip: {
			
			autoPlay: true,
			
			scaling:'fit',
			
			//provider: 'rtmp',
			
			onStart: function(clip) {
				pageTracker._trackEvent("Music", "Play", clip.url);
			},

			onFinish: function(clip) {
				pageTracker._trackEvent("Music", "Finish", clip.url);
			}
		},				

		canvas: {
			backgroundColor: '#000',
			backgroundGradient: 'none'
		},

		play: {
			opacity: 0,
			label: null,
			replayLabel: null
		},
		
		plugins: {	
		
			audio: { 
            	url: 'http://kanobu.ru/flowplayer/flowplayer.audio-3.2.0.swf'
			},
			
			//rtmp: {
			//	url: 'http://kanobu.ru/flowplayer/flowplayer.rtmp-3.2.1.swf',
			//	proxyType: 'best',
			//	netConnectionUrl: 'rtmp://audio.kanobu.ru:1935/flowplayer',
			//	durationFunc: 'getStreamLength'
			//},
						
			controls: {

				url: 'http://kanobu.ru/flowplayer/flowplayer.controls-3.2.1.swf',
				
				backgroundGradient: 'none',
				backgroundColor: 'transparent',
				background: '#114455 url(http://static.kanobu.ru/kanobu/modern/skin/kanobu-ver_0.4/img/audio_bg.jpg) no-repeat top center',
				height: 30,
				
				border: 'none',
				
				hideDelay: 1000,

				all:false,
				
				enabled: {scrubber: true},
				
				scrubber:true,
				volume:true,
				play:true,
				mute:true,
				playlist:false,
				fullscreen: false,
				time: true,
				
				scrubberHeightRatio: 0.4,
				volumeSliderHeightRatio: 0.4,
				
				progressColor: '#47ff91',
				volumeColor: '#47ff91',				
				bufferColor: 'rgba(163, 163, 163, 0.4)',
				volumeSliderColor: 'rgba(50, 50, 50, 1)',
				buttonOverColor: '#47ff91',
				tooltipColor: '#ffffff',
				tooltipTextColor: '#000000',

				autoHide: 'never',
				bottom: 0,
				left: '50%'
			}
		}

	}).playlist(strm, {scaling:'fit', loop:true});
		});

	}
	
	if($("#player_main")[0]){
        $theScroller = $(".playlist").scrollable({size: 3,next:'a.next',prev:'a.prev', mousewheel: true});
        $theScroller.mouseenter(toggleKeyboardScroll).mouseleave(toggleKeyboardScroll).data("scrollable").getConf().keyboard = false;
		$(".clips a").click(function() {
        	$(this).fadeOut().fadeIn();
//			return false;
    	});

		$f("player_main", {src: "http://kanobu.ru/flowplayer/flowplayer.commercial-3.2.2.swf", wmode: 'opaque'}, mainplayer_settings).playlist("div.mainplayer", {scaling:'fit', loop:false});
	}

	if($("#mainaudio")[0]){
		$theScroller = $($(".musiclist", $("#mainaudio").parent())).scrollable({size: 5,vertical:true,next:'a.next',prev:'a.prev', mousewheel: true});
		$theScroller.mouseenter(toggleKeyboardScroll).mouseleave(toggleKeyboardScroll).data("scrollable").getConf().keyboard = false;
		$f("mainaudio", {src: "http://kanobu.ru/flowplayer/flowplayer.commercial-3.2.2.swf", wmode: 'opaque'}, mainaudio_settings).playlist("#main_pls", {scaling:'fit', loop:true});		
		//$("#mainaudio").show();	
	}

	if($("#pl_sortable")[0]){
		$("#pl_sortable").sortable({ opacity: 0.6 });
	}

	if($(".image-lightbox").length){
		$(".image-lightbox").click(function(){

			var preloaderDiv = $(document.createElement('DIV'));
			preloaderDiv.html('<div class="img-preloader"></div>');
			preloaderDiv.openPopup({bgColor:"#000",popupClass:"popup-image-block",showCloser:false});

			var imgLink = $(this).attr('href');
			var imgTitle = $(this).attr('title');
			var image = $('<img src="'+ imgLink  +'" alt="'+ imgTitle +'" class="popup-image"/>');

			var imageContainer = $(document.createElement('DIV'));
			imageContainer.appendTo($("body"));

			image.appendTo(imageContainer);
			image.load(function(){
				var imageWidth = image.width();
				var imageHeight = image.height();
                                var imageRatio = imageWidth/imageHeight;
				var frameWidth = $(".backlight").width()-80;
				var frameHeight = $(window).height()-80;

				// Вписываем картинку в размер окна,
				// если она шире, чем окно
				if(imageWidth > frameWidth) {
					image.width(frameWidth);
                                        imageWidth = image.width();
                                        image.height(imageWidth/imageRatio);
					imageHeight = image.height();
				}

				// Вписываем картинку в размер окна,
				// если она выше, чем окно
				if(imageHeight > frameHeight) {
					image.height(frameHeight);
                                        imageHeight = image.height();
                                        image.width(imageHeight*imageRatio);
					imageWidth = image.width();
				}

				imageContainer.openPopup(/*{bgColor:"#000",popupClass:"popup-image-block"}*/);
			});

			return false;
		});
	}

	$(".illustration").each(function(){
		if(!$(this).find("span").length){
        if($(this).find("img").attr("alt"))
            $(this).append("<span style='width:auto;'>"+$(this).find("img").attr("alt")+"</span>");
		}
	});

    $(".balloonNotify").click(function(e) {
        
        MSG = {
            'msgForeignUser': 'К сожалению, эта функция недоступна в вашем регионе',
            'msgLowRating'  : 'У вас недостаточно рейтинга. <a href="http://kanobu.ru/blog/id71631/">Почему?</a>'
        }
        
        dx = 15;
        dy = 40;
        leftVal = (e.pageX-dx)+"px";
        topVal = (e.pageY-dy)+"px";

        msgid = $(this).attr("alt");
        if (MSG[msgid]) {
            msg = MSG[msgid];
        } else {
            msg = msgid;
        }
        $("#balloon-msg").html(msg);

        $("#balloon-notify").css({left:leftVal,top:topVal}).fadeIn("fast");
        $("#balloon-notify").oneTime(3000,"hideBalloonNotification",function(){
            $("#balloon-notify").fadeOut("slow");
        });
        return false;
	});		
	
});

function selectNode(node_id) {
	$('#topmenu li.active').hide();
	$('#topmenu li:not(.active)').show();

	$('#'+node_id+'_active').show();
	$('#'+node_id).hide();

	$('.submenu').hide();
	$('#submenu_'+node_id).show();
}


$(function() {
	// email and embed tab actions
	/*$("#panes + #shareTabs a").click(function(e)  {
		$f().hide(true);

		// toggle tab class
		var tab = $(this);
		$("#shareTabs a").removeClass("current");
		tab.addClass("current");

		// show / hide panes
		$(tab.attr("href")).show();
		var other = (tab.attr("href") == "#emailPane") ? $("#embedPane") : $("#emailPane");
		other.hide();

		// prevent link's default behaviour
		return e.preventDefault();
	});*/
	var reEmbed = new RegExp(".*EMBED.*");
	var reDownload = new RegExp(".*DOWNLOAD.*");
	var reLicensed = new RegExp(".*LICENSED.*");
	$('.embedTabClass').click(function(){
                // rel - id плеера
                // rev - содежит комбинацию EMBED, DOWNLOAD, LICENSED по 
		// наличию этого определяется какие ссылки должны быть активны
                var embedTab = $(this);
		if (!embedTab.attr('rev').match(reEmbed)) {
			embedTab.css('display', 'none');
			$(embedTab.attr('id')+'Dis').css('display', 'inline');
			return false;
		} else {
			embedTab.css('display', 'inline');
			$(embedTab.attr('id')+'Dis').css('display', 'none');
		}
                var player_id = embedTab.attr('rel');
		if ($('#'+player_id)[0]) {
	                f_player = flowplayer(player_id);
		} else {
	                f_player = flowplayer(0);
		}
		embedTab.removeClass("inactive");
		if(!embedTab.attr('rev').match(reEmbed)) {
			f_player.play();
		} else {
			$("#player_actions a").removeClass("active");
			embedTab.addClass("active");
			var embedPane = $(embedTab.attr("href"));
			embedPane.show();
//			$('#emailPane').hide();
			$('#playlist-blocker').show();
			var clipPreview = $("#currentClipPreviewImg").html();
			
			var embedCode = EMBED(
				$('#player_main img').attr('src') || $('#currentClipPreviewImg').html(),
				$('.clips.items a.active').attr('href') || $('.clips.items a.first').attr('href') || $('.player.player_centered').attr('href')
			);

			//document.getElementById("clipEmbedCode").innerHTML = embedCode;
			$("#"+embedPane.attr('id')+" .item:first").html('<textarea id="clipEmbedCode" class="embed-text input-text" onfocus="this.select()">'+embedCode+'</textarea>');
		}
		return false;
	});

	$('.downloadTabClass').click(function(){
                var downloadTab = $(this);
		if (!downloadTab.attr('rev').match(reDownload)) {
			downloadTab.css('display', 'none');
			$(downloadTab.attr('id')+'Dis').css('display', 'inline');
			return false;
		} else {
			downloadTab.css('display', 'inline');
			$(downloadTab.attr('id')+'Dis').css('display', 'none');
		}

	});

	$("#copyCode").click(function(){
		window.clipboardData.setData('Text',document.getElementById("clipEmbedCode").innerHTML);
	});

	$('#emailTab').click(function(){
	/*	var tab = $(this);
		$("#player_actions a").removeClass("active");
		tab.addClass("active");
		$(tab.attr("href")).show();

		$('#embedPane').hide();
		$('#playlist-blocker').show();*/

		return false;
	});
	$(".playlist a").click(function(){
		$('#embedTab').attr('rev', $(this).attr('rev'));
		$('#downloadTab').attr('rev', $(this).attr('rev'));
		$('#downloadTab').attr('href', $(this).attr('rel'));
		if (!$(this).attr('rev').match(reEmbed)) {
			$('#embedTab').css('display', 'none');
			$('#embedTabDis').css('display', 'inline');
		} else {
			$('#embedTab').css('display', 'inline');
			$('#embedTabDis').css('display', 'none');
		}
		if (!$(this).attr('rev').match(reDownload)) {
			$('#downloadTab').css('display', 'none');
			$('#downloadTabDis').css('display', 'inline');
			if (!$(this).attr('rev').match(reLicensed)) {
				try {
				document.getElementById("downloadTabDis").onclick = function (){ light_register_popup();return false;   };
				} catch(e) {};
			}
			else {
				try {
				document.getElementById("downloadTabDis").onclick = function (){ return false; };
				} catch(e) {};
			}
		} else {
			$('#downloadTab').css('display', 'inline');
			$('#downloadTabDis').css('display', 'none');
		}

		$("#currentClipPreviewImg").html($(this).find("img").attr("src").replace("120x90_crop_autocrop","400x300_crop"));
	});

	// close buttons
	$(".pane .close").click(function() {
		$("#player_actions a").removeClass("active");
		$(this).parent().parent().hide();
		$('#playlist-blocker').hide();
		document.getElementById("clipEmbedCode").innerHTML = "";
	});

    // выравнивание высот элементов в списках (сущностей, аккаунтов) при их табличном просмотре
	$(".itemlist ul").each(function(){
		var elemCount = 5, currentLine = 1;
		var elemArray = $(this).find("li");

		var lineCount = Math.ceil(elemArray.length / elemCount);

		for (var currentLine = 1; currentLine <= lineCount; currentLine++) {
			var currentLineElems = $(this).find("li").splice((currentLine-1)*elemCount, elemCount);

			var maxHeight = $(currentLineElems[0]).height();
			for(var currentElem = 0; currentElem < currentLineElems.length; currentElem++) {
				if ($(currentLineElems[currentElem]).height() > maxHeight)
					maxHeight = $(currentLineElems[currentElem]).height();
			}
			$(currentLineElems).each(function(){$(this).height(maxHeight);});
		}
	});

	$("#rating-bubble").oneTime(5000,"hideRatingBubble",function(){
		$("#rating-bubble").fadeOut("slow");
	});

	$(".result tbody tr:odd").addClass("even");


	$(".cry-block .minimize").click(function(){
	        var comments = $(this).parents(".cry-block").find(".cry-comments");

	        if(comments[0].style.display == ""){
	                comments.hide();
	                $(this).html("развернуть");
	        } else {
                    // Заполняем через ajax
                    var comments_block = $(comments[0]);
                    var url = "/shout/get_cry_comments/" + comments_block.attr('id') + "/?from_cas=1";
                    var loading = $('#' + comments_block.attr('id') + '_loading');
                    loading.show();
                    comments_block.load(url,
                        function() {
                            loading.hide();
                        }
                        );
	                comments.show();
	                $(this).html("свернуть");
	                comments[0].style.display="";
	        }

	        return false;
	});

	$("#input-cry").keydown(function(){
	        if ($(this)[0].value.length > 140)
	                $(this)[0].value = $(this)[0].value.substring(0, 140);
	        else
	                $("#cry-letters-left").html(140-$(this)[0].value.length);
	});

	$("#input-cry").change(function(){
	        if ($(this)[0].value.length > 140)
	                $(this)[0].value = $(this)[0].value.substring(0, 140);
	        else
	                $("#cry-letters-left").html(140-$(this)[0].value.length);
	});

	$(".cry-comment-add").click(function(){

		var comments = $(this).parents(".cry-block").find(".cry-comments");

		if(comments[0].style.display != ""){
			comments.show();
			$(this).parents(".cry-block").find(".minimize").html("свернуть");
			comments[0].style.display="";
		}

		var cry_new_comment = $(this).parents(".cry-block").find(".cry-new-comment");
		// Получаем html для формы
		var cry_comment_form_url = $(this).attr('rel').replace('/comment', '/form');;
		$.get( cry_comment_form_url, {}, function(data) {
			var form = $(data);
			cry_new_comment.html(form);
			cry_new_comment.show();
			apply_form_hijax(form);
		});

		$(this).parents(".cry-block").find(".cry-comment-cancel").show();

		if(jQuery.browser.msie){
			$(this).parents(".cry-block").find(".ccb-left").hide().show();
			$(this).parents(".cry-block").find(".ccb-right").hide().show();
			$(this).parents(".cry-complect").find(".ccomplect-lb").hide().show();
			$(this).parents(".cry-complect").find(".ccomplect-rb").hide().show();
		}

		$(this).hide();
		return false;
	});

	$(".cry-comment-cancel").click(function(){
		$(this).parents(".cry-block").find(".cry-new-comment").hide();
		$(this).parents(".cry-block").find(".cry-comment-add").show();
		$(this).hide();

		if(!$(this).parents(".cry-block").find(".comment").length){
			$(this).parents(".cry-block").find(".cry-comments")[0].style.display = "none";
		}

		if(jQuery.browser.msie){
			$(this).parents(".cry-block").find(".ccb-left").hide().show();
			$(this).parents(".cry-block").find(".ccb-right").hide().show();
			$(this).parents(".cry-complect").find(".ccomplect-lb").hide().show();
			$(this).parents(".cry-complect").find(".ccomplect-rb").hide().show();
		}

		return false;
	});

	$("#soc-embed-selector a").click(function(){
		$("#soc-embed-selector a").each(function(){
			$(this).removeClass("active");
		});
		$(this).addClass("active");

		$(".soc-embed-input").each(function(){
			$(this).hide();
		});
		$("#"+$(this).attr("id").replace("select","input")).show();

		return false;
	});

    $('.soc-embed-input').focus(function(){
        this.select();
    });

	$(".autofocus").focus(function(){
		$(this)[0].select();
	});

	$(".up-links-hider").click(function(){
		$($(".achiev_panel", $(this).parent())).show();
		$($("h2", $(this).parent())).toggleClass("closed");
										
		$(this).parent().find(".link-box").slideUp("fast");
		$(this).hide();
		$(this).parent().find(".up-links-opener").show();

		return false;
	});

	$(".up-links-opener").click(function(){
		
		$(this).parent().find(".link-box").slideDown("fast");
		$(this).hide();
		$(this).parent().find(".up-links-hider").show();

		
		$($(".achiev_panel", $(this).parent())).hide();
		$($("h2", $(this).parent())).toggleClass("closed");
		
		$(this).parent().find(".achiev-hider").hide();
		$(this).parent().find(".achiev-opener").show();
		$($(".achiev_panel", $(this).parent().parent())).find("ul").addClass("min");
		
		
		return false;
	});
	
	$(".achiev-opener").click(function(){
		
		$($(this).parent()).removeClass("closed");
		$($(".achiev_panel", $(this).parent().parent())).show();
		$($(".achiev_panel", $(this).parent().parent())).find("ul").removeClass("min");
		
		$(this).parent().parent().find(".link-box").hide();
		$(this).parent().parent().find(".up-links-hider").hide();
		$(this).parent().parent().find(".up-links-opener").show();

        $('.achiev-opener-nostyle').hide();
        $('.achiev-hider-nostyle').show();  
		
		$(this).hide();
		$(this).parent().find(".achiev-hider").show();

		return false;
	});
	
	$(".achiev-hider").click(function(){		
		$($(".achiev_panel", $(this).parent().parent())).find("ul").addClass("min");		

        $('.achiev-hider-nostyle').hide();
        $('.achiev-opener-nostyle').show();
		
		$(this).hide();
		$(this).parent().find(".achiev-opener").show();

		return false;
	});

    $('.achiev-opener-nostyle').click(function() {
        $('.achiev-opener-nostyle').hide();
        $('.achiev-hider-nostyle').show();        
        $(".achiev-opener").click();
        return false;
    });

    $('.achiev-hider-nostyle').click(function() {
        $(".achiev-hider").click();
        return false;
    });
	
	$(".sider-hider").click(function(){
		 $(this).parent().parent().parent().find(".bcontent").slideUp("fast");
		 
		 $(this).hide();
		 $(this).parent().find(".sider-opener").show();
		 	
		$(this).parent().parent().parent().find(".player_panel").slideUp();
		$(this).parent().parent().parent().find(".bcontent").slideUp("fast");
		$(this).hide();
		$(this).parent().find(".sider-opener").show();
		
		if(jQuery.browser.msie){			
			$(this).parent().parent().parent().find(".bfoot").toggleClass("bfoot_closed");
		}

		return false;
	});
	
	$(".sider-opener").click(function(){
		 $(this).parent().parent().parent().find(".bcontent").slideDown("fast");
		 
		 $(this).hide();
		 $(this).parent().find(".sider-hider").show();
			
		$(this).parent().parent().parent().find(".player_panel").slideDown();
		$(this).parent().parent().parent().find(".bcontent").slideDown("fast");
		$(this).hide();
		$(this).parent().find(".sider-hider").show();
		 
		if(jQuery.browser.msie){			
			$(this).parent().parent().parent().find(".bfoot").toggleClass("bfoot_closed");
		}

		return false;
	});
    // функции для сохранения состояния аудио плеера - отображается или нет
    $(".sider-hider.audioplayer_block").click(function(){
        $.cookie("hide_audio_block", "1", {path: '/'});
    })
    $(".sider-opener.audioplayer_block").click(function(){
        $.cookie("hide_audio_block", null,  {path: '/'});
    })

	$(".playlist-opener").click(function(){
		$(this).parent().parent().find(".audio_img").toggleClass("audio_img_min");
		$(this).parent().parent().find(".media-description").toggleClass("media-description_min");
		$(this).parent().parent().find(".audio_wrapper").show();
		
	
		$(this).parent().parent().find(".ufoot").show();
		$(this).hide();
		$(this).parent().find(".playlist-hider").show();

		return false;
	});
	
	$(".playlist-hider").click(function(){
		$(this).parent().parent().find(".audio_img").toggleClass("audio_img_min");
		$(this).parent().parent().find(".media-description").toggleClass("media-description_min");
		$(this).parent().parent().find(".audio_wrapper").hide();
		$(this).parent().parent().find(".ufoot").hide();
		$(this).hide();
		$(this).parent().find(".playlist-opener").show();

		return false;
	});

	$(".album-opener").click(function(){

		$(this).parent().parent().find(".illustration").each(function (i) {
			if (i > 3) {
				$(this).show();
        	}
});

		$(this).parent().parent().find(".pager").show();

		$(this).parent().parent().find(".media-description").toggleClass("media-description_min");
		$(this).parent().parent().find(".ufoot").show();
		$(this).hide();
		$(this).parent().find(".album-hider").show();

		return false;
	});

	$(".album-hider").click(function(){

		$(this).parent().parent().find(".illustration").each(function (i) {
			if (i > 3) {
				$(this).hide();
        	}
      	});

		$(this).parent().parent().find(".pager").hide();

		$(this).parent().parent().find(".media-description").toggleClass("media-description_min");
		$(this).parent().parent().find(".ufoot").hide();
		$(this).hide();
		$(this).parent().find(".album-opener").show();

		return false;
	});

});

function hide_cry_block(cry_id) {
	if (confirm("Уверены, что хотите удалить?"))
	$.getJSON('/shout/delete/'+cry_id+'/', 
			function (data) {
				var block_id = '#id_cry_block'+cry_id;
				if (!data.error)  {
					$(block_id).css('display','none');
				}
			}
	);
	return false;
}

function favorite_user_entry(entry_id) {
	var link = $('#id_fav_link');
	var action = link.attr('rev');
	var url = '/blog/favorite_user_entry/'+entry_id+'/'+action+'/';
	if (link.attr('rel') == '') {
		link.attr('rel', 'run');
		$.getJSON(url, 
			function (json) {
				if (!json.error) {
					var label = $('#id_fav_label');
					if (action == 'add') {
						label.html('Убрать из избранного');
						label.attr('class', 'icon-dislike');
						link.attr('rev', 'del');
					} else {
						label.html('В избранное');
						label.attr('class', 'icon-like');
						link.attr('rev', 'add');
					}
				}
				link.attr('rel', '');
			}
		);
	}
}
