  $().ready(doOnLoad);
  var sliderTimeout = 9000;
  var sliderTimer = 0;
  var isMouseOver = false;
  var sliderCache = 0
  var accordionCache = 0
  
  
  function doOnLoad(){
      $('#header').find('.menu').children('li').bind({"mouseout": jsddm_timer, "mouseover": jsddm_open});      
      $("#addmenublock").find(".ico").click(toggleMenu); 
      var menuCookie = GetCookie("menu");
      if((!menuCookie &&($(window).width() > 1300)) || (menuCookie &&(menuCookie == "visible"))) {toggleMenu();};
      $("#addmenublock").find("li").hover(function(){$(this).find(".list").show()}).mouseleave(function(){$(this).find(".list").hide()}); 
  }
  
  function videoInit(){

      var el = $('#fancybox-inner a.flv-video');
      var p = flowplayer('fancybox-inner', "/player/flowplayer.swf", {
              clip: { url: el.attr('href') , autoPlay: true, autoBuffering: true, provider: 'pseudo' },
              plugins: { pseudo: { url: 'flowplayer.pseudostreaming.swf' } 
              }
          });
          p.play();
  }
  function innerInit(){      
      $("#links").has("a").css("display", "block");
      $("#sidebar").find(".feed:not(:has(.rss))").css("display", "none");
      var textContent = $('#text');      
      textContent.find("table.tbl").each(function(){$(this).find("tr:even").addClass("even")});             
      textContent.find('ul[rel="accordion"]').microAccordion({linkElm: 'a'});


      $('a[href^="http"]:not(.demo, .iframe, [href*="directum.ru"])').click(function () { window.open(this.href); return false; });         
      textContent.find('a[href$="png"], a[href$="JPG"], a[href$="gif"], a[href$="jpeg"], a[href$="jpg"]').fancybox({
        'autoScale' : true,'transitionIn' : 'elastic', 'transitionOut' : 'elastic', 'titlePosition'	:	'over'
	      ,'titlePosition' 		: 'inside',
	      'titleFormat'		: formatTitle        
      });

	  textContent.find('.iframe').each(function () {
	      var height = parseInt(this.getAttribute("popheight"));
	      var width = parseInt(this.getAttribute("popwidth"));
	      if ((height == null) || (height.length == 0)) height = 576;
	      if ((width == null) || (width.length == 0)) width = 1024;
	      $(this).fancybox({ 'width': width, 'height': height, 'autoScale': false, 'transitionIn': 'none', 'transitionOut': 'none', 'type': 'iframe' });
	  }); 
      
      textContent.find("a.demo").click(function() {
	          $.fancybox({'padding'		: 0, 'autoScale'		: false, 'transitionIn'	: 'none', 'transitionOut'	: 'none',
			          'title'			: this.title, 'width'		: 680, 'height'		: 495, 'href'			: this.href.replace(new RegExp(".htm", "i"), '_skin.swf'),
			          'type'			: 'swf', 'swf'			: { 'wmode'		: 'transparent', 'allowfullscreen'	: 'true'  } });
	          return false;
          });                 
          
      $("a.pop_demo").each(function() {
        var height = parseInt(this.getAttribute("popheight"));
        var width = parseInt(this.getAttribute("popwidth"));
        if((height == null) || (height.length == 0)) height = 576;
        if((width == null) || (width.length == 0)) width = 1024;
	      $(this).fancybox({'autoDimensions': false, 'width': width, 'height': height, 'titlePosition': 'inside', 'transitionIn': 'none', 'autoScale': false, 'transitionOut': 'none',  'onComplete' : function(){ videoInit();} });	      	      	     
      }); 
                    
          
      $.extend($.expr[":"], {"innerNC": function(elem, i, match, array) { return (elem.textContent || elem.innerText || "").toLowerCase() == match[3].toLowerCase()} });           
      breadcrumbsInit();      
           
  }

