/// <reference path="../../../js/jquery-1.4.1-vsdoc.js" />
/// <reference path="../../../js/MicrosoftAjax.debug.js" />

var storage = {}

hs.graphicsDir = '/scripts/highslide/graphics/';
hs.wrapperClassName = 'wide-border';
hs.align = 'center';
hs.transitions = ['fade', 'crossfade'];
hs.fadeInOut = true;
hs.dimmingOpacity = .5;
hs.dimmingDuration = 300;
hs.dimmingGeckoFix = true;
hs.expandDuration = 300;
hs.restoreDuration = 300;

hs.lang.number = 'Изображение %1 из %2';
hs.lang.nextText = 'Следующее';
hs.lang.nextTitle = 'Следующее (стрелка вправо)';
hs.lang.previousText = 'Предыдущее';
hs.lang.previousTitle = 'Предыдущее (стрелка влево)';
hs.lang.loadingText = 'Загрузка';
hs.lang.loadingTitle = 'Кликните для отмены';
hs.lang.playText = 'Слайдшоу';
hs.lang.playTitle = 'Слайдшоу (пробел)';
hs.lang.pauseText = 'Остановить';
hs.lang.pauseTitle = 'Остановить (пробел)';
hs.lang.closeText = 'Закрыть';
hs.lang.closeTitle = 'Закрыть (esc)';
hs.lang.moveTitle = 'Двигать';
hs.lang.restoreTitle = 'Кликните, чтобы закрыть изображение. Удерживайте клик для перемещения изображения. Используйте стрелки "Влево" / "Вправо" для навигации по галерее';
hs.lang.loadingText   = 'Загрузка..';

var galleryOptions = {
	slideshowGroup: 'gallery'
};
$('.media .cover').live('click', function() {
		hs.expand($(this).next('a').get(0), galleryOptions);
	});

slideshowOptions = {
	interval: 3000,
	repeat: true,
	useControls: true,
	fixedControls: true,
	overlayOptions: {
		opacity: 1,
		position: 'bottom center',
		hideOnMouseOut: true
	},
	thumbstrip: {
			position: 'bottom center',
			mode: 'horizontal',
			offsetY: 90
	}
};

$(function() {
	hs.addSlideshow($.extend({}, slideshowOptions, { slideshowGroup: 'gallery' }));
});

function show_progress(block) {
	block = $(block)
	if (!block.hasClass('block'))
		block = $(block).parents(".block:first");
	$('<div class="block-overlay"><h5>Загрузка</h5></div>')
		.appendTo(block)
		.css({
			'height': block.height() - 38,
			'width': block.width() - 10
		})
		.efadeIn(300);
	return block;
}
function show_noresults(block) {
	var blockNoFound = $('#block-notfound');
	blockNoFound.show();
	return blockNoFound;
}

function hide_noresults(block) {
	$('#block-notfound').hide();
	block = $(block).hasClass('block') ? block : $(block).parents(".block:first");
	block.show();
}

function hide_progress(block) {
	block = $(block).hasClass('block') ? block : $(block).parents(".block:first");
	$('.block-overlay', block)
		.efadeOut(300)
		.remove();
}

function googleTranslateElementInit() {
	new google.translate.TranslateElement({
		pageLanguage: 'ru',
		autoDisplay: false,
		multilanguagePage: true
	}, 'google_translate_element');
}

jQuery.fn.fadeToggle = function(speed, easing, callback) {
	return this.animate({ opacity: 'toggle' }, ($.browser.msie ? 0 : speed), easing, callback);
};
jQuery.fn.efadeIn = function(speed, easing, callback) {
	return this.fadeIn(($.browser.msie ? 0 : speed), easing, callback);
}
jQuery.fn.efadeOut = function(speed, easing, callback) {
	return this.fadeOut(($.browser.msie ? 0 : speed), easing, callback);
}
jQuery.fn.mediaGallery = function(galleryId) {
		
		
		
				this.each(function() {
						var target = $(this);
						var galleryId = $(this).attr('id');
						var url = "/media/gallery/" + galleryId;
						$.getJSON(url, function(data) {
							if (!data){ 
								target.remove();
								return;}
							var htmlStr = "<div class='media'>";
							if (data.Folder && data.Folder.CoverId)
								htmlStr += "<img class='cover' src='/media/bmsiDocumentImage/" + data.Folder.CoverId + "' alt='' />";
							else
								htmlStr += "<img class='cover' src='/media/bmsiDocumentImage/" + data.Items[0].ID + "' alt='' />";
							for (var i = 0; i < data.Items.length; i++) {
								htmlStr += '<a class="none" href="/media/bmsi_sourceimage_highslide/' + data.Items[i].ID + '" alt="" onclick="return hs.expand(this, galleryOptions);"> '
													+ '<img src="/media/bmsiDocumentImage/' + data.Items[i].ID + '" alt="" />'
													+ '</a>'
													+ '<div class="highslide-caption">'
													+ 'Фото: ' + data.Items[i].MediaDescription
													+ '</div>';
							}
							htmlStr += '<p class="gallery"> \
											Изображений в галерее: ' + data.Items.length + ' <a href="#" onclick="$(this).parent().parent().find(\'a:first\').click(); return false;">Посмотреть</a> \
										</p>';
							htmlStr += "</div>";
							$(htmlStr).insertAfter(target);
							$('.doc-content .media').each(function() {
								$(this).css('width', $('img', this).first().width());
								$('img', this).first().load(function() {
									t_media = $(this).closest('.media');
									t_media.css('width', $('img', t_media).first().width());
								});
							});
							target.remove();
						});
				});
		
	};

function carousel_scroll(direction) {

	var carousel = {
		top: $('#central-carousel-top'),
		bottom: $('#central-carousel-bottom'),
		list: $('#central-carousel ul')
	}

	carousel.top.unbind('click');
	carousel.bottom.unbind('click');

	clearInterval(int_a);

	if (direction == 'down') {
		$('#central-carousel li').first()
			.clone()
				.attr('style', '')
				.appendTo(carousel.list);
	} else {
		$('#central-carousel li').last()
			.clone()
				.attr('style', 'margin-top:-89px')
				.prependTo(carousel.list);
	}

	$('#central-carousel li').first()
		.animate({ 'margin-top': (direction == 'up' ? "+=89" : "-=89") }, 1000, "swing", function() {

			if (direction == 'down') {
				$(this).remove();
			} else {
				$('#central-carousel li').last().remove();
			}

			datasource = $('#central-carousel li img').eq(1)

			$('#main-image')
		        .find("img")
		            .attr("src", datasource.attr("alt"))
		        .end()
		        .find("a")
		            .attr("href", datasource.attr("title"));

			int_a = setInterval("carousel_scroll('down')", 4000);

			carousel.top.bind('click', function() { carousel_scroll('up'); });
			carousel.bottom.bind('click', function() { carousel_scroll('down'); });

		});

}

