$(function(){
	$('html').addClass('js');
	$('.b-index-news').each(function(){
		new News(this);
	});

	$('.b-popup-open').click(function(){

		var popup = $(this).data('popup');

		$('div.b-overlay').show();
		$('div.' + popup).show();

		return false;

	});

	$('div.b-popup .close').click(popupClose);

	$('td.b-popup__valign').click(function(e){
		if (e.target === this) popupClose();
	});

	$('.b-text > ul').each(function(){
		if($(this).attr('class')==""){
			if($(this).find('li').has('ul').is('li')) {
				$(this).addClass('b-fold');
				$(this).find('li').each(function(){
					multiListDetector = true;
					if($(this).children().size()==0 && $(this).parent().hasClass('b-fold') && multiListDetector){
						multiListDetector = false;
						$(this).parent().addClass('b-fold-multi');
					}
				});
			}
			$(this).find('ul').addClass('b-fold-element');
			$(this).find('li').wrapInner('<div class="li"></div>');
			$(this).find('ul').each(function(){$(this).insertAfter($(this).parent());});
			$(this).find('.li').each(function(){$(this).html($.trim($(this).html()))});
			$(this).find('li:has(ul) > .li').wrapInner('<a class="b-fold-link" href="#"><span></span></a>')
		}
	});
	
	$('.b-fold-link').attr('title', 'Развернуть');
	$('.b-fold-link').click(function(){
		if($(this).hasClass('b-fold-link-open')){
			$(this).removeClass('b-fold-link-open');
			if($.browser.msie) {
				$(this).parent().next().hide();
			} else {
				$(this).parent().next().slideUp(300);
			}
			$(this).attr('title', 'Развернуть');
		} else {
			$(this).addClass('b-fold-link-open');
			if($.browser.msie) {
				$(this).parent().next().show();
			} else {
				$(this).parent().next().slideDown(300);
			}
			$(this).attr('title', 'Свернуть');
		}
		return false;
	});
		
	if ($.browser.webkit) {
		$('.b-foot-made img').load(function(){addCarousel();});
	} else {
		addCarousel();
	}
	
	if ($.browser.msie && parseInt($.browser.version, 10)>=8) {
		$(".content-img").addClass("g-pie");
	}
	
	//ie6 fixes
	if ($.browser.msie && parseInt($.browser.version, 10)==6) {
		$(".b-index-news__right dl:first-child, .b-index-events__right dl:first-child").addClass("first-child");
		$(".b-head-lang__wrap").mouseover(function(){$(this).addClass("b-head-lang__wrap_hover");});
		$(".b-head-lang__wrap").mouseout(function(){$(this).removeClass("b-head-lang__wrap_hover");});
		$(".b-foot-map").mouseover(function(){$(this).addClass("b-foot-map_hover");});
		$(".b-foot-map").mouseout(function(){$(this).removeClass("b-foot-map_hover");});
	}
	
	// Tabs
	$('#tabs_container .tabs li').mouseover(function(){
		if(!$(this).hasClass('active')) {$(this).addClass('hover');}
	});
	$('#tabs_container .tabs li').mouseout(function(){
		if($(this).hasClass('hover')) {$(this).removeClass('hover');}
	});
	$('#tabs_container .tabs li').click(function(){
		if(!$(this).hasClass('active')) {
			$('#tabs_container .boxes .box').eq($('#tabs_container .tabs li.active').index()).hide();
			$('#tabs_container .tabs li.active').removeClass('active');
			$(this).addClass('active');
			newBoxIndex = $(this).index();
			$('#tabs_container .boxes .box').eq(newBoxIndex).fadeIn(500);
			tdHeight($('#tabs_container .boxes .box').eq(newBoxIndex));
		}
	});
	
	if ($.browser.webkit) {
		$('#tabs_container .boxes .box').eq(0).find('img').load(function(){
			tdHeight($('#tabs_container .boxes .box').eq(0));
		});
	} else {
		tdHeight($('#tabs_container .boxes .box').eq(0));
	}
	
	var margin = $('#tabs_container .tabs').width() - $('#tabs_container .tabs li').width() * $('#tabs_container .tabs li').size();
	margin = margin / ($('#tabs_container .tabs li').size() + 1);
	$('#tabs_container .boxes .box').each(function(){
		var boxTop = $(this).find('.boxes_top');
		var posLeft = ($(this).index() + 1) * (50 + margin) - 1026; 
		boxTop.css({backgroundPosition: posLeft+"px 0px"});
	});
	$('#tabs_container .tabs li').css({marginLeft: margin+'px'});
	lastBoxIndex = 0;
	newBoxIndex = 0;
	
	$(document).everyTime(4000, "boxes", tabsChange);
	$('#tabs_container').mouseover(function(){$(document).stopTime("boxes");});
	$('#tabs_container').mouseout(function(){$(document).everyTime(4000, "boxes", tabsChange);});
	
	/*
	*	Слайдер событий
	*/
//	var current = 100;   // Текущая дата в unix timestamp
        var current = $('#seminars-current').val()!=false ? $('#seminars-current').val() : 100;
        
        var seminarsData = '';
        if($('#seminars-data').val())
        {
            seminarsData = eval('('+$('#seminars-data').val()+')');
        }
        else
        {
            seminarsData = {
                        0 : {},
			10 : {
				sdate: '12 апреля',
				slink: 'Семинары, проводимые на базе ОАО «ВО „Радиоэкспорт”» иностранными производителями ЭКБ и оборудования',
				shref: 'http://google.ru'
			},
			45 : {
				sdate: '23 апреля',
				slink: 'Семинар по чистке чакр по чистке чакр по чистке чакр 2',
				shref: 'http://google.ru'
			},
			65 : {
				sdate: '27 мая',
				slink: 'Семинар по чистке чакр  по чистке чакр 3',
				shref: 'http://google.ru'
			},
			95 : {
				sdate: '30 мая',
				slink: 'Семинар по чистке чакр  по чистке чакр 4',
				shref: 'http://google.ru'
			},
			150 : {
				sdate: '11 июня',
				slink: 'Семинар по чистке чакр  по чистке чакр 5',
				shref: 'http://google.ru'
			},
                        200 : {}
            };
        }

	var values = [];
	$.each(seminarsData, function(key, value) {
	   values.push(parseInt(key));
	});

//	var min = values[0];
//	var max = values[values.length - 1];
        var min = parseInt(current) - parseInt($('#seminars-data-days').val());
        var max = parseInt(current) + parseInt($('#seminars-data-days').val());

	var sliderWidth = $('#slider').width();


	var slider = $("#slider").slider({
		animate: 500,
		min: min,
		max: max,
	//	value: 30,
		create: function() {
			var pixelsPerUnit = sliderWidth / (max - min);
			for (var i = 0; i < values.length; i++) {
				var divider = $('<div class="checkpoint"></div>');
				divider.css('left', (pixelsPerUnit * (values[i] - min)) + 'px');
				divider.fadeTo(0, 0.5);
				$(this).append(divider);
			}
                        
                        if(values.length != 1)
                        {
                            $('#slider_layout').mouseenter(function() {
                                    $('#hint').show();
                            });
                            $('#slider_layout').mouseleave(function() {
                                    $('#hint').hide();
                            });
                        }

			var futureWidth = (1 - (current - min) / (max - min)) * sliderWidth;
			var pastWidth = sliderWidth - futureWidth;

			if (futureWidth > sliderWidth) {
                futureWidth = sliderWidth;
				pastWidth = 0;
			}
			if (futureWidth < 0) {
                futureWidth = 0;
				pastWidth = sliderWidth;
			}

			var curDatePosition = sliderWidth - futureWidth - $('#current_date').width() / 2;
			if (curDatePosition > sliderWidth - $('#current_date').width()) {
			    curDatePosition = sliderWidth - $('#current_date').width();
			} else if (curDatePosition < 0) {
                curDatePosition = 0;
			}

			$('#current_date').css('left', curDatePosition + 'px');

			// Ширина цветной полоски
			$('#future_zone').css('width', futureWidth + 'px');

			$('#slider #past_seminars').css('left', pastWidth / 2 - $('#slider #past_seminars').width() / 2 + 'px');
			$('#slider #future_seminars').css('left', pastWidth + futureWidth / 2 - $('#slider #future_seminars').width() / 2 + 'px');

			if (pastWidth < $('#slider #past_seminars').width() + 10) {
			    $('#slider #past_seminars').hide();
			}
			if (futureWidth < $('#slider #future_seminars').width() + 10) {
				$('#slider #future_seminars').hide();
			}

		},
		current: current,
		checkpoints: values,
		seminarsData: seminarsData
	});
        
        $("#future_date").pxgradient({
		step: 10,
		colors: [
			'#37d500',
			'#edde06',
			'#fe9a01',
			'#fe7801',
			'#fe9201'
		],
		dir: "x"
	});
	
});