function formatTitle(title, currentArray, currentIndex, currentOpts) {
    var title = $("#fancybox-img").attr("alt"); 
    if(title.length > 0) title += "<br/>";
    return title + "<a target='_blank' href='" + $("#fancybox-img").attr("src") + "'>\u041E\u0442\u043A\u0440\u044B\u0442\u044C \u0432 \u043D\u043E\u0432\u043E\u043C \u043E\u043A\u043D\u0435</a>";
}

  function sliderInit(){
    $("#header .home").hide();
    sliderCache = $('#slider');
    accordionCache = $('#accordion');
    
    var sliderElements = accordionCache.children('li');
    $("#header div.menu, #slider").bind({"mouseover": function(){ sliderCancelTimer(); isMouseOver = true}, "mouseout": function(){isMouseOver = false; sliderTimerStart()}});      
    
    if(sliderElements.length > 0) sliderElements.click(showSlide).hover(hoverSlide, outSlide);
    sliderCache.find("#titles").children("li").bind({"mouseover": function(){accordionCache.children(".bg" + $(this).attr("rel")).mouseover()}, "click": function(){accordionCache.children(".bg" + $(this).attr("rel")).click()}});
    /*.hover(function(){accordionCache.children(".bg" + $(this).attr("rel")).mouseover()});*/
    sliderTimerStart();
  }
  
  function sliderTimerStart() { sliderCancelTimer();	if(!isMouseOver) sliderTimer = setTimeout(sliderRotation, sliderTimeout);}
  function sliderCancelTimer(){	if(sliderTimer){	window.clearTimeout(sliderTimer); sliderTimer = null;}}
  
  function setActive(itemName){if(itemName.length > 0 ) $('#header').find(".menu a:innerNC('" + itemName + "')").closest("li").addClass("online")}
  
  function sliderRotation(){
    var opnEl = accordionCache.find(".opn");
    var nextNum = 0;
    if(opnEl.length > 0) nextNum =  parseInt(opnEl.attr("rel")) - 1;
    if(!nextNum) nextNum = 4;
    accordionCache.children('li[rel="' + nextNum + '"]').click();
  }
  
  
  function breadcrumbsInit(){ 
    var breadcrumbs = $('#breadcrumbs').find('.breadcrumbs').children('li');
    if(breadcrumbs.length > 0){
      if(typeof(actPosition) != "undefined") setActive(actPosition);
      breadcrumbs.bind({"mouseout": slide_timer, "mouseover": jsddm_open});
    }
  }
  
  function printInit(){
    var content = $("#content");
    var href = ""
    content.find("table").each(function(){$(this).find("tr:even:not(:has(th))").addClass("even")});             
    content.find("a:not(:has(img))").each(function() { 
      href =  $(this).attr("href");
      if(href.indexOf("http://") == -1){ href.replace(new RegExp("^/", "i"),""); href = "http://directum.ru/" + href;}           
      $(this).append(" (" + href + ")"); 
    });
  }
  
  function toggleMenu(){
    var el = $("#addmenublock");    
    var position = "0px";
    if (el.css("margin-right") == "0px"){ position = "-150px"; $("#addmenublock").removeClass("opn"); SetCookie("menu","hidden");}
    else{$("#addmenublock").addClass("opn"); SetCookie("menu","visible");}
    $("#addmenublock").stop().animate({ 'margin-right': position }, 500);
  }
  
  function CrumbGo(link, el){
    var menuItem =          $('#header').find(".menu a:innerNC('" + link + "')");
    if(menuItem.size() > 0) $(el).attr("href", menuItem.attr("href"));
    else                    return false;
  }
  
  