function recalculate_all() {
	$('#central-carousel h2').css('width', $('#main-image').width() - 169 + 'px');

	
	$('.papers .new').each(
		function() {
			$(this).css('right', 'auto').css('left', 50 - ($('.center', this).width() + $('.right', this).width() + $('.left', this).width()) + 5);
		}
	);

	for (block in storage.scrollable_blocks) {
		storage.scrollable_blocks[block].update();
	}

	$('#register-block fieldset.captcha label').each(function() {
		$(this).css('padding-top', ($(this).parent().outerHeight() - $(this).height()) / 2);
	});

	$('#register-success').css({
		'width': $('#register-block form').width(),
		'height': $('#register-block form').height()
	});

	$('#block-sources ul.main li.clearfix').each(function() {
		$('dd', this).width($(this).width()-250);
	});
	$('#block-sources ul.main li.clearfix h4 a').each(function() {
		$(this).width($(this).closest('li').width() - $(this).position().left - 10);
	});
	$('#block-sources ul.main li.clearfix dd.afterlink a').each(function() {
		$(this).width($(this).closest('dl').width() - $(this).position().left - 10);
	});
	$('#block-sources ul.main li.clearfix img').load(function() {
		$('#block-sources ul.main li.clearfix').each(function() {
			$('dd', this).width($(this).width()-250);
		});
		$('#block-sources ul.main li.clearfix dd.afterlink a').each(function() {
			$(this).width($(this).closest('dl').width() - $(this).position().left - 10);
		});
		$('#block-sources ul.main li.clearfix h4 a').each(function() {
			$(this).width($(this).closest('li').width() - $(this).position().left - 10);
		});
	});
	
	if ($.browser.msie) {
		$('#block-sources ul.main li.clearfix dd.afterlink a').css('display','inline');
	}
	
	if ($.browser.msie && $.browser.version == 6) {

		$('#central-carousel ul, #central-carousel #selection').each(function() {
			$(this).css('right', 'auto').css('left', $(this).parent().width() - $(this).outerWidth() + 4);
		});
		$('#footer-right').each(
			function() {
				$(this).css('right', 'auto').css('left', $(this).parent().width() + 3);
			}
		);
		$('.s-right').each(
			function() {
				$(this).css('right', 'auto').css('left', $(this).parent().width() + 9);
			}
		);

		$('.block .br, .block .tr').each(
			function() {
				$(this).css('right', 'auto').css('left', $(this).parent().width() - 7);
			}
		);
		$('.block .bl, .block .br').each(
			function() {
				$(this).css('bottom', 'auto').css('top', $(this).parent().height() - 8);
			}
		);

		$('.block').append('<div class="rr"></div>');

		$('.rr').each(function() {
			$(this).css({
				'height': $(this).parent().height() - 16,
				'left': $(this).parent().width() - 7
			});
		});

		e_value = $(window).scrollTop();
	}

	// $('.paginator-bottom').css('width', $('.paginator-bottom').closest('.b-content').width() - 18);

	if ($('#block-partners').width() < 930) {
		$('#block-partners li').css('width', '33.33%');
	} else {
		$('#block-partners li').css('width', ($.browser.msie && $.browser.version <= 7) ? '24.99%' : '25%');
	}


	$('#overlay')
		.css('width', $('body').outerWidth())
		.css('height', $('body').outerHeight());

    $('#CommentFormOverlay').css({
        'height': $('#block-comments form').outerHeight()
    }).focus(function(){$(this).blur();});

}

function loadTips() {
	$.getJSON('/gettooltips/All/', function(data) {

		selector = '';
		for (i in data) {

			tip = data[i];

			selector += tip.Selector + (data.length == parseInt(i) + 1 ? '' : ', ');

			$(tip.Selector).data("style", tip.Style);

			if (tip.Text.indexOf("$content") >= 0 || tip.Text.indexOf("$tipdata") >= 0) {
				$(tip.Selector).each(function() {
					$(this).data("dynamic", true); 
				})
			}
			
			$(tip.Selector).data("title", tip.Text);

		}

		$(selector)
            .attr("title", "")
            .hoverIntent({
            	over: function() {
            		if ($(this).data("title").length > 0 && !$('.disabled-suggestion').get(0)) {
            			
            			tip_content = $(this).data("title");
            			
            			if ($(this).data("dynamic")) {
            				tip_content = tip_content.replace("$content", $(this).html());
            				tip_content = tip_content.replace("$tipdata", $('.tipdata', this).html() || '' );
            			}
            			
            			if (tip_content) {
	            			$.raisepopup({
	            				classes: 'icon-popup' + ($(this).data("style") ? ' ' + $(this).data("style") : ''),
	            				mode: 'tip',
	            				target: $(this),
	            				html: tip_content
	            			});
            			}
            		}
            	},
            	out: function() {
            		$('.icon-popup').not('.disabled-suggestion').efadeOut(300, function() { $(this).remove() });
            	},
            	interval: 300
            });

	});
	
	if ($.browser.opera) {
		$('#block-sources ul.main li.clearfix dd.afterlink a').css({
			'display': 'inline',
			'text-overflow': 'none'
		});
	}
	
}

function remove_error() {
	$(this).closest('div')
		.find("label.error-notice")
			.remove()
		.end()
		.find("input.error")
			.removeClass("error")
			.focus()
}

function raise_cabinet_popup(text, target, tiptarget) {
	var b_t = $('<div class="block t-block"></div>')
		.html('<div class="top"></div><div class="t-tip"></div><div class="b-right"><div class="b-left"><div class="b-content clearfix"></div></div></div><div class="br"></div><div class="bl"></div><div class="tl"></div><div class="tr"></div><div class="bottom"></div>')
		.find('.b-content')
			.append(text)
		.end()
		.width(target.width() + 12)
		.css({
			'top': target.offset().top + 28,
			'left': target.offset().left - 6
		})
		.appendTo('body')
		.efadeIn(300);

	if ($.browser.msie && $.browser.version == 6) {
		$('.t-block .br, .t-block .tr').each(
			function() {
				$(this).css('right', 'auto').css('left', $(this).parent().width() - 8);
			}
		);
		$('.t-block .bl, .t-block .br').each(
			function() {
				$(this).css('bottom', 'auto').css('top', $(this).parent().height() - 8);
			}
		);
	}

	if (tiptarget) {
		$('.t-tip', b_t).css({
			'left': tiptarget.offset().left - target.offset().left + tiptarget.width() / 2 + 5
		});
	}
}

jQuery.fn.cabinetpopup = function(text, tiptarget) {
	return $(this).hoverIntent({
		over: function() {
			raise_cabinet_popup(text, $(this), tiptarget);
		},
		out: function() {
			$('.t-block').efadeOut(300);
		},
		interval: 300
	});
}

var int_a = setInterval("carousel_scroll('down')", 2000);
var e_value = 0;

function raiseregistrationtip(list) {
	
	$.each(list,
	function() {
		_self = this;
		$(this[0])
			.each(function() { $(this).data("target", _self[1] || this); } )
			.click(function() {
				options = {
					classes: 'icon-popup disabled-suggestion',
					mode: 'tip',
					target: $($(this).data("target")),
					html: '<p class="main">Необходима регистрация</p><p>Чтобы пользоваться данной функцией, необходимо <a class="login-trigger" href="">войти</a> или <a href="/user/new">зарегистрироваться</a>.</p>'
				}
				if ($('.disabled-suggestion .b-content, .block-tip').get(0)) {
					$('.disabled-suggestion .b-content, .block-tip').closest('.block').fadeOut(300, function() {
						$('.disabled-suggestion .b-content, .block-tip').closest('.block').remove();
						$.raisepopup(options);
					});
				} else {
					$.raisepopup(options);
				}
				return false;
			})
			.mouseout(function() {
				storage.hoverevent = setTimeout("if (!$('.disabled-suggestion').hasClass('hovered')) { $('.disabled-suggestion').fadeToggle(300, function() { $(this).remove(); }) }", 600);
			});
	});
	
}

function scrollbar_button (direction) {

	var container = $(this).closest('.b-content');
	var overview = $('.overview', container);
	var viewport = $('.viewport', container);

	switch (direction) {
		case 'left':
			orientation = 'left';
			offset = -parseInt(overview.css("left"));
			animation = '+=';
			break;
		case 'right':
			orientation = 'left';
			offset = overview.width() + parseInt(overview.css("left")) - viewport.width();
			animation = '-=';
			break;
		case 'top':
			orientation = 'top';
			offset = -parseInt(overview.css("top"));
			animation = '+=';
			break;
		case 'bottom':
			orientation = 'top';
			offset = overview.height() + parseInt(overview.css("top")) - viewport.height();
			animation = '-=';
			break;
	}

	if (overview.queue("fx").length == 0) {
		var updater = setInterval('storage.scrollable_blocks[' + container.data("s_index") + '].update();', 10);
		overview.animate(eval('[{ ' + orientation + ' : animation+(offset > 200? 200 : offset) }][0]'), 300, function() {
			clearInterval(updater);
			storage.scrollable_blocks[container.data("s_index")].update();
		});
	}

	return false;
}

