/// <reference path="../../../js/jquery-1.4.1-vsdoc.js" />
/// <reference path="../../../js/MicrosoftAjax.debug.js" />
function carousel_scroll_up() {

	$('#central-carousel-top').unbind('click');
	$('#central-carousel-bottom').unbind('click');

	clearInterval(int_a);

	$('#central-carousel li').last()
		.clone()
			.attr('style', 'margin-top:-89px')
			.prependTo($('#central-carousel ul'));

	$('#central-carousel li').first()
		.animate({ 'margin-top': "+=89" }, 1000, "swing", function() {
			$('#central-carousel li').last().remove();
			$('#main-image')
		        .find("img")
		            .attr("src", $('#central-carousel li img').eq(1).attr("alt"))
		        .end()
		        .find("h2")
		            .html($('#central-carousel li img').eq(1).attr("title"));

			int_a = setInterval("carousel_scroll_down(true)", 10000);

			$('#central-carousel-top').bind('click', carousel_scroll_up);
			$('#central-carousel-bottom').bind('click', carousel_scroll_down);

		});

}

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();
}

jQuery.fn.fadeToggle = function(speed, easing, callback) {
	if ($.browser.msie) {
		return ($(this).is(':visible')) ? this.hide() : this.show();
	} else {
		return this.animate({ opacity: 'toggle' }, 0, easing, callback);
	}
};
jQuery.fn.efadeIn = function(speed, easing, callback) {
	if ($.browser.msie) {
		return this.fadeIn(0, easing, callback);
	} else {
		return this.fadeIn(speed, easing, callback);
	}
}
jQuery.fn.efadeOut = function(speed, easing, callback) {
	if ($.browser.msie) {
		return this.fadeOut(0, easing, callback);
	} else {
		return this.fadeOut(speed, easing, callback);
	}
}


function carousel_scroll_down(e) {
	$('#central-carousel-top').unbind('click');
	$('#central-carousel-bottom').unbind('click');

	clearInterval(int_a);

	$('#central-carousel li').first()
		.clone()
			.attr('style', '')
			.appendTo($('#central-carousel ul'));

	$('#central-carousel li').first()
		.animate({ 'margin-top': "-=89" }, 1000, "swing", function() {
			$(this).remove();
			$('#main-image')
		        .find("img")
		            .attr("src", $('#central-carousel li img').eq(1).attr("alt"))
		        .end()
		        .find("h2")
		            .html($('#central-carousel li img').eq(1).attr("title"));

			int_a = setInterval("carousel_scroll_down(true)", 10000);

			$('#central-carousel-bottom').bind('click', carousel_scroll_down);
			$('#central-carousel-top').bind('click', carousel_scroll_up);

		});

}