/* Menu */
  var timeout     = 300;
  var closetimer  = 0;
  var ddmenuitem  = 0;
  var activeitem  = 0;
  
  document.onclick = jsddm_close;

  function jsddm_open(){	
    jsddm_canceltimer();
	  jsddm_close();
	  activeitem = $(this);	  
	  ddmenuitem = activeitem.find('div').eq(0).show();
	  activeitem.addClass("active");
  }
  
  function slide_close(){ if(ddmenuitem) ddmenuitem.slideUp(500) }
  function slide_timer(){ closetimer = window.setTimeout(slide_close, timeout)}
  function jsddm_close(){ if(ddmenuitem) ddmenuitem.hide(); if(activeitem) activeitem.removeClass("active"); }
  function jsddm_timer(){ closetimer = window.setTimeout(jsddm_close, timeout)}
  function jsddm_canceltimer(){	if(closetimer){	window.clearTimeout(closetimer); closetimer = null;}}



/* Slider */
   
    var animationSpeed = 600;
    var margings    =  Array(0, 805, 625, 445, 0);
    var margings2   =  Array(0, 565, 370, 185, 0);
    var titleMarg   =  Array(0, 850, 660, 485, 25);
    
    var titleMarg2   =  Array(0, 845, 410, 230, 25);   
    var titleHMarg   =  Array(0, 850, 660, 485, 25);
    
    
    if($.browser.msie){ 
      margings    =  Array(0, 785, 585, 430, 0);
      margings2   =  Array(0, 545, 350, 165, 0);
    }
    
    var moremargin   =  Array(0, 577, 403, 218, 24);
    var slides = 0
    
    
    function hoverSlide() {
        sliderCancelTimer();
        var $this = $(this);
        if ($this.hasClass("opn")) return;     
           
        //$('.heading.back', $this).css("background-color", "#EC912D");
        $('.heading.back', $this).css("background-color", "#EC912D");
        var num =  parseInt($this.attr("rel"));
        var opNum =  $('li.opn').attr("rel");
       
        var sib = new Array()
        var off = new Array()
        
        switch(num){
          case 1:
            sib.push(num);
            off.push(-50);
            sib.push(num + 1);
            off.push(-25);
            break;
          case 4:
            sib.push(num - 1);
            off.push(50);
            sib.push(num - 2);
            off.push(25);
            break;          
          default:
            sib.push(num);
            off.push(-25);
            sib.push(num - 1);
            off.push(25);
        };        
        
        for (key in sib){
          var elnum = sib[key];
          if(elnum >= opNum){
            if(elnum == opNum) sliderCache.find('.slide' + opNum).stop().animate({ 'margin-left': moremargin[opNum] +  off[key] + 'px' }, animationSpeed);
            accordionCache.children('li.bg' + elnum).stop().animate({ 'margin-left': margings2[elnum] + off[key]  + 'px' }, animationSpeed);
            sliderCache.find('#titles').children('.head' + elnum).stop().animate({ 'margin-left':  titleMarg2[elnum] + off[key]  + 'px' }, animationSpeed);
          }else{
            accordionCache.children('li.bg' + elnum).stop().animate({ 'margin-left': margings[elnum] + off[key]  + 'px' }, animationSpeed);
            sliderCache.find('#titles').children('.head' + elnum).stop().animate({ 'margin-left':  titleMarg[elnum] + off[key]  + 'px' }, animationSpeed);
          }
        }                               
    };
    
    
    function outSlide() {
      var $this = $(this);
      var num =  parseInt($this.attr("rel"));
      if ($this.hasClass("opn")){ sliderTimerStart(); return }              
      
      var isOpen = false;
      var curEl = 0;
        
        if(slides == 0) slides = accordionCache.children(':not(.bleft)');
        slides.each(function(){
          curEl = $(this);
          if(curEl.hasClass("opn")) isOpen = true;
          if(!isOpen){
            curEl.stop().animate({ 'margin-left': margings[curEl.attr("rel")] + 'px' }, animationSpeed);
            sliderCache.find('#titles').children('.head' + curEl.attr("rel")).stop().animate({"margin-left": titleMarg[curEl.attr("rel")] + "px"}, animationSpeed);
          }
          else{
            curEl.stop().animate({ 'margin-left': margings2[curEl.attr("rel")] + 'px' }, animationSpeed);
            sliderCache.find('#titles').children('.head' + curEl.attr("rel")).stop().animate({"margin-left" : titleMarg2[curEl.attr("rel")] + "px"}, animationSpeed);            
          }          
        });
        
        
        var opNum = $('li.opn').attr("rel");
        sliderCache.find('.slide' + opNum).stop().animate({ 'margin-left': moremargin[opNum] + 'px' }, animationSpeed);
        $('.heading.back', $this).css("background-color", "");
        sliderTimerStart();
    };
    
  function showSlide() {
      var $this = $(this);
      if ($this.hasClass("opn")) return;           
      sliderCancelTimer();     
      //$('#slider').find(":animated").stop();
      
      var num =  parseInt($this.attr("rel"));
      var openned = accordionCache.children(".opn");
      sliderCache.find('.slide' + openned.attr("rel")).stop().hide();      
      openned.find('.heading').css("background-color", "").stop().fadeIn();
      openned.removeClass('opn');      
      $this.addClass('opn');
                    
      
      
      var sibling1 = 0;
      var sibling2 = 0;
      var isOpen = false
      var curEl = 0;
      sliderCache.find('#titles').children('.head' + num).stop().hide();
      
      
      if(slides == 0) slides = accordionCache.children(':not(.bleft)');
      slides.each(function(){
        curEl = $(this);
        if(curEl.hasClass("opn")) isOpen = true;
        if(!isOpen){
          curEl.stop().animate({ 'margin-left': margings[curEl.attr("rel")] + 'px' }, animationSpeed);
          sliderCache.find('#titles').children('.head' + curEl.attr("rel")).stop().animate({"margin-left": titleMarg[curEl.attr("rel")]  + 'px'},animationSpeed);
        }
        else{
          curEl.stop().animate({ 'margin-left': margings2[curEl.attr("rel")] + 'px' }, animationSpeed);
          sliderCache.find('#titles').children('.head' + curEl.attr("rel")).stop().animate({"margin-left": titleMarg2[curEl.attr("rel")]  + 'px'},animationSpeed);
        }
        
      })
      
      $('.heading', $this).stop().fadeOut();
               
      sliderTimerStart();
      //$('#accordion > li:animated').queue("fx", function(){console.log("done")});
      $this.queue("fx", function(){
        sliderCache.find('.slide' + num).stop().show().css("margin-left", "");
        sliderCache.find('#titles').children('li:not(.head' + num + ')').show();    
        $this.dequeue();
      });
  };
  
  
  function hideSlide() {
    var $this = $(this);
    $('.heading', $this).css("background-color", "").stop(true,true).fadeIn();;    
    $this.removeClass('opn');
  }






  /* accordion */
  var acnum = 0;
