;(function ($) {
	// Добавляем метки браузера IE по каждой версии
	if ($.browser.msie && parseInt($.browser.version, 10) == 6) {
		$.browser.msie6 = true;
	} else if ($.browser.msie && parseInt($.browser.version, 10) == 7) {
		$.browser.msie7 = true;
	} else if ($.browser.msie && parseInt($.browser.version, 10) == 8) {
		$.browser.msie8 = true;
	}
	
	// Рисуем векторы шрифтов и тут же подгоняем всяческие отступы (Cufon)
	$(document).ready(function () {
		// Логотип
		Cufon.replace('#head SPAN.konkurs, #head SPAN.better, #head SPAN.text, #head SPAN.year');
		$('#head SPAN.konkurs').css('margin-bottom', '-1px');
		$('#head SPAN.better').css('margin-bottom', '-6px');
		if ($.browser.opera) {
			$('#head SPAN.better').css('margin-bottom', '0');
		}
		if ($.browser.webkit || $.browser.safari || $.browser.msie8) {
			$('#head SPAN.konkurs').css('padding-top', '5px');
		}
		if ($.browser.msie6 || $.browser.msie7) {
			$('#head SPAN.konkurs').css('padding-top', '4px');
		}
		
		Cufon.replace('.contact .phone');
		// Меню
		Cufon.replace('UL.menu LI A, UL.menu LI SPAN');
		
		// Промо на главной
		if ($meh.general_page) {
			Cufon.replace('#intro_block DIV.promo UL LI DIV.inner H2');
		}
		
		if (!$meh.general_page) {
			Cufon.replace([
				'H1.page_title SPAN:not([class])',
				'#content DIV.tab_block > UL.tabs A > SPAN',
				'#content DIV.tab_block DIV.tab_block_content P.tab_prize_title SPAN',
				'#content UL.bigred_marklist LI',
				//'#content UL.groups LI DL DT DIV',
				'#content UL.groups LI DL DT SPAN',
				'#content .groups_detail H2',
				'#content A.travel_button SPAN.wrapper SPAN',
				'#content DIV.player DIV.title H2',
				'#content DIV.player DIV.title H3',
				'#content DIV.player DIV.title EM',
				'#content DIV.player DIV.tab_block UL.tabs LI UL.subitems LI A',
				'#content DIV.player DIV.vote DIV.rating SPAN',
				'DIV.tab_block_playerstats DIV.innerscroll TABLE TD DIV.counter',
				'DIV.tab_block_playerstats DIV.innerscroll TABLE TD DIV.note',
				'DIV.tab_block_playerstats DIV.innerscroll TABLE TD.leader DIV.leader_compare DIV.to_leader SPAN',
				'DIV.razvod A SPAN',
				'DIV.press-center DIV.news_block DIV.cap H2',
				'#content DIV.press-center DIV.tab_block_press > UL.tabs A > SPAN',
				'#content DIV.press-center DIV.tab_block_press UL.tabs LI UL.subitems LI A',
				'DIV.news_detail DIV.returner A'
			].join(','));
		}
	});
	
	// Главная страница
	if ($meh.general_page) {
		$(document).ready(function () {
			var ani = false;
			
			$('#intro_block DIV.promo A.slider').click(function () {
				if (!ani) {
					ani = true;
					$(this).closest('DIV.promo').children('UL').slideToggle('600', function () {
						ani = false;
					});
					if ($(this).find('SPAN.cold').size() > 0) {
						$(this).append('<span class="hot" style="display:none"></span>').find('SPAN.hot').fadeIn('600')
							.end().find('SPAN.cold').fadeOut('600', function () {
								$(this).remove();
							}).end().attr('title', 'Нажмите, чтобы скрыть дополнительное меню');
					} else {
						$(this).append('<span class="cold" style="display:none"></span>').find('SPAN.cold').fadeIn('600')
							.end().find('SPAN.hot').fadeOut('600', function () {
								$(this).remove();
							}).end().attr('title', 'Нажмите, чтобы раскрыть дополнительное меню');
					}
				}
				return false;
			});
			
			swfobject.embedSWF('/bitrix/templates/rsm-konkurs/images/flash_main.swf', 'intro_movie', '986', '468', '9', '/bitrix/templates/rsm-konkurs/images/expressInstall.swf', null, {'wmode': 'transparent'}, null);
		});
	}
	
	
	// Блок с табами
	$(document).ready(function () {
		if($("#flash_preloader").size() > 0)
		{
			swfobject.embedSWF('/bitrix/templates/rsm-konkurs/images/preloader.swf', 'flash_preloader', '66', '66', '9', '/bitrix/templates/rsm-konkurs/images/expressInstall.swf', null, {'wmode': 'transparent'}, null);
		}
		if($("#flash_preloader_gray_loader").size() > 0)
		{
			swfobject.embedSWF('/bitrix/templates/rsm-konkurs/images/preloader_gray.swf', 'flash_preloader_gray_loader', '66', '66', '9', '/bitrix/templates/rsm-konkurs/images/expressInstall.swf', null, {'wmode': 'transparent'}, null);
		}		
		
		if($("#field_region").size() > 0)
		{
			$("#field_region").selectBox();
		}
		if($("#field_nomination").size() > 0)
		{
			$("#field_nomination").selectBox();
		}
		if($("#field_type").size() > 0)
		{
			$("#field_type").selectBox();
		}	
		
		// Обычные таб-блоки (страница "О конкурсе")
		// немного гавнокода, чтобы барбекю не прикручивать
		/*
		if(location.hash){
			setTimeout(function() {
				$("a[href="+ location.hash + "]").click();
			}, 1100);
		}*/
		
		Cufon.replace(".name_panel_back, .custom_submit span, .accreditation_registration .add");
		
		$(".hidden_form input").change(function()
		{
			$(".custom-file-input span").text($(this).val());
		});
		/*
		$(".custom-file-input").file().choose(function(e, input)
		{
			$(this).find("span").text(input.val());
		});*/
	  
  	$(window).bind( 'hashchange', function(e)
  	{	 
  		var full_url = str_replace("#", "/", $.param.fragment());  
    	var small_url = full_url.indexOf("/") == -1 ? full_url : full_url.substr(0, full_url.indexOf("/")); 
    	var ajax_loader = $(".ajax_loader").filter(".nominations");
    	ajax_loader.show();
    	full_url && $("a[href=#" + small_url + "]").trigger("click");
    	
    	function str_replace(search, replace, subject)
    	{
    		return subject.split(search).join(replace);
		} 

		var cur_loc = new String(window.location);
    	if(cur_loc.indexOf("about_competition") != -1 || cur_loc.indexOf("press_accreditation") != -1 || cur_loc.indexOf("winners") != -1)
    	{
    		var bbq_content = $(".bbq-content");
    	}
    	else
    	{
    		var bbq_content = $(".active .bbq-content");
    	}

    	
    	bbq_content.fadeOut("fast", function()
    	{
    		$('.bbq-content').empty();
    		
			bbq_content.load(full_url, function()
			{
				ajax_loader.hide();
				setTimeout(function()
				{
					$(".active .big_listing .list_big").jScrollPane();
					$('.active .big_listing .jScrollPaneTrack').prepend('<div class="plug"></div>');
				} , 10);
				
				$('.bbq-content').fadeIn("fast");
			});    		
    	});
   	
  });
  
  	// Участники соревнований
	$(".competitors_nomination").live('click', function()
	{
		var cur_img = $(this).find("img");
		var pre_act = $(".groups_detail li.active");
		var pre_img = pre_act.find("dt img");

		pre_act.find("dt").append($('<a href="#' + pre_img.attr("alt") + '" class="competitors_nomination" title=""></a>').append('<span class="logo_plug"></span>').append(pre_img));
		pre_act.removeClass("active");
		$(this).parent().parent().parent().addClass("active");
		$(this).parent().find("a").remove().end().append(cur_img);	
		
		$("#sort_name").attr("href", "#" + cur_img.attr("alt") + "#NAME");
		$("#sort_grainall").attr("href", "#" + cur_img.attr("alt") + "#GRAINALL")
		$("#sort_biography").attr("href", "#" + cur_img.attr("alt") + "#BIOGRAPHY");
	});

  $(window).trigger( 'hashchange' );
  
	// Первый показываем сразу
	$('#content DIV.tab_block DIV.tab_block_content DIV.contentbox.first').show();
	
		$('DIV.tab_block:not([class*=player])').each(function () {
			$(this).children('UL.tabs').find('A').each(function () {
				$(this).click(function () {
					
					if ($(this).hasClass('active') > 0) {
						return false;
					}
					$(this).closest('UL').find('A').removeClass('active');
					$(this).addClass('active');
					
					if($.browser.msie && $.browser.version.indexOf("6") != -1)
					{
						$('#content DIV.tab_block DIV.tab_block_content > DIV:visible').hide();
						$($(this).attr('href')).show();
					}
					else
					{
						$('#content DIV.tab_block DIV.tab_block_content > DIV:visible').hide('300');
						$($(this).attr('href')).show('300');						
					}
					//$('#content UL.groups_detail DL DD DIV.list').jScrollPane();
					return false;
				});
				/*$(this).closest('DIV.tab_block').children('DIV.tab_block_content')
					.find('A[href="' + $(this).attr('href') + '"]').click(function () {
						var $DOM = $(this)
						setTimeout(function () {
							var $HTML = $('HTML')
							$HTML.scrollTo({
								left: $HTML.scrollLeft() + 'px',
								top: 0
							}, 600, function () {
								$DOM.closest('DIV.tab_block').children('UL.tabs').find('A[href="' + $DOM.attr('href') + '"]').trigger('click');
							});
						}, 100);
						return false;
					});
				*/
			});
		});
		
/*		// Блог участника из "Ход соревнований"
		$('DIV.tab_block.player').each(function () {
			$(this).children('UL.tabs').find('A').each(function () {
				$(this).click(function () {
					if ($(this).filter('[class]').size() > 0) {
						return false;
					}
					var $GEN = $(this).closest('UL.tabs');
					$GEN.find('A').removeClass('active');
					$GEN.find('A[href="' + $(this).attr('href') + '"]').addClass('active');
					if ($(this).closest('UL').filter('.subitems').size() > 0) {
						$(this).closest('UL.subitems').closest('LI').children('A').addClass('active');
					}
					$(this).closest('DIV.tab_block.player').find('DIV.tab_block_content > DIV.scrollbox:visible').fadeOut('300');
					$($(this).attr('href')).fadeIn('300');
					Cufon.replace('#content DIV.player DIV.tab_block UL.tabs LI UL.subitems LI A');
					return false;
				});
			});
		});
		
		// Табы статистики участника из "Ход соревнований"
		$('DIV.tab_block_playerstats').each(function () {
			$(this).children('UL.tabs').find('A').each(function () {
				$(this).click(function () {
					if ($(this).filter('[class]').size() > 0) {
						return false;
					}
					$(this).closest('UL').find('A').removeClass('active');
					$(this).addClass('active');
					$(this).closest('DIV.tab_block_playerstats').find('DIV.tab_block_content > DIV:visible').fadeOut('300');
					$($(this).attr('href')).fadeIn('300');
					return false;
				});
			});
		});
		

		// Сразу крутим скрулл в конец к последним показателям
		$('DIV.tab_block_playerstats DIV.tab_block_content DIV.contentbox').each(function () {
			var dom = this;
			setTimeout(function () {
				$(dom).scrollTo({
					left: $(dom).width() + 'px',
					top: 0
				}, 600);
			}, 1000);
		});
*/	
		// Табы пресс-центра
		$('#content DIV.press-center DIV.tab_block_press').each(function () {
			$(this).children('UL.tabs').find('A').each(function () {
				$(this).click(function () {
					if ($(this).filter('[class]').size() > 0) {
						return false;
					}
					var $GEN = $(this).closest('UL.tabs');
					$GEN.find('A').removeClass('active');
					$GEN.find('A[href="' + $(this).attr('href') + '"]').addClass('active');
					if ($(this).closest('UL').filter('.subitems').size() > 0) {
						$(this).closest('UL.subitems').closest('LI').children('A').addClass('active');
					}
					$(this).closest('DIV.tab_block_press').find('DIV.tab_block_content > DIV.contentbox:visible').hide('300');
					$($(this).attr('href')).show('300');
					Cufon.replace('#content DIV.press-center DIV.tab_block_press UL.tabs LI UL.subitems LI A');
					return false;
				});
			});
		});
		if (!$.browser.msie6) {
			$('#content DIV.press-center DIV.tab_block_press DIV.tab_block_content DIV.contentbox.first').show();
		} else {
			$('#content DIV.press-center DIV.tab_block_press DIV.tab_block_content DIV.contentbox.first').show(1);
		}
		
		// Листинг фотоГ и видосов
		ListInit = function () {
			
			$('.fancy[rel=group]').fancybox({
'titlePosition': 'inside'
	
			});
			var $LISTER = $(this).children('DIV.lister');
			var $UL = $LISTER.children('DIV.list').children('UL');
			var $LISTL = $LISTER.children('A.left_hand'); // Кнопка "назад"
			var $LISTR = $LISTER.children('A.right_hand'); // Кнопка "вперёд"
			var activate; // Активация кнопок (вперёд-назад)
			var deActivate; // Деактивация кнопок
			var activator; // Функция распределения активирования и деактивирования кнопок
			var boxWidth = 0; // Ширина контейнера
			var listWidth = 0; // Ширина списка (по заполнению)
			var animate = false; // Флаг передвижения по фоткам
			var getListWidth; // Функция получения ширины списка фоток
			
			// Добавляем круглые уголки
			$UL.children('LI').children('DIV')
				.prepend('<span class="top-left"></span><span class="top-rigth"></span>'
					+ '<span class="bottom-left"></span><span class="bottom-right"></span>');
			
			getListWidth = function () {
				listWidth = 0;
				$UL.children('LI').each(function () {
					listWidth += $(this).outerWidth() + 5;
				});
				if (listWidth > 5) {
					listWidth -= 5;
				}
			};
			
			// Показываем все табы, чтобы получить отрисовку всех размеров
			$('#content DIV.press-center DIV.tab_block_press DIV.tab_block_content DIV.contentbox').show();
			boxWidth = $LISTER.children('DIV.list').width();
			getListWidth();
			// Скрываем все табы, кроме помеченного первого
			$('#content DIV.press-center DIV.tab_block_press DIV.tab_block_content DIV.contentbox:not(.first)').hide();
			
			// Огорошиваем по голове ослов, чтобы они взбодрились
			if ($.browser.msie7) {
				$('#content DIV.press-center UL.tabs').css('padding-left', '0');
			}
			if ($.browser.msie6) {
				$('#content DIV.press-center UL.tabs').css('margin-left', '1px');
			}
			
			activate = function (side) {
				side = (side || 'left');
				if (side === 'left') {
					$LISTL.addClass('left_hand_active');
				} else if (side === 'right') {
					$LISTR.addClass('right_hand_active');
				}
			};
			
			deActivate = function (side) {
				side = (side || 'left');
				if (side === 'left') {
					$LISTL.removeClass('left_hand_active');
				} else if (side === 'right') {
					$LISTR.removeClass('right_hand_active');
				}
			};
			
			activator = function (without_getting_width) {
				var left = parseInt($UL.css('margin-left').replace('-', ''), 10);
				
				if (!without_getting_width) {
					getListWidth();
				}
				
				if (listWidth > boxWidth) {
					activate('right');
					if (left >= (listWidth-(91*7)-5)) {
						deActivate('right');
					}
				} else {
					deActivate('right');
				}
				
				if (left > 0) {
					activate('left');
				} else {
					deActivate('left');
				}
			};
			
			activator(true);
			
			$LISTL.click(function () {
				var left = parseInt($UL.css('margin-left').replace('-', ''), 10);
				var newLeft = left;
				
				if ($(this).hasClass('left_hand_active') && !animate) {
					animate = true;
					newLeft -= 91;
					$UL.animate({'margin-left': '-' + newLeft + 'px'}, 200, function () {
						animate = false;
						activator();
					});
				}
				activator();
				return false;
			});
			
			$LISTR.click(function () {
				var left = parseInt($UL.css('margin-left').replace('-', ''), 10);
				var newLeft = left;
				
				if ($(this).hasClass('right_hand_active') && !animate) {
					animate = true;
					newLeft += 91;
					$UL.animate({'margin-left': '-' + newLeft + 'px'}, 200, function () {
						animate = false;
						activator();
					});
				}
				activator();
				return false;
			});
		};
		
		$('#content DIV.list-photos, #content DIV.list-video').each(ListInit);
	});
	
	
	// Обязательные поля для форм
	$(document).ready(function () {
		var warning_color = '#ffd6e1';
		var count = 0;
		$('FORM.accreditation_registration .add').click(function(){
			count++;
			$(this).parent().find('dl dd:last').after('<dt><label for="author_name">Фамилия</label></dt>'
					+ '<dd><input type="text" name="author_name[]" id="author_name" class="text" title="Фамилия" style="width: 180px" /></dd>'
					+ '<dt><label for="author_sname">Имя</label></dt>'
					+ '<dd><input type="text" name="author_sname[]" id="author_sname" class="text" title="Имя" style="width: 180px" /></dd>'
					+ '<dt><label for="author_patr">Отчество</label></dt>'
					+ '<dd><input type="text" name="author_patr[]" id="author_patr" class="text" title="отчество" style="width: 180px" /></dd>');
		});
		$('FORM.accreditation_registration, FORM.participation_request').submit(function () {
			var $FORM = $(this);
			var next_step = true;
			var show_loader;
			var hide_loader;
			var $LOADER;
			 			
			
			var ajax_loader = $(".ajax_loader");
    					
			
			
			$(this).find('INPUT.text, TEXTAREA.textarea').css('background', '');
			
			$(this).find('INPUT.text[value=]:not(.opt)').each(function () {
				next_step = false;
				$(this).css('background', warning_color);
			});
			
			if ( !next_step ) {
				alert('Вы должны заполнить все поля!');
			}
			
			if ( $(this).hasClass('accreditation_registration') ) {
				var $PASS1 = $(this).find('INPUT[name=password]');
				var $PASS2 = $(this).find('INPUT[name=password2]');
				var not_empty = ( $PASS1.is(':not([value=])') || $PASS2.is(':not([value=])') ) ? true : false;
				
				if ( not_empty && $PASS1.val() != $PASS2.val() ) {
					alert('Пароли не совпадают!');
					$PASS1.css('background', warning_color);
					$PASS2.css('background', warning_color);
					next_step = false;
				}
			}
			
			// Дальше разруливаем отправку аяксом
			if ( !next_step ) {
				return next_step;
			}
			  
			
			show_loader = function () {
				$FORM.hide(1);
				$FORM.before('<div class="ajax_loader">Идёт отправка данных...</div>');
				$LOADER = $FORM.parent().children('DIV.ajax_loader');
			};
			
			
			
			hide_loader = function () {
				$FORM.show(1);
				$LOADER.remove();
			};
			

			
			if ( $(this).hasClass('accreditation_registration') ) {
				
				$('FORM.accreditation_registration').ajaxForm();
				  
				  // submit form
				  ajax_loader.css("top", $(document).height / 2).show();
				  $("FORM.accreditation_registration").ajaxSubmit({ 
				        url: $(this).attr('action'),
				        type: $(this).attr('method').toUpperCase(),
				        iframe: true,
				        dataType: 'json',
				        success:    function(res) { 
							var res = $.parseJSON( res );
							var form_stop = false;
							form_stop = true;
							ajax_loader.hide();
							$FORM.before('<div class="complete_message"><h3>Данные успешно отправлены!</h3><p>После проверки данных администратор свяжется с Вами!</p></div>');
							
								
							if ( form_stop ) {
								$FORM.hide(1);
							}
				        }
				   });
				/*show_loader();
				$.ajax({
					url: $(this).attr('action'),
					type: $(this).attr('method').toUpperCase(),
					cache: false,
					data: $(this).serialize() + '&ajaxnospam=1',
					success: function ( res ) {
						//console.log(res);
						var res = $.parseJSON( res );
						var login_error = false;
						var form_stop = false;
						
						if ( typeof res.errors != 'undefined' ) {
							$.each(res.errors, function () {
								if ( typeof this.login_error != 'undefined' && this.login_error == 1 ) {
									login_error = true;
								}
							})
							
							if ( login_error ) {
								alert('Ошибка!\n\nТакой логин уже занят.\nПопробуйте ввести другой логин.');
							} else {
								alert('Ошибка!\n\nПроизошла неизвестная ошибка при регистрации.\nОбратитесь к администратору сайта.');
							}
						} else {
							form_stop = true;
							$FORM.before('<div class="complete_message"><h3>Данные успешно отправлены!</h3><p>После проверки данных администратор свяжется с Вами!</p></div>');
						}
						
						hide_loader();
						
						if ( form_stop ) {
							$FORM.hide(1);
						}
					}
				});*/
			} else if ( $(this).hasClass('participation_request') ) {
				
				$('#participant-form').ajaxForm();
				  ajax_loader.show();
				  // submit form
				  $("#participant-form").ajaxSubmit({ 
				        url: $(this).attr('action'),
				        type: $(this).attr('method').toUpperCase(),
				        iframe: true,
				        dataType: 'json',
				        success:    function(res) { 
							var res = $.parseJSON( res );
							var form_stop = false;
							form_stop = true;
							ajax_loader.hide();
							$FORM.before('<div class="complete_message"><h3>Данные успешно отправлены!</h3><p>После проверки данных администратор свяжется с Вами!</p></div>');
							
								
							if ( form_stop ) {
								$FORM.hide(1);
							}
				        }
				   });
	/*			$.ajax({
					url: $(this).attr('action'),
					type: $(this).attr('method').toUpperCase(),
					cache: false,
					data: $(this).serialize() + '&ajaxnospam=1',
					success: function ( res ) {
						var res = $.parseJSON( res );
						var form_stop = false;
						
						if ( typeof res.status !== 'undefined' && res.status == 'error' ) {
							alert('Ошибка!\n\nПроизошла ошибка при отправке данных.\nПроверьте правильность указанных Вами данных.');
						} else {
							form_stop = true;
							$FORM.before('<div class="complete_message"><h3>Данные успешно отправлены!</h3><p>После проверки данных администратор свяжется с Вами!</p></div>');
						}
						
						hide_loader();
						
						if ( form_stop ) {
							$FORM.hide(1);
						}
					}
				});*/
			}
			
			return false;
		});
		
		
		
	});
	
	
	// Инициализируем оформленные скруллы
	$(document).ready(function () {
		$('#content UL.groups_detail DL DD DIV.list').jScrollPane();
		$('#content UL.groups_detail LI DL DD .jScrollPaneTrack').prepend('<div class="plug"></div>');
		
		$('#content DIV.player DIV.about DIV.tab_block_content DIV.scrollbox').show();
		$('#content DIV.player DIV.about DIV.tab_block_content DIV.scrollbox DIV.fleshbox').jScrollPane();
		$('#content DIV.player DIV.about DIV.tab_block_content DIV.scrollbox .jScrollPaneTrack').prepend('<div class="plug"></div>');
		$('#content DIV.player DIV.about DIV.tab_block_content DIV.scrollbox:not(.first)').hide();
		
		// Вот ж мля не получилось :'( не хочет работать зараза...
		/*$('DIV.tab_block_playerstats DIV.tab_block_content DIV.contentbox').show();
		$('DIV.tab_block_playerstats DIV.tab_block_content DIV.contentbox DIV.innerscroll').jScrollHorizontalPane();
		$('DIV.tab_block_playerstats DIV.tab_block_content DIV.contentbox:not(.first)').hide();*/
	});
	
	
	// Плейсхолдеры для формы
	$(document).ready(function () {
		$('FORM.participation_request, FORM.accreditation_registration').each(function () {
			var $FORM = $(this); // дом формы
			var counter = 1; // резервуар для счётчика плейсхолдеров
			
			// делаем плейсхолдеры тем, кто имеет title
			$('INPUT:text[title], INPUT:password[title], TEXTAREA[title]').each(function () {
				var ident = 'participation_request_input_' + (counter++); // будущий ID дома
				var $LABEL; // плейсхолдер
				
				// Opera == IE6 === true
				if ($.browser.opera || ($.browser.msie6 && $(this).filter('.ie6_when_you_die').size()>0)) {
					$(this).wrap('<span class="i_hate_opera"></span>');
					$FORM.find('SPAN.i_hate_opera').css('position', 'relative');
					if ($.browser.msie6) {
						$FORM.find('SPAN.i_hate_opera').css('padding-bottom', '2px');
					}
				}
				
				// Если дом уже имеет ID - используем его
				if ($(this).is('[id]')) {
					ident = $(this).attr('id');
				} else {
					$(this).attr('id', ident);
				}
				
				$(this).before('<label class="placeholder" for="' + ident + '">' + $(this).attr('title') + '</label>');
				$LABEL = $(this).parent().children('LABEL[for="' + ident + '"]').css('position', 'absolute');
				$(this).focusin(function () {
					$LABEL.css('visibility', 'hidden');
				}).focusout(function () {
					if ($(this).val() == '') {
						$LABEL.css('visibility', 'visible');
					}
				});
				
				$(this).trigger('focusin').trigger('focusout');
			});
		});
	});
	
	
	// Подробные просмотры Пресс-центра
	$(document).ready(function () {		
		var showDetail; // выводилка подробного вывода
		var hideDetail; // скрывалка подробного вывода
		var $dviewer = $('#detail_viewer'); // сам блок для детального вывода
		var $dcontent = $dviewer.find('DIV.detail_content'); // блок детального контента
		var $press_center = $('DIV.press-center'); // блок пресс-центра
		var cufon_selector = 'DIV.press-center DIV.news_block DIV.cap H2,'
			+ '#content DIV.press-center DIV.tab_block_press > UL.tabs A > SPAN,'
			+ '#content DIV.press-center DIV.tab_block_press UL.tabs LI UL.subitems LI A';
		//var loader_html = '<div class="ajax_loader">Идёт получение данных...</div>'; // контент лоадера
		
		var ajax_loader = $(".ajax_loader");
    	
		
		showDetail = function ( tape, url ) {
			tape = ( tape || '' ); // лента, в которою открыли (новости/статьи/...)
			url = ( url || '' ); // запрашиваемый аяксом урл (урл новости/статьи/...)

			switch ( tape ) {
				case 'news':
					$press_center.addClass('press-center_detailnews');
					//$dcontent.html( loader_html );
					
					ajax_loader.show();

					$.ajax({
						url: url,
						type: 'get',
						cache: false,
						data: 'ajax=1',
						success: function ( res ) {
							$dcontent.html( res );
							
							ajax_loader.hide();
							
							Cufon( 'DIV.news_detail DIV.returner A' );
							$('#content DIV.list-photos').each(ListInit);
							$('DIV.news_detail DIV.returner A').click(function () {
								hideDetail();
								return false;
							});
						},
						error: function () {
							alert('Ошибка!\n\nПроизошла ошибка при открытии материала!');
							hideDetail();
						}
					});
					
					cufon_selector = 'DIV.press-center > DIV.news_block DIV.cap H2';
					
				break;
				
				case 'notes':
					$press_center.addClass('press-center_detailmat');
					//$dcontent.html( loader_html );
						
					$.ajax({
						url: url,
						type: 'get',
						cache: false,
						data: 'ajax=1',
						success: function ( res ) {
							$dcontent.html( res );
							
							ajax_loader.hide();
							
							Cufon( 'DIV.news_detail DIV.returner A' );
							$('#content DIV.list-photos').each(ListInit);
							$('DIV.news_detail DIV.returner A').click(function () {
								hideDetail();
								return false;
							});
						},
						error: function () {
							alert('Ошибка!\n\nПроизошла ошибка при открытии материала!');
							hideDetail();
						}
					});
					
					cufon_selector = 'DIV.press-center > DIV.material_block DIV.cap H2';
	
				break;
			}
		
			Cufon.replace( cufon_selector ); // перекуфониваем кнопки (чтобы изменялся цвет)
		};
		
		hideDetail = function () {
			$dcontent.html('');
			$press_center.removeClass('press-center_detailnews').removeClass('press-center_detailmat');
			
			Cufon.replace( cufon_selector ); // перекуфониваем кнопки (чтобы изменялся цвет)
		};
		
		
		$('DIV.press-center > DIV.material_block DIV.contentbox DIV.news-list H4.title A').click(function () {
			
			hideDetail();
			showDetail('notes', $(this).attr('href'));
			return false;
		});		
		
		$('DIV.press-center > DIV.news_block DIV.contentbox DIV.news-list H4.title A').click(function () {
			
			hideDetail();
			showDetail('news', $(this).attr('href'));
			return false;
		});
		
		$dviewer.find('A.detail_closer').click(function () {
			hideDetail();
			return false;
		});
	});
	
	
	// Активированный уголь для IE6
	if ($.browser.msie6) {
		$(document).ready(function () {
			DD_belatedPNG.fix([
				'UL.menu LI SPAN',
				'UL.menu LI A',
				'#intro_block DIV.promo A.slider',
				'#intro_block DIV.promo A.slider SPAN',
				'#intro_block DIV.promo UL',
				'#intro_block DIV.promo UL LI',
				'H1.page_title SPAN',
				'#content UL.bigred_marklist LI',
				'#content A.travel_button',
				'#content A.travel_button SPAN',
				//'#content UL.groups_detail LI DL DT A DIV.logo_plug',
				'#content UL.groups_detail LI DL DT A SPAN.logo_plug',
				'#content DIV.player DIV.vote DIV.opinions DIV.innerbox',
				'#content DIV.player DIV.vote DIV.rating DIV.innerbox',
				'DIV.tab_block_playerstats DIV.innerscroll TABLE TD DIV.counter',
				'.ddpng',
				'#content UL.groups_detail LI DL DT A SPAN.logo_plug',
				'#content UL.groups LI DL DD DIV.description',
				'.submit_wrapper button',
				'#competition_order_link img',
				'.accreditation_registration .add'
			].join(','));
			
			if(!$.browser.msie6)
			{
				DD_belatedPNG.fix([
					'#content UL.groups LI DL DD OL',
					'#content UL.groups LI DL DT IMG'
				].join(','));				
			}
			
		});
	}
	// Активированный уголь для Opera и трёх её кровных братьев
	if (($.browser.opera || $.browser.msie) && !$.browser.msie7) {
		$(window).resize(function () {
			document.body.style.position = 'relative';
			setTimeout(function () {
				document.body.style.position = 'static';
			}, 1);
		});
	} else if ($.browser.msie7) {
		$(window).resize(function () {
			$('#general_container').append('<div id="ie7_bugkiller"></div>').find('#ie7_bugkiller').remove();
		});
	}
	

})(jQuery);