function recalculate_all() {

	$('.scrollbar, .scrollbar .track').css('width', $('.papers').width() - 8);

	if ($('#mine_papers_wrap').get(0)) {
		var wndo_mine = new dw_scrollObj('mine_papers_wrap', 'mine_list_wrap', 'mine_list');
		wndo_mine.setUpScrollbar('mine_dragBar', 'mine_track', 'h', 1, 1, true);
		wndo_mine.setUpScrollControls('mine_scrollbar');
	}

	if ($('#magazines_papers_wrap').get(0)) {
		var wndo_magazines = new dw_scrollObj('magazines_papers_wrap', 'magazines_list_wrap', 'magazines_list');
		wndo_magazines.setUpScrollbar('magazines_dragBar', 'magazines_track', 'h', 1, 1, true);
		wndo_magazines.setUpScrollControls('magazines_scrollbar');
	}

	if ($('#books_papers_wrap').get(0)) {
		var wndo_books = new dw_scrollObj('books_papers_wrap', 'books_list_wrap', 'books_list');
		wndo_books.setUpScrollbar('books_dragBar', 'books_track', 'h', 1, 1, true);
		wndo_books.setUpScrollControls('books_scrollbar');
	}

	$('#central-carousel h2').css('width', $('#main-image').width() - 169 + 'px');
	$('#block-news .video-block li').each(function() {
		var t_e = $(this);
		var a_e = $('li', $('#block-news .halved').first()).eq($(this).index('.video-block li'));
		if (t_e.height() > a_e.height()) {
			a_e.css('height', t_e.height());
		} else {
			t_e.css('height', a_e.height());
		}
	});
	$('#column-separator').css('height', $('#block-news').height() - 7);

	$('.papers .new').each(
		function() {
			$(this).css('right', 'auto').css('left', 50 - ($('.center', this).width() + $('.right', this).width() + $('.left', this).width()) + 5);
		}
	);

	$('#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()
	});

	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);
			}
		);
		$('.right').each(
			function() {
				$(this).css('right', 'auto').css('left', $(this).parent().width() + 2);
			}
		);

		$('.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').parent().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());

}

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="t-tip"></div><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>')
		.append('<div class="bottom"></div>')
		.prepend('<div class="top"></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(true)", 10000);
var e_value = 0;

$(function() {

	//	$('#register-block .button-stylish').live('click', function() {
	//		$('#register-success').efadeIn(300);
	//		return false;
	//	})

	//	$('#register-block .fields input.error').live('focus', remove_error);
	//	$('#register-block .fields label.error-notice').live('click', remove_error);



	$('.block')
		.each(function() {
			$(this).html('<div class="b-right"><div class="b-left"><div class="b-content clearfix">' + $(this).html() + '</div></div></div>');
		})
		.append('<div class="br"></div><div class="bl"></div><div class="tl"></div><div class="tr"></div>')
		.append('<div class="bottom"></div>')
		.prepend('<div class="top"></div>');

	$('#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>')
		.append('<div id="selection"></div>')
		.prepend('<div class="top"></div>');
	$('#block-logout .b-content').height($('#block-favs .b-content').height());
	$('.video-block li').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>');

	qtipconfig = {
		content: {
			title: {
				text: 'Необходима регистрация'
			},
			text: 'Чтобы пользоваться разделом &laquo;Избранное&raquo,<br />необходимо <a href="" class="login-trigger">войти</a> или <a href="">зарегистрироваться</a>.'
		},
		position: {
			target: $('#block-favs .icon-register'),
			adjust: {
				y: 5,
				x: -210
			}
		},
		hide: {
			fixed: true,
			delay: 500
		},
		show: {
			when: {
				event: 'click'
			}
		},
		style: {
			border: {
				color: "#233a53",
				width: 3,
				radius: 2
			},
			tip: {
				corner: 'topLeft',
				size: {
					x: 10,
					y: 10
				}
			},
			title: {
				background: "#4c637c",
				color: "white",
				"font-size": "12px",
				"font-weight": "normal"
			},
			classes: {
				tip: "inactive-tip",
				tooltip: "s-tip"
			},
			"background": "#6d849d",
			"color": "white",
			"font-size": "12px",
			"width": 300,
			"line-height": 1.25,
			"padding": "7px 10px"
		}
	}

	qtipconfiglight = {
		//		content: {
		//			text: '<p>Выбрано 50 источников</p><a href="">Показать</a>'
		//		},
		position: {
			corner: {
				target: 'bottomMiddle',
				tooltip: 'topMiddle'
			},
			adjust: {
				y: 5
			}
		},
		hide: {
			fixed: true,
			delay: 500
		},
		show: {
			when: {
				event: 'mouseover',
				delay: 500
			}
		},
		style: {
			border: {
				color: "#82868a",
				width: 1,
				radius: 0
			},
			tip: {
				corner: 'topMiddle',
				size: {
					x: 14,
					y: 7
				}
			},
			title: {
				background: "#4c637c",
				color: "white",
				"font-size": "12px",
				"font-weight": "normal"
			},
			classes: {
				tip: "light-tip",
				tooltip: "l-tip"

			}
		},
		api: {
			beforeShow: function(event) {
				var newT = this.elements.target.attr('title');
				if (newT != '') {
					this.elements.target.attr('title', '');
					this.updateContent(newT);
				}
			}
		}
	}

	$('#block-favs .inactive-list').qtip(qtipconfig);
	//	$('a[title]').each(function() {
	//		var str = String(this.title).split(";");
	//		if (str.length > 1)
	//			$(this).qtip(
	//				$.merge({}, qtipconfig
	//					, {
	//						content: { title: { text: str[0] }, text: str[1] }
	//						, position: { target: this }
	//					}
	//			));
	//		else
	//			$(this).qtip(
	//				$.merge(qtipconfig
	//					, { content: { title: null, text: str[0] }, position: { target: this} }
	//			));
	//		//.qtip(qtipconfig);
	//	});


	qtipconfig.position.target = $('#block-document ul.icons');
	qtipconfig.position.adjust.x = -300

	$('#block-document.inactive ul.icons')
		.qtip(qtipconfig)
		.click(function() { return false; });

	qtipconfig.position.target = $('#button-paid-add');
	qtipconfig.position.adjust.x = -220;
	qtipconfig.position.adjust.y = -112;
	qtipconfig.style.tip.corner = 'bottomRight';
	qtipconfig.style.classes.tip = 'paid-tip';
	qtipconfig.style.classes.title = 'paid-title';
	qtipconfig.style.classes.content = 'paid-content';
	qtipconfig.content.title.text = 'Документ добавлен в корзину';
	qtipconfig.content.text = '<a href="">Перейти в корзину</a><br /><a href="">Продолжить просмотр сайта</a>';
	qtipconfig.style.width = 230;

	$('#button-paid-add')
		.qtip(qtipconfig)
		.click(function() { return false; });

	$('.papers li:not(.active)').live('click', function() {
		$('li.active', $(this).closest('.papers'))
			.animate({ "width": "-=125" }, 1000)
			.removeClass('active');
		$(this)
			.animate({ "width": "+=125" }, 1000)
			.addClass('active');
	})


	// Qtip-light


	$("#menu-main li a[title], #search-form li a[title], #search-form button[title], ul.icons li a[title], h2 .icon-edit[title], ul.list-icons li a[title], #block-filter button[title]").each(function() {
		if ($(this).is('#icon-periodic')) {
			qtipconfiglight.style.classes.tip = 'left-tip';
			qtipconfiglight.position.corner.tooltip = 'leftTop';
			qtipconfiglight.position.adjust.x = -19;
		}
		if ($(this).is('#icon-advanced, #icon-construct, #icon-calendar, #block-document .icon-picture a')) {
			qtipconfiglight.style.classes.tip = 'right-tip';
			qtipconfiglight.position.corner.tooltip = 'rightTop';
			qtipconfiglight.position.adjust.x = 19;
		}
		//qtipconfiglight.content.text = $(this).attr("title");
		//$(this).attr("title", "");
		//if (qtipconfiglight.content.text.length > 0) {
		$(this).qtip(qtipconfiglight);
		//}
		qtipconfiglight.style.classes.tip = 'light-tip';
		qtipconfiglight.position.corner.tooltip = 'topMiddle';
		qtipconfiglight.position.adjust.x = 0;
	});

	$('#block-favs .inactive-list').click(function() {
		return false;
	});
	$('.settings>div>div>div>label:contains(Виды спорта)').cabinetpopup(
		'Документы по выбранным видам спорта будут автоматически добавляться в Ваше избранное',
		$('.settings>div>div>div>label:contains(Виды спорта)>a>span')
	);
	$('.settings>div>div>div>label:contains(Источники)').cabinetpopup(
		'Документы по выбранным источникам будут автоматически добавляться в Ваше избранное',
		$('.settings>div>div>div>label:contains(Источники)>a>span')
	);
	$('.settings>div>div>div>label:contains(Рубрики)').cabinetpopup(
		'Документы по выбранным рубрикам будут автоматически добавляться в Ваше избранное',
		$('.settings>div>div>div>label:contains(Рубрики)>a>span')
	);
	$('.settings>div>div>div>label:contains(Регионы)').cabinetpopup(
		'Документы по выбранным регионам будут автоматически добавляться в Ваше избранное',
		$('.settings>div>div>div>label:contains(Регионы)>a>span')
	);
	$('.settings>div>div>div>label:contains(Языки)').cabinetpopup(
		'Выберите языки отображения для документов и источников. По-умолчанию показываются документы и источники на всех доступных языках',
		$('.settings>div>div>div>label:contains(Языки)>a>span')
	);

	$('.block .papers ul').each(function() {
		var s_width = 0;
		$('li', this).each(function() { s_width += $(this).width(); })
		$(this).css('width', s_width);
	});

	$('#central-carousel-top, #central-carousel-bottom').mouseenter(function() {
		$('img', this).efadeIn(500);
	});
	$('#central-carousel-top, #central-carousel-bottom').mouseleave(function() {
		$('img', this).efadeOut(500);
	});

	$('#central-carousel-bottom').click(carousel_scroll_down);
	$('#central-carousel-top').click(carousel_scroll_up);

	$('.scrollbar').mouseenter(function() {
		if ($.browser.msie) {
			$(this).children().show();
		} else {
			$(this).children().efadeIn(500);
		}
	});
	$('.scrollbar').mouseleave(function() {
		if ($.browser.msie) {
			$(this).children().hide();
		} else {
			$(this).children().efadeOut(500);
		}
	});

	$('#basket-checkbox-all').change(function() {
		if ($(this).attr('checked') == true) {
			$('td input[type=checkbox]', $(this).closest("form")).attr('checked', 'checked');
		} else {
			$('td input[type=checkbox]', $(this).closest("form")).attr('checked', '');
		}
	})
	$('#basket-block h2').prepend('<img alt="" src="/content/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);
	});

	if (!$('#login-username').val())
		$('label[for=login-username]').show()
	if (!$('#login-password').val())
		$('label[for=login-password]').show()

	$('#login-username, #login-password, #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();
		});

	recalculate_all();
	$(window).resize(recalculate_all);

	if ($.browser.msie && $.browser.version == 6) {
		DD_belatedPNG.fix('.tr, .tl, .br, .bl, .top, .bottom, .left, .right, .a-right, .shadow, .marker, #selection, .new, .s-right, .s-left, .b-left, .scrollbar, .center, .track, .dragbar, .scrollbar a, #central-carousel h2, h2 img, #block-search, #central-carousel-top img, #central-carousel-bottom img, #block-login, .rr, #register-success .main, #block-404 h1, #block-403 h1, #overlay, .block-overlay');
		try {
			document.execCommand('BackgroundImageCache', false, true);
		} catch (e) { }
	}

	$('.scrollbar').children().hide();
	$('#block-search').hide();
	$('#block-login').hide();
	$('#block-logout').hide();
	$('#block-recovery').hide();

	$('#icon-construct').click(function() {
		$('#block-search').fadeToggle(300);
		return false;
	});
	$('.block .icon-close').click(function() {
		$(this).closest('.block').efadeOut(300);
		$('#overlay').efadeOut(300);
		return false;
	});
	$('#block-login a.forgot-b, #block-login a.forgot').live('click', function() {
		$('#block-recovery').efadeIn(300);
		return false;
	});

	$('#block-sources a.desc, #block-document a.actionlink').live('click', function() {
		$('.description-block').css('top', e_value + (($(window).height() - $('.description-block').height()) / 2) - 10);
		$('.description-block').efadeIn(300);
		$('#overlay').efadeIn(300);
		return false;
	});

	$('.block-news h5 a').live('click', function() {
		$('.block-news-popup').css('top', e_value + (($(window).height() - $('.block-news-popup').height()) / 2) - 10);
		$('.block-news-popup').efadeIn(300);
		$('#overlay').efadeIn(300);
		return false;
	});

	// var e_interval = setInterval("carousel_scroll_down(true)", 3000);

	//$('.login-trigger, #icon-login, .icon-login').live('click', function() { $('.qtip').hide(); $('#block-login').efadeIn(300); return false; });

	//	$('#block-login .button-stylish').live('click', function() {
	//		$('#block-login a.forgot').efadeOut(300, function() {
	//			if (!$('#block-login p.error').get(0)) {
	//				$('#block-login fieldset.fields').append('<p class="error">Неверный логин или пароль</p><a href="" class="forgot-b">Восстановить пароль</a>');
	//			}
	//			$('#block-login p.error, #block-login a.forgot-b').efadeIn(300);
	//		});
	//		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').live('click', function() {
		$(this).closest("div").find("div.popup").efadeIn(300);
		return false;
	});

	$('#block-document h2 a.expander, #block-document h2 a.action-link').click(function() {
		$('a.expander', $(this).parent()).toggleClass('collapsed');
		$(this).closest('.block').find('.info').toggle();
		recalculate_all();
		return false;
	});
	$('#block-document a.announce-link').click(function() {
		$('span.icon', this).toggleClass('collapsed');
		$(this).closest('.block').find('.announce-content').toggle();
		recalculate_all();
		return false;
	});
	$('#block-document a.file-link').click(function() {
		$('span.icon', this).toggleClass('collapsed');
		$(this).closest('.block').find('.file-list').toggle();
		recalculate_all();
		return false;
	});
	$('#block-biblio h2 a.expander, #block-biblio h2 a.action-link').click(function() {
		$('a.expander', $(this).parent()).toggleClass('collapsed');
		$(this).closest('.block').find('.biblio-content').toggle();
		recalculate_all();
		return false;
	});
	$('#block-comments h2 a.expander, #block-comments h2 a.action-link').click(function() {
		$('a.expander', $(this).parent()).toggleClass('collapsed');
		$(this).closest('.block').find('.comments-content').toggle();
		recalculate_all();
		return false;
	});

	$('#icon-setup').click(function() {
		show_progress(document.body);
		//return false;
	});

	$('.biblio-content a').live('click', function() {
		$('#biblio-full-block').css('top', e_value + (($(window).height() - $('#biblio-full-block').height()) / 2));
		$('#biblio-full-block').efadeIn(300);
		$('#overlay').efadeIn(300);
		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() { $('.qtip').hide(); $('#block-login').efadeIn(300); return false; });
	$('#block-login form').live('submit', function() {
		login(this);
		return false;
	});
	$('#block-login .button-stylish').live('click', function() {
		login($(this).parents('form:first'));
		return false;
	});

	function loginSuccess() {
		window.location.reload();
	}
	function loginError(messages) {
		var form = this;
		//alert(messages["_FORM"]);
		hide_progress(this);
		$('a.forgot', form).efadeOut(300, function() {
			if (!$('p.error', form).get(0)) {
				$('fieldset.fields', form)
					.append($('<p class="error">Неверный логин или пароль</p>'))
					.append('<a href="" class="forgot-b">Восстановить пароль</a>');
			}
			$('p.error, a.forgot-b', form).efadeIn(300);
		});
	}
	function login(form) {
		//var progressBlock = $(form).hasClass('block') ? form : $(form).parents(".block:first");
		show_progress(form);
		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() { $('.qtip').hide(); $('#block-logout').efadeIn(300); 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);
	}
	function recoverpwdError(messages) {
		hide_progress(this);
		/*
		messages["captchaText"] - ошибки в коде изображения;
		messages["userEmail"] - ошибки в адресе
		messages["server"] - ошибки сервера
		messages["_FORM"] - ошибка отправки формы
		*/

	}
	/*
	---------------------------------------------------------------------------
	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(); });

	$('#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')
			.parent().append(
				$('<label class="error-notice" style="white-space:nowrap"></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"]);
					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() {
	$.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' });
	$('#docfilter-categories').entitySuggestions({ type: 'Category' });
	$('#docfilter-sport').entitySuggestions({ type: 'SportType' });
	$('#docfilter-regions').entitySuggestions({ type: 'MbsiRegion' });
	$('#docfilter-tags').entitySuggestions({ type: 'Tag' });
	$('#docfilter-authors').entitySuggestions({ type: 'Author' });
	$('#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 = $(this).prev('select')[0];
				if (!m) return;
				var mv = m.options[m.selectedIndex].value;
				$(m).empty().append('<option> </option>');
				if (this.selectedIndex == 0)
					return;
				$.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();

	$('a.submit').live('click', function() {
		$(this).parents("form:first").submit();
		return false;
	});
	$('a.clear').live('click', function() {
		$(this).parent().parent()
			.find(':checkbox, :radio').clearField().end()
			.find('ul.selected').remove();
		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); }
			});
		});
		$("#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);
					},
					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() {
			$.get($(this).attr('href'), function(data) {
				var block = $('#block-document');
				var docData = eval('[' + data + ']');
				if (docData.length < 1) return;
				//block.empty();
				var content = block.find('div.doc-content:first');
				block.find('h2:first').text(docData[0].Title);
				block.find('h1:first').text(docData[0].Title);
				var htmlStr = '';
				if (docData[0].Images && docData[0].Images.length > 0) {
					htmlStr += '<div class="media">';
					htmlStr += '	<img src="/media/bmsi_source_floatwidth/' + docData[0].Images[0].ID + '" alt="" />';
					htmlStr += '	<p>' + docData[0].Images[0].MediaDescription + '</p>';
					htmlStr += '</div>';

				}
				htmlStr += '<p>' + docData[0].Body + '</p>';
				content.html(htmlStr);

				$('#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;
		});


	});
});
/*
---------------------------------------------------------------------------
Basket
*/
$('#complete-form .button-stylish').live('click', function() {
	$(this).parents('#complete-form').submit();
	return false;
});