function loginform () {
	
	function showlabels () {
		$('#login-username, #login-password')
			.each(function() {
				$(this).val('');
				$('label[for=' + $(this).attr("id") + ']')
					.css('top', $(this).position().top + $(this).outerHeight() / 2)
					.show();
			})
			.blur(function() {
				if (!$(this).val())
					$('label[for=' + $(this).attr("id") + ']').show();
			})
			.focus(function() {
				$('label[for=' + $(this).attr("id") + ']').hide();
			});
	}
	
	options = {
		'mode': 'overlay',
		'target': $('#block-favs'),
		'id': 'block-login',
		'showClose': true,
		'title': '<span></span>Вход на сайт',
		'html': '<form action="/login"> \
					<fieldset class="fields"> \
						<label for="login-username" id="login-username-label">Логин</label> \
						<label for="login-password" id="login-password-label">Пароль</label> \
						<input type="text" id="login-username" name="userEmail" /> \
						<input type="password" id="login-password" name="userPassword"/> \
						<a href="" class="forgot">Забыли пароль?</a> \
					</fieldset> \
					<fieldset> \
						<div class="button-container"> \
							<ul> \
								<li> \
									<a href="" class="button-stylish"><span>Войти</span></a> \
								</li> \
							</ul> \
						</div> \
					</fieldset> \
					<button class="none" type="submit">Войти</button> \
				</form>'
	};
	
	if ( $(window).scrollTop() > $('#content-wrap').offset().top ) {
		$.scrollTo($('#content-wrap'), 300, function() {
			$.raisepopup(options);
			showlabels();
			setTimeout('$("#block-login fieldset").effect("highlight", {color: "#faff66"}, 750)', 500);
		});
	} else {
		$.raisepopup(options);
		showlabels();
	}
	
}

function logoutform () {
	$.raisepopup({
		'mode': 'overlay',
		'target': $('#block-favs'),
		'id': 'block-logout',
		'showClose': true,
		'title': '<span></span>Выход',
		'html': '<form action=""> \
					<p>Вы уверены, что хотите выйти?</p> \
					<fieldset> \
						<div class="button-container"> \
							<ul> \
								<li> \
									<a href="/SignOut" class="button-stylish"><span>Выйти</span></a> \
								</li> \
								<li> \
									<a href="" class="button-stylish icon-close"><span>Отмена</span></a> \
								</li> \
							</ul> \
						</div> \
					</fieldset> \
				</form>'
	});
}

function recoveryform() {
	$.raisepopup({
		'mode': 'overlay',
		'target': $('#block-favs'),
		'width': 310,
		'height': 240,
		'id': 'block-recovery',
		'showClose': true,
		'title': 'Восстановление пароля',
		'html': '<div id="recovery-result" style="display:none; padding:10px 10px 10px 10px"> \
					<ul class="errors"></ul> \
					<div id="recovery-complite"> \
						<p>Вам отправлено письмо с новым паролем.</p> \
					</div> \
					<a href="#" id="recovery-back">Назад</a> \
				</div> \
				<form id="recovery-form" action=""> \
					<fieldset class="mail"> \
						<input type="text" id="recovery-email" name="userEmail" /> \
						<label for="recovery-email" id="recovery-email-label">Адрес электронной почты</label> \
					</fieldset> \
					<fieldset class="captcha"> \
						<label for="recovery-captcha" id="recovery-captcha-label">Введите код, указанный на изображении:</label> \
						<input type="text" id="recovery-captcha" name="captchaText" /> \
						<button id="refresh-captcha">Обновить изображение</button> \
						<img src="/i/generateImage" alt="" /> \
					</fieldset> \
					<fieldset> \
						<div class="button-container">  \
							<ul> \
								<li> \
									<a href="" class="button-stylish"><span>Получить пароль</span></a> \
								</li> \
							</ul> \
						</div> \
					</fieldset> \
				</form>'
	});
	
	$('#recovery-email')
		.each(function() {
			c_label = $('label[for=' + $(this).attr("id") + ']');
			if (!$(this).val())
				c_label.show();
			c_label.css('top', $(this).position().top + $(this).outerHeight() / 2);
		})
		.blur(function() {
			if (!$(this).val())
				$('label[for=' + $(this).attr("id") + ']').show();
		})
		.focus(function() {
			$('label[for=' + $(this).attr("id") + ']').hide();
		});
		
}


function searchform() {
	var input = $('#search-form input').eq(0);
	if (!input[0])
		return;
	var builder = new Bmsi.QueryBuilder(input[0]);


	$.raisepopup({
		'mode': 'append',
		'target': $('#content-wrap'),
		'id': 'block-search',
		'title': 'Формирование запроса',
		'html': '<h3 class="s">Параметр</h3> \
				<ul class="params clearfix first"> \
					<li><a href="Заг" class="zone">Заголовок</a></li> \
					<li><a href="Анн" class="zone">Аннотация</a></li> \
					<li><a href="Авт" class="zone">Автор</a></li> \
					<li><a href="Вид" class="zone">Вид спорта</a></li> \
					<li><a href="Ист" class="zone">Источник</a></li> \
					<li><a href="Руб" class="zone">Рубрика</a></li> \
					<li><a href="Рег" class="zone">Регион</a></li> \
					<li><a href="Тег" class="zone">Тег</a></li> \
				</ul> \
				<h3 class="s">Логический оператор</h3> \
				<ul class="params clearfix"> \
					<li><a href="И" class="operator">И</a></li> \
					<li><a href="ИЛИ" class="operator">ИЛИ</a></li> \
					<li><a href="НЕ" class="operator">НЕ</a></li> \
					<li><a href="(" class="operator">(</a></li> \
					<li><a href=")" class="operator">)</a></li> \
					<li><a href="*" class="operator">*</a></li> \
				</ul>',
		'load': function() {
			$('#search-form input').animate({ width: "360px" });
			$(this)
				.click(function(e) { e.preventDefault(); e.stopPropagation(); return false; })
				.find('a.zone').click(builder.AddZone).end()
				.find('a.operator').click(builder.AddOperator).end();
		}
	});
}

function wrap_blocks() {
	$('.block').not(':has(.b-content)')
		.wrapInner('<div class="b-right"><div class="b-left"><div class="b-content clearfix"></div></div></div>')
		.append('<div class="br"></div><div class="bl"></div><div class="tl"></div><div class="tr"></div><div class="bottom"></div>')
		.prepend('<div class="top"></div>');
}

