/* Настройка highslide */
var a_t = null;
var tipdata = {};

var popupdays = {
	width: 180,
	height: 56,
	targetX: 'headline 130px',
	targetY: 'headline 31px',
	contentId: 'popup-days'
};
var popupsport = {
	width: 400,
	height: null,
	targetX: 'headline 365px',
	targetY: 'headline',
	contentId: 'popup-sport',
	allowHeightReduction: true
}
var popupchannels = {
	width: 400,
	height: null,
	targetX: 'headline 365px',
	targetY: 'headline',
	contentId: 'popup-channels',
	allowHeightReduction: true,
	enableKeyListener: false	
}
var popupevents = {
	width: 388,
	height: 612,
	targetX: 'current-event 1px',
	targetY: 'current-event 1px',
	contentId: 'events-today',
	allowHeightReduction: false
}
var popupcomment = {
	width: 730,
	height: 255,
	targetX: 'highslide-bottom',
	targetY: 'highslide-bottom -275px',
	contentId: 'comment-form',
	allowHeightReduction: false	
}
var popupadvert = {
	targetX: 'advertisement-trigger -90px',
	targetY: 'advertisement-trigger -79px',
	contentId: 'advertisement-list',
	height: 68,
	width: 240,
	allowHeightReduction: false,
	outlineType: null,
	transitions: ["fade"]
}

var slideshowOptions = {
	dimmingOpacity: 0.3,
	align: 'center',
	transitions: ['expand', 'crossfade'],
	fadeInOut: true,
	wrapperClassName: 'borderless highslide-gallery-container',
	numberPosition: 'heading',
	captionEval: 'this.thumb.title',
	allowSizeReduction: true,
	allowWidthReduction: true,
	allowHeightReduction: true,
	targetX: null,
	targetY: null,
	width: null,
	height: null,
	interval: 5000,
	repeat: true,
	useControls: true,
	fixedControls: 'fit',
	overlayOptions: {
		opacity: 0.75,
		position: 'bottom center'
	}
};
var galleryOptions = {
	slideshowGroup: 'gallery'
};
$(function() {
	hs.addSlideshow($.extend({}, slideshowOptions, { slideshowGroup: 'gallery' }));
});

hs.graphicsDir = '/scripts/highslide/graphics/';
hs.outlineType = 'drop-shadow';
hs.width = 730;
hs.height = 726;
hs.allowHeightReduction = false;
hs.targetX = 'content 20px';
hs.targetY = 'content 15px';
hs.showCredits = false;
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.restoreTitle = 'Кликните, чтобы закрыть изображение. Удерживайте клик для перемещения изображения. Используйте стрелки "Влево" / "Вправо" для навигации по галерее';

hs.onKeyDown = function(sender, e) {
	if ((e.keyCode == 37 || e.keyCode == 38 || e.keyCode == 39 || e.keyCode == 40) && !$('.highslide-gallery-container').get(0)) return false;
}

hs.Expander.prototype.onAfterExpand = function () {
	if (this.custom == 'event') {
		var pos = $('#link-events-all').offset();
		$('<div id="popup-arrow"></div>').appendTo('body').css({ 'top': pos.top - 2, 'left': pos.left + 180 });
		$('#link-events-all').addClass('active');
	}
	if (this.custom == 'popup-sport') {
		$('.popup-sport').addClass('expanded');
	}
	if (this.custom == 'popup-channels') {
		$('.popup-channels').addClass('expanded');
	}
	if (this.custom == 'popup-days') {
		$('#headline .day').addClass('expanded');
	}
	if (this.custom == 'popup-advert') {
		$('#advertisement-trigger').addClass('active');
	}		
}

/*
hs.Expander.prototype.onBeforeExpand = function () {
	if (this.custom == 'gallery') {
		$('.highslide-caption').parent().addClass('highslide-cap');
		$('.highslide-container').addClass('highslide-gallery-container');
	}
}
*/

