//PRINTAREA PLUGIN 1.1
(function(b){var a=0;b.fn.printArea=function(){var f=b(this);var e="printArea_";c(e+a);a++;var i=e+a;var d="position:absolute;width:0px;height:0px;left:-500px;top:-500px;";iframe=document.createElement("IFRAME");b(iframe).attr({style:d,id:i});document.body.appendChild(iframe);var g=iframe.contentWindow.document;b(document).find("link").filter(function(){return b(this).attr("rel").toLowerCase()=="stylesheet"});g.write('<div id="iframe-wrapper" class="'+b(f).attr("class")+'">'+b(f).html()+"</div>");g.close();var h=iframe.contentWindow;h.close();h.focus();h.print()};var c=function(d){b("iframe#"+d).remove()}})(jQuery);

//SCROLLTO PLUGIN 1.4.1
;(function($){var m=$.scrollTo=function(b,h,f){$(window).scrollTo(b,h,f)};m.defaults={axis:'xy',duration:parseFloat($.fn.jquery)>=1.3?0:1};m.window=function(b){return $(window).scrollable()};$.fn.scrollable=function(){return this.map(function(){var b=this,h=!b.nodeName||$.inArray(b.nodeName.toLowerCase(),['iframe','#document','html','body'])!=-1;if(!h)return b;var f=(b.contentWindow||b).document||b.ownerDocument||b;return $.browser.safari||f.compatMode=='BackCompat'?f.body:f.documentElement})};$.fn.scrollTo=function(l,j,a){if(typeof j=='object'){a=j;j=0}if(typeof a=='function')a={onAfter:a};if(l=='max')l=9e9;a=$.extend({},m.defaults,a);j=j||a.speed||a.duration;a.queue=a.queue&&a.axis.length>1;if(a.queue)j/=2;a.offset=n(a.offset);a.over=n(a.over);return this.scrollable().each(function(){var k=this,o=$(k),d=l,p,g={},q=o.is('html,body');switch(typeof d){case'number':case'string':if(/^([+-]=)?\d+(\.\d+)?(px)?$/.test(d)){d=n(d);break}d=$(d,this);case'object':if(d.is||d.style)p=(d=$(d)).offset()}$.each(a.axis.split(''),function(b,h){var f=h=='x'?'Left':'Top',i=f.toLowerCase(),c='scroll'+f,r=k[c],s=h=='x'?'Width':'Height';if(p){g[c]=p[i]+(q?0:r-o.offset()[i]);if(a.margin){g[c]-=parseInt(d.css('margin'+f))||0;g[c]-=parseInt(d.css('border'+f+'Width'))||0}g[c]+=a.offset[i]||0;if(a.over[i])g[c]+=d[s.toLowerCase()]()*a.over[i]}else g[c]=d[i];if(/^\d+$/.test(g[c]))g[c]=g[c]<=0?0:Math.min(g[c],u(s));if(!b&&a.queue){if(r!=g[c])t(a.onAfterFirst);delete g[c]}});t(a.onAfter);function t(b){o.animate(g,j,a.easing,b&&function(){b.call(this,l,a)})};function u(b){var h='scroll'+b;if(!q)return k[h];var f='client'+b,i=k.ownerDocument.documentElement,c=k.ownerDocument.body;return Math.max(i[h],c[h])-Math.min(i[f],c[f])}}).end()};function n(b){return typeof b=='object'?b:{top:b,left:b}}})(jQuery);

//SERIALSCROLL PLUGIN 1.2.1
;(function($){var a='serialScroll',b='.'+a,c='bind',C=$[a]=function(b){$.scrollTo.window()[a](b)};C.defaults={duration:1e3,axis:'x',event:'click',start:0,step:1,lock:1,cycle:1,constant:1};$.fn[a]=function(y){y=$.extend({},C.defaults,y);var z=y.event,A=y.step,B=y.lazy;return this.each(function(){var j=y.target?this:document,k=$(y.target||this,j),l=k[0],m=y.items,o=y.start,p=y.interval,q=y.navigation,r;if(!B)m=w();if(y.force)t({},o);$(y.prev||[],j)[c](z,-A,s);$(y.next||[],j)[c](z,A,s);if(!l.ssbound)k[c]('prev'+b,-A,s)[c]('next'+b,A,s)[c]('goto'+b,t);if(p)k[c]('start'+b,function(e){if(!p){v();p=1;u()}})[c]('stop'+b,function(){v();p=0});k[c]('notify'+b,function(e,a){var i=x(a);if(i>-1)o=i});l.ssbound=1;if(y.jump)(B?k:w())[c](z,function(e){t(e,x(e.target))});if(q)q=$(q,j)[c](z,function(e){e.data=Math.round(w().length/q.length)*q.index(this);t(e,this)});function s(e){e.data+=o;t(e,this)};function t(e,a){if(!isNaN(a)){e.data=a;a=l}var c=e.data,n,d=e.type,f=y.exclude?w().slice(0,-y.exclude):w(),g=f.length,h=f[c],i=y.duration;if(d)e.preventDefault();if(p){v();r=setTimeout(u,y.interval)}if(!h){n=c<0?0:n=g-1;if(o!=n)c=n;else if(!y.cycle)return;else c=g-n-1;h=f[c]}if(!h||d&&o==c||y.lock&&k.is(':animated')||d&&y.onBefore&&y.onBefore.call(a,e,h,k,w(),c)===!1)return;if(y.stop)k.queue('fx',[]).stop();if(y.constant)i=Math.abs(i/A*(o-c));k.scrollTo(h,i,y).trigger('notify'+b,[c])};function u(){k.trigger('next'+b)};function v(){clearTimeout(r)};function w(){return $(m,l)};function x(a){if(!isNaN(a))return a;var b=w(),i;while((i=b.index(a))==-1&&a!=l)a=a.parentNode;return i}})}})(jQuery);

//SEARCH FOR TEXT PATTERN WITH jQUERY
/*
$.fn.egrep=function(b){var a=[];var c=function(e){if(e.nodeType==Node.TEXT_NODE){var d=typeof b=="string"?e.nodeValue.indexOf(b)!=-1:b.test(e.nodeValue);if(d){a.push(e.parentNode)}}else{$.each(e.childNodes,function(g,f){c(f)})}};this.each(function(){c(this)});return a};
*/

