$(function(){
	var txtShow={'ru':'Показать', 'en':'Show'};
	var txtHide={'ru':'Скрыть', 'en':'Hide'};
	var txtPollResults={'ru':'Показать результаты голосования...', 'en':'Show Poll Results...'};
	var txtPollVote={'ru':'Перейти к голосованию...', 'en':'Vote...'};
	var txtPollIpBlocked={'ru':'Голос с Вашего IP-aдреса сегодня уже был засчитан. Вы сможете проголосовать завтра','en':''};
	var patternShow=new RegExp(txtShow[cskabasketLang],"g");
	var patternHide=new RegExp(txtHide[cskabasketLang],"g");
	var txtResults={'ru':'матчи', 'en':'Games'};

	// ховеры для IE6
	if ($.browser.msie&&$.browser.version=='6.0') {
		$('a[id^=resNav]').not('a.resultNavDisabled').add('a[id^=gameNote]').add('a[id^=gameTV]').add('a[id^=pressPage]').attr('href','#');
	}
	// Открываем все примечания к предстоящим играм
	var gamesWithNotes=$('a[id^=gameNote]').addClass('navigationLineSelected').removeClass('navigationLine');
	if (gamesWithNotes.attr('title')) { gamesWithNotes.attr('title',gamesWithNotes.attr('title').replace(patternShow,txtHide[cskabasketLang])); }
	$('div[id^=gameNoteInfo]').show();
	
	// навигация предстоящих матчей ЦСКА
	$('a[id^=game]').click(
		function(){
			var idShowHide=$(this).attr('id').replace(/_/,'Info_');
			var elementShowHide=$('div[id='+idShowHide+']');
			if ($(elementShowHide).is(':hidden')) {
				// скрываем, все что было открыто
				var navigationSelected=$('a.navigationLineSelected').addClass('navigationLine').removeClass('navigationLineSelected');
				if (navigationSelected.size()) {
					navigationSelected.attr('title',navigationSelected.attr('title').replace(patternHide,txtShow[cskabasketLang]));																								
					$('div.hiddenInfo').hide();
				}
				var thisA=$(this).addClass('navigationLineSelected').removeClass('navigationLine');
				thisA.attr('title',thisA.attr('title').replace(patternShow,txtHide[cskabasketLang]));
				$(elementShowHide).show(); 
			} else {
				var thisA=$(this).addClass('navigationLine').removeClass('navigationLineSelected');
				thisA.attr('title',thisA.attr('title').replace(patternHide,txtShow[cskabasketLang]));
				$(elementShowHide).hide(); 
			}
			return false;
		});
	// Навигация результатов
	$('a[id^=resNav]').click(function(){
		if (!$(this).attr('class').replace(/resultNav/,'')) {
			$('div[id^=resContainer'+$('a.resultNavSelected').not('a[id^=pollNav]')
			.addClass('resultNav')
			.removeClass('resultNavSelected')
			.attr('title',txtShow[cskabasketLang]+' '+txtResults[cskabasketLang]).attr('id').replace(/resNav/,'')+']')
			.hide();
			$('div[id^=resContainer'+$(this).removeClass('resultNav')
			.addClass('resultNavSelected')
			.attr('title','')
			.attr('id').replace(/resNav/,'')+']')
			.show();
		}
		return false;
	});

	// Навигация евроньюсов и прессы
	$('a[id^=euronewsButton]').add('a[id^=pressButton]').click(function(){
		var buttonName=$(this).attr('id');
		var section=buttonName.slice(0,buttonName.indexOf('Button'));
		var patternNav=new RegExp(section+'Nav',"g");
		var patternButton=new RegExp(section+'Button',"g");
		if (!$(this).attr('class').replace(patternNav,'')) { //работаем только, если текущаяя ссылка не выбрана		
			var idToSelected=$(this).attr('id').replace(patternButton,'');
			var idToEnabled=$('a.'+section+'NavSelected').removeClass(section+'NavSelected').addClass(section+'Nav')
				.attr('title',txtShow[cskabasketLang]+'...').attr('id').replace(patternButton,'');
			$(this).removeClass(section+'Nav').addClass(section+'NavSelected').attr('title','');		
			var divToView='div[id='+section+'Page'+idToSelected+']';
			var divToHide='div[id='+section+'Page'+idToEnabled+']';
			if ($(divToView).html().length) {
				$(divToHide).hide();
				$(divToView).show();
			} else {
				$.ajax({
					url: '../main_new/ajax.php',
					data: 'section='+section+'&page='+idToSelected+'&lang='+cskabasketLang,
					dataType: 'html',
					cache: false,
					beforeSend: function (){
						$(divToHide).addClass('uploader');
					},
					success: function(html){ 
						if (html=='Error') {

						} else {
							$(divToHide).removeClass('uploader').hide();
                   			$(divToView).html(html);
							$('#'+section+'AjaxLoading').hide();
							$(divToView).show();
						}
                 	}  
				});
			}
		}
		return false;
	});
	
	// Обновление евроньюсов и прессы
	$('#euronewsRefresh').add('#pressRefresh').click(function(){											  
		var buttonName=$(this).attr('id');
		var section=buttonName.slice(0,buttonName.indexOf('Refresh'));
		var patternButton=new RegExp(section+'Button',"g");
		var divToView='#'+section+'Page1';
		var idToEnabled=$('a.'+section+'NavSelected').attr('id').replace(patternButton,'');
		var divToHide='div[id='+section+'Page'+idToEnabled+']';
		if (idToEnabled>1) {
			$('a.'+section+'NavSelected').removeClass(section+'NavSelected').addClass(section+'Nav').attr('title',txtShow[cskabasketLang]+'...');
			$('a#'+section+'Button1').removeClass(section+'Nav').addClass(section+'NavSelected').attr('title','');		
		}
		$.ajax({
			url: '../main_new/ajax.php',
			data: 'section='+section+'&page=1&lang='+cskabasketLang,
			dataType: 'html',
			cache: false,
			beforeSend: function (){
				$(divToHide).addClass('uploader');
			},
			success: function(html){ 
				if (html=='Error') {

				} else {
					$(divToHide).removeClass('uploader').hide();
					$(divToView).html(html);
					$('#'+section+'AjaxLoading').hide();
					$(divToView).show();
					$('div[id^='+section+'Page]').not('#'+section+'Page1').html('');
				}
			}  
		});
		return false;
	});
	
	// Навигация голосования
	$('a[id^=pollNav]').click(function(){
		if (!$(this).attr('class').replace(/resultNav/,'')) { // если ссылка кликабельна
			var pollId=$(this).attr('id').replace(/pollNavForm/,'Results').replace(/pollNavResults/,'Form'); // реверсим кнопку в рамках одного голосования
			if (pollId.indexOf('Results')==0) {navTitle=txtPollResults[cskabasketLang];} else {navTitle=txtPollVote[cskabasketLang];}
			$('div[id^=pollContainer'+$('a[id=pollNav'+pollId+']')
			.addClass('resultNav')
			.removeClass('resultNavSelected')
			.attr('title',navTitle).attr('id').replace(/pollNav/,'')+']')
			.hide();
			$('div[id^=pollContainer'+$(this).removeClass('resultNav')
			.addClass('resultNavSelected')
			.attr('title','')
			.attr('id').replace(/pollNav/,'')+']')
			.show();
		}
		return false;
	});
	// инициализация кнопки голосования
	$('form[id^=poll] :radio').click(function(){
		$('input[id=btn_submit'+$(this).attr('name').replace(/pollOption/,'')+']').attr('disabled', false);
		$('form[id^=poll] :radio').unbind();
	});
	// кнопки голосования
	$('form[id^=poll] input[id^=btn_submit]').click(function(){ 
		if (!$(this).is('.btn_disable')) {
			var pollId=$(this).attr('id').replace(/btn_submit/,'');
			var checkedPollOption=$('form[id=poll'+pollId+'] :radio:checked').attr('value');
			var userId=$('form[id=poll'+pollId+'] input[name=pollUser]').attr('value');
			$.ajax({
      			url: "../main_new/ajax.php",
      			global: false,
      			type: "POST",
      			data: ({poll:pollId,pollOption:checkedPollOption,pollUser:userId,lang:cskabasketLang}),
      			dataType: "html",
      			async: false,
     			success: function(html){
      				if (html!='Error') {
						$('#poll_results_cont'+pollId).html(html);
						var voting_tab = $('a[tabcontent=poll_voting' + pollId + ']');
						var title = voting_tab.html();
						voting_tab.parent().removeClass('active_button_center').html('<span>' + title + '</span>');
						$('a[tabcontent=poll_results' + pollId + ']').click(); 
					}
				}
   			});	
		}
	});
	
	$("#main_news_buttons").newsblock({target: "#main_news_list", selectedClass: "active"});

	$("a[tabcontent]").bind("click", function(){
		var id = $(this).attr("tabcontent");
		var color = $(this).attr("tabcolor");
		var blockId = id.substring(id.indexOf('_')+1);
		var oldUrl = $(this).parent().parent().parent().find("#block_url").attr("href");
	
		if(!color)
			color = 'red';
		
		$(this).parent().parent().parent().find(".active_button").removeClass("active_button active_button_color-" + color).addClass('title_panel_item').find("a").addClass('dotted');
		$(this).removeClass('dotted').parent().addClass("active_button_center").parent().addClass("active_button active_button_color-" + color).removeClass('title_panel_item');
		var content = $("#" + id);
		if (content.length)	{
			var hideId = content.parent().find(".tabs_items:not(:hidden)").attr("id");
			var hideBlockId = new RegExp(hideId.substring(hideId.indexOf('_')+1)); 
			
			content.parent().find(".tabs_items").hide();
			content.show();
		}
		
		if(oldUrl && hideId && hideBlockId)
			$(this).parent().parent().parent().find("#block_url").attr("href",oldUrl.replace(hideBlockId,blockId));
	});
	
	$("a[tabcontent-simple]").bind("click", function(){
		var id = $(this).attr("tabcontent-simple");
		
		$(this).parent().parent().find("[tabcontent-simple]").addClass("dotted").removeClass("active");
		$(this).addClass("active").removeClass("dotted");
		
		var content = $("#" + id);
		if(content.length)
		{
			content.parent().find(".tabs_items").hide();
			content.show();
		}
	});
});