function tabsChange() {
	$('#tabs_container .tabs li.active').each(function(){
		lastBoxIndex = newBoxIndex;
		if ($(this).index()+1 == $('#tabs_container .tabs li').size()) {
			$('#tabs_container .tabs li:first-child').addClass('active');
			newBoxIndex = 0;
		} else {
			$(this).next().addClass('active');
			newBoxIndex = $(this).index() + 1;
		}
		$(this).removeClass('active');
		$('#tabs_container .boxes .box').eq(lastBoxIndex).hide();
		$('#tabs_container .boxes .box').eq(newBoxIndex).fadeIn(500);
		tdHeight($('#tabs_container .boxes .box').eq(newBoxIndex));
	})
}

function tdHeight(selector) {
	var boxImage = selector.find('img');
	var tdTable = selector.find('td')
	tdTable.height(540-boxImage.height());
}

function addCarousel() {
	$('#mycarousel').jcarousel({
		wrap: ($.browser.safari ? 'both' : 'circular'),
		scroll: 1,
		auto: 1,
		initCallback: function(jc, state) {
			if (state == 'init') {
				jc.startAutoOrig = jc.startAuto;
				jc.startAuto = function(){
					if(!jc.paused) {
						jc.startAutoOrig();
					}
				};
				jc.pause = function(){
					jc.paused = true;
					jc.stopAuto();
				};
				jc.play = function(){
					jc.paused = false;
					jc.startAuto();
				};
				$(".jcarousel-container").mouseover(function(){jc.pause()});
				$(".jcarousel-container").mouseout(function(){jc.play()});
			}
		}
	});

	$(".jcarousel-clip").after('<div class="jcarousel-left-gragient"></div><div class="jcarousel-right-gragient"></div>');
	$(".jcarousel-skin-tango .jcarousel-next-horizontal, .jcarousel-skin-tango .jcarousel-prev-horizontal").css({top: "50%", marginTop: "-16px"});
        $(".jcarousel-skin-tango").css({height: "53px"});
        $(".jcarousel-skin-tango li").css({visibility: "visible"});
}

function popupClose(){
	$('div.b-popup').hide();
	$('div.b-overlay').hide();
}

/* News */

function News(container){

	this.container = $(container);
	this.menu = this.container.find('.menu');
	this.content = this.container.find('.tab-content');

	this.init();

}

News.prototype = {
	container: null,
	menu: null,
	content: null
};

News.prototype.init = function(){

	var _this = this;

	this.menu.delegate('.b-pseudo-link', 'click', function(){
		_this.change(this);
		return false;
	});

	this.menu.find('.b-pseudo-link').eq(0).click();

};

News.prototype.change = function(handler){

	var li = $(handler).parent(),
		index = li.parent().children().index(li);

	li.addClass('act').siblings().removeClass('act');

	this.content.eq(index)
		.addClass('tab-content_act')
		.siblings().removeClass('tab-content_act');

};