(function ($) {
    $.fn.microAccordion = function (options) {
        var opts = $.extend({}, $.fn.microAccordion.defaults, options);
        return this.each(function () {
            var obj = $(this);
            var e = 0;
            var c = opts.cssClassClosed;
            var o = opts.cssClassOpen;
            var hc = opts.cssClassHoverClosed;
			var oc = opts.cssClassHoverOpen;
			var ln = opts.linkElm;
            var lid = "accrd" + acnum + "-";
            var opn = window.location.hash;
            if(opn.length > 0){ opn = opn.replace("#",""); opn = opn.replace("_","")}
            acnum ++;
            
        
        obj.children('li').each(function () { 
          $(this).attr('id', lid + e);
				  $(this).children('div').addClass(opts.cssClassContent);
				  
				  
          $(this).children(ln).addClass("itemHead").click(function () {
                    var a = $(this);                    
                    if (opts.openSingle) {
                        obj.children('li').each(function () {
                            if ($(this).attr('id') != a.parent().attr('id')) {
                                opts.closeFunction($(this).children('div'));
                                $(this).children(ln).removeClass(o).addClass(c);
                            }
                        });
                    }
                    opts.toggleFunction(a.siblings('div'));

                    if(a.parent().hasClass(c)){ 
                        a.parent().addClass(o).removeClass(c);
                        if(a.attr('id').length > 0){window.location.hash = "_" + a.attr('id');}
                    }else{ a.parent().addClass(c).removeClass(o);}
                    return false;
                }).each(function () {                    
                    (((e == opts.defaultOpen) && (opn.length == 0)) || (($(this).attr('id') == opn) && (opn.length != 0))) ? $(this).parent().addClass(o) : $(this).parent().addClass(c).find('div').css('display', 'none');
                }).attr('href', '#');
                e++;
            });
        });
    };
    
    $.fn.microAccordion.defaults = {
        linkElm: 'a',
        cssClassOpen: 'accrd-open',
        cssClassClosed: 'accrd-closed',
		cssClassHoverOpen: 'accrd-hover-open',
		cssClassHoverClosed: 'accrd-hover-closed',
		cssClassContent: 'accrd-content',
        openSingle: false,
        toggleFunction: function (obj) {
            obj.slideToggle();
        },
        closeFunction: function (obj) {
            obj.slideUp();
        },
        defaultOpen: 0
    };
})(jQuery);
  
  
  
  /* Search */  
  function FillValue(ASender, AValue) { if (ASender.value == "") ASender.value = AValue }
  function ClearValue(ASender, AValue){ if (ASender.value == AValue) ASender.value = "" }