$(function() {

	wrap_blocks();

	$('#block-topics .important')
		.append('<div class="marker"></div>');

	$('#block-persons ul li, .papers li, #block-news li')
		.append('<div class="shadow"></div>');

	$('#central-carousel')
		.append('<div class="bottom"></div><div class="right"></div><div class="left"></div><div id="selection"></div>')
		.prepend('<div class="top"></div>');
	$('#block-sources .block a.close').live('click', function () {
		$(this).closest('.cat-popup').efadeOut(300, function () {
			$(this).remove();
			$('#block-sources table.cat-main td.first>span').removeClass('active');
		});
		return false;
	});

	$('#block-sources table.cat-main td.first>span>a').live('click', function () {

		if ($(this).parent().is('.active')) {

			_span = $(this).parent();
			$('.cat-popup, .cat-annotation-popup').efadeOut(300, function () { $(this).remove(); _span.removeClass('active'); });

		} else {

			options = {
				classes: 'cat-popup',
				mode: 'append',
				target: $(this).closest('td'),
				width: $(this).closest('td').outerWidth(),
				height: $(this).closest('td').outerHeight() + 5,
				before: function () {
					$(this)
						.css('top', $(this).data("target").position().top)
						.find(".block")
							.css({
								'top': $(this).outerHeight() - 17
							})
						.end()
						.find(".bottom, .br, .bl").not(".block .block .block *")
							.remove();
				},
				html: $('.cat-info', $(this).closest('td')).html()
			}

			if ($('.cat-popup').get(0)) {
				$('.cat-popup, .cat-annotation-popup').efadeOut(300, function () {
					$('>span', $(this).closest('td')).removeClass('active');
					$(this).remove();
					$.raisepopup(options);
				});
			} else {
				$.raisepopup(options);
			}
			$.scrollTo($('.cat-popup').last(), 300);

			$(this).parent().addClass('active');

		}

		return false;

	});

	$('.media .cover').live('click', function () {
		hs.expand($(this).next('a').get(0), galleryOptions);
	});

	$('#block-sources table.cat-main td.first .actionlink').live('click', function () {
		cell = $(this).closest('td.first');
		placeholder = $(this).closest('td');
		t_content = $('.cat-annotation', cell).html();

		$.raisepopup({
			mode: 'overlay',
			target: placeholder,
			html: '<a href="" class="actionlink">Скрыть описание</a>' + '<div class="description-content">'+t_content+'</div>',
			classes: 'cat-annotation-popup',
			width: placeholder.outerWidth() + 10,
			height: 270
		});

		return false;
	});
	$('.cat-annotation-popup .actionlink').live('click', function () {
		$('.cat-annotation-popup').efadeOut(300, function () { $(this).remove(); });
		return false;
	});
	raiseregistrationtip([
		[
			'#block-favs .inactive-list',
			'#block-favs .icon-login'
		],
		[
			'.disabled-tip a, #CommentFormOverlay, a.addFavoritesInactive, #block-document.inactive ul.icons, #button-paid-add.inactive'
		]
	]);

	$('.disabled-suggestion')
		.live('mouseenter', function() {
			$(this).addClass('hovered');
			clearTimeout(storage.hoverevent);
		})
		.live('mouseleave', function() {
			$(this).fadeToggle(300, function() { $(this).remove(); })
		});

	$('.video-block li:not(.nomarker)').append('<div class="marker"></div>');
	$('#block-news').append('<div id="column-separator"></div>');
	$('#footer').append('<div id="footer-left"></div><div id="footer-right"></div>');

	$('.doc-content .media').each(function() {
		$(this).css('width', $('img', this).first().width());
		$('img', this).first().load(function() {
			t_media = $(this).closest('.media');
			t_media.css('width', $('img', t_media).first().width());
		});
	});

	$('#block-document img').load(function() {
		//$('#block-document .info').css('padding-left', $('#block-document img').width() + 22);
		$('.one-link #document-link-download, .one-link #document-link-read').css({
			'width': $('#block-document img').width() / 2 + 5,
			'padding-left': $('#block-document img').width() / 2 - 5,
			'background-position': $('#block-document img').width() / 2 - 48 + 'px 5px'
		});
	});
	$('form#AddCommentForm').live('submit',function(e){
		if ($.trim($('#DocumentCommentText').val()) == '') {
			return false;
		}
		$(this).ajaxSubmit({
			type: 'POST', dataType: 'json',
			success: function(result) {
				var commentsUrl = $('#AddCommentForm').attr('action');
				commentsUrl = commentsUrl.replace('addcomment', 'comments');
				$('#DocumentCommentText').val('');
				Bmsi.UpdateContent('#document-coments-container');
//				$('#commentsContainer').empty();
//				$('#commentsContainer').html(html);
//				var commentsCount = $('#commentsContainer').find('li').length;
//				$('#commentsTitle').text('Комментарии (' + commentsCount + ')');

			}
		});
		return false;
	});
	$('#addCommentBtn').click(function() {
		
		$('#AddCommentForm').submit();
		return false;

	});

	$('a.author').live('click', function() {
		var pr = $(this).parent();
		var a = $(this);
		$.get($(this).attr('href'), function(data) {
			var d = $(data).appendTo($('body'));
			d.css({
				'top': a.offset().top,
				'left': a.offset().left
			}).find('a.authorInfo_close').click(function() {
				$(d).remove();
				return false;
			});
			raiseregistrationtip([['a.mailFormInactive']]);
		});
		return false;
	});

	$('#button-paid-add.active')
		.click(function(event) {
			if (event.originalEvent) {
				var popup = {
					classes: 'icon-popup disabled-suggestion paid-tip',
					mode: 'tip',
					target: $(this),
					html: '<p class="main paid-title">Номер добавлен в корзину</p><p class="paid-content"><a href="/cart">Перейти в корзину</a><br /><a class="popup-close" href="">Продолжить просмотр сайта</a></p>'
				}
				$.get($(this).attr('href'), function(data) {
					if (data.Errors) {
						popup.html = '<p class="main paid-title paid-title-error">Ошибка</p><p class="paid-content">' + data.Errors["_FORM"].toString() + '</p>';
					}
					$.raisepopup(popup);
				}, "json");
			}
			event.preventDefault();
		})
		.mouseout(function() {
			storage.hoverevent = setTimeout("if (!$('.disabled-suggestion').hasClass('hovered')) { $('.disabled-suggestion').fadeToggle(300, function() { $(this).remove(); }) }", 600);
		});


	loadTips();
	/*$('a.clear').live('click', function() {
	$(this).parent().parent()
	.find(':checkbox, :radio').clearField().end()
	.find('ul.selected').remove();
	return false;
	})*/
	$('#block-filter fieldset input[type=checkbox], #block-filter fieldset input[type=radio], #block-filter a.clear').each(function() {
		$(this).click(function() {
			if ($(this).is('a') && $(this).hasClass('clear')) {
				$(this).parent().parent()
				.find(':checkbox, :radio').clearField().end()
				.find('ul.selected').remove();
			}
			options = {
				id: 'filter-tip',
				classes: 'icon-popup filter-tip',
				target: $(this).parent().parent(),
				mode: 'tip',
				before: function(popup) {
					$(this).css({
						'top': $(this).data("target").offset().top + (($(this).data("target").outerHeight() - $(this).outerHeight()) / 2),
						'left': $(this).data("target").offset().left + $(this).data("target").outerWidth() - 5
					});
					$('#filter-show', popup).live('click', function() {
						$('#filter-submit').click();
						return false;
					});
				}
			}
			var url = window.location.href;
			var urlParams = "";
			if (url.indexOf('?') >= 0) {
				urlParams = "&" + url.substring(url.indexOf('?') + 1, url.length);
				url = url.substr(0, url.indexOf('?'));
			}
			if (url.charAt(url.length - 1) != '/')
				url = url + '/'

			urlParams = urlParams.toLowerCase();
			var form = $(this).closest('form');
			var fromInputs = $("input", form);
			for (var i = 0; i < fromInputs.length; i++) {
				var name = String($(fromInputs[i]).attr("name")).toLowerCase();
				if (urlParams.indexOf(name) >= 0 && name != '') {
					var regexS = "[&]" + name + "=([^&#]*)";
					var regex = new RegExp(regexS, "gi");
					urlParams = urlParams.replace(regex, "");
				}
			}
			$.ajax({
				url: url + "count",
				data: form.serialize() + urlParams,
				dataType: 'json',
				cache: false,
				success: function(data) {
					$('#count', $('.tip-selected')).text(data);
					options.html = $('.tip-selected').html();
					$('#filter-tip').remove();
					$.raisepopup(options);
					$('#filter-show', $('.filter-tip')).live('click', function() {
						$('#filter-show').closest('form').submit();
						return false;
					});
					var timout;
					var outFunc = function() {
						timout = setTimeout("if (!$('#filter-tip').hasClass('hovered')) { $('#filter-tip').fadeToggle(300, function() { $(this).remove(); }) }", 600);
						$(this).unbind("mouseleave");
					}

					if (!options.target.parent().data("mouseleaveAttached")) {
						options.target.parent().data("mouseleaveAttached", true);
						options.target.parent().bind("mouseleave", outFunc);
					}
					$('#filter-tip').mouseover(function() {
						clearTimeout(timout);
						options.target.parent().unbind("mouseleave");
						$(this).bind("mouseleave", outFunc);
						options.target.parent().data("mouseleaveAttached", false);
					});
				}
			});
			/*$.getJSON(url + "count", form.serialize() + "&" + urlParams, function(data) {
			$('#count', $('.tip-selected')).text(data);
			options.html = $('.tip-selected').html();
			$('#filter-tip').remove();
			$.raisepopup(options);
			$('#filter-show', $('.filter-tip')).live('click', function() {
			$('#filter-show').closest('form').submit();
			return false;
			});
			var timout;
			var outFunc = function() {
			timout = setTimeout("if (!$('#filter-tip').hasClass('hovered')) { $('#filter-tip').fadeToggle(300, function() { $(this).remove(); }) }", 600);
			$(this).unbind("mouseleave");
			}

				if (!options.target.parent().data("mouseleaveAttached")) {
			options.target.parent().data("mouseleaveAttached", true);
			options.target.parent().bind("mouseleave", outFunc);
			}
			$('#filter-tip').mouseover(function() {
			clearTimeout(timout);
			options.target.parent().unbind("mouseleave");
			$(this).bind("mouseleave", outFunc);
			options.target.parent().data("mouseleaveAttached", false);
			});
			});*/
			if ($(this).is('a') && $(this).hasClass('clear'))
				return false;

		});
	});

	$('#block-filter .autosuggest a.close').live('click', function() { $('div.autosuggest').parent().removeClass('selected'); $(this).closest('.block').efadeOut(300, function() { $(this).hide(); }) });

	$('#block-favs .inactive-list').click(function() {
		return false;
	});

	$.each([
		[
			'Виды спорта',
			'Документы по выбранным видам спорта будут автоматически добавляться в Ваше избранное'
		],
		[
			'Источники',
			'Документы по выбранным источникам будут автоматически добавляться в Ваше избранное'
		],
		[
			'Рубрики',
			'Документы по выбранным рубрикам будут автоматически добавляться в Ваше избранное'
		],
		[
			'Регионы',
			'Документы по выбранным регионам будут автоматически добавляться в Ваше избранное'
		],
		[
			'Языки',
			'Выберите языки отображения для документов и источников. По-умолчанию показываются документы и источники на всех доступных языках'
		]
	],
	function() {
		$('.settings>div>div>div>label:contains(' + this[0] + ')').cabinetpopup(
			this[1], $('.settings>div>div>div>label:contains(' + this[0] + ')>a>span')
		);
	});

	$('.block .papers ul').each(function() {
		var s_width = 0;
		$('li', this).each(function() {
			$('h3', this).css('width', $('h3 a', this).width());
			if ($('h3', this).width() != $('.info', this).css('max-width')) {
				$('.info', this)
	                .css('max-width', '')
	                .css('width', $('h3 a', this).width());
			}
			$('>div', this).width($('img', this).outerWidth() + $('.info', this).width());
			s_width += $(this).width();
		});
		$(this).css('width', s_width);
	});

	$('#central-carousel-top, #central-carousel-bottom').hover(
		function() {
			$('img', this).efadeIn(500);
		},
		function() {
			$('img', this).efadeOut(500);
		}
	);


	$('#central-carousel-bottom').click(function() { carousel_scroll('down'); });
	$('#central-carousel-top').click(function() { carousel_scroll('up'); });

	$('#basket-checkbox-all').change(function() {
		if ($(this).is(':checked') == true) {
			$('td :checkbox', $(this).closest("form")).attr('checked', 'checked');
		} else {
			$('td :checkbox', $(this).closest("form")).attr('checked', '');
		}
	})
	$('#basket-block h2').prepend('<img alt="" src="/temp/BmsiNew/images/icon-basket.png" />');

	$('a.cart-new').each(function() {
		var m_width = 0;
		$(this).children().each(function() { m_width += $(this).width(); });
		$(this)
			.css('width', m_width + 1)
			.css('margin-left', -((m_width + 13) / 2));
	});

	$('.button-stylish').each(function() {
		$(this).css('width', $(this).width() + 1);
	});

	storage.scrollable_blocks = [];
	storage.scrollable_news = [];

	

	if ($('.papers').get(0)) {

		$('.papers').closest('.b-content').each(function() {
			a = storage.scrollable_blocks.push($(this)) - 1;
			$(this).data("s_index", a);
			storage.scrollable_blocks[a].tinyscrollbar({ axis: 'x' });
		});
	}
	$('#block-news .b-content').each(function() {
		a = storage.scrollable_blocks.push($(this)) - 1;
		$(this).data("s_index", a);
		storage.scrollable_blocks[a].tinyscrollbar({ axis: 'y' });
	});
	recalculate_all();
	$(window).resize(recalculate_all);

	function make_active() {
		$('li.active', $(this).closest('.papers'))
			.animate({ "width": "75" }, 1000)
			.removeClass('active');
		$(this)
			.animate({ "width": $('>div', this).width() + 15 }, 1000, function() {

				var s_width = 0;
				$('li', $(this).parent()).each(function() {
					s_width += $(this).width();
				});
				$(this).parent().css('width', s_width);

				storage.scrollable_blocks[$(this).closest('.b-content').data("s_index")].update();

			})
			.addClass('active');
	}

	$('.papers li:not(.active)').live('click', function() {
		make_active.call(this);
	});

	$('.papers').each(function() {
		make_active.call($('li', this).first());
	});

	$('.scrollbar-c').hover(
		function() {
			$(this).children().efadeIn(500);
		},
		function() {
			$(this).children().efadeOut(500);
		}
	);
	$('.scrollbar-c').children().hide();

	$('.scrollbar-c .prev').click(function() {
		return scrollbar_button.call(this, 'left');
	});
	$('.scrollbar-c .next').click(function() {
		return scrollbar_button.call(this, 'right');
	});

	$('#block-news .b-content').hover(
		function() {
			$('.scrollbar-v', this).efadeIn(500);
		},
		function() {
			$('.scrollbar-v', this).efadeOut(500);
		}
	);

	$('.scrollbar-v .prev').click(function() {
		return scrollbar_button.call(this, 'top');
	});
	$('.scrollbar-v .next').click(function() {
		return scrollbar_button.call(this, 'bottom');
	});
	/*
	
	$('.scrollbar').hover(
	function() {
	$(this).children().efadeIn(500);
	},
	function() {
	$(this).children().efadeOut(500);
	}
	);
	$('.scrollbar').children().hide();
	
	*/

	if ($.browser.msie && $.browser.version == 6) {
		DD_belatedPNG.fix('.tr, .tl, .br, .bl, #main-image h2, .right, .left, .top, .bottom, .a-right, .marker, .shadow, #selection, .new, .s-right, .s-left, .b-left, .scrollbar, .center, .track, .dragbar, .scrollbar a, h2 img, .rr, #register-success .main, .t-tip, .b-right, ul.icons li a');
		try {
			document.execCommand('BackgroundImageCache', false, true);
		} catch (e) { }
	}

	$('#icon-construct').click(function() {

		if ($('#block-search').get(0)) {
			$('#search-form input').animate({ width: "133px" }, function() {
				$('#block-search').fadeToggle(300, function() { $(this).remove(); });
				$('#search-form .delete-link').fadeToggle(300);
			});
		} else {
			$('#search-form .delete-link').fadeToggle(300);
			searchform();
		}

		$(this).toggleClass('perm-active');
		return false;
	});
	$('#block-search .delete-link').click(function() {
		$('#search-form input').val('');
		return false;
	});

	$('.block .icon-close').live('click', function() {
		$(this).closest('.block').efadeOut(300);
		$('#overlay').efadeOut(300);
		return false;
	});
	$('#block-login a.forgot-b, #block-login a.forgot').live('click', function() {
		recoveryform();
		$('#recovery-result').css('display', 'none');
		return false;
	});

	//$('#block-sources a.desc, #block-document a.actionlink').live('click', function() {
	/*$('#block-document a.actionlink').live('click', function() {
	alert(222);
	$.raisepopup({
	classes: 'description-block',
	html: $('.description-block .b-content').html(),
	showClose: true,
	modal: true
	});
	return false;
	});*/
	$('div.annotation a.actionlink').live('click', function() {
		$('#annotation-full').parent().css('position', 'relative');
		$('#annotation-full').parent().css('height', '100%');
		$('#annotation-full').css('position', 'absolute');
		$('#annotation-full').css('margin', '0');
		$('#annotation-full').css('width', '100%');
		$('#annotation-full').find("#description-body").height($('#annotation-full').parent().parent().height() - 62);
		$('#annotation-full').find("#description-body").css('overflow', 'auto');
		$('#annotation-full').css('top', 7);
		$('#annotation-full').css('left', -5);
		$('#annotation-full').show();
		return false;
	});



	$('#block-cabinet fieldset.settings div.popup>div>label>a').live('click', function() {
		$(this).closest("div.popup").efadeOut(300);
		return false;
	})

	$('#block-cabinet fieldset.settings>div>div>div>label>a.add').live('click', function() {
		$('.t-block').efadeOut(300);
		$(this).closest("div").find("div.popup").efadeIn(300);
		return false;
	});

	$.each([
		[
			'#block-document h2 a.expander, #block-document h2 a.action-link',
			'a.expander',
			'.info'
		],
		[
			'#block-document a.announce-link',
			'span.icon',
			'.announce-content'
		],
		[
			'#block-document a.file-link',
			'span.icon',
			'.file-list'
		],
		[
			'#block-biblio h2 a.expander, #block-biblio h2 a.action-link',
			'a.expander',
			'.biblio-content'
		],
		[
			'#block-comments h2 a.expander, #block-comments h2 a.action-link',
			'a.expander',
			'.comments-content'
		]
	],
	function() {
		$(this[0])
			.data({
				'expand-icon': this[1],
				'expandable': this[2]
			})
			.click(function() {
				$($(this).data('expand-icon'), $(this).parent()).toggleClass('collapsed');
				$(this).closest('.block').find($(this).data('expandable')).toggle();
				recalculate_all();
				return false;
			});
	});

	$('#icon-setup').click(function() {
		show_progress(document.body);
		//return false;
	});

	$('.biblio-content a').live('click', function() {
		$.raisepopup({
			id: 'biblio-full-block',
			html: $('#biblio-full-block .b-content').html(),
			showClose: true,
			modal: true,
			target: $(this)
		});
		recalculate_all();
		return false;
	});




	/*
	---------------------------------------------------------------------------
	Captcha
	*/
	$("button#refresh-captcha").live('click', function() {
		var i = $(this).next('img'), s = i.attr('src');
		if (String(s).indexOf("?") == -1)
			s = s + "?";
		s = s + Math.random();
		i.attr("src", s).efadeOut(250).load(function() { $(this).efadeIn(300); }).nextAll('.error-notice').efadeOut(400);
		return false;
	});

	/*
	---------------------------------------------------------------------------
	Login form
	*/
	$('.login-trigger, #icon-login, .icon-login').live('click', function() { $('.disabled-suggestion').remove(); loginform(); return false; });

	$('#block-login .button-stylish').live('click', function() {
		login($(this).parents('form:first'));
		return false;
	});
	$('#block-login form').live('submit', function() {
		login($(this));
		return false;
	});

	function loginSuccess() {
		window.location.reload();
	}
	function loginError(messages) {
		var form = this;
		hide_progress(this);
		$('a.forgot', form).efadeOut(300, function() {
			if (!$('p.error', form).get(0)) {
				$('fieldset.fields', form)
					.append($('<p class="error"><span id="error-message">' + messages['_FORM'] + '</span></p>'))
					.append('<a href="" class="forgot-b">Восстановить пароль</a>');
				if ($.browser.msie && $.browser.version == 6) {
					$('.block .bl, .block .br').each(
						function() {
							$(this).css('bottom', 'auto').css('top', $(this).parent().height() - 8);
						}
					);
				}
			}
			else {
				$('#error-message').html(messages['_FORM'].toString());
			}
			$('p.error, a.forgot-b', form).efadeIn(300);
		});
	}
	function login(form) {
		//var progressBlock = $(form).hasClass('block') ? form : $(form).parents(".block:first");
		show_progress(form);
		$(form).closest('.b-content').height('auto');
		Bmsi.Login(
			$('input[name=userEmail]', form).val()
			, $('input[name=userPassword]', form).val()
			, loginSuccess.delegate(form)
			, loginError.delegate(form)// function(msg) { loginError.call(form, msg); }
		);
	}

	/*
	---------------------------------------------------------------------------
	Login form
	*/

	$('#icon-logout').live('click', function() { $('.disabled-suggestion').hide(); logoutform(); return false; });
	/*
	---------------------------------------------------------------------------
	Recover password
	*/
	$('#block-recovery form').live('submit', function() {
		recoverpwd(this);
		return false;
	});
	$('#block-recovery .button-stylish').live('click', function() {
		recoverpwd($(this).parents('form:first'));
		return false;
	});
	function recoverpwd(form) {
		show_progress(form);
		Bmsi.RecoverPassword(
			$('input[name=userEmail]', form).val()
			, $('input[name=captchaText]', form).val()
			, recoverpwdSuccess.delegate(form)
			, recoverpwdError.delegate(form)// function(msg) { loginError.call(form, msg); }
		);
	}
	function recoverpwdSuccess() {
		hide_progress(this);
		$("#recovery-form").remove();
		$('#recovery-result').css("display", "block");
		$('#recovery-back').css("display", "none");
	}
	function recoverpwdError(messages) {
		hide_progress(this);
		//        if (messages["userEmail"] != null) {
		//            addErrorMessage(this, 'userEmail', messages["userEmail"]);
		//        }
		//        if (messages["captchaText"] != null) {
		//            addErrorMessage(this, "captchaText", messages["captchaText"]);
		//        }

		if (messages["captchaText"]) {
			$("fieldset.captcha", this)
							.append('<p class="error-notice">&#160;</p>')
							.find('p.error-notice')
							.hide()
							.text(messages["captchaText"].toString())
							.efadeIn(300);
		}
		/*
		messages["captchaText"] - ошибки в коде изображения;
		messages["userEmail"] - ошибки в адресе
		messages["server"] - ошибки сервера
		messages["_FORM"] - ошибка отправки формы
		*/

	}
    
    if ($('#document-link-download').offset() &&   $('#document-link-read').offset() && $('.info td:first img').width() > 0) {
        if ($('#document-link-download').offset().top > $('#document-link-read').offset().top) { $('#document-link-download').css('float','left') }
    };
    $('.info td:first img').load(function() {
    	if ($('#document-link-download').offset() && $('#document-link-read').offset() && $('#document-link-download').offset().top > $('#document-link-read').offset().top) { $('#document-link-download').css('float', 'left') }
    });
    
    
	/*
	---------------------------------------------------------------------------
	Registration
	*/
	$('#register-block .fields input.error').live('focus', remove_error);
	$('#register-block .fields label.error-notice').live('click', remove_error);
	$('#register-block fieldset.captcha p.error-notice').live('click', function() { $(this).remove(); });
	$('#register-block fieldset.captcha input').live('click focus', function() { $(this).nextAll('p.error-notice').remove(); });
	$('#block-recovery fieldset.captcha p.error-notice').live('click', function() { $(this).remove(); });

	$('#register-block form').live('submit', function() {
		register(this);
		return false;
	});
	$('#register-block .button-stylish').live('click', function() {
		register($(this).parents('form:first'));
		return false;
	});
	function addErrorMessage(form, inputName, msgText) {
		$("input[name=" + inputName + "]", form)
			.addClass('error')
			.val('')
			.parent().append(
				$('<label class="error-notice" style="white-space:nowrap; margin-left:-150px"></label>')
					.text(msgText.toString())
			);
	}
	function register(form) {
		//		var f = $(form);
		//		var progressBlock = f.hasClass('block') ? f : f.parents(".block:first");
		show_progress(form);
		$(form).ajaxSubmit({
			type: 'POST', dataType: 'json'
			, success: function(result) {
				Sys.Debug.traceDump(result);
				if (!result)
					throw new Error();
				if (result.Errors) {
					Sys.Debug.traceDump(result.Errors["captchaText"]);
					if (result.Errors["captchaText"]) {
						$("fieldset.captcha", form)
							.append('<p class="error-notice">&#160;</p>')
							.find('p.error-notice')
							.hide()
							.text(result.Errors["captchaText"].toString())
							.efadeIn(300);
					}
					if (result.Errors["MbsiUser_Email"])
						addErrorMessage(form, 'userEmail', result.Errors["MbsiUser_Email"]);
					else if (result.Errors["MbsiUser_Name"])
						addErrorMessage(form, 'userEmail', result.Errors["MbsiUser_Name"]);
					if (result.Errors["MbsiUser_DisplayName"])
						addErrorMessage(form, 'userDisplayName', result.Errors["MbsiUser_DisplayName"]);
					if (result.Errors["MbsiUser_Password"]) {
						if (result.Errors["userPasswordConfirm"]) {
							if (result.Errors["MbsiUser_Password"].length > 1) {
								addErrorMessage(form, 'userPassword', result.Errors["MbsiUser_Password"][0]);
								addErrorMessage(form, 'userPasswordConfirm', result.Errors["MbsiUser_Password"][1]);
							}
							else
								addErrorMessage(form, 'userPasswordConfirm', result.Errors["MbsiUser_Password"]);
						}
						else
							addErrorMessage(form, 'userPassword', result.Errors["MbsiUser_Password"][0]);
					}
				} else {
					$(form).parent().find('#register-success').efadeIn(300);
				}
				hide_progress(form);
				recalculate_all();
			}
			, error: function(xhr, status, e) { hide_progress(form); }
		});
	}
})