$(document).ready(function() {
		//Увеличиваем размер шрифта на pub'ах
	$(".font-increment").click(function() {
		var currentFontSize = $('html').css('font-size');
		var currentFontSizeNum = parseFloat(currentFontSize, 10);
		var newFontSize = currentFontSizeNum * 1.04;
		$('p,h3').css('font-size', newFontSize);
		$(".font-increment").addClass('bt_m_notactive').css('text-decoration','none');
		return false;
	});

	//Увеличиваем размер шрифта на главной
	$(".font-increment-menu").click(function() {
		var currentFontSize = $('html').css('font-size');
		var currentFontSizeNum = parseFloat(currentFontSize, 10);
		var newFontSize = currentFontSizeNum * 0.7
		;
		$('#hc_cols ol li').css('font-size', newFontSize);
		$('#hc_cols ol').css('height', '350px');
		$(".font-increment-menu").css('color','#B2B4B6').css('cursor','default');
		return false;
	});
	
	//Мягкий скролл к началу страницы
	$('a[href^=#header],a[href^=#margins]').click(function() {
		$.scrollTo( this.hash, 1500);
		return false;
		});
	//alert('hidetable');
	//===========================================================САМОЕ ГЛАВНОЕ=======================================
	
	//$('#logo').append('<div id="beta"><a title="Сайт работает в тестовом режиме. Пожалуйста, следите за обновлениями и сообщайте редактору об ошибках по адресу, данному внизу этой страницы" onclick=$("#roadmap").slideToggle(); href="javascript:;">beta</a></div>');
	$('#logo a').wrapInner('<span></span>');
	$('#logo span').hide();
	$('.bt_m_tools li a').wrapInner('<span></span>');
	//$('.bt_m_tools li a span').hide();
	$('#ht_left p:last, .summary a').append('...');
	$("#content:has('#hc_filter')").css("position", "relative");
	$("#li:has('#map-img')").css("position", "relative");
	$("#hc_cols li:last-child").css("border-bottom", "none").css("padding-bottom", "none");
	$("#hc_cols ol li:last-child").css("padding-bottom", ".6em");
	$('.lenta_summary').css('overflow-x', 'hidden');
	$('.autoselect').hide().focus(function() {$(this).select();});
	$('#news_nav a:not(a[href])').hide();
	$('.permalink').click(function () {$(this).parent('li').find('.autoselect').attr("value",location.href).toggle();});
	$('#hc_ms_tem_link').click(function () {$('#hc_ms_tem').show();$('#hc_ms_story').hide();$('#hc_ms_story_link').addClass('rc_h_a');$(this).removeClass('rc_h_a');});
	$('#hc_ms_story_link').click(function () {$('#hc_ms_story').show();$('#hc_ms_tem').hide();$('#hc_ms_tem_link').addClass('rc_h_a');$(this).removeClass('rc_h_a');});
	$('#rightcol_cat-msk_link').click(function () {
													$('#rightcol_cat-msk').show();
													$('#rightcol_cat-spb').hide();
													$('#rightcol_cat-spb_link').addClass('rc_h_a');
													$(this).removeClass('rc_h_a');
													$('#rightcol_cat_more').attr('href','/catalog/rubrica.aspx?rId=0&cityId=7&countryId=0');
												});
	$('#rightcol_cat-spb_link').click(function () {
													$('#rightcol_cat-spb').show();
													$('#rightcol_cat-msk').hide();
													$('#rightcol_cat-msk_link').addClass('rc_h_a');
													$(this).removeClass('rc_h_a');
													$('#rightcol_cat_more').attr('href','/catalog/rubrica.aspx?rId=0&cityId=26&countryId=0');
												});
	$('#calendar_date_link').click(function () {$('#calendar').show();$('#calendar_period').hide();$('#calendar_period_link').addClass('rc_h_a');$(this).removeClass('rc_h_a');$("#filter_button_go2cat").removeAttr("disabled");});
	$('#calendar_period_link').click(function () {$('#calendar_period').show();$('#calendar').hide();$('#calendar_date_link').addClass('rc_h_a');$(this).removeClass('rc_h_a');});
	
	var showText="<span>Открыть фильтр</span>";
	var hideText="<span>Закрыть фильтр</span>";
	$('#hc_left:not(:has("#catalog_search"))').before('<div class="open-button" id="hc_toggle"><a href="javascript:;" class="font-increment-menu">масштаб</a>&nbsp;|&nbsp;<a href="javascript:;" id="hc_toggle_close">' + showText + '</a></div>');
	$('#hc_toggle_close').toggle(
		  function () {$(this).html(hideText);},
		  function () {$(this).html(showText);
	});
	
/*	$(function () { 
  var $el = $('.bt_m_typelist'), 
      originalTop = $el.offset().top;  // store original top position
	  offsetMaterialsLeft = $el.parents('td').offset().left;
	  offsetMaterialsTop = $el.parents('td').offset().top;

  $(window).scroll(function(e){ 
    if ($(this).scrollTop() > originalTop ){ 
      $el.css({'position': 'fixed', 'top':'160px', 'left': offsetMaterialsLeft - 177 + "px"}); 
    } else { 
      $el.css({'position': 'absolute', 'left':'-141px', 'top': offsetMaterialsTop + 100 + "px"}); 
    } 
  }); 
});*/


	

	$('#hc_toggle_close').click(function () {
		$('#hc_filter').slideToggle();
		//$.ajaxSetup({async: false});
		//$.getScript("js/jq.ui.min.js");
		//$.getScript("js/jq.ui-init.js");
		//$.ajaxSetup({async: true});	
		//if (!location.hash) window.location += '#hc_filter';

	});
	
	
	/*function openHiddenDivsFromAnchor() {
    var hash = window.location.hash; // would be "#div1" or something
    if(hash != "") {
        var id = hash.substr(1); // get rid of #
        document.getElementById(id).style.display = 'block';
		location.href = '#' + id;
    }};
	openHiddenDivsFromAnchor();*/
	
	
	$(".jumpmenu").change(function() {
       		window.location.href = $(this).val();
    	});
	
	
	$(".origlink").each(function () {$(this).val(window.location.href);$(this).prev('a').attr('href',window.location.href);});
	$(".origlink").prev('a').click(function () {return false;});
	
	$('#lenta').append('<div id="lenta_wr"></div>');
	$('.categ_nh_news').append('<div class="categ_nh_news_wr"></div>');
	
		//Сделать прописной первую букву - аналог text-transform:sentence case
	/*$('#texthead h1 small,.categ_nh_catlink').each(function() {
		 var text = $(this).html();
		 var first = $('<em style="text-transform:capitalize;font-style:normal">'+text.charAt(2)+'</em>');
		 $(this).html(text.substring(3)).prepend(first);
	  });*/
	
	//Закрыть открытые элементы (юзабилити)
	$("#hc_filter").hide();
	if ($("#texthead h1:contains('Лаборатория прикладной лингвистики')").size()) {return this;} else {$("#structure-block").hide();};
	$("#rightcol_cat-spb").hide();
	$("#hc_ms_story").hide();
	$("#filter_buttons input").attr("disabled","disabled");
	$('tr.bt_materials').hide();
	$('ul.bt_m_typelist li ul').hide();
	$('.bt_m_tools a').addClass('bt_m_notactive');
	$('.bt_m_tools').hide();
	
	//Лента
	$('.hc_shownews').click(function () {
					$(this).next('div').slideToggle();
					$(this).css('margin-bottom','0');
					$(this).parent().next().css('padding-top','.5em');
	});
	$('#ls_outer_open').click(function () {$('.ls_outer').slideUp();});
	
	$('#lenta dt a').click(function () {
		$('.ls_outer').slideDown();	
		$('#structure-block').slideUp();
	});
	
	$('#pages input').keyup(function(e) {
if(e.which==13) return false;
c = $(this).val().replace( /[A-Za-z\s]/g ,'');
$(this).val(c);
})
	
	var showArrow="Структура раздела <span>&darr;</span>";
	var hideArrow="Структура раздела <span>&uarr;</span>";
	$('#structure-block_link').toggle(
		  function () {$(this).html(hideArrow);},
		  function () {$(this).html(showArrow);
	});
	$('#structure-block_link').click(function () { 
		$('#structure-block').slideToggle();
		$('.ls_outer').slideUp(); 
	});

	
										

														//"Безопасный" код только для конкретной страницы  (одна новость)
	if ($(".sourcelink").size()) {
var domain = $('.sourcelink').attr('href');
$('.sourcelink_domain').attr('href', domain.replace(/(http\:\/\/(www\.)?([a-zA-Z0-9\-]+\.){0,1}[a-zA-Z0-9\-]+\.[a-zA-Z0-9\-]{2,4})(.*)/, "$1"));
}




														//все с новостями
if ($("#texthead").size()) {
    if ($('#texthead h1 small').text().length > 22) {
        $('#texthead h1 small').css('font-size', '.45em');
    }
}

if ($("#texthead h1 small:contains(', ')").size()) {
    if ($("#texthead h1 small:contains(' за ')").size()) {
        var sevDataEl = $("#texthead h1 small");
        var sevDataArr = sevDataEl.html().split(' за ');
        var sevData = sevDataArr[1];
        var sevCat = $("#texthead h1 small");
        $(sevCat).html(sevDataArr[0]);
        var sevCatArr = sevCat.html().split(', ');
        $(sevCat).html('');
        $(sevCatArr).each(function (i) {
            i = i + 1;
            $(sevCat).append("<option>" + i + ". " + this + "</option>");
            // value='#cat" + i + "'
        });
        var sevSelect = document.createElement("select");
        //sevSelect.className = "jumpmenu";
        $(sevCat).wrapInner(sevSelect);
		var sevCatLength = $(sevCat).find('option:first').html().length * 12;//13 пикселей ширина одной буквы
		$(sevCat).find('select').css('width',sevCatLength + 'px');
        $(sevCat).append(' за ' + sevData);
    }
    else if ($("#texthead h1 small:contains(' с ')").size()) {
        var sevDataEl = $("#texthead h1 small");
        var sevDataArr = sevDataEl.html().split(' с ');
        var sevData = sevDataArr[1];
        var sevCat = $("#texthead h1 small");
        $(sevCat).html(sevDataArr[0]);
        var sevCatArr = sevCat.html().split(', ');
        $(sevCat).html('');
        $(sevCatArr).each(function (i) {
            i = i + 1;
            $(sevCat).append("<option>" + i + ". " + this + "</option>");
        });
        var sevSelect = document.createElement("select");
        $(sevCat).wrapInner(sevSelect);
		var sevCatLength = $(sevCat).find('option:first').html().length * 12;//13 пикселей ширина одной буквы
		$(sevCat).find('select').css('width',sevCatLength + 'px');
        $(sevCat).append(' с ' + sevData);
    }
    else {
        var sevCat = $("#texthead h1 small");
        var sevCatArr = sevCat.html().split(', ');
        $(sevCat).html('');
        $(sevCatArr).each(function (i) {
            i = i + 1;
            $(sevCat).append("<option>" + i + ". " + this + "</option>");
        });
        var sevSelect = document.createElement("select");
        $(sevCat).wrapInner(sevSelect);
		var sevCatLength = $(sevCat).find('option:first').html().length * 12;//13 пикселей ширина одной буквы
		$(sevCat).find('select').css('width',sevCatLength + 'px');
    }
}
	//==========================================Фильтр================================
	
	
		var filterInitialText = 'Выберите нужные параметры запроса.';
		var temAQuant = 'span#fs_tem a';
		
		
		//Иконки удаления параметров запроса из панели статуса
		
				//Для тем (все параметры кроме последнего)
		$('span#fs_tem .hcc-close-sm').live('click', function () {
		  $(this).prev('a').andSelf().next('em').remove().andSelf().remove();
		  $('#filter_status:not(:contains(", "))').find('i').html(' в категории');
		  $('#filter_status:not(:has("a"))').html(filterInitialText).andSelf().prev().find('#hc_ms_tem option').attr('selected', false);
 
		});
		
				//Для тем (последний по порядку параметр)
		$('span#fs_tem .hcc-close-sm:last').live('click', function () {
		$('#filter_status em:last').remove();
		$('span#fs_tem:not(:contains(", "))').parent('#filter_status').find('i').html(' в категории ');
		if ($(temAQuant).size() < 2) {$('#filter_status').find('i').remove();}
	
		});
				
				//Для гео
		$('span#fs_geo .hcc-close-sm').live('click', function () {
		  $(this).prev('a').andSelf().remove();
		  $('span#fs_geo').html('');
		  $('#filter_status:not(:has("a"))').html(filterInitialText);
		  $('#form_map option:eq(0)').attr('selected', true);
		  if ($(temAQuant).size() < 2) {$('#filter_status').prev().find('#hc_ms_tem option').attr('selected', false);}
		  $('#map-img').attr('src', 'img/mappa.gif');
		});
		
		
		//Категории
			
		$("#hc_ms_tem").change(function () {
				$('#filter_status:not(:has("span"))').html('Ваш запрос: Новости<i> в категории</i> <span id="fs_tem"></span> <span id="fs_geo"></span>');
				$('span#fs_tem:has("a.hcc-close-sm ~ a.hcc-close-sm")').before('<i> в категории</i>');
				$("#hc_ms_tem option").each(function () {
								var temOptionValue = $(this).text();
								if ($(this).attr('title') == '') {$(this).attr("title",temOptionValue);}
				});
				var str = "";
				$("#hc_ms_tem option:selected").each(function () {
								var selTemOption = $(this).attr('title');
								str += "<a href='javascript:;'>&quot;" + selTemOption + "&quot;</a><a href='javascript:;' class='hcc-close-sm' title='удалить параметр запроса'></a><em>, </em>";
								
								
								//адреса на кнопке "отобрать"
								$("#filter_button_go2cat:not('#filter_button_go2cat[onclick]')").attr("onclick","location.href='http://www.forensicsciences.ru/new/newscategory.aspx?subj=" + selTemOption + "';");
								if ($("#filter_button_go2cat[onclick]").size()) {
								var onclickAttr = $(this).attr('onclick');
								 $('#filter_button_go2cat').attr("onclick","" + onclickAttr + "&subj=" + selTemOption + "';");
								}
								else {$('#filter_button_go2cat').attr("onclick","location.href='http://www.forensicsciences.ru/new/newscategory.aspx?subj=" + selTemOption + "';");}
								
								
								
								});
				$("#filter_status span#fs_tem").html(str);
				$("#filter_status span#fs_tem em:last").remove();
				$('#filter_status:not(:has("a"))').html(filterInitialText);
				$('#filter_status:not(:has("i"))').find('span#fs_tem').before('<i>в категории </i>');
				$('#filter_status:contains(", ")').find('i').html(' в категориях ');
				$('#filter_status:not(:contains(", "))').find('i').html(' в категории ');
				$("#filter_status span#fs_tem a span").css('text-transform','lowercase');
				if ($(".ui-state-active:not('.ui-state-highlight')").size()) {$("#filter_button_go2cat").attr("disabled","disabled");} else {$("#filter_button_go2cat").removeAttr("disabled");}; //Проверка на существование отмеченного пункта в календаре
				$("#filter_button_add").removeAttr("disabled");
				if ($('#filter_status').html() == filterInitialText) {$("#filter_buttons input").attr("disabled","disabled");}
		})
		.trigger('change');
		
		//Гео
			
		$('#form_map option:eq(0)').attr('selected', true);	
		$("#form_map option").each(
		function() {
			var okr = $(this).attr('id');
			var okrVal = $(this).val();
			okrVal = okrVal.replace(/(ый|ий) федеральный округ/ig, "ого федерального округа").replace(/Москва/ig, "Москвы").replace(/Санкт-Петербург/ig, "Санкт-Петербурга");
			if ($('#filter_status').html() == filterInitialText) {$("#filter_buttons input").attr("disabled","disabled");}
			$(this).not("#form_map option:eq(0)").bind("click",
			function() {

				$('#map-img').attr('src', 'img/' + okr + '.gif');
				if ($('#filter_status').html() == filterInitialText) {
				$('#filter_status').html('Ваш запрос: Новости <span id="fs_tem"></span> <span id="fs_geo">из <a href="javascript:;">Санкт-Петербурга</a><a href="javascript:;" class="hcc-close-sm" title="удалить параметр запроса"></a></span>');
				}
				else {$('#filter_status span#fs_geo').html(' из <a href="javascript:;">Санкт-Петербурга</a><a href="javascript:;" class="hcc-close-sm" title="удалить параметр запроса"></a></span>');};
				$('#filter_status span#fs_geo>a:first-child').text(okrVal);
				$("#filter_button_go2cat").removeAttr("disabled");
				$("#filter_button_add").removeAttr("disabled");
			});
			
			
			$("#form_map option:eq(0)").bind("click", function() {
				$('span#fs_geo').html('');
				$('#map-img').attr('src','img/mappa.gif');
				$('#filter_status:not(:has("a"))').html(filterInitialText);
			});
			
		});
			
			
						   
	
		
		
  		//=======================================================ЭКСТРЕМИЗМ================================
		
		
		
		$(".bt_m_text").live('dblclick', function(x) {
this._toggle;
  if ( $(this).height() > 500 ) {
  $(this).css({'overflow-y':'auto','height':'450px'});
  $.scrollTo(this, 450, {offset:-23});
   this._toggle = false;
  } else {
    $(this).css({'overflow-y':'visible','height':'100%'});
    
    
    this._toggle = true;
  }
  x.preventDefault();
  return false; 

  }); 
		
		$(".bt_m_typelist li ul").live('dblclick', function(x) {
		
		this._toggle;
  if ( $(this).height() > 500 ) {
	  $(this).css({'overflow-y':'auto','height':'371px'});
	$(this).parents('.bt_m_typelist').css({'height':'391px'});
	//$(this).parents('.bt_m_typelist ul').css({'padding-right':'12px'});
    $.scrollTo(this, 450, {offset:-23});
   
   this._toggle = false;
  } else {
   
    $(this).css({'overflow-y':'visible','height':'auto'});
	var linklistHeightMax = $(this).height();
   $(this).parents('.bt_m_typelist').css({'height':linklistHeightMax+'px'});
    this._toggle = true;
  }
  x.preventDefault();
  return false; 
  }); 
	


	$(".bt_m_story:not(:contains('Пока истории нет'))").live('dblclick', function(x) {
this._toggle;
  if ( $(this).height() > 400 ) {
  $(this).css({'overflow-y':'auto','max-height':'350px'});
  //$.scrollTo(this, 450, {offset:-23});
   this._toggle = false;
  } else {
    $(this).css({'overflow-y':'visible','max-height':'100%'});
    
    
    this._toggle = true;
  }
  x.preventDefault();
  return false; 

  });
  
  
	
	var initialText = 'Выберите ссылку в меню слева:';
	function resetFrame() {$('.bt_m_frame').remove();
						   $('.bt_m_wrapper').prepend('<div class="bt_m_frame"><span class="choose">' + initialText + '</span></div>').find('.choose').text(initialText);
						   };
	//Найти фамилии с инициалами и выделить жирным
		$(".bt_m_about div").each(function () {
			$(this).html($(this).html().replace(/((([А-Я][а-я]+)\s)?[А-Я]\.(\s)?[А-Я]\.(\s|,)(([А-Я][а-я]+)(ев|ов|ин|ева|ова|ина|ий|ого|ая|ой|ич|ича|аж|нко|юк|юка|ым))?)/g,'<em rel="person">$1</em>'));
		});
		
		$('.bt_m_ab_comment').click(function() {
		
		$(this).parents('.bt_materials').find('.bt_m_comment').show();
		$(this).parents('h4').find('a').removeClass('bt_m_ab_current');
		$(this).parents('.bt_materials').find('.bt_m_story').hide();
		$(this).addClass('bt_m_ab_current');
		
		});
		
		$('.bt_m_ab_story').click(function() {
		
		$(this).parents('.bt_materials').find('.bt_m_story').show();
		$(this).parents('h4').find('a').removeClass('bt_m_ab_current');
		$(this).parents('.bt_materials').find('.bt_m_comment').hide();
		$(this).addClass('bt_m_ab_current');
		
		});
		
	//$('.bt_m_story:not(:contains("Пока истории нет"))').attr('title','Щелкните дважды для того, чтобы раскрыть комментарий целиком');
				
	
	
		$('.bt_m_t_print a').click(function() {
		if ($(".bt_m_frame iframe").size()) {
						var iframeDoc = $('.bt_m_frame iframe').contents();
						$(iframeDoc).find("body").attr('id','printArea');
						$(iframeDoc).find("style").prepend('body');
						//$(iframeDoc).find("link").prepend('body');
						$(iframeDoc).find('#printArea').printArea();
			
		}
		else {
			$('.bt_m_frame').wrapInner('<div id="printArea"></div>');
			$('.bt_m_frame').find('#printArea').printArea();
						   }
			});
		
	
	//обычный курсор у тех строк в таблице, у которых не материалов
	$('#bigtable tr').next().next('tr:not(".bt_materials")').prev('tr:not(".bt_materials")').css({'cursor':'default'}); 
	$('#bigtable tr:last-child:not(".bt_materials")').css({'cursor':'default'});
	
	
	
	
    $('.bt_materials').prev().click(function() { 		    //this - .bt_ma_open!!!
			$(this).siblings('tr.bt_materials').hide();
			$(this).addClass('bt_ma_open').next('tr.bt_materials').toggle();
			$('.bt_m_current').removeClass('bt_m_current');
			$('.bt_m_active').removeClass('bt_m_active');
			$('.bt_m_typelist>li ul').hide();
			$(this).siblings().removeClass('bt_ma_open');
			$(this).siblings('tr:not(".bt_materials")').find('td').css({'border-left':'none'});
			$(this).siblings('tr:not(".bt_materials")').find('td').css({'border-right':'none'});
			$(this).find('td:first-child').css({'border-left':'1px solid #B2B4B6'});
			$(this).find('td:last-child').css({'border-right':'1px solid #B2B4B6'});
			$(this).next('tr.bt_materials').find('td').css({'border-left':'1px solid #B2B4B6','border-right':'1px solid #B2B4B6'});
			$(this).next('tr.bt_materials').find('.bt_m_typelist>li:first-child>a').addClass('bt_m_active');
			$(this).next('tr.bt_materials').find('.bt_m_typelist>li:first-child ul').show();
			var linklistHeight = $(this).next('tr.bt_materials').find('.bt_m_typelist>li:first-child ul').height();
			$(this).next('tr.bt_materials').find('.bt_m_typelist').css('height',linklistHeight+40+'px');
			$('.bt_m_tools').hide();
			$(this).find('.bt_close').show();
			
			//$('.bt_m_tools li').hide();
			//$(this).next('tr.bt_materials:has(".bt_m_text_link")').find('.bt_m_t_link,.bt_m_t_zoom,.bt_m_t_print').show();
			//$(this).next('tr.bt_materials:has(".bt_m_iframe_link")').find('.bt_m_t_fs,.bt_m_t_link,.bt_m_t_print').show();
			$('.bt_m_tools a').addClass('bt_m_notactive');
			resetFrame();
			$('.bt_m_frame_close').hide();
			$.scrollTo('.bt_ma_open', 700, {offset:-23});
			//var offsetBTMaterialsTop = $(this).find('td').offset().top;
			//alert(offsetBTMaterialsTop);
			//$(this).next('tr.bt_materials').find('.bt_m_typelist').css({'top':offsetBTMaterialsTop + 50 + 'px'});
			});
			
			$('.bt_close').live('click',function() {
			$(this).parents('tr').removeClass('bt_ma_open').next('.bt_materials').hide();
			$(this).hide();
			$(this).parents('tr').find('td:first-child').css({'border-left':'none'});
			$(this).parents('tr').find('td:last-child').css({'border-right':'none'});
			
			});
			
			

	$('.bt_m_video_link li a[href*="audio"]').append(' (аудио)').after('<img src="./img/clearbits_music.gif">');
	$('.bt_m_video_link li a[href*="video"]').append(' (видео)').after('<img src="./img/clearbits_videocamera.gif">');
	$('.bt_m_video_link li a[href*="foto"]').append(' (фото)').after('<img src="./img/clearbits_camera.gif">');
	//=====================================Меню и подменю материалов========================================
	$('.bt_m_typelist>li>a').wrapInner('<span />');
	$('.bt_m_typelist>li>a').click(function() {
				$('.bt_m_typelist').find('ul').hide();
				$('.bt_m_active').removeClass('bt_m_active');
				$(this).next('ul').find('.bt_m_current').removeClass('bt_m_current');
				$(this).addClass('bt_m_active').next().toggle();
				$('.autoselect').hide();
				var linklistHeight = $(this).next('ul').height();
				$(this).parents('.bt_m_typelist').css('height',linklistHeight+40+'px');
				resetFrame();
	});		
	
	$('.bt_m_typelist>li li a').click(function() {
			$(this).parents('.bt_m_typelist').find('a').removeClass('bt_m_current');
			$(this).addClass('bt_m_current');
	});		
											 
											 
	//====================Нажатие на кнопки меню типов медиа========================
	
	
	$('.bt_m_text_link>a').click(function() {								//Текст
			//$('.bt_m_tools li').hide();
			//$('.bt_m_tools a').addClass('bt_m_notactive');
			//$('.bt_m_t_link,.bt_m_t_zoom,.bt_m_t_print').show();
			$('.bt_m_tools').slideUp(200);
	});	
	
	
	$('.bt_m_doc_link>a').click(function() {								//Документы
			//$('.bt_m_tools a').addClass('bt_m_notactive');
			$('.bt_m_tools').slideUp(200);
			$(".bt_m_frame_close").remove();								
	});
	
	
	$('.bt_m_foto_link>a').click(function() {								//Фото
		//$('.bt_m_tools li').hide();
		//$('.bt_m_tools a').removeClass('bt_m_notactive');
		$('.bt_m_frame').addClass('bt_m_foto_fr').load('ajax/slideshow.html');	
		//$('.bt_m_tools').slideDown(200);
		$(".bt_m_frame_close").remove();
	});
	
	
	$('.bt_m_video_link>a').click(function() {								//Мультимедиа
			//$('.bt_m_tools a').addClass('bt_m_notactive');
			$('.bt_m_tools').slideUp(200);
			$(".bt_m_frame_close").remove();
	});
	
	
	$('.bt_m_iframe_link>a').click(function() {								//Интернет
			//$('.bt_m_tools li').hide();
			//$('.bt_m_tools a').addClass('bt_m_notactive');
			//$('.bt_m_t_fs,.bt_m_t_link,.bt_m_t_print').show();
			$('.bt_m_tools').slideUp(200);
			$(".bt_m_frame_close").remove();
	});	
	

	
	
	//========================Нажатие на ссылки подменю материалов========================
	
	
	$('.bt_m_text_link li a').click(function() {                //Текст
			resetFrame();
			$('.bt_m_frame').addClass('bt_m_text');
			$('.bt_m_tools a').removeClass('bt_m_notactive');
			$('.bt_m_t_fs').hide();
			$('.bt_m_t_zoom').show();
			$('.bt_m_tools').slideDown(200);
			var toLoadText = $(this).attr('href');
			$('.bt_m_frame').load(toLoadText);
			$('.autoselect').hide();
			$('.bt_m_wrapper').append('<a href="javascript:;" class="bt_m_frame_close" title="Закрыть"><span>Закрыть</span></a>');
			return false;	
			
	});
	
	
	
	$('.bt_m_frame_close').live('click',function() {								//Закрытие блока с материалами
			resetFrame();
			$(".bt_m_frame_close").remove();
			$('.bt_m_typelist a').removeClass('bt_m_current');
	});
	
	
	
	$('.bt_m_doc_link li a').click(function() {					//Документы
			$('.bt_m_tools').slideUp(200);								
			$('.bt_m_tools a').removeClass('bt_m_notactive');
			$('.bt_m_frame').removeClass('bt_m_video,bt_m_foto_fr').addClass('bt_m_doc');
			$('.bt_m_typelist a').removeClass('bt_m_current');
			$(this).addClass('bt_m_current');
			var toLoadDoc = $(this).attr('href');
			$('.bt_m_frame').load(toLoadDoc);
			return false;
			
	});
	
	
	/*$('.bt_m_foto_link li a').click(function() {                //Фото
			
		});*/


	$('.bt_m_video_link li a').click(function() {				  //Мультимедиа
			$('.bt_m_tools').slideUp(200);								
			$('.bt_m_frame').removeClass('bt_m_text');
			$('.bt_m_tools a').removeClass('bt_m_notactive');
			$('.bt_m_frame').removeClass('bt_m_foto_fr').addClass('bt_m_video');
			var toLoadVideo = $(this).attr('href');
			$('.bt_m_frame').load(toLoadVideo);
			return false;
			
	});
	
	
	$('.bt_m_iframe_link li a').click(function() {				//Интернет
			$('.bt_m_tools').show();
			$('.bt_m_tools a').removeClass('bt_m_notactive');
			$('.bt_m_t_fs').show();
			$('.bt_m_t_zoom').hide();
			$('.bt_m_frame').addClass('bt_m_iframe');
			$('.autoselect').hide();
			var toLoadIframe = $(this).attr('href');
			$('.bt_m_frame').html('<iframe></iframe>');
    		$('.bt_m_frame iframe').attr('src',toLoadIframe);
		    return false;
	});
	
	
	
	
	
	//========================Ссылки в комментариях========================
	
	$('.bt_m_about div a[rel="file"]').attr('target','_blank').css('font-weight','bold').attr('title','ссылка откроется в новом окне').append("<img src='./img/file.gif'>");
	$('.bt_m_about div a[rel="external"]').attr('target','_blank').css('font-weight','bold').attr('title','ссылка откроется в новом окне').append("<img src='./img/ext.gif'>");
	
	$('.bt_m_about div a[rel="text"]').click(function() {                //Текст
			resetFrame();
			$('.bt_m_typelist').find('a.bt_m_current').removeClass('bt_m_current');
			$('.bt_m_tools li').hide();
			$('.bt_m_tools a').addClass('bt_m_notactive');
			$('.bt_m_t_zoom,.bt_m_t_print').show();
			$('.bt_m_tools').slideDown(200);
			$('.autoselect').hide();
			
			$('.bt_m_frame').addClass('bt_m_text');
			$('.bt_m_t_zoom,.bt_m_t_print').show();
			$('.bt_m_tools a').removeClass('bt_m_notactive');						
			
			var toLoadText = $(this).attr('href');
			$('.bt_m_frame').load(toLoadText);
			return false;
	});
	
	$('.bt_m_about div a[rel="document"]').click(function() {                //Документы
			$('.bt_m_tools').slideUp(200);								
			$('.bt_m_tools a').removeClass('bt_m_notactive');
			$('.bt_m_frame').removeClass('bt_m_video,bt_m_foto_fr').addClass('bt_m_doc');
			$('.bt_m_typelist a').removeClass('bt_m_current');
			$(this).addClass('bt_m_current');
			var toLoadDoc = $(this).attr('href');
			$('.bt_m_frame').load(toLoadDoc);
			return false;
	});
	
	$('.bt_m_about div a[rel="multimedia"]').click(function() {                //Мультимедиа
			$('.bt_m_tools').slideUp(200);								
			$('.bt_m_tools a').removeClass('bt_m_notactive');
			$('.bt_m_tools').slideUp(200);
			$('.bt_m_frame').removeClass('bt_m_text');
			$('.bt_m_frame').removeClass('bt_m_foto_fr').addClass('bt_m_video');
			var toLoadVideo = $(this).attr('href');
			$('.bt_m_frame').load(toLoadVideo);
			return false;
	});
	
	$('.bt_m_about div a[rel="web"]').click(function() {				//Интернет
			$('.bt_m_tools').show();
			$('.bt_m_tools a').removeClass('bt_m_notactive');
			$('.bt_m_t_fs').show();
			$('.bt_m_t_zoom').hide();
			$('.bt_m_frame').addClass('bt_m_iframe');
			$('.autoselect').hide();
			var toLoadIframe = $(this).attr('href');
			$('.bt_m_frame').html('<iframe></iframe>');
    		$('.bt_m_frame iframe').attr('src',toLoadIframe);
		    return false;
	});
	
	
	//Инструменты
	$('.bt_m_t_link>a').live('click', function() {
										
											   	var curListItem = $(document).find('.bt_m_current');
											   		if ($(curListItem).attr('title')) {
											   			curListItem = curListItem.attr('title');
											   			$(this).next().toggle().attr('value',curListItem);
															} else {
														}
											   			curListItem = curListItem.attr('href');
											   			$(this).next().toggle().attr('value','http://www.forensicsciences.ru/' + curListItem);
											   	
											   /*var curListItem = $(this).parents('.bt_materials').find('.bt_m_current');
											   		if ($(curListItem).attr('title')) {
											   			curListItem = curListItem.attr('title');
											   			$(this).next().toggle().attr('value',curListItem);
											   			if ($(this).parent('bt_m_tools').find('.origlinkopen').size()) {
											   			$(this).parent().append('<a class="origlinkopen" href="'+curListItem+'" target="_blank">Ссылка на источник</a>');} 
											   			else {
											   			$(this).next('.origlinkopen').toggle();}
															} else {
														}
											   			curListItem = curListItem.attr('href');
											   			$(this).next().toggle().attr('value','http://www.forensicsciences.ru/' + curListItem);*/
											   
											   });
											   
	
		

	
		//Фуллскрин
	$('.bt_m_t_fs>a').click(function() { 			
						$('#overlay').css({'background':'black'}).fadeIn();
						$('.bt_m_iframe').clone().addClass('bt_m_iframe_fs').prependTo('body');
						var scrollPos = $(window).scrollTop() + 50;	
						$('.bt_m_iframe_fs').css('top',scrollPos+'px');
						var toLoadIframe = $(this).parents('.bt_m_wrapper').find('iframe').attr('src');
						var sourceTitle = $(this).parents('.bt_materials').find('.bt_m_typelist:has("a.bt_m_active")').find('.bt_m_current').attr('title');
						var sourceTitleLink = '';
						if (sourceTitle == '') {sourceTitleLink = ''}
						else {sourceTitleLink = '<a href="'+sourceTitle+'" target="_blank" title="Открыть в новом окне">Ссылка на источник</a><img src="./img/ext_gray.gif"> | '};
						$('.bt_m_iframe_fs').append('<div id="bt_m_i_fs_info"><a id="bt_m_i_fs_info_close" href="javascript:;">Закрыть окно</a>'+sourceTitleLink+'<label for="fs_thislink"><a href="' + toLoadIframe + '" target="_blank" title="Открыть в новом окне">Ссылка на эту страницу</a><img src="./img/ext_gray.gif"> :</label><input id="fs_thislink" name="origlink" class="autoselect" value="http://www.forensicsciences.ru/new/' + toLoadIframe + '" type="text" onfocus="$(this).select();"></div>');
		});
	
	
	
	
	
	
	
	//===========================================================КАТАЛОГ==========================================
	
	//$('.search_tema').val('');
	
		var showOnlyRusCities="Страна: <span>Россия</span> (выбрать все страны)";
		var showAllCities="Страны: <span>Все</span> (выбрать только Россию)&nbsp;";
	
	
	
	
	
	
	$('#search_loc_allcountries').toggle(
		  function () {
			  
					$('#search_loc_allcountries').html(showOnlyRusCities);
			  		$("#ctl00_ContentPlaceHolder1_allCities").hide();
			  		$("#ctl00_ContentPlaceHolder1_rusCities").show();
			  
			  },
		  function () {
			  
				  $('#search_loc_allcountries').html(showAllCities);
				  $("#ctl00_ContentPlaceHolder1_allCities").show();
				  $("#ctl00_ContentPlaceHolder1_rusCities").hide();
			 
	});
	
	/*var catTypeOpt = $('#search_type option');
	$(catTypeOpt).each(function() {
	 var catTypeOptVal = $(this).attr('value');
     $(this).val('/catalog/rubrica.aspx?rId=' + catTypeOptVal);
  });
	
	var catLocOpt = $('#search_loc option');
	$(catLocOpt).each(function() {
	 var catLocOptVal = $(this).attr('value');
     $(this).val('/catalog/rubrica.aspx?rId=0&cityId=' + catLocOptVal + '&countryId=0');
  });*/
	
	
	
	
	
	
	//Инструменты списка категорий/новостей на главной

	
	var clist_h4 = '#hc_cols li h4';
	

	$(clist_h4).each(function(/*i*/) {
    /* var text = $(this).html();
     var first = $('<em style="text-transform:capitalize;font-style:normal">'+text.charAt(0)+'</em>');
     $(this).html(text.substring(1)).prepend(first);*/
	 
	 /*i = i++;
	 $(this).attr("id","ctl0" + i + "_lbDelCat");
	 $(this).prepend('<span><a href="javascript:;" class="hcc-text hcc-back">нет</a> <a href="javascript:;" onclick=__doPostBack("ctl0' + i + '$lbDelCat",""); class="hcc-text hcc-delete">да</a>Удалить эту категорию?</span> <a href="javascript:;" class="hcc-close"></a><a href="javascript:;" class="hcc-hide"></a>');*/
   });

	/*var clist_buttons = '<span style="padding-right:50px"><a href="javascript:;" class="hcc-text hcc-back">нет</a> <a href="javascript:;" class="hcc-text hcc-delete">да</a>Удалить эту категорию?</span> <a href="javascript:;" class="hcc-close"></a><a href="javascript:;" class="hcc-hide"></a>';
	$(clist_h4).prepend(clist_buttons);*/
	
	/*$(clist_h4).click(function() {
			$(this).next().slideToggle();
			$(this).find('a.hcc-hide').toggleClass("hcc-hide-closed");
	});*/
	
	$(clist_h4 + ' a.hcc-close').click(function() {	
					$(this).parents('h4').addClass('hcc_h4-categdelete').find('span').show();
					return false;
																					   
	});
	
	$(clist_h4 + ' a.hcc-back').click(function() {	
					$(this).parents('h4').removeClass('hcc_h4-categdelete').find('span').hide();
					return false;																	   
	});
	
	/*$(clist_h4 + ' a.hcc-delete').click(function() {	
					$(this).parents('li').fadeOut("slow", function() {$(this).parents('li').remove();});
					return false;																	   
	});*/
	
	$(clist_h4 + ' a.hcc-hide').click(function() {
			$(this).toggleClass("hcc-hide-closed").parent('h4').next().slideToggle();
			return false;
	});

	//Очищение текстовых полей
	var inputs = $('input[type="text"], input[type="password"]').not('.autoselect,#calendar_period input');
	inputs.css('color', '#969696');
	inputs.click(
	function() {
		if (this.value == this.defaultValue) {
			this.value = '';
			
		}
	});
	inputs.focus(
	function() {
		if (this.value == this.defaultValue) {
			this.value = '';
			this.css('color', 'black');
			
		}
	});

	inputs.blur(
	function() {
		if (this.value == '') {
			this.value = this.defaultValue;
		}
	});
	
	//Перевод текста ссылки в текстовое поле	
	$(".input-example a").click(function () {
	  var text = $(this).text();
	  $(this).parent('div').next('input[type="text"]').val(text);
	});

	//Закрытие диалога при щелке по оверлею
	$('.auth_link a').click(function() { 
					var authSpan = $(this).parent('.auth_link');
					$('#overlay').fadeIn();
					$('#auth-form').fadeIn().appendTo(authSpan);
	});
	$('#overlay').click(function() {
								 $("#overlay").fadeOut(160);
								 $("#auth-form").fadeOut(290);
								 $(".bt_m_iframe_fs").hide();
								 });
	
	$('#bt_m_i_fs_info a').live('click', function() {
								 $("#overlay").fadeOut();
								 $(".bt_m_iframe_fs").hide();
								 });
	
	$('#auth_close').click(function() {
								 $("#overlay").fadeOut(160);
								 $("#auth-form").fadeOut(290);
								 });
	$('#btnShutDown').click(function() {    				//ASP-specific
								 $("#overlay").fadeOut(160);
								 $("#LoginView1").fadeOut(290);
								 });




	
	
	$(document).keyup(function(e) {
		if ((e == null ? event.keyCode: e.which) == 37) $('.lenta_summary').trigger('prev');
	});
	$(document).keyup(function(e) {
		if ((e == null ? event.keyCode: e.which) == 39) $('.lenta_summary').trigger('next');
	});
	$(document).keyup(function(e) {
		if ((e == null ? event.keyCode: e.which) == 40) $('.lenta_summary').trigger('goto', [1]);
	});
	$(document).keyup(function(e) {
		if ((e == null ? event.keyCode: e.which) == 38) $('.ls_outer').slideUp();
	});
	// Нажмите + для увеличения текста на экране
	//$(document).keyup(function(e) {
	//   if ((e == null ? event.keyCode: e.which) == 107) $('.lenta_summary').trigger('prev');
	//});
	
	
	function preloader(){
			if ($("#hidetable").size()) {
			if (document.getElementById("hidetable").style.display == "none") {
                document.getElementById("hidetable").style.display = "block";
                document.getElementById("bigtable").style.display = "none";
			}
			else {
				document.getElementById("bigtable").style.display = "table";
                document.getElementById("hidetable").style.display = "none";
				}
        }}

	
	$(document).ready(preloader);
	
});