/* Partners map */
function LoadMap()
{
  if(GBrowserIsCompatible())
  {
    map = new GMap2(document.getElementById("MapPanel"));
    map.addControl(new GLargeMapControl());
    map.addControl(new GOverviewMapControl());
    map.addControl(new GMapTypeControl());
    map.setCenter(new GLatLng(66.416667, 94.250000), 2);
  }  
}

function CreateIcon(AMarker, AMarkerShadow)
{
  var ico = new GIcon();
  ico.iconSize = new GSize(20, 33);
  ico.iconAnchor = new GPoint(10,34);
  ico.infoWindowAnchor = new GPoint(10,0);
  ico.shadowSize = new GSize(37, 34);
  ico.image = AMarker;
  ico.shadow = AMarkerShadow;
  return ico;
}

function CreateMarker(APoint, AIcon, AInfoTabs)
{
  var marker = new GMarker(APoint, {icon: AIcon});
  GEvent.addListener(marker, 'click', function(){ marker.openInfoWindowTabsHtml(AInfoTabs)});
  return marker;
}

function Content(APartner, APartnersCount){
  if(APartnersCount > 4)
    APartnersCount = APartnersCount * 90;
  else APartnersCount = 420;
  var content = "<table style='width: " + APartnersCount + "px; height: 150px;'><tr><td align='left'><table style='width: 420px; height: 150px;'><tr>";
  content += "<td rowspan='2' style='height: 150px; width: 150px;'>";
  content += "<img src='/images/partners/" + APartner[5] + "' />";
  content += "</td><td valign='top' align='left' style='border-bottom: solid 1px black; padding-left: 10px;'>";
  content += "\u041F\u0430\u0440\u0442\u043D\u0435\u0440: <b>" + APartner[0] + "</b><ul>";
  for(var i = 0; i < APartner[10].length; i++)
    content += "<li>" + APartner[10][i] + "</li>";
  content += "</ul></td></tr><tr><td valign='top' align='left' style='padding-left: 10px;'>";
  content += "\u0422\u0435\u043B.\u0444\u0430\u043A\u0441: " + APartner[1] + "<br />";
  content += "E-mail: <a href='malto:" + APartner[3] + "' title='\u041E\u0442\u043F\u0440\u0430\u0432\u0438\u0442\u044C \u043F\u0438\u0441\u044C\u043C\u043E'>" + APartner[3] + "</a><br />";
  content += "<a href='" + APartner[4] + "' target='_blank'>" + APartner[4] + "</a><br />";
  content += "</td></tr>";
  content += "</table></td></tr></table>";
  return content;
}