$(function() {

	$('#menu-main li a, #search-form button, #search-form li a')
	.each(function() {
		if (!$(this).hasClass('active'))
			$(this).data("togglable", true);
	})
	.live('mouseover mouseout', function(event) {
		if (event.type == 'mouseover') {
			$(this).addClass('active');
		} else {
			if ($(this).data("togglable"))
				$(this).removeClass('active');
		}
	});
	$('#block-popular li, #block-favs li, #block-navigation li')
	.each(function() {
		if (!$(this).hasClass('active'))
			$(this).data("togglable", true);
	})
	.hover(
		function() {
			$(this).addClass('active');
		},
		function() {
			if ($(this).data("togglable"))
				$(this).removeClass('active');
		}
	);

	$('#search-form .delete-link').click(function() {
		$('#search-form input').val('');
		return false;
	});

	$.fn.clearField = function() {
		this.filter(':checkbox, :radio').attr('checked', false);
		this.filter(':text, textarea').val('');
		this.filter('select').each(function() { this.selectedIndex = 0; })
		return this;
	}
	$('#block-filter button').live('click', function() { $(this).parents('form:first').submit(); return false; });
	$('#docfilter-sources').entitySuggestions({ type: 'Source', wrapper: $('#FilterWrapperSourceID'), appendTo: $('#FilterWrapperSourceID').find('.clearfix') });
	//$('#FilterWrapperSourceID').hide();

	$('#docfilter-categories').entitySuggestions({ type: 'Category', wrapper: $('#FilterWrapperCategoryID'), appendTo: $('#FilterWrapperCategoryID').find('.clearfix'), popup: ({ iconId: 'categories-popup-ref', id: 'categories-popup', title: 'Рубрики', pageSize: 24 }) });//, template: 'rubriclist.xslt'
	//$('#FilterWrapperCategoryID').hide();

	$('#docfilter-sport').entitySuggestions({ type: 'SportType', wrapper: $('#FilterWrapperSportTypeID'), appendTo: $('#FilterWrapperSportTypeID').find('.clearfix') });
	//$('#FilterWrapperSportTypeID').hide();

	$('#docfilter-regions').entitySuggestions({ type: 'MbsiRegion', wrapper: $('#FilterWrapperRegionID'), appendTo: $('#FilterWrapperRegionID').find('.clearfix') });
	//$('#FilterWrapperRegionID').hide();

	$('#docfilter-tags').entitySuggestions({ type: 'Tag', wrapper: $('#FilterWrapperTagID'), appendTo: $('#FilterWrapperTagID').find('.clearfix') });
	//$('#FilterWrapperTagID').hide();

	$('#docfilter-authors').entitySuggestions({ type: 'Author', wrapper: $('#FilterWrapperAuthorID'), appendTo: $('#FilterWrapperAuthorID').find('.clearfix') });
	//$('#FilterWrapperAuthorID').hide();

	$('#docfilter-interpreters').entitySuggestions({ type: 'Interpreter', wrapper: $('#FilterWrapperInterpreterID'), appendTo: $('#FilterWrapperInterpreterID').find('.clearfix') });
	//$('#FilterWrapperInterpreterID').hide();

	$('#docfilter-issuecategories').entitySuggestions({ type: 'Rubric', wrapper: $('#FilterWrapperRubricID'), appendTo: $('#FilterWrapperRubricID').find('.clearfix'), criteria: { 'SourceId': $('#SourceID').val() }, popup: ({ iconId: 'source-rubrics-ref', id: 'categories-popup', title: 'Рубрики издания', pageSize: 24 }) });//, template: 'sourcerubriclist.xslt'

	$('#docfilter-publishers').entitySuggestions({ type: 'Source', wrapper: $('#FilterWrapperPublishersID'), appendTo: $('#FilterWrapperPublishersID').find('.clearfix'), criteria: { 'SourceTypeId': $('#PublisherTypeID').val()} });
	//$('#FilterWrapperRubricID').hide();
	$('#sourcefilter-issueyear')
			.find('>option').each(function(i) {
				if (i != 0)
					$(this).data('AvailableMonths', eval(this.title)).attr("title", null);
			}).end().bind('change', function initMonths() {
				var m = $("#sourcefilter-issuemonth")[0];
				if (!m) return;
				var mv = m.options[m.selectedIndex].value;
				$(m).empty().append('<option>Месяц</option>');
				if (this.selectedIndex == 0) {
					$("#sourcefilter-issuemonth").attr('disabled', 'disabled');
					return;
				}
				else {
					$("#sourcefilter-issuemonth").removeAttr('disabled');
					$(m).empty().append('<option>&nbsp;</option>')
				}

				$.map($(this.options[this.selectedIndex]).data('AvailableMonths'), function(month) {
					var opt = $('<option/>').val(month.MonthNumber).text(month.Month).appendTo(m);
					if (month.MonthNumber == mv)
						opt.attr("selected", true);
				});
			}).change();

	/*	if ($('#sourcefilter-issuemonth:disabled').get(0)) {
	m_s = $('#sourcefilter-issuemonth:disabled');
	m_s.closest('div').css('position', 'relative');
	$('<div />')
	.css({
	'position': 'absolute',
	'top': m_s.position().top,
	'left': m_s.position().left + 7,
	'width': m_s.outerWidth(),
	'height': m_s.outerHeight(),
	'-ms-filter': 'progid:DXImageTransform.Microsoft.Alpha(Opacity=1)',
	'filter': 'alpha(opacity=1)',
	/*'background': 'white',
	'opacity': '.01',
	'z-index': 300
	})
	.click(function() {
	$.raisepopup({
	classes: 'icon-popup clicked-tip',
	mode: 'tip',
	target: m_s,
	html: 'Пожалуйста, выберите год'
	});
	})
	.mouseleave(function() {
	$('.clicked-tip').fadeOut(300);
	})
	.appendTo(m_s.closest('div'));
	}
	*/

	$('a.submit').live('click', function() {
		$(this).parents("form:first").submit();
		return false;
	});
	$('a.clear-field').live('click', function() {
		var p = $(this).parent(), ff = p.attr('for');
		if (ff && ff.toString().length)
			$(this).parents('form:first').find('#' + ff).clearField();
		else
			p.nextAll('input').clearField();
		return false;
	});
	/*
	Кабинет пользователя
	*/
	jQuery(function() {
		$("#cabinet-lang").change(function() {
			if (this.selectedIndex == 0)
				return;
			var list = $(this).parents('div.popup:first').next('ul');
			var s = $(':nth-child(' + (this.selectedIndex + 1) + ')', this);
			if (list.hasValue(this.name, s.val()))
				return false;
			$(this).parents('div.popup:first').efadeOut(300);
			$.fn.entitySuggestions.renderItem({ ID: s.val(), value: s.text() }, { name: this.name })
				.prepend(
					$('<input type="hidden"/>').attr("name", 'LanguageID').val(s.attr('id'))
				).appendTo(list);
			this.selectedIndex = 0;
		});
		$("#cabinet-sport").each(function() {
			var t = $(this);
			t.entitySuggestions({
				type: 'SportType',
				targetList: t.parents('div.popup:first').next('ul'),
				close: function() { t.parents('div.popup:first').efadeOut(300); }
			});
		});
		$("#cabinet-region").each(function() {
			var t = $(this);
			t.entitySuggestions({
				type: 'MbsiRegion',
				targetList: t.parents('div.popup:first').next('ul'),
				close: function() { t.parents('div.popup:first').efadeOut(300); }
			});
		});
		$("#cabinet-category").each(function() {
			var t = $(this);
			t.entitySuggestions({
				type: 'Category',
				targetList: t.parents('div.popup:first').next('ul'),
				close: function() { t.parents('div.popup:first').efadeOut(300); },
				popup: ({ iconId: 'categories-popup-ref', id: 'categories-popup', title: 'Рубрики', pageSize: 24 })//, template: 'rubriclist.xslt'
			});
		});
		$("#cabinet-source").each(function() {
			var t = $(this), f = t.parent().find('#cabinet-source-type');
			t.entitySuggestions({
				type: 'Source',
				targetList: t.parents('div.popup:first').next('ul'),
				close: function() { t.parents('div.popup:first').efadeOut(300); },
				criteria: function() { return { SourceTypeID: f.val() }; }
			});
		});
		function saveUserData(form) {
			show_progress(form);
			$(form).ajaxSubmit({
				type: 'POST', dataType: 'json'
				, success: Bmsi.responseParser(
					function(data) {
						hide_progress(form);
						$.ajax({
							url: '/user/favorites',
							cache: false,
							success: function(html) {
								$('#favorite-items').html(html);
								$('#block-favs .inactive-list').click(function() {
									return false;
								});
								$('#block-favs li')
									.each(function() {
										if (!$(this).hasClass('active'))
											$(this).data("togglable", true);
									})
									.hover(
										function() {
											$(this).addClass('active');
										},
										function() {
											if ($(this).data("togglable"))
												$(this).removeClass('active');
										}
									);
									wrap_blocks();

							}
						});
					},
					function(errors) {
						Sys.Debug.traceDump(errors);
						alert(Bmsi.GetFirstError(errors));
						hide_progress(form);
					}, form)
				, error: function(xhr, status, e) { hide_progress(form); }
			});
		}
		$('form#block-cabinet').live('submit', function() {
			saveUserData(this);
			return false;
		});
		//новое на сайте
		$('a.doc-popup').live('click', function() {
			$.getJSON($(this).attr('href'), function(data) {
				var block = $('#block-document');

				//block.empty();
				var content = block.find('div.doc-content:first');
				block.find('h2:first').text(data.Title);
				block.find('h1:first').text(data.Title);
				var htmlStr = '';
				if (data.Images && data.Images.length > 0) {
					htmlStr += '<div class="media">';
					htmlStr += '	<img src="/media/bmsi_source_floatwidth/' + data.Images[0].ID + '" alt="" />';
					htmlStr += '	<p>' + data.Images[0].MediaDescription + '</p>';
					htmlStr += '</div>';

				}
				htmlStr += '<p>' + data.Body + '</p>';
				content.html(htmlStr);
				$('.doc-content .media').each(function() {
					$(this).css('width', $('img', this).first().width());				
					$('img', this).load(function() {
						$(this).closest('.media').css('width', $(this).width());
					});
				});
				$('#block-document').css('top', e_value + (($(window).height() - $('#block-document').height()) / 2));
				$('#block-document').efadeIn(300);
				$('#overlay').efadeIn(300);
				//alert("Data Loaded: " + data);
			});
			return false;
		});

		$('#block-sources a.desc').live('click', function() {
			var id = $(this).attr('sourceId');
			$('#annotation-full' + id).css('position', 'absolute');
			$('#annotation-full' + id).css('margin', '0');
			$('#annotation-full' + id).css('width', 'auto');
			//$('#annotation-full' + id).find("#description-body").height(140);
			$('#annotation-full' + id).find("#description-body").css('overflow', 'auto');
			$('#annotation-full' + id).parent().css('position', 'relative');
			$('#annotation-full' + id).css('top', 0);
			$('#annotation-full' + id).css('left', 125);
			$('#annotation-full' + id).show();
			return false;
		});

		$('#block-sources a.descAnnotation').live('click', function() {
			var id = $(this).attr('id').replace("annotation", "");
			$.get($(this).attr('href'), function(data) {
				var dataObj = eval('[' + data + ']');
				if (!data)
					return false;
				if (!data.length)
					return false;
				if (dataObj.length <= 0)
					return false;
				$('#annotation-full' + id).css('position', 'absolute');
				$('#annotation-full' + id).css('margin', '0');
				$('#annotation-full' + id).css('width', 'auto');

				var title = dataObj[0].Title;
				if (title.length > 80)
					title = title.substring(0, 80) + "...";
				$('#annotation-full' + id).find('#description-title').text(title);
				$('#annotation-full' + id).find("#description-body").html(dataObj[0].Abstract);
				$('#annotation-full' + id).find("#description-body").height($('#annotation-full' + id).parent().height() - 40);
				$('#annotation-full' + id).find("#description-body").css('overflow', 'auto');
				$('#annotation-full' + id).parent().css('position', 'relative');
				$('#annotation-full' + id).css('top', 0);
				$('#annotation-full' + id).css('left', 130);
				$('#annotation-full' + id).show();
			});
			return false;
		});


		$('#form_mail_close').live('click', function() {
			$('#form_mailTo').remove();
			return false;
		});

		$('a.mailForm').live('click', function() {
			var pr = $(this).parent().parent();
			if ($(this).attr('id') == 'authorInfoSendLink') {
				pr = $('#author-block-popup').find('.top');
			}
			var email = $(this).attr("email");
			var pageUrl = window.location.href;
			$.get($(this).attr('href'), function(data) {
				var txt = data;
				txt = txt.replace(/#pageUrl#/g, pageUrl);
				txt = txt.replace(/#mailTo#/g, email);
				pr.append(txt);
			});
			return false;
		});
		$('#authorInfoSend').live('click', function() {
			var pr = $(this).parent().parent();
			var email = $(this).attr("email");
			var pageUrl = window.location.href;
			$.get($(this).attr('href'), function(data) {
				var txt = data;
				txt = txt.replace(/#pageUrl#/g, pageUrl);
				txt = txt.replace(/#mailTo#/g, email);
				pr.append(txt);
			});
			return false;
		});
		//для источниковиконка "Документ с видео"
		$('#set-issues-filter-video').click(function() {
			$('#docfilter-settings-WithVideo').attr("checked", "true");
			$('#docfilter-settings-WithVideo').parents("form:first").submit();
			return false;
		});

		//библиографическое описание
		$('.icon-card a').live('click', function() {
			$.get($(this).attr('href'), function(data) {
				$.raisepopup({
					showClose: true,
					modal: true,
					title: 'Полное библиографическое описание',
					id: 'biblio-full-block',
					html: data,
					target: $(this)
				});
			});
			return false;
		});
	});
	$.getScript("http://translate.google.com/translate_a/element.js?cb=googleTranslateElementInit");
	$('.gallery-container').mediaGallery();
});
/*
---------------------------------------------------------------------------
Basket
*/
$('#complete-form .button-stylish').live('click', function() {
	$(this).parents('#complete-form').submit();
	return false;
});

function GetTotalHeightOfHiddenElements(elem) {

}