// плагин для листалки новостей на главной
(function( $ ){
	var params = {
		time: 4000,
		target: '#newsblock',
		selectedClass: ''
	};

 	var methods = {
		init : function( options ) 
		{
			var settings = $.extend(true, {}, params, options); 			
			
			return this.each(function()
			{
				$(this)
					.data("newsblock-params", settings)
					.bind({'mouseover.newsblock': methods.stop, 'mouseout.newsblock': methods.start})
					.newsblock("start");
					
				$(this).children().bind({'mouseover.newsblock': methods.over});
				
				var self = $(this);
				
				$(settings.target).bind({'mouseover.newsblock': function(){ self.newsblock("stop") }, 'mouseout.newsblock': function(){ self.newsblock("start") }});
			});
		},
		start : function( ) {
			var self = $(this);
			if(typeof $(this).data('number') === 'undefined')
				$(this).data('number', 0);
				
			$(this).data('_interval', setInterval(function(){ self.newsblock("next"); }, $(this).data('newsblock-params').time));
		},
		stop : function( ) { 
			if(typeof $(this).data('_interval') != "undefined")
			{
				clearInterval($(this).data('_interval'));
				$(this).removeData('_interval');
			}
		},
		next : function( ) {
			var settings = $(this).data('newsblock-params');			
			var number   = $(this).data('number') + 1;
			
			$(this).newsblock("select", number);		
		},
		over : function()
		{
			var number = 0;
			var self   = this;
			var children = $(this).parent().children().each( function(){ if(self !== this) number++; return self !== this; } );

			$(this).parent().newsblock("select", number);
		},
		select : function(number)
		{
			var settings = $(this).data('newsblock-params');
			var length   = $(settings.target).children().length;
			
			if(number + 1 > length)
				number = 0;
					
			$(this).children().removeClass(settings.selectedClass);
			$(this).children(":eq(" + number +  ")").addClass(settings.selectedClass);
			
			$(settings.target).children().hide();
			$(settings.target).children(":eq(" + number +  ")").show();
			$(this).data('number', number);
		},
		destroy : function( ) {
			return this.each(function(){
				clearInterval($(this).data('_interval'));
				$(this).removeData();
				$(this).unbind('.newsblock');
				$(this).children().unbind('.newsblock');
			})
		}
	};

	$.fn.newsblock = function( method ) {
		if ( methods[method] ) 
		{
			return methods[method].apply( this, Array.prototype.slice.call( arguments, 1 ));
		} 
		else if ( typeof method === 'object' || ! method ) 
		{
			return methods.init.apply( this, arguments );
		} 
		else
		{
			$.error( 'Method ' +  method + ' does not exist on jQuery.reverse' );
		}
	};
})( jQuery );