function TitleTab(AName, ANewLen){
  var newname = AName;
  if(AName.length > ANewLen)
  {
    newname = newname.substr(0, ANewLen);
    newname += "...";
  }
  return newname;
}

function SwitchMapList(){
  showlist = document.getElementById("ShowList");
  showmap = document.getElementById("ShowMap");
  COUNT = 6;
  legend = new Array();
  for(var i = 0; i < COUNT; i++)
    legend[i] = document.getElementById("marker" + (i + 1));
  if(list.style.display == "none")
  {
    showlist.className = "";
    showmap.className = "link";
    list.style.display = "block";
    mapp.style.display = "none";
    for(var i = 0; i < COUNT; i++)
      legend[i].style.display = "none";
     setFilter(0);
  }
  else
  {
    showlist.className = "link";
    showmap.className = "";
    list.style.display = "none";
    mapp.style.display = "block";
    for(var i = 0; i < COUNT; i++)
      legend[i].style.display = "inline";
    if(map == null)
    {
      LoadMap();
      setFilter(0);
      MapProcessing();
    }
  }
}

function SwitchList(AFlag){
  theShort = document.getElementById("Short");
  theFull = document.getElementById("Full");
  if (AFlag == true)
  {
    theShort.className = "SwitchSelect";
    theFull.className = "SwitchNotSelect";
    theFlag = true;
  }
  else
  {
    theShort.className = "SwitchNotSelect";
    theFull.className = "SwitchSelect";
    theFlag = false;
  }
  SelectionMenu();
}



function FromCookie() {
    thecookie = document.cookie;
    start = 0;
    end = 0;
    start = thecookie.indexOf(theID);
    if (start != -1) {
        start = theID.length + 1;
        end = thecookie.indexOf(";", start);
        if (end == -1) end = start + (thecookie.length - start);
        substr = thecookie.substring(start, end);

        split = substr.indexOf("|");
        activeTreeNodeNodeI = substr.substring(0, split);
        activeTreeNodeID = substr.substring(split + 1, substr.indexOf("|", split + 1));
        split = substr.indexOf("|", split + 1);
        activeTreeImgID = substr.substring(split + 1);
    }
}


// получение cookie по имени
function GetCookie(name) {
    var key = name + "=";
    var i = 0;
    while (i < document.cookie.length) {
        var j = i + key.length;
        if (document.cookie.substring(i, j) == key) return GetValue(j);
        i = document.cookie.indexOf(" ", i) + 1;
        if (i == 0)
            break;
    }
    return null;
}

// установка cookie по имени
function SetCookie(name, value) {
    var argv = SetCookie.arguments;
    var argc = SetCookie.arguments.length;
    var expires = new Date();
    expires.setDate(expires.getDate() + 31);
    var path = '/';
    var domain = (argc > 4) ? argv[4] : null;
    var secure = (argc > 5) ? argv[5] : false;
    document.cookie = name + "=" + escape(value) +
			((expires == null) ? "" : ("; expires=" +
			expires.toGMTString())) +
			((path == null) ? "" : ("; path=" + path)) +
			((domain == null) ? "" : ("; domain=" + domain)) +
			((secure == true) ? "; secure" : "");
}

function DeleteCookie(strName) {
    document.cookie = strName + "=0; path=/ ; expires="
					+ (new Date(0)).toGMTString();
}

function GetValue(offset) {
    var strEnd = document.cookie.indexOf(";", offset);
    if (strEnd == -1) {strEnd = document.cookie.length;}
    return unescape(document.cookie.substring(offset, strEnd));
}

function LoadDynamicFeedControl() {  
    google.load('feeds', '1');
    google.setOnLoadCallback(function(){
      var feeds = [{title: 'Новое на ECM-Journal', url: 'http://www.ecm-journal.ru/rss.aspx?Search=content::64*begin::new'}];
      var options = { stacked : false, horizontal : false, title : ""}
      new GFdynamicFeedControl(feeds, 'feed-control', options);
    })
}