hs.Expander.prototype.onBeforeClose = function () {
	if (this.custom == 'event') {
		$('#popup-arrow').remove();
	}
	if (this.custom == 'popup-advert') {
		$('#advertisement-trigger').removeClass('active');
	}
}
hs.Expander.prototype.onAfterClose = function () {
	if (this.custom == 'event') {
		$('#link-events-all').removeClass('active');
	}
}

/* Конец настроек highslide */

function load_tips() {
	$.getJSON('/gettooltips/All/', function(data) {

		selector = '';
		for (i in data) {

			tip = data[i];
			tipdata[tip.Selector] = tip;

			selector += tip.Selector + (data.length == parseInt(i) + 1 ? '' : ', ');

		}
		
		
		$(selector)
            .attr("title", "")
            .live("mouseover", function() {
            
            	for (selector in tipdata) {
            		if ($(this).is(selector)) {
            			tip = tipdata[selector];
            			$(this).data("style", tip.Style);
            			if (tip.Text.indexOf("$content") >= 0 || tip.Text.indexOf("$tipdata") >= 0) {
            				$(this).each(function() {
            					$(this).data("dynamic", true); 
            				})
            			}
            			$(this).data("title", tip.Text);
            		}
            	}
            
            	if (!$(this).data("init")) {
            		$(this).data("init", true);
            		$(this).hoverIntent({
        				over: function() {
        					if ($(this).data("title").length > 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').fadeOut(300, function() { $(this).remove() });
        				},
        				interval: 300
            		});
            		$(this).trigger("mouseover");
            	}
            });

	});
}


function align_double_feed_height() {
	$('#double-feed li').removeAttr('style');
	$('#double-feed li:nth-child(odd)').each(function () {
		item_odd = $(this);
		item_even = $('#double-feed li').eq($(this).index('#double-feed li') + 1);
		if (item_even.height() > item_odd.height()) {
			item_odd.css('height', item_even.height());
		} else {
			item_even.css('height', item_odd.height());
		}
	});
}
function align_contacts_height() {
	$('#contacts>.crew>li>ul').each(function () {
		$(this).find(">li:nth-child(odd)").each(function () {
			item_odd = $(this);
			item_even = $(this).next();
			if (item_even.height() > item_odd.height()) {
				item_odd.css('height', item_even.height() + 1);
				item_even.css('height', item_even.height() + 1);
			} else {
				item_even.css('height', item_odd.height() + 1);
				item_odd.css('height', item_odd.height() + 1);
			}
		});
	});
}
function align_large_double_feed_height() {
	$('#large-double-feed li').removeAttr('style');
	$('#large-double-feed li:nth-child(odd)').each(function () {
		item_odd = $(this);
		item_even = $('#large-double-feed li').eq($(this).index('#large-double-feed li') + 1);
		if (item_even.height() > item_odd.height()) {
			item_odd.css('height', item_even.height());
		} else {
			item_even.css('height', item_odd.height());
		}
	});
}
function align_translation_height() {

	if ($.browser.msie && $.browser.version == 6) {
		var height_needed = 246;
		if ($('#translation-summary .collapse-target').is(":hidden"))
			height_needed += 121;
		if ($('#translation-players .collapse-target').is(":hidden"))
			height_needed += 251;
		$('#translation-text div.scroll').css('height', height_needed);
	} else {
		$('#translation-text div.scroll').css('height', $('#translation-block').height() - ($('#translation-summary').outerHeight() + $('#translation-players').outerHeight() + 15 + 18) + 'px');
	}

	$('#translation-text ul').css('height', $('#translation-text ul').outerHeight() < $('#translation-text div.scroll').height() ? $('#translation-text div.scroll').height() - 6 : 'auto');

	resize_separators();
}
function resize_separators(offset) {
	if (!offset) { offset = 0 }
	$('.vertical-separator').each(function () {
		$(this).css('height', $(this).parent().outerHeight() - offset + 'px');
	});
}

$(function () {

	$('.media-element + p').css('cursor', 'pointer').live('click', function() { $(this).prev().find("a").first().click() });
	$('.media-element span.gallery').css('cursor', 'pointer').live('click', function() { $(this).parent().find("a").first().click() });

	/* Вертикальное выравнивание кнопок формы и подсказок */
	$('#forms button').not('#form-recovery button').each(function () {
		$(this).css('margin-top', Math.ceil(($('#forms').height() - $(this).outerHeight()) / 2) + 'px')
	});
	$('#form-login label').each(function () {
		$(this).css('top', Math.ceil(($(this).parent().outerHeight() - $(this).outerHeight()) / 2) + 'px')
	});

	$('#form-login button').click(function () {
		if (!$(this).parent().hasClass('active')) {
			$(this).parent()
				.addClass('active')
				.append('<p>Неверно введен логин или пароль.<br />Попробуйте еще раз.</p>');
			return false;
		}
	});
	$('#form-recovery a').click(function () {
		$('#recovery-result').css('display', 'none');
		$("#recovery-form").css('display', '');
		if (!$(this).parent().hasClass('active')) {
			$(this).parent()
				.addClass('active')
			return false;
		}
		else {
			$(this).parent()
				.removeClass('active')
			return false;
		}
	});
	$('#form-registration a').click(function () {
		$("#reg-form").css("display", "");
		$('#registration-complite').css("display", "none");
		$(this).parent().toggleClass('active');
		if ($(this).parent().hasClass('form-cabinet')) {
			$(this).parent()
				.toggleClass('cabactive')
		}
		return false;
	});


	load_tips();

	/* Стрелки выбора месяца в календаре.
	Не включены в разметку сразу, чтобы в
	браузерах без скриптов просто отображался
	текущий месяц. */
	//$('.event-calendar').prepend('<a href="" class="previous-month">&lt;</a><a href="" class="next-month">&gt;</a>');

	/* Выравнивание высоты в новостных элементах
	и горизонтальный разделитель там же */
	$('#double-feed, #large-double-feed').append('<li id="double-feed-separator"></li>');

	$('#double-feed img').load(function () {
		align_double_feed_height();
		$('#double-feed-separator').css('height', $('#double-feed').height() - 10);
	});
	align_double_feed_height();
	
	$('#large-double-feed img').load(function () {
		align_large_double_feed_height();
		$('#large-double-feed-separator').css('height', $('#large-double-feed').height() - 40);
	});
	align_large_double_feed_height();

	align_contacts_height();

	$('#double-feed-separator').css('height', $('#double-feed').height() - 10);
	if ($('#large-double-feed').get(0)) {
		$('#double-feed-separator').css('height', $('#large-double-feed').height() - 40);
	}

	/* Подсказки к формам */
	if (!$('#login-field').val())
		$('label[for=login-field]').show()
	if (!$('#password-field').val())
		$('label[for=password-field]').show()

	$('#login-field, #password-field')
		.blur(function () {
			if (!$(this).val())
				$('label[for=' + $(this).attr("id") + ']').show();
		})
		.focus(function () {
			$('label[for=' + $(this).attr("id") + ']').hide();
		});

	/* Меню */
	$('#menu>li').mouseleave(function () {
		$('#menu li li a').removeClass('active');
		$(this).removeClass('active');
	});

	$('#menu').mouseleave(function () {
		$('#menu>li ul').hide();
		$('#menu li').removeClass('active');
	});

	$('#menu li li').mouseover(function () {
		$('.h', $('#menu')).removeClass('h');
		$(this).closest('ul')
			.find('a.active')
				.removeClass('active')
			.end()
			.children('li.active')
				.not($(this))
					.removeClass('active');
		if ($('ul', $(this)).get(0)) {
			$(this).addClass('active').children('a').addClass('active');
		}
	});

	$('#menu li').mouseover(function () {
		if ($('ul', this).get(0)) {
			if ($('ul.ht', this)) {
				$(this).addClass('h');
			}
			$('#menu>li>ul').not($('ul', this)).hide().parent().removeClass('active');
			$(this).addClass('active').children('ul').show();
		}
		$(this).closest("ul").find("ul").not($('ul', this)).hide();
	});

	$('#menu li li ul').mouseleave(function () {
		a_t = $(this);
		$(this).addClass('ht');
		setTimeout("if (!a_t.parent().hasClass('h')) {$('#menu li li ul').hide();a_t.parent().removeClass('active');}", 50);
	})
	.mouseover(function () {
		$('.h', $('#menu')).removeClass('h');
	});
	/* Конец меню */

	resize_separators();
	align_translation_height();

	/* Свертывание блоков в трансляциях */

	$('.collapse-trigger').click(function () {
		$(this)
			.toggleClass("expand-trigger")
			.find("div")
				.toggle()
			.end()
			.parent()
				.find(".collapse-target")
					.toggle();

		align_translation_height();
		return false;
	});

	$('#advertisement-trigger a').click(function () {
		if ($(this).parent().hasClass("active")) {
			hs.getExpander('advertisement-list').close();
			return false;
		} else {
			return hs.htmlExpand(this, popupadvert, 'popup-advert');
		}
	});
	$('#headline .day').click(function () {
		if ($(this).hasClass("expanded")) {
			$(this).removeClass('expanded');
			$('shape', this).remove();
			hs.getExpander('popup-days').close();
			return false;
		} else {
			return hs.htmlExpand(this, popupdays, 'popup-days');
		}
	});
	$('.stripe .popup-sport').click(function () {
		if ($(this).hasClass("expanded")) {
			$(this).removeClass('expanded');
			$('shape', this).remove();
			hs.getExpander('popup-sport').close();
			return false;
		} else {
			return hs.htmlExpand(this, popupsport, 'popup-sport');
		}
	});
	$('.stripe .popup-channels').click(function () {
		if ($(this).hasClass("expanded")) {
			$(this).removeClass('expanded');
			$('shape', this).remove();
			hs.getExpander('popup-channels').close();
			return false;
		} else {
			return hs.htmlExpand(this, popupchannels, 'popup-channels');
		}
	});

	$('#link-events-all').click(function () {
		if ($(this).hasClass('active')) {
			hs.getExpander('events-today').close();
			return false;
		}
	});

	$('#button-comment-cancel, #comment-form .stripe a').click(function () {
		hs.getExpander('comment-form').close();
		return false;
	})
	/* Конец скриптов для свертывания блоков */

	/* Календарь */

	$('#date-b, #date-e').datepicker({
		buttonImage: '/css/msport/images/calendar-icon.png',
		firstDay: 1,
		monthNames: [
			'Январь',
			'Февраль',
			'Март',
			'Апрель',
			'Май',
			'Июнь',
			'Июль',
			'Август',
			'Сентябрь',
			'Октябрь',
			'Ноябрь',
			'Декабрь'
		],
		buttonImageOnly: true,

		showOn: 'button',
		dateFormat: 'dd.mm.yy'

	});

	$('#events').datepicker({
		buttonImage: '/css/msport/images/calendar-icon.png',
		firstDay: 1,
		monthNames: [
			'Январь',
			'Февраль',
			'Март',
			'Апрель',
			'Май',
			'Июнь',
			'Июль',
			'Август',
			'Сентябрь',
			'Октябрь',
			'Ноябрь',
			'Декабрь'
		],
		buttonImageOnly: true,

		showOn: 'button',
		dateFormat: 'dd.mm.yy',
		onChangeMonthYear: function (year, month, inst) {
			LoadEvents(month, year);
		},
		beforeShowDay: function (date) {
			var cssClass = '';
			var currentDate = new Date();
			if (currentDate.getDate() == date.getDate()
				&& currentDate.getMonth() == date.getMonth()
				&& currentDate.getYear() == date.getYear()) {
				cssClass = 'active';
			}
			return [false, cssClass, ''];
		}

	});
	var date = new Date();

	var day = parseInt($('#event-selected-day').val(), 10);
	var month = parseInt($('#event-selected-month').val(), 10);
	var year = parseInt($('#event-selected-year').val(), 10);
	if (!isNaN(day) && !isNaN(month) && !isNaN(year)) {
		var selectedDate = new Date();
		selectedDate.setFullYear(year);
		selectedDate.setMonth(month - 1);
		selectedDate.setDate(day);
		$('#events').datepicker("setDate", selectedDate);
		if (month == date.getMonth() + 1 && year == date.getFullYear())
			LoadEvents(month, year);
	}
	else {
		LoadEvents(date.getMonth() + 1, date.getFullYear());
	}


	/* Конец скриптов для календаря */
	$("#link-events-all").click(function () {
		if ($(this).attr('close') != 'true') {
			$('#events-today div ul').load($(this).attr('href'));
			$(this).attr('close', 'true');
		}
		else {
			$(this).attr('close', 'false');
		}
		return hs.htmlExpand(this, popupevents, 'event')
	});
	function updateContainer(c, url) {
		c = $(c); url = url || c.attr('url');
		c.empty();
		$("#comments", c).empty();
		c.addClass("loading").load(url, { _ajax: true }, function () {
			$(this).removeClass("loading");
		});
	}
	$('div.updateable-content ul.pagination a').live('click', function () {
		updateContainer($(this).parents('div.updateable-content:first'), this.href);
		return false;
	});
	$('form#comment-form').live('submit', function (e) {
		if ($("#comment-text", this).val() == '' || $("#comment-author", this).val() == '') {
			return false;
		}
		hs.getExpander(this).close();
		$("#comment-add").css('display', 'none');
		$("#document-coments-container").empty();
		$("#document-coments-container").addClass("loading");

		$.post($("#comment-form").attr('action'), $("#comment-form").serialize(), function (data) {
			$("#comments").removeClass("loading");
			Sys.Debug.traceDump(data === true);
			if (data && !data.Errors) {
				$("#comment-text", this).val('');
				$("#comment-author", this).val('');
				$("#comment-add").css('display', '');
				updateContainer('#document-coments-container');
				return;
			}
			$("#document-coments-container").removeClass("loading");
			$("#comment-add").css('display', '');
			//ToDo: добавить обработку ошибок
		});
		return false;
	});
	//$('#comment-form').attr('action','<xsl:value-of select="mbsi:addDocAnonimCommentLink($Model/Document/@id)"/>');
	//			return hs.htmlExpand(this, popupcomment, 'comments' )
	$('a.comment-add').live('click', function (e) {
		$('#comment-form').attr('action', $(this).attr('href'));
		$("#comment-text", this).val('');
		$("#comment-author", this).val('');
		hs.htmlExpand(this, popupcomment, 'comments');
		return false;
	});
	$("a#button-comment-publish").live('click', function () {
		$(this).parents('form:first').submit();
		return false;
	});
});

function LoadEvents(month, year) {
	var url = '/events/id?month=' + month + '&year=' + year;

	$.getJSON(url, function (data) {
		$.each($('#events table tbody td'), function (td, obj) {
			if ($(obj).text() != '') {
				var dayNum = parseInt($(obj).text(), 10);
				if (!isNaN(dayNum)) {
					if (data[dayNum - 1]) {
						if (data[dayNum - 1].ID) {
							$(obj).html("<a href='/events/" + data[dayNum - 1].ID + "?year=" + year + "&month=" + month + "&day=" + dayNum + "'>" + dayNum + "</a>");
						}
					}
				}
			}
		});
	});
}