(function( $ ){
	var params = {
		scrollbar:'',
		scrollPane:'',
		scrollContent:''
	};
	
	var methods = {
		init : function( options ) {
			var settings = $.extend(true, {}, params, options);
			
			return this.each(function()
			{
				var scrollPane = $( settings.scrollPane ),
					scrollContent = $( settings.scrollContent );
				
				//build slider
				if ( scrollContent.width() > scrollPane.width() ) {
					var scrollbar = $( settings.scrollbar ).slider({
						slide: function( event, ui ) {
							if ( scrollContent.width() > scrollPane.width() ) {
								scrollContent.css( "margin-left", Math.round(
									ui.value / 100 * ( scrollPane.width() - scrollContent.width() )
								) + "px" );
							} else {
								scrollContent.css( "margin-left", 0 );
							}
						}
					});
								
					var handleHelper = scrollbar.find( ".ui-slider-handle" )
					.wrap( "<div class='ui-handle-helper-parent'></div>" ).parent();
					
					//change overflow to hidden now that slider handles the scrolling
					scrollPane.css( "overflow", "hidden" );
					
					var self = $(this);
					setTimeout( function(){ self.scroller("sizeScrollbar"); }, 10 );
					
					settings.scrollbar = scrollbar;
					settings.scrollPane = scrollPane;
					settings.scrollContent = scrollContent;
					settings.handleHelper = handleHelper;
					
					$(this)
						.data("slider-params", settings);
				}
			});
		},
		sizeScrollbar: function() {
			var settings = $(this).data("slider-params");
			
			var handleSize = 45;
			settings.scrollbar.find( ".ui-slider-handle" ).css({
				width: handleSize,
				"margin-left": -handleSize / 2
			});
			settings.handleHelper.width( "" ).width( settings.scrollbar.width() - handleSize );
		},
		destroy : function( ) {
			return this.each(function() {
				$(this).removeData();				
			})
		}
	};

	$.fn.scroller = function( method ) {
		if ( methods[method] ) 
		{
			return methods[method].apply( this, Array.prototype.slice.call( arguments, 1 ));
		} 
		else if ( typeof method === 'object' || ! method ) 
		{
			return methods.init.apply( this, arguments );
		} 
		else
		{
			$.error( 'Method ' +  method + ' does not exist on jQuery.reverse' );
		}
	};
})( jQuery );