jQuery.fn.fadeToggle = function(speed, easing, callback) {
	return this.animate({
		opacity: 'toggle'
	},
	speed, easing, callback);

};

jQuery(function($) {

	$('.lenta_summary').serialScroll({
		items: '.ls_news-item',
		prev: 'a#ls_rw',
		next: 'a#ls_fw',
		duration: 300,
		offset: -11,
		navigation: '#lenta dt',
		lock: true,
		cycle: true,

	});

	$('.bt_m_frame').serialScroll({
		items: 'li',
		axis: 'x',
		lazy: true,
		offset: -20,
		prev: '.bt_m_t_sl_rw a',
		next: '.bt_m_t_sl_fw a',
		duration: 1000,
		navigation: '.bt_m_foto_link li',
		cycle: true,
		jump: true,
		force: true,
	});

	

	// Toggle Single Portlet
	//$('#hc_cols h4').click(function() {
	//	$(this).next('ol').slideToggle();
	//$(this).css('border-bottom','1px solid black');
	//	return false;
	//}); 
	// Invert All Portlets
	$('a#all_invert').click(function() {
		$('ol').toggle();
		return false;
	}); // Expand All Portlets
	$('a#all_expand').click(function() {
		$('ol:hidden').show();
		return false;
	}); // Collapse All Portlets
	$('a#all_collapse').click(function() {
		$('ol:visible').hide();
		return false;
	}); // Open All Portlets
	$('a#all_open').click(function() {
		$('ol:hidden').show();
		$('a#all_open:visible').hide();
		$('a#all_close:hidden').show();
		return false;
	}); // Close All Portlets
	$('a#all_close').click(function() {
		$('ol:visible').hide();
		$('a#all_close:visible').hide();
		$('a#all_open:hidden').show();
		return false;
	});

	

});
