
var
  hlRubric = null;
var
  defaultURL = '',        // http://www.flexum.ru/science?query=...
  queryEscaped = '',      // %F5%F3%E9
  curRubric = 0,
  noArticles = 0,
  curPage = 0,
  curPageIdx = 0,
  pagesNum = 0,
  viewingNotes = false,
  curDoc = '',            // 0000002234
  curDocURL = '',         // http://...
  curDocSite = '',
  curURL = '',            // http://science.flexum.ru/?query=...[&theme=28][&page=1]
  curAnchor = '',         // #r=28;p=1
  curIframeSrc = '',      // http://science.flexum.ru/z.html?query=...&theme=28&page=1
                          // http://science.flexum.ru/z.html?http://...
  curSite = null,         // null / 0 / nnnn
  blankPage = '/z.html';  // http://science.flexum.ru/z.html
  
var xquery_id;

var 
  documentTitle = null,
  statusLoadingImg = null,
  statusReadyImg = null,
  logBlock = null,
  searchResults = null,
  rubricsLoader = null,
  rubricsBuffer = null,
  rubricsContainer = null,
  resultsLeft = null,
  pagesContainer = null,
  pagerColors = '',
  pagerBgColor = '',
  opinionFormContainer = null,
  inRubricChkBox = null,
  inRubricLabel = null,
  inRubricText = null,
  iframeElement = null,
  iframeInnerElement = null;

var
  prevDocBtn = null,
  nextDocBtn = null,
  addNoteBtn = null,
  showNotesBtn = null,
  addCommentBtn = null,
  showCommentsBtn = null,
  docCommentCountLabel = null,
  kooResultBtn = null,
  kiuResultBtn = null;
  firstcall = 1;

function highlightRubric(event) {
  var active = (event.type == 'mouseover');
  var el = (event.toElement || (active ? event.target : event.relatedTarget));
  while (el && !(/^rubric\d+$/.test(el.id) || el.id=='rubricAbstract')) {
    el = el.parentNode;
  }
  if (active) { // mouseover
    if (el && el.className != 'selected' && el != hlRubric) {
      hlRubric = el;
      hlRubric.className = 'rubric_active';
      window.status = el.anchorURL;
      var elrubric=el.rubric;
      if(typeof(elrubric)=="undefined")
        {
         if (el.id!='rubricAbstract')
            {
            elrubric=el.id;
            elrubric=elrubric.replace(/^rubric(\d+)$/,"$1");
            }
        else
            {
            elrubric='abstract';
            rubricsSize[elrubric]=1;
            }
        }
    setTimeout('hint.show("&nbsp;&nbsp;'+(el.id!='rubricAbstract'?rubricsSize[elrubric]:1)+'")', 0);
    }
  } else { // mouseout
    if (el != hlRubric && hlRubric != null) {
      if (hlRubric != selectedRubric) {
        hlRubric.className = (hlRubric.isVisited ? 'visited' : 'rubric');
      }
      hlRubric = null;
      window.status = '';
      setTimeout('hint.hide()', 0);
    }
  }
}

var rubrics = [],
    rubricsParent = null,
    selectedRubric = null;

function resetRubrics() {
  rubrics.length = 0;
  var url, tlist = rubricsContainer.getElementsByTagName(catalog_type ? 'A' : 'TABLE');
  for (var i = 0; i < tlist.length; i++) {
    r = tlist[i];
    if (r.id.match(/^rubric(\d+)$/)) {
        initRubric(r,  parseInt(RegExp.$1));
        rubrics.push(r);
        if (r.className == 'selected') selectedRubric = r; 
    }
    else if (r.id=='rubricAbstract')
        {
        initRubric(r, 'abstract');
        rubrics.push(r);
        if (r.className == 'selected') selectedRubric = r;
        }
  }
}

function initRubric(rubric, num) {
  rubric.rubric = num;
  rubric.anchorURL = curURL + getAnchor(num, 0);
  if (num == curRubric)
    rubric.isVisited = true;
  else {
    rubric.isVisited = isLinkVisited(isIE ? getIframeURL(num, 0) : rubric.anchorURL);
    rubric.className = (rubric.isVisited ? 'visited' : 'rubric');
  }
}

function getRubricElementByNum(rubricNum) {
  var r;
  for (var i = 0; i < rubrics.length; i++) {
    r = rubrics[i];
    if (r.rubric == rubricNum) return r;
  }
  //warn('Rubric \''+rubricNum+'\' not found.');
  return null;
}

function makeRubricSelected(el) {
  if (typeof(el) == 'number') {
    curRubric = el;
    el = getRubricElementByNum(el);
  } else {
    if (el == selectedRubric) {
      if (viewingNotes) loadContent();
      return;
    }
    curRubric = el.rubric;
    curPage = 0;
    curDoc = '';
    curDocSite = '';
    updateAnchor('rubric');
    if (isIE) markAsVisited('rubric');
  }
  if (curRubric && inRubricLabel.offsetHeight == 0) inRubricChkBox.checked = true;
  inRubricLabel.style.display = (curRubric ? '' : 'none');
  window.status = '';
  hidePages();
  foundXQLinks=0;
  loadContent();
  if (selectedRubric != null) selectedRubric.className = 'visited';
  if (el != null) {
    el.isVisited = true;
    el.className = 'selected';
  }
  selectedRubric = el;
  if (catalog_type)
    loadRubrics();
}


var
  passDocClick = false;

function docLinkClicked(el,site) {
  if (passDocClick) {
    passDocClick = false;
    return true;
  }
  if (el != lastClickedLink || showCommentsBtn.isDown) {
    loadSnippet(el, 'click', undefined, site);
    updateAnchor('doc');
  }
  return isIE;
}

function getIframeURL(rubric, page) {
  if (rubric == undefined) rubric = curRubric;
  if (page == undefined) page = curPage;
  return blankPage + '?' + 'query='+queryEscaped +
         (rubric > 0 ? '&theme='+rubric : '') +
         (page > 0 ? '&page='+page : '') +
         (noArticles > 0 ? '&noarticles=1' : '');
}

function getAnchor(rubric, page) {
  if (rubric == undefined) rubric = curRubric;
  if (page == undefined) page = curPage;
  return '#' + (rubric > 0 ? 'r='+rubric+';' : '') + 'p='+page+(noArticles > 0 ? ';n=1' : '');
}

var
  theLink = null;

function markAsVisited(what) {
  if (!isIE) {
    warn('Assertion: markAsVisited пока работает только для IE.');
    return;
  }
  if (theLink == null) {
    theLink = document.createElement('A');
    theLink.target = 'h';
    theLink.style.position = 'absolute';
  }
  if (what == 'page' || what == 'rubric') {
    document.appendChild(theLink);
    theLink.href = getIframeURL(); 
    theLink.click();
    document.removeChild(theLink);
  } else if (what == 'doc') {
    iframeInnerElement.location.replace('about:blank');
    passDocClick = true;
    lastClickedLink.click();
  }
}



var
  docLinks = [],
  lastClickedLink = null,
  snippetBlock = null,
  snippetLoader = null,
  resultsRight = null,
  buttonsPanel = null,
  docLoaded = false,
  docCommentCount = 0;

// click / hist / doc
function loadSnippet(el, sour, comments, site) {
  //alert(" el="+el+" sour="+sour+" comments="+comments+" site="+site+" siteId="+el.siteId)
  if (lastClickedLink) {
    var titleEl = $('t'+lastClickedLink.docId);
    if (titleEl) {
      if (titleEl.className == 'title_selected') {
        titleEl.className = 'title';
      } else {
        var commEl = $('comm'+lastClickedLink.docId);
        if (commEl) commEl.className = 'comm';
      }
    }
  }
  if (typeof(el) == 'string') {
    el = getDocLinkBy(el);
  }
  lastClickedLink = el;
  curDoc = (el ? el.docId : '');
  curDocURL = (el ? el.docURL : '');
  curDocRDI = (el ? el.realDocId : '');
  curDocSite = (el && el.siteId? el.siteId : site);
  updateDocCommentCount();
  updateBtnState('docLoaded = false');
  if (showCommentsBtn.isDown != comments) showCommentsBtn.setDown(comments);
  zoom(snippetBlock, '-');
  if (!el) { loadSnippet(docLinks[0], 'doc',undefined,docLinks[0].siteId);/*alert('Выбранный докумен в результатах поиска не обнаружен');*/ return;}
  if (isIE && sour == 'doc') markAsVisited('doc');
  if (comments)
    $('comm'+curDoc).className = 'comm_selected'
  else
    $('t'+curDoc).className = 'title_selected';
  if (!snippetLoader) {
    snippetLoader = new RemoteFileLoader('snippetLoader');
    snippetLoader.onCopyContent = snippetLoaded;
  } else if (snippetLoader.isBusy) {
    snippetLoader.cancel();
  }
  var docURL = curDocURL;
  if (isIE && docURL.match(/#r=\d+;p=\d+$/)) docURL = RegExp.leftContext;
  var url = (comments ? '/opinion.html?doc_id='+curDoc+(site?'&site_id='+site:'')
                      : '/?doc='+escape(docURL)+'&query='+(xquery_query?escapeQueryStr(xquery_query):queryEscaped)+(site?'&site_id='+site:'')+(curDocRDI?'&docid='+curDocRDI:''));
  snippetLoader.isBusy = true;
  beginLoad('snippet');
  snippetLoader.loadInto(url, 'snippet_container');
  moveButtonsPanel();
}

function snippetLoaded(doc, text, id) {
  snippetLoader.isBusy = false;
  endLoad('snippet');
  if (text == null) return; // viewingNotes
//if (doc == null) log3('request.docDOM == null!');
  var snippetContainer = $('snippet_container');
  snippetContainer.innerHTML = text;
  if (showCommentsBtn.isDown) updateUnixTimeBlocks(snippetContainer, 'SMALL', 'unix_time');
  updateBtnState('docLoaded = true');
  zoom(snippetBlock, '+');
  if (!imagesPreloaded) preloadImages();
  return true;
}

function updateDocCommentCount() {
  var opCntText = (curDoc ? $('comm'+curDoc) : null);
  if (opCntText) opCntText = opCntText.getElementsByTagName('SPAN')[0]; 
  docCommentCount = (opCntText ? parseInt(opCntText.innerHTML) || 0 : 0);
  docCommentCountLabel.innerHTML = (docCommentCount || '-');
  updateBtnState();
}

function incDocCommentCount() {
  docCommentCount++;
  docCommentCountLabel.innerHTML = docCommentCount;
  updateBtnState();
  var opCntText = (curDoc ? $('comm'+curDoc) : null);
  if (opCntText) {
    var opCntSpan = opCntText.getElementsByTagName('SPAN')[0];
    if (opCntSpan) {
      opCntSpan.innerHTML = docCommentCount;
      if (opCntText.offsetHeight == 0) opCntText.style.display = 'inline';
    }
  }
}

function getDocLinkBy(param) {
  var i, a, field = (param.indexOf('http://') == 0 ? 'docURL' : 'docId');
  for (i = 0; i < docLinks.length; i++) {
    a = docLinks[i];
    if (a[field] == param) return a;
  }
//warn('DocLink '+field+' \''+param+'\' not found.');
//log3('DocLink '+field+' \''+param+'\' not found.');
  return null;
}

function toggleShowMoreDocs(el, num) {
  var d = $('title_other_'+num);
  var pm = findSubChild(el, 'DIV', '');
  if (d.offsetWidth == 0) {
    pm.innerHTML = '&minus;';
    el.className = 'minus';
    zoom(d, '+');
  } else {
    pm.innerHTML = '+';
    el.className = 'plus';
    zoom(d, '-');
  }
}

function parseURL(s) {
  var res = { query: '', rubric: 0, page: 0, site: null, group: 0 };
  if (s == undefined) s = location.search;
  if (s.charAt(0) == '?') s = s.substr(1);
  if (s != '') {
    var i, n, a = s.split('&');
    for (i = 0; i < a.length; i++) {
      if (a[i].match(/^(\w+)(=(.*))?$/)) {
        n = parseInt(RegExp.$3);
        switch (RegExp.$1.toLowerCase()) {
          case 'query':
            res.query = RegExp.$3;
            break;
          case 'theme':
            if (!isNaN(n)) res.rubric = n;
            break;
          case 'page':
            if (!isNaN(n)) res.page = n;
            break;
          case 'site_id':
            res.site = (RegExp.$3 == 'articles'?'articles':(isNaN(n)?null:n));
            break;
          case 'site':
            res.site = (RegExp.$3 == 'articles'?'articles':(isNaN(n)?null:n));
            break;
          case 'nogroup':
            res.group = (RegExp.$3 != '' && parseInt(RegExp.$3) == 0) ? 1 : 2;
            break;
          case 'group1':
            res.group = (RegExp.$3 == 'group') ? 1 : 2;
        }
      }
    }
  }
  return res;
}

function parseIframeSrc(s) {
  var haveRes = false, res = { rubric: null, page: null, doc: null },zp=false;
  s = s.substr(s.indexOf('?')+1);
  if (s != '') {
    if (s.indexOf('http://') == 0) {
      res.doc = s;
      haveRes = true;
    } else {
      var i, n, a = s.split('&');
      for (i = 0; i < a.length; i++) {
        if (a[i].match(/^(\w+)=(.+)$/)) {
          n = parseInt(RegExp.$2);
          if (!isNaN(n)) {
            switch (RegExp.$1.toLowerCase()) {
              case 'theme':
                res.rubric = n;
                haveRes = true;
                break;
              case 'page':
                res.page = n;
                haveRes = true;
            }
          }
          if(RegExp.$1.toLowerCase()=='query')     // fix баги в листалке, которая не пишет page=0
            zp=true;                               // fix баги в листалке, которая не пишет page=0
        }
      }
      if(zp&&!haveRes){ haveRes=true; res.page=0;} // fix баги в листалке, которая не пишет page=0
    }
  }
  return (haveRes ? res : null);
}

function parseAnchor(s) {
  var res = { rubric: 0, page: 0, doc: '', notes: false, noarticles: 0 };
  if (s == undefined) s = location.hash;
  if (s.charAt(0) == '#') s = s.substr(1);
  if (s != '') {
    if (s == 'notes') res.notes = true;
    else {
      var i, n, a = s.split(';');
      for (i = 0; i < a.length; i++) {
        if (a[i].match(/^(\w)=(.+)$/)) {
          n = parseInt(RegExp.$2);
          switch (RegExp.$1.toLowerCase()) {
            case 'r':
              if (!isNaN(n)) res.rubric = n;
              break;
            case 'p':
              if (!isNaN(n)) res.page = n;
              break;
            case 'n':
              res.noarticles = 1;
              break;
            case 'd':
              res.doc = RegExp.$2;
          }
        }
      }
    }
  }
  return res;
}

function makeAnchor(rubric, page, doc, notes) {
  if (notes) return '#notes';
  var s = 'p='+page;
  if (rubric)  s = 'r='+rubric+';'+s;
  if (doc)     s += ';d='+doc;
  if (noArticles) s += ';n=1';
  return '#'+s;
}

var
  isFirstDoc = false;

// sour = 'init' / 'rubric' / 'page' / 'doc' / 'firstdoc'
function updateAnchor(sour) {
  if (sour == 'firstdoc') isFirstDoc = true;
  else if (sour == 'doc') isFirstDoc = false;
  curAnchor = makeAnchor(curRubric, curPage, (isFirstDoc ? '' : curDoc)); // <-- notes
  if (curAnchor == '#p=0') {
    if (sour != 'rubric' && sour != 'page') {
      curAnchor = location.hash;
      return;
    }
  }
  if (location.hash != curAnchor) {
//  if (flashInstalled) resetPagesFlash('clear');
    location.hash = curAnchor;
//  if (flashInstalled) resetPagesFlash('fast');
  }
  markPageVisited();
}

function markPageVisited() {
  var url = (isIE ? getIframeURL() : getAnchor());
  linkVisitedCache[url] = true;
//log3('markPageVisited, url: ' + url);
}



function escapeQueryStr(s) {
  return s.replace(/&/g, '%26');
}


function submitSearchForm() {
  var searchForm = $('search_form');
  if (queryEscaped!=escapeQueryStr(searchForm.query.value))
    xquery_id=0;
  queryEscaped = escapeQueryStr(searchForm.query.value);
  if(typeof(exprt)!="undefined" && exprt==1){
    location.assign('/?query='+queryEscaped+
      (curRubric > 0 && inRubricChkBox.checked ? '&theme='+curRubric : '')+( curSite!=null && inRubricChkBox.checked ?'&site='+curSite:(groupSites==null?'':(groupSites?'&group1=group':'&group1=')))+(xquery_id?'&xq='+xquery_id:'')+(noArticles ? '&noarticles=1' : ''));
  }else{ 
  location.assign('/?query='+queryEscaped+
    ( curSite!=null && inRubricChkBox.checked ?'&site_id='+curSite:(groupSites==null?'':(groupSites?'&nogroup=0':'&nogroup')))+(xquery_id?'&xq='+xquery_id:'')+(curRubric > 0 && inRubricChkBox.checked ? '#r='+curRubric+(noArticles ? ';n=1' : '') : (noArticles ? '#n=1' : '')));


    //             (groupSites||curSite ? '&part=2'+(curSite != null ? '&site='+curSite+'&full_mode=1' : '') 
    //                         : '&part=3');
}

}




function subinit(){
  searchResults = $('search_results');
  curRubric = $('cur_rubric').innerHTML;
  if(typeof($('no_articles'))!='undefined'&&$('no_articles')!=null) noArticles= parseInt($('no_articles').innerHTML);
  inRubricChkBox = $('in_rubric');
  inRubricLabel = $('in_rubric_label');
  inRubricText = $('in_rubric_text');
  var url = parseURL();
  curSite = url.site;
  if (url.group > 0)
    groupSites = (url.group == 1 ? true : false);
}

function init() {
  if (!window.commonLoaded) {
    setTimeout(init, 100);
    return;
  }
  documentTitle = document.title;
  statusLoadingImg = $('status_loading');
  statusReadyImg = $('status_ready');
  logBlock = $('log_block');
  searchResults = $('search_results');
  rubricsBuffer = $('rubrics_buffer');
  rubricsContainer = $('rubrics_container');
  resultsLeft = $('results_left');
  pagesContainer = $('pages');
  snippetBlock = $('snippet_block');
  rubricsParent = $('rubrics_parent');
  resultsRight = $('results_right');
  buttonsPanel = $('buttons_panel');
  opinionFormContainer = $('opinion_form_container');
  inRubricChkBox = $('in_rubric');
  inRubricLabel = $('in_rubric_label');
  inRubricText = $('in_rubric_text');
  iframeElement = $('h');
  if (document.frames) iframeInnerElement = document.frames['h'];
  initButtons();
  chkFlash();
  var url = parseURL();
  var anc = parseAnchor();
  queryEscaped = url.query;
  curRubric = anc.rubric; // || url.rubric;
  if(typeof($('no_articles'))!='undefined'&&$('no_articles')!=null) noArticles= parseInt($('no_articles').innerHTML);
  if(anc.noarticles) noArticles=1;
  curPage = anc.page; // || url.page;
  curSite = url.site;
  if(curSite){
    inRubricText.innerHTML=" на выбранном сайте&nbsp;";
    inRubricLabel.style.display='';
    resetMovedBlocksPos();
  }
  if (url.group > 0)
    groupSites = (url.group == 1 ? true : false);
  curDoc = anc.doc;
  curURL = location.href;
  var p = curURL.indexOf('#');
  if (p >= 0) curURL = curURL.substr(0, p);
  defaultURL = location.href.match(/^(.+?)\?/)[1]+'?query='+queryEscaped;
  blankPage =  defaultURL.substr(0, defaultURL.indexOf('/', 8)) + blankPage;
  updateAnchor('init');
  if (isIE) markAsVisited('page');
  setInterval(chkAnchorChanged, 100);
  if (isIE) setInterval(chkIframeChanged, 100);
  if (abstract_id)
    {
    if (curSite == null || curSite == 0) 
        {
        //if (!curRubric)curRubric='abstract';
        loadRubrics();
        }
    loadContent();
    }
  else
    {
    if (viewingNotes) showNotes(); else loadContent();
    if (flashInstalled) setTimeout(getPagerColors, 1);
    if (curSite == null || curSite == 0) loadRubrics();
    }
}

var
  flashInstalled = false;

function chkFlash(minVer) {
  if (!minVer) minVer = 6;
  var plugin;
  if (navigator.plugins) {
    if (navigator.plugins['Shockwave Flash']) {
      var plugin = navigator.plugins['Shockwave Flash'].description;
      var flashVer = plugin.match(/(\d+)\./)[1];
      flashInstalled = (parseInt(flashVer) >= minVer);
    } else {
      if ((navigator.userAgent.indexOf('MSIE') != -1) && (navigator.userAgent.indexOf('Win') != -1)) {
        var vb = '<script language="VBScript">\n'
               + '  on error resume next\n'
               + '  flashInstalled = IsObject(CreateObject('
               + '   "ShockwaveFlash.ShockwaveFlash.'+minVer+'"))\n'
               + '<' + '/script>';
        document.write(vb);
      }
    }
  }
}

function getPagerColors() {
  var  selBgColor = 'FFF2AA',  selTxColor = '000000',
       visBgColor = 'FFFFFF',  visTxColor = 'BBBBBB',
       othBgColor = 'F0F0D6',  othTxColor = '353626',
       allBgColor = 'FFFFFF';

  var findPagerColor = function(selector, style) {
    if (selector.substr(0, 12) == '#pages_inner') {
      switch (selector) {
        case '#pages_inner td.selected .rounded':
          selBgColor = extractCssColor(style.backgroundColor);
          break;
        case '#pages_inner td.selected .rounded a:visited':
          selTxColor = extractCssColor(style.color);
          break;
        case '#pages_inner td.visited .rounded':
          visBgColor = extractCssColor(style.backgroundColor);
          break;
        case '#pages_inner td.visited .rounded a:visited':
          visTxColor = extractCssColor(style.color);
          break;
        case '#pages_inner .rounded':
          othBgColor = extractCssColor(style.backgroundColor);
          break;
        case '#pages_inner a':
          othTxColor = extractCssColor(style.color);
      }
    } else if (selector == 'body') {
      allBgColor = extractCssColor(style.backgroundColor);
    }
  }

//var start = (new Date()).getTime();
  try {
    for (var i = 0, slen = document.styleSheets.length; i < slen; i++) {
      var sheet = document.styleSheets[i];
      var rules = (sheet.rules || sheet.cssRules);
      if (rules == null) return;
      for (var j = 0, rlen = rules.length; j < rlen; j++) {
        var rule = rules[j];
        var sel = rule.selectorText.toLowerCase();
        if (sel.indexOf(',') < 0) {
          findPagerColor(sel, rule.style)
        } else {
          var style = rule.style;
          var sels = sel.split(/,\s*/);
          for (var k = 0, klen = sels.length; k < klen; k++) {
            findPagerColor(sels[k], style);
          }
        }
      }
    }
//  var end = (new Date()).getTime();
//  log3('getPagerColors: '+(end - start)+'ms');
    pagerColors = (selBgColor+','+selTxColor+','+visBgColor+','+visTxColor+','+othBgColor+','+othTxColor);
    pagerBgColor = '#'+allBgColor;
  } catch(e) { 
  }
}

function extractCssColor(color) {
  if (!color) return '';
  if (color.charAt(0) == '#') {
    if (color.length == 4) {
      return color.charAt(1)+color.charAt(1)+
             color.charAt(2)+color.charAt(2)+
             color.charAt(3)+color.charAt(3)
    } else {
      return color.substr(1)
    }
  } else if (color.match(/rgb\((\d+),\s?(\d+),\s?(\d+)\)/i)) {
    return hex2(RegExp.$1)+hex2(RegExp.$2)+hex2(RegExp.$3)
  }
  return '';
}

function hex2(i) {
  var h = '0123456789ABCDEF';
  return (h.charAt(i>>4) + h.charAt(i&15));
}

function initButtons() {
  prevDocBtn = initImgButton('button_prev', showPrevDoc);
  nextDocBtn = initImgButton('button_next', showNextDoc);
  addNoteBtn = initImgButton('button_note_new', addNote);
  showNotesBtn = initImgButton('button_note_open', toggleShowNotes, true);
  addCommentBtn = initImgButton('button_comment_new', toggleOpinionForm, true);
  showCommentsBtn = initImgButton('button_comment_open', toggleShowComments, true);
  docCommentCountLabel = initImgButtonLabel('doc_comment_count', showCommentsBtn);
  showCommentsBtn.btnLabel = docCommentCountLabel;
  kooResultBtn = initImgButton('button_result_plus', sendKoo);
  kiuResultBtn = initImgButton('button_result_minus', sendKiu);
  updateBtnState();
}

function initImgButton(id, onclick, isTrigger) {
  var btn = $(id);
  applyIntf(btn, IImgButton);
  btn.isTrigger = isTrigger;
  btn.onBtnClick = onclick;
  btn.updateSrc();
  return btn;
}

var
  IImgButton = {
    inProcess: false,
    isEnabled: true,
    isDown: false,
    isHover: false,
    isTrigger: false,
    setInProcess: function(inProcess) { this.inProcess = inProcess; this.updateSrc() },
    setEnabled: function(enabled) { this.isEnabled = enabled; this.updateSrc() },
    setDown: function(down) { this.isDown = down; this.updateSrc() },
    setHover: function(hover) { this.isHover = hover; this.updateSrc() },
    onmouseover: function() { this.setHover(true) },
    onmouseout: function() { this.setHover(false) },
    onmousedown: IImgButton_mouseDown,
    onmouseup: IImgButton_mouseUp,
    updateSrc: IImgButton_updateSrc,
    updateHintState: IImgButton_updateHintState
  }

function IImgButton_updateSrc() {
  if (this.defaultSrc == undefined) this.defaultSrc = this.src;
  var suffix, path, name, ext;
  if (this.inProcess) suffix = this.getAttribute('inProcessSuffix') || '_p'
  else if (!this.isEnabled) suffix = this.getAttribute('disabledSuffix') || '_u'
  else if (this.isDown) suffix = this.getAttribute('downSuffix') || '_d'
  else if (this.isHover) suffix = this.getAttribute('hoverSuffix') || '_a'
  else suffix = '';
  if (suffix && suffix.charAt(0) == '^') {
    suffix = suffix.substr(1);
    path = extractPath(suffix);
    name = extractNameNoExt(suffix);
    ext = extractExt(suffix);
  }
  if (!path) path = extractPath(this.defaultSrc);
  if (!name) name = extractNameNoExt(this.defaultSrc) + suffix;
  if (!ext) ext = extractExt(this.defaultSrc);
  var newSrc = path + name + ext;
  if (this.curSrc != newSrc) {
    this.src = this.curSrc = newSrc;
  }
  var cursor = (this.isEnabled && !this.inProcess ? 'pointer' : 'default');
  this.style.cursor = cursor;
  if (this.btnLabel) this.btnLabel.style.cursor = cursor;
  this.updateHintState();
}

function IImgButton_updateHintState() {
  var text;
  if (this.isHover) {
    text = this.getAttribute('hint');
    if (this.inProcess) text = this.getAttribute('inProcessHint') || text
    else if (!this.isEnabled) text = this.getAttribute('disabledHint') || text
    else if (this.isDown) text = this.getAttribute('downHint') || text;
  }
  this.hintVisible = (this.isHover && text);
  if (this.hintVisible) hint.show(text); else hint.hide();
}

function IImgButton_mouseDown(event) {
  if (event) cancelEvent(event);
  if (!this.isEnabled || this.inProcess) return;
  this.wasDown = this.isDown;
  this.setDown(true);
  return false;
}

function IImgButton_mouseUp(event) {
  if (event) cancelEvent(event);
  if (!this.isEnabled || this.inProcess) return;
  if (!this.isTrigger || this.wasDown) {
    this.setDown(false);
  }
  if (this.onBtnClick) this.onBtnClick();
  return false;
}


function initImgButtonLabel(id, linkedBtn) {
  var lbl = $(id);
  applyIntf(lbl, IImgButtonLabel);
  lbl.linkedBtn = linkedBtn;
  return lbl;
}

var
  IImgButtonLabel = {
    onmouseover: function() { this.linkedBtn.onmouseover() },
    onmouseout: function() { this.linkedBtn.onmouseout() },
    onmousedown: function() { this.linkedBtn.onmousedown() },
    onmouseup: function() { this.linkedBtn.onmouseup() }
  };


function updateBtnState(val) {
  if (val) eval(val);
  var idDoc = (curDoc && !viewingNotes);
  prevDocBtn.setEnabled(idDoc);
  nextDocBtn.setEnabled(idDoc);
  addNoteBtn.setEnabled(idDoc);
//showNotesBtn.setEnabled(true);
  addCommentBtn.setEnabled(idDoc);
  showCommentsBtn.setEnabled(idDoc && (docCommentCount > 0));
  kooResultBtn.setEnabled(idDoc);
  kiuResultBtn.setEnabled(idDoc);
}

var preloadedImages = [
  'search_button.gif',   //  /i/search/...
  'search_button_a.gif',
  'search_button_d.gif',

  'prev.gif',            //  /i/search/panel/...
  'prev_a.gif',
  'prev_d.gif',
  'next.gif',
  'next_d.gif',
  'next_a.gif',
  'button_loader.gif',
  'note_new.gif',
  'note_new_a.gif',
  'note_new_d.gif',
  'note_open.gif',
  'note_open_a.gif',
  'note_open_d.gif',
  'comment_new.gif',
  'comment_new_a.gif',
  'comment_new_d.gif',
  'comment_open.gif',
  'comment_open_a.gif',
  'comment_open_d.gif',
  'result_plus.gif',
  'result_plus_a.gif',
  'result_plus_d.gif',
  'result_minus.gif',
  'result_minus_a.gif',
  'result_minus_d.gif'
];

var imagesPreloaded = false;

function preloadImages() {
  var i, s;
  for(i = 0; i < preloadedImages.length; i++) {
    s = preloadedImages[i];
    preloadedImages[i] = new Image();
    preloadedImages[i].src = '/i/search/' + (i >= 3 ? 'panel/' : '') + s;
  }
  imagesPreloaded = true;
}

function loadRubrics() {
  if (parseInt(curRubric)) {
    if (inRubricLabel.offsetHeight == 0) inRubricChkBox.checked = true;
    inRubricLabel.style.display = '';
  }
  if (!rubricsLoader) {
    rubricsLoader = new RemoteFileLoader('rubricsLoader');
    rubricsLoader.onCopyContent = rubricsLoaded;
  }
  if (!rubricsLoader.isBusy) {
    rubricsLoader.isBusy = true;
    beginLoad('rubrics');
  }
  var url = '/?query='+queryEscaped+(curRubric ? '&theme='+curRubric : '')+'&part=1'+(groupSites?'&group=1':'&nogroup=1')+(xquery_id?'&xq='+xquery_id:'');
  rubricsLoader.loadInto(url, 'rubrics_buffer');
}

var
  rubricsSize = {};
//rubricsSizeTotal = null;

function rubricsLoaded(docDOM, docText, destId) {
  rubricsLoader.isBusy = false;
  endLoad('rubrics');
  rubricsBuffer.innerHTML = docText;
  var div = findSubChild(rubricsBuffer, 'DIV');
  if (div) {
//  rubricsContainer.style.height = '0px';
//  rubricsContainer.style.width = '100%';
//  rubricsContainer.style.overflow = 'hidden';
//  rubricsContainer.style.display = 'block';
    rubricsContainer.innerHTML = div.innerHTML;
    resetRubrics();
//  var mh = 0;
//  for (var i = 0; i < rubrics.length; i++) {
//    mh = Math.max(rubrics[i].offsetHeight, mh);
//  }
//  rubricsContainer.style.height = mh+'px';
    resetMovedBlocksPos();
    do {
      div = div.nextSibling;
    } while (div && div.tagName != 'DIV');
    if (div) {
      var tags = div.innerHTML.split(',');
      for (var i = 0; i < tags.length; i++) {
        if (tags[i].match(/(\d+)=(\d+)/)) {
          rubricsSize[parseInt(RegExp.$1)] = parseInt(RegExp.$2);
        }
      }
    }
  }
  resetMovedBlocksPos();
  rubricsBuffer.innerHTML = '';
  if (viewingNotes && selectedRubric != null) selectedRubric.className = 'visited';
  
  return true;
}

var
  docToLoad = '';

var 
  anchorMonitoringDisabled = false;

function chkAnchorChanged() {
  if (document.title != documentTitle) document.title = documentTitle;
  if (anchorMonitoringDisabled) return;
  var newAnchor = location.hash;
  if (newAnchor != curAnchor) {
    curAnchor = newAnchor;
    var a = parseAnchor(newAnchor);
    var reload = '';
    if (a.page != curPage) {
      curPage = a.page;
      reload = 'page';
    }
    if (a.rubric != curRubric) {
      curRubric = a.rubric;
      reload = 'rubric';
    }
    if (reload) {
      if (a.doc != curDoc) {
        curDoc = a.doc;
        docToLoad = a.doc;
      }
      if (reload == 'rubric')
        makeRubricSelected(curRubric);
      else
        loadContent();
    } else if (a.doc != curDoc) {
      loadSnippet(a.doc || docLinks[0], 'hist', undef, (a.doc?'':docLinks[0].siteId));
      updateAnchor(a.doc ? 'doc' : 'firstdoc');
    }
  }
}

function chkIframeChanged() {
  if (document.title != documentTitle) document.title = documentTitle;
  var newIframeSrc = (iframeInnerElement ? 
    iframeInnerElement.location.href : 
    iframeElement.contentWindow.location.href);
  if (newIframeSrc != curIframeSrc) {
    var c2n = ' ['+curIframeSrc+'] -&gt; ['+newIframeSrc+']';
    curIframeSrc = newIframeSrc;
    var a = parseIframeSrc(newIframeSrc);
    if (a) {
      var reload = '';
      if (a.doc != null) {
        if (a.doc != curDocURL) {
          reload = 'doc';
          var prm = a.doc.match(/(.+)#r=(\d+);p=(\d+)/);
          var newRubric = parseInt(prm[2]);
          var newPage = parseInt(prm[3]);
          if (newRubric != curRubric) {
            curRubric = newRubric;
            docToLoad = a.doc;
            makeRubricSelected(curRubric);
            updateAnchor('rubric');
          } else if (newPage != curPage) {
            curPage = newPage;
            docToLoad = a.doc;
            loadContent();
            updateAnchor('page');
          } else {
            loadSnippet(a.doc, 'hist');
            updateAnchor('doc');
          }
        }
      } else {
        if (a.page == null) a.page = 0;
        if (a.rubric == null) a.rubric = 0;
        if (a.page != curPage) {
          curPage = a.page;
          reload = 'page';
        }
        if (a.rubric != curRubric) {
          curRubric = a.rubric;
          reload = 'rubric';
        }
        if (reload != '') {
          curDoc = '';  // стираем тек. документ, чтоб не грузить его из нового контента
          curDocSite = '';
          updateAnchor(reload);
          if (reload == 'rubric')
            makeRubricSelected(curRubric);
          else
            loadContent();
        }
      }
    }
  }
}

//-- Pages --------------------------------------------------------

function resetPages(prm) {
  if (flashInstalled)
    resetPagesFlash(prm)
  else
    resetPagesHtml(prm)
}

var
  prevRubric = null,
  prevNotes = false;

function resetPagesFlash(action) {
  if (pagesNum == 0) {
    pagesContainer.innerHTML = '';
    firstVisPageNum = 0;
    return;
  }
  if (action == 'clear')
    pagesContainer.innerHTML = ''
  else {
    var rubric;
    if (action == 'fast') {
      rubric = prevRubric;
    } else {
//    if (prevRubric === curRubric) return;
      rubric = prevRubric = curRubric;
    }
    var page = (viewingNotes ? pagesNum-1 : curPage);
    var w = 110;
    var h = Math.max(115, Math.min(Math.min(maxVisPageNum, pagesNum)*70+40, 375));
    var flashFile = '/i/search/pagerv3.swf?3';
    var flashVars = 'maxVis='+maxVisPageNum + '&sel='+page + 
                    '&rubric='+curRubric + '&pages='+(viewingNotes ? '1' : getVisitedPages(rubric, pagesNum, page)) +
                     (isIE ? '&query='+queryEscaped : '') +
                     (pagerColors ? '&colors='+pagerColors : '') +
                    '&isIE='+(isIE ? '1' : '0');
    // Обходим баг в IE: при вызове javascript:pageClicked() функция копируется в адресную строку
    // Вместо этого просим flash загрузить нужный нам url в iframe c id=h
//  if (action == 'fast') flashVars += '&fast=1'; // - cейчас не работает
    // Нейтрализуем баг в IE: при наличии flash-ки на странице и при её перегрузке
    // к document.title добавляется location.hash
    var t = document.title;
    pagesContainer.innerHTML = '\n\
      <p class="pb05"><b>'+(pagesNum == 1 ? Stranitsa : Stranitsy)+'</b></p>\n\
      <object classid="clsid:d27cdb6e-ae6d-11cf-96b8-444553540000" codebase="http://download.macromedia.com/pub/shockwave/cabs/flash/swflash.cab#version=6,0,0,0" width="'+w+'" height="'+h+'" style="display: block;">\n\
       <param name="allowScriptAccess" value="sameDomain" />\n\
       <param name="movie" value="'+flashFile+'" />\n\
       <param name="FlashVars" value="'+flashVars+'" />\n\
       <param name="menu" value="false" />\n\
       <param name="wmode" value="opaque" />\n\
       <param name="bgcolor" value="'+pagerBgColor+'" />\n\
       <param name="salign" value="lt" />\n\
       <param name="scale" value="noscale" />\n\
       <param name="quality" value="high" />\n\
       <embed src="'+flashFile+'" FlashVars="'+flashVars+'" menu="false" salign="lt" wmode="opaque" bgcolor="'+pagerBgColor+'" quality="high" width="'+w+'" height="'+h+'" allowScriptAccess="sameDomain" type="application/x-shockwave-flash" pluginspage="http://www.macromedia.com/go/getflashplayer" />\n\
      </object>\n\
';
    document.title = t;
  }
}

function getVisitedPages(rubric, pagesNum, sel) {
//log3('getVisitedPages(' + rubric + ', ' + pagesNum + ', ' + sel + ')');
  var a = Math.min(9, pagesNum-1);
  var b = Math.max(0, sel - 10);
  var c = Math.min(sel + 10, pagesNum-1);
  if (a+1 >= b) {
    b = null;
    a = c;
  }
  var visited = (a < pagesNum-1 ? pagesNum + '~' : '');
  for (var i = 0; i <= a; i++) {
    var url = (isIE ? getIframeURL(rubric, i) : getAnchor(rubric, i));
    visited += (isLinkVisited(url) ? '1' : '0');
  }
  if (b != null) {
    visited += ',' + b + ':';
    for (i = b; i <= c; i++) {
      url = (isIE ? getIframeURL(rubric, i) : getAnchor(rubric, i));
      visited += (isLinkVisited(url) ? '1' : '0');
    }
  }
//log3('visited="' + visited + '", sel: ' + sel);
  return visited;
}


var
  pageFontSizes = [5.0, 4.2, 3.5, 2.8, 2.3]; // [5.0, 4.2, 3.8, 2.8, 2.2, 2.0, 1.8, 1.7, 1.6, 1.5],
  firstVisPageNum = 0,
  maxVisPageNum = 5, // только нечётные числа
  pageBoxes = [],
  pageBoxSizes = [],
  Stranitsa = '&#x421;&#x442;&#x440;&#x430;&#x43D;&#x438;&#x446;&#x430;',
  Stranitsy = '&#x421;&#x442;&#x440;&#x430;&#x43D;&#x438;&#x446;&#x44B;';

function getPageFontSize(i) {
  return pageFontSizes[Math.min(i, pageFontSizes.length-1)];
}

//resetPages('soft') - cохранить старые размеры и перерисовать только ячейки, поменяв selected
function resetPagesHtml(firstNum) {
  if (pagesNum == 0) {
    pagesContainer.innerHTML = '';
    firstVisPageNum = 0;
    return;
  }
  var cPage = (viewingNotes ? 0 : curPage);
  var soft = false;
  if (firstNum == 'soft') {
    firstNum = null;
    soft = true;
  }
  var first = firstNum, last = null, more = Math.floor(maxVisPageNum/2);
  if (first == null) {
    first = firstVisPageNum;
    last = Math.min(first+maxVisPageNum, pagesNum)-1;
    if (cPage < first || cPage > last) {
      first = Math.min(Math.max(0, cPage-more), pagesNum-maxVisPageNum);
    }
  }
  firstVisPageNum = first;
  last = Math.min(first+maxVisPageNum, pagesNum)-1;
  var url, num, fsz, gap, vis, s = '';
  var prefix = (isIE ? '?' : '#');
  for (var i = first; i <= last; i++) {
    url = (isIE ? getIframeURL(curRubric, i) : getAnchor(curRubric, i));
    vis = isLinkVisited(url);
    num = i+1;
    if (soft) {
      fsz = pageBoxSizes[i-first];
    } else {
      fsz = getPageFontSize(Math.abs(i-cPage));  // class="page'+(Math.abs(i-curPage)+1)+'" 
      pageBoxSizes[i-first] = fsz;
    }
    gap = (1.8 - fsz/3);
    s +='\
        <table id="page'+(i+1)+'" border="0" cellspacing="0" cellpadding="0" onClick="pageClicked(this)" style="margin-bottom: '+gap+'em"><tr><td'+(i == cPage ? ' class="selected"' : (vis ? ' class="visited"' : ''))+'>\n\
         <div class="rounded">\n\
          <b class="r2"></b><b class="r1"></b>\n\
          <table border="0" cellspacing="0" cellpadding="0" style="font-size: '+fsz+'em"><tr><td align="center"><a href="'+url+'" onClick="return false">'+num+'</a></td></tr></table>\n\
          <b class="r1"></b><b class="r2"></b>\n\
         </div>\n\
        </td></tr></table>\n'
  } // for
  if (firstNum == null) {
    freePageButtons();
    pagesContainer.innerHTML = '\n\
      <b>'+(pagesNum == 1 ? Stranitsa : Stranitsy)+'</b><br>\n\
      <img class="page_prev" src="/i/page_prev.gif"><br>\n\
      <div id="pages_inner">\n'+s+'\
      </div>\n\
      <img class="page_next" src="/i/page_next.gif"><br>\n';
    initPageButtons();
  } else {
    $('pages_inner').innerHTML = s;
  }
  initPageBoxes(first, last, soft);
  updatePageButtonsState();
}

var
  pagePrevBtn = null,
  pageNextBtn = null;

function initPageButtons() {
  pagePrevBtn = findSubChild(pagesContainer, 'img', 'page_prev');
  pageNextBtn = findSubChild(pagesContainer, 'img', 'page_next');
  setupEvent(pagePrevBtn, 'mousedown', pagePrevNextBtnDownEvent);
  setupEvent(pageNextBtn, 'mousedown', pagePrevNextBtnDownEvent);
}

function freePageButtons() {
  if (pagePrevBtn) {
    removeEvent(pagePrevBtn, 'mousedown', pagePrevNextBtnDownEvent);
    pagePrevBtn = null;
  }
  if (pageNextBtn) {
    removeEvent(pageNextBtn, 'mousedown', pagePrevNextBtnDownEvent)
    pageNextBtn = null;
  }
}

function pagePrevNextBtnDownEvent(event) {
  var el = (event.target || event.srcElement);
  if (el.enabled) {
    setTimeout((el == pagePrevBtn ? scrollPrevPage : scrollNextPage), 0);
  }
  cancelEvent(event);
}

function updatePageButtonsState() {
  var en = (firstVisPageNum > 0);
  if (pagePrevBtn.enabled == null || pagePrevBtn.enabled != en) {
    if (!pagePrevBtn.enabledSrc) {
      var s = pagePrevBtn.src;
      pagePrevBtn.enabledSrc = s;
      pagePrevBtn.disabledSrc = extractPath(s) + extractNameNoExt(s)+'_u' + extractExt(s);
    }
    s = (en ? pagePrevBtn.enabledSrc : pagePrevBtn.disabledSrc);
    if (s != pagePrevBtn.src) pagePrevBtn.src = s;
    pagePrevBtn.enabled = en;
    pagePrevBtn.style.cursor = (en ? 'pointer' : 'default');
  }
  en = (firstVisPageNum < pagesNum-maxVisPageNum);
  if (pageNextBtn.enabled == null || pageNextBtn.enabled != en) {
    if (!pageNextBtn.enabledSrc) {
      s = pageNextBtn.src;
      pageNextBtn.enabledSrc = s;
      pageNextBtn.disabledSrc = extractPath(s) + extractNameNoExt(s)+'_u' + extractExt(s);
    }
    s = (en ? pageNextBtn.enabledSrc : pageNextBtn.disabledSrc);
    if (s != pageNextBtn.src) pageNextBtn.src = s;
    pageNextBtn.enabled = en;
    pageNextBtn.style.cursor = (en ? 'pointer' : 'default');
  }
}


var
  pagesVisible = false;

function showPages() {
  if (pagesVisible) return;
  if (flashInstalled) {
//  moveAbsBlock(pagesContainer, null, null, 'quick');
    pagesContainer.style.visibility = '';

    // Обходим баг в IE: при наличии flash-ки на странице и при её показе через visibility = ''
    // при первом чтении cвойства offsetHeight/offsetWidth к document.title добавляется location.hash
    if (isIE) {
      var t = document.title;               // сохраняем title
      var v = pagesContainer.offsetHeight;  // тут к title добавляется якорь
      document.title = t;                   // восстанавливаем title
    }
  } else {
    pagesContainer.afterMove = null;
    if (!('movePosX' in pagesContainer)) {
      moveAbsBlock(pagesContainer, -pagesContainer.offsetWidth, null, 'quick');
      pagesContainer.style.visibility = '';
    }
    moveAbsBlock(pagesContainer);
  }
  pagesVisible = true;
}

function hidePages() {
  if (pagesVisible) {
    pagesVisible = false;
    if (flashInstalled) {
      pagesContainer.style.visibility = 'hidden';
    } else if (!('movePosX' in pagesContainer)) {
      moveAbsBlock(pagesContainer, -pagesContainer.offsetWidth, null, 'quick');
//    pagesContainer.style.visibility = 'hidden';
    } else {
      moveAbsBlock(pagesContainer, -(pagesContainer.offsetWidth+pagesContainer.movePosX));
    }
  }
}

// вызывается из body.onscroll
function reposPagesContainer() {
  var rT = getAbsPos(resultsLeft).top; // Y-позиция блока с контентом, отступ от верхнего края окна
  var rH = resultsLeft.offsetHeight;   // высота блока с контентом
  var rB = rT + rH;                    // нижняя граница контента
  var pT = getAbsPos(pagesContainer).top;  // Y-позиция pager-а ( = cT + 1em)
  var pH = pagesContainer.offsetHeight - (pagesContainer.curTopPos || 0);  // высота pager-а
  var sT = document.body.scrollTop;    // Y-позиция скроллинга
  var sH = document.body.scrollHeight; // высота всего контента окна
  var cH = document.body.clientHeight; // высота видимой области окна
  var sTmax = sH - cH;                 // максимальная величина body.scrollTop
  var pTmax = sTmax - pT;              // отступ pager-а при sTmax чтоб он был всегда вверху вид.области
  var pVmax = rB - sTmax - pH;         // макс. отступ pager-а внутри видимой области (при sTmax)
  var pTcur = sT - pT;
  var pVcur = (pTcur > 0 && pTmax > 0 ? Math.round(pVmax*pTcur/pTmax)-2 : 0);
  var pos = pTcur + pVcur;
  startMovingPagesContainer(pos);
}

function startMovingPagesContainer(pos) {
  pagesContainer.newTopPos = Math.max(pos, 1);
  if (!('curTopPos' in pagesContainer)) pagesContainer.curTopPos = 1;
  if (pagesContainer.newTopPos != pagesContainer.curTopPos) {
    if (pagesContainer.moveIntervalId != null) return;
    if (pagesContainer.moveTimeoutId != null) clearInterval(pagesContainer.moveTimeoutId);
    pagesContainer.moveTimeoutId = setTimeout(stepMovingPagesContainer, 150);
  }
}

function stepMovingPagesContainer() {
  pagesContainer.moveTimeoutId = null;
  var pos = Math.round((pagesContainer.curTopPos + pagesContainer.newTopPos)/2);
  if (Math.abs(pos - pagesContainer.newTopPos) <= 1) pos = pagesContainer.newTopPos;
  pagesContainer.curTopPos = pos;
  pagesContainer.style.paddingTop = pos+'px';
  if (pos != pagesContainer.newTopPos) {
    if (pagesContainer.moveIntervalId == null) {
      pagesContainer.moveIntervalId = setInterval(stepMovingPagesContainer, 50);
    }
  } else if (pagesContainer.moveIntervalId != null) {
    clearInterval(pagesContainer.moveIntervalId);
    pagesContainer.moveIntervalId = null;
  }
}

function resetMovedBlocksPos() {
  reposPagesContainer();
  buttonsPanel.minTopPos = getAbsPos(resultsRight).top+26 - 10;
  if (!buttonsPanel.curTopPos) {
    buttonsPanel.curTopPos = 0;
    buttonsPanel.style.paddingTop = '0px';
  } else {
//  moveButtonsPanel();
  }
}


function moveButtonsPanel() {
  if (!buttonsPanel.minTopPos) return;
  var pos = Math.max(document.body.scrollTop-buttonsPanel.minTopPos, 0);
  if (pos != buttonsPanel.curTopPos) {
    buttonsPanel.newTopPos = pos;
    if (buttonsPanel.moveIntervalId != null) {
      clearInterval(buttonsPanel.moveIntervalId);
      buttonsPanel.moveIntervalId = null;
    }
    if (buttonsPanel.moveTimeoutId != null)
      clearTimeout(buttonsPanel.moveTimeoutId);
    buttonsPanel.moveTimeoutId = setTimeout(startMovingButtonsPanel, 150);
  }
}

function startMovingButtonsPanel() {
  buttonsPanel.moveTimeoutId = null;
  if (buttonsPanel.moveIntervalId == null)
    buttonsPanel.moveIntervalId = setInterval(stepMovingButtonsPanel, 50);
}

function stepMovingButtonsPanel() {
  if (Math.abs(buttonsPanel.curTopPos - buttonsPanel.newTopPos) <= 1)
    buttonsPanel.curTopPos = buttonsPanel.newTopPos
  else
    buttonsPanel.curTopPos = Math.round((buttonsPanel.curTopPos + buttonsPanel.newTopPos)/2);
  buttonsPanel.style.paddingTop = buttonsPanel.curTopPos+'px';
  if (buttonsPanel.curTopPos == buttonsPanel.newTopPos) {
    clearInterval(buttonsPanel.moveIntervalId);
    buttonsPanel.moveIntervalId = null;
  }
}


function initPageBoxes(first, last, soft) {
  pageBoxes.length = 0;
  var t, s, resize = false, pageNum = first, tables = $('pages_inner').getElementsByTagName('TABLE');
  for (var i = 0; i < tables.length; i++) {
    t = tables[i];
    if (t.id.match(/^page\d+$/)) {
      t.pageIdx = pageBoxes.length;
      t.pageNum = pageNum;
      s = getPageFontSize(t.pageIdx);
      t.curSize = (soft && (t.pageIdx in pageBoxSizes) ? pageBoxSizes[t.pageIdx] : s);
      t.newSize = s;
      if (t.curSize != t.newSize) resize = true;
      t.isPrevBtn = false;
      t.isNextBtn = false;
      t.firstCell = t.rows[0].cells[0];
      t.innerTable = t.firstCell.getElementsByTagName('TABLE')[0];
      t.pageLink = t.innerTable.getElementsByTagName('A')[0];
      pageBoxes.push(t);
      if (pageNum == curPage) curPageIdx = t.pageIdx;
      pageNum++;
    }
  }
}

var
  anchorUpdateTimeoutId = null;
  
function pageClicked(pageBox, fromFlash) { 
  if (typeof(pageBox) != 'number') {
    if (pageBox.pageNum == curPage || pageBox.isPrevBtn || pageBox.isNextBtn) return;
    curPage = pageBox.pageNum;
  } else {
    curPage = pageBox;
  }
  curDoc = '';
  curDocSite = '';
  if (!fromFlash) updateAnchor('page');
  else {
    anchorMonitoringDisabled = true;
    if (anchorUpdateTimeoutId != null) clearTimeout(anchorUpdateTimeoutId);
    anchorUpdateTimeoutId = setTimeout(enableAnchorUpdate, 500);  // отдаляем измнение anchor для flash
  }
  if (isIE) markAsVisited('page');
  if (!fromFlash) resetPagesHtml();  // 'soft'
  loadContent();
  return false;
}

function enableAnchorUpdate() {
  anchorUpdateTimeoutId = null;
  anchorMonitoringDisabled = false;
  updateAnchor('page');
}

// вызывается по Ctrl+<-
function showPrevPage() {
  if (viewingNotes) return;
  if (curPage > 0) pageClicked(curPage-1);
}

// вызывается по Ctrl+->
function showNextPage() {
  if (viewingNotes) return;
  if (curPage < pagesNum-1) pageClicked(curPage+1);
}

function scrollPrevPage() {
  if (firstVisPageNum > 0) {
    firstVisPageNum--;
    resetPagesHtml(firstVisPageNum);
  }
}

function scrollNextPage() {
  if (firstVisPageNum < pagesNum-maxVisPageNum) {
    firstVisPageNum++;
    resetPagesHtml(firstVisPageNum);
  }
}




var
  contentLoader = null,
  foundDocs = 0,
  foundSites = 0,
  foundXQLinks = 0;

function loadContent() {
  if (!contentLoader) {
    contentLoader = new RemoteFileLoader('contentLoader');
    contentLoader.onCopyContent = contentLoaded;
  } else if (contentLoader.isBusy) {
    warn('contentLoader request is busy.');
    return;
  }
  updateBtnState('docLoaded = false');
  zoom(snippetBlock, '-');
  zoom(searchResults, '-');
  startMovingPagesContainer(0);
  if (viewingNotes) {
    if (showNotesBtn.isDown) showNotesBtn.setDown(false);
    viewingNotes = false;
    if (selectedRubric != null) selectedRubric.className = 'selected';
  }
  beginLoad('results');
  contentLoader.isBusy = true;
  var url;
  if (curRubric=='abstract')
    {
    url = "/abstract.html?abstract="+abstract_id;
    }
  else
    {
    url = '/?query='+queryEscaped+(curRubric ? '&theme='+curRubric : '')+
                 (curPage ? '&page='+curPage : '')+
                 (groupSites||curSite ? '&part=2'+(curSite != null ? '&site='+curSite+'&full_mode=1' : '') 
                             : '&part=3')+
                 (xquery_id?'&xq='+xquery_id+(foundXQLinks?'&xqlinks='+foundXQLinks:''):'')+
                 (noArticles?'&n=1':'');
    }
  contentLoader.loadInto(url, 'search_results');
  autoUpScroll();
}

function contentLoaded(docDOM, docText, destId) {
  contentLoader.isBusy = false;
  endLoad('results');
  if (viewingNotes) return true;
  searchResults.innerHTML = docText;
  processAdBlocks();
  pagesNum = 0;
  var infoEl = $('content_info');
  if (infoEl) {
    var info = infoEl.innerHTML.split('/');  // size_total/size_groups/pages/xqlinks
    foundDocs = parseInt(info[0]);
    foundSites = parseInt(info[1]);
    pagesNum = parseInt(info[2]);
    foundXQLinks = parseInt(info[3]);
//  if (curRubric == 0) rubricsSizeTotal = foundSites;
  }
  else {
    foundDocs = 1;
    foundSites = 1;
    pagesNum = 0;
    foundXQLinks = 0;
  }    
  if (parseInt(curRubric) && !foundDocs && !curSite)
    {
    curRubric=(abstract_id?'abstract':'^'+curRubric);
    inRubricLabel.style.display = 'none';
    var rubLbl=(abstract_id?$('rubricAbstract'):$('rubric0'));
    if (rubLbl)
        {
        if (catalog_type)
            rubLbl.parentNode.className="ct_selected";
        else
            rubLbl.className="selected";
        }
    loadContent();
    return true;
    }
  resetPages();
  if (pagesNum > 0) showPages();
  searchResults.afterZoom = searchResults_afterZoom;
  zoom(searchResults, '+');
  resetDocLinks();
  if (docToLoad) {
    loadSnippet(docToLoad, 'hist');
    updateAnchor('doc');
    docToLoad = '';
  } else if (docLinks.length > 0) {
    var sour = (curDoc ? 'doc' : 'firstdoc');
    loadSnippet(curDoc || docLinks[0], 'doc',undefined,(curDoc?curDocSite:docLinks[0].siteId));   //!!!!!!!!!!!!!!!!!!!!!!!! #!!!!!!!!!!!!!!!!!!! !!!!!!!!!!!!!!!!!!!!!!!!!!!!!! !!!!!!!!!!!!!!!!!!!!!1
    updateAnchor(sour);
  } else {
    curDoc = '';
    curDocSite = '';
  }
  setupSearchHotKeys();
  if (firstcall) 
    firstcall=0;
  else {
    if(typeof(window.yandex_metrika_ajax_callback) != "undefined")
      window.yandex_metrika_ajax_callback();
    if(typeof(window.google_analytics_ajax_callback) != "undefined")
      window.google_analytics_ajax_callback();
    if(typeof(seoRateAjax) != "undefined")
      seoRateAjax();
  }
  if(isIE && ieVersion<9) img_in_res_fix();
  return true;
}

var
  documentWriteDestBlock,
  documentWriteScriptBlock;

function processAdBlocks() {
  if (document.write != documentWrite) {
    document.write = documentWrite;
    document.writeln = documentWriteln;
  }
  documentWriteScriptBlock = null;
  for (var i = 0; i <= 3; i++) {
    var block = $('ad'+i);
    if (block) {
      documentWriteDestBlock = block;
//    processBlockHTML(block.innerHTML);
      processBlockScripts(block);
    }
  }
  documentWriteDestBlock = null;
}

function processBlockScripts(block) {
  var scr = block.getElementsByTagName('SCRIPT');
  var l = scr.length;
  if (!l) return;
  var scripts = new Array(l);
  for (var i = 0; i < l; i++) scripts[i] = scr[i];
  for (var i = 0; i < l; i++) {
    var script = scripts[i];
    if (script.src) {
      if (documentWriteDestBlock) documentWriteScriptBlock = documentWriteDestBlock;
      var script2 = document.createElement('SCRIPT');
      block.appendChild(script2);
      script2.src = script.src;
    } else {
      var code = script.text;
      if (window.execScript) 
        window.execScript(code);
      else
        eval.call(window, code);
    }
  }
}

function processBlockHTML(html) {
  var scripts = html.match(/<script(.|\s)*?>(.|\s)*?<\/script>/ig);
  if (!scripts) return;
  for (var i = 0, l = scripts.length; i < l; i++) {
    var scr = scripts[i];
    var s = scr.match(/<script((.|\s)*?)>/i);
    if (s && s[1]) {
      var t = s[1].replace(/\s*=\s*/g, '=').split(/\s+/);
      var src = false;
      for (var j = 0, lj = t.length; j < lj; j++) {
        if (t[j].match(/^src=("|')?(.*?)("|')?$/i)) { //'
          if (s = trim(RegExp.$2)) {
            if (documentWriteDestBlock) documentWriteScriptBlock = documentWriteDestBlock;
            var script = document.createElement('SCRIPT');
            document.body.appendChild(script);
            script.src = s;
            src = true;
            break;
          }
        }
      }
      if (src) continue;
    }
    if (scr.match(/^<script(.|\s)*?>((.|\s)*?)<\/script>$/i) && (s = trim(RegExp.$2))) {
      if (window.execScript) 
        window.execScript(s);
      else
        eval.call(window, s);
    }
  }
}

function documentWrite(s) {
  var block = (documentWriteDestBlock || documentWriteScriptBlock);
  if (block) block.innerHTML += s;
  processBlockHTML(s);
}

function documentWriteln(s) {
  documentWrite(s+'\n');
}

var
  copyBegunIntervalId,
  copyBegunTryCount;

function tryCopyBegunBanners() {
  if (!copyBegunIntervalId) {
    copyBegunIntervalId = setInterval(copyBegunBanners, 500);
  }
  copyBegunTryCount = 20;
}

function copyBegunBanners() {
  if (!window.begunBanners) {
    if (--copyBegunTryCount <= 0) {
      clearInterval(copyBegunIntervalId);
      copyBegunIntervalId = null;
    }
    return;
  }
  clearInterval(copyBegunIntervalId);
  copyBegunIntervalId = null;
  var n = 0, bl = begunBanners.length;
  for (var i = 0, sl = begun_spans.length; (i < sl) && (n < bl); i++) {
    var sp = begun_spans[i], s = '';
    for (var j = 0, l = sp.limit; j < l; j++) {
      if (n >= bl) break;
      var b = begunBanners[n];
      s += '<div class="ad_title"><a href="'+b[2]+'" target="_blank">'+b[0]+'</a></div><div class="ad_text"><a href="'+b[2]+'" target="_blank">'+b[1]+'</a></div><div class="ad_site"><a href="'+b[2]+'" target="_blank">'+b[4]+'</a></div>';
      n++;
    }
    var block = document.getElementById(sp.span_id);
    if (block) {
      block.innerHTML = s;
      block.style.display = 'block';
    }
  }
}


function searchResults_afterZoom() {
  this.afterZoom = null;
  $('footer').style.visibility = 'visible';
}

var
  searchHotKeysInstalled = false;

function setupSearchHotKeys() {
  if (!searchHotKeysInstalled) {
    setupHotKey('Ctrl+Left', showPrevPage);
    setupHotKey('Ctrl+Right', showNextPage);
    setupHotKey('Ctrl+Up', showPrevDoc);
    setupHotKey('Ctrl+Down', showNextDoc);
    searchHotKeysInstalled = true;
  }
}

var
  moreDocsLoader = null;

function loadMoreDocs(el, siteId, plain) {
  if (el.style.cursor == 'wait') {
    alert('busy');
    return;
  }
  var docId = el.parentNode.id.match(/^more(.*)/)[1];
  var docsCont = $('docs'+docId);
  if (!docsCont.sitePages) docsCont.sitePages = 1; else docsCont.sitePages++;
  if (!moreDocsLoader) {
    moreDocsLoader = new RemoteFileLoader('moreDocsLoader');
    moreDocsLoader.showRequestIndicator = true;
    moreDocsLoader.onCopyContent = moreDocsLoaded;
  }
  var url = '/?query='+queryEscaped +
             '&site='+siteId + '&page='+docsCont.sitePages + '&show=3' + '&part=2' + (plain?'&plain=1':'');
  moreDocsLoader.loadInto(url, docId);
  el.style.cursor = 'wait';
}

function moreDocsLoaded(doc, text, docId) {
  var moreEl = $('more'+docId);
  var el = moreEl.getElementsByTagName('SPAN')[0];
  el.style.cursor = 'pointer';
  var docsCont = $('docs'+docId);
  var div = document.createElement('DIV');
  div.style.display = 'none';
  div.innerHTML = text;
  moreEl.parentNode.insertBefore(div, moreEl);
  resetDocLinks();
  zoom(div, '+');
  var docsNum = parseInt(docsCont.innerText || docsCont.textContent) || 0;
  docsNum -= (docsCont.sitePages+1)*3;
  if (docsNum > 0) el.innerHTML = 'Ещё с сайта ('+docsNum+')';
  else el.style.display = 'none';
  if(isIE && ieVersion<9) img_in_res_fix();
  return true;
}

function resetDocLinks() {
  docLinks.length = 0;
  var a, x, links = searchResults.getElementsByTagName('A');
  for (var i = 0; i < links.length; i++) {
    a = links[i];
    if (a.id != '' && a.id.charAt(0) == 'a') {               // Только какой-то мусорный docId
      if (!('docId' in a)) {
        if (isIE) a.href += '#r='+curRubric+';p='+curPage;
        a.docId = a.id.substr(1);
        a.docURL = a.href.substr(a.href.indexOf('?')+1);
      }
      docLinks.push(a);
    }else
    if (a.id != '' && a.id.charAt(0) == 's') {               // siteId и какой-то мусорный docId
      if (!('docId' in a)) {
        if (isIE) a.href += '#r='+curRubric+';p='+curPage;
        a.siteId = a.id.substring(1,a.id.indexOf('t'));
        a.docId = a.id.substr(a.id.indexOf('t')+1);
        a.docURL = a.href.substr(a.href.indexOf('?')+1);
//        alert("siteId="+a.siteId+" docId="+a.docId+" docURL="+a.docURL);
      }
      docLinks.push(a);
    }else 
    if (a.id != '' && a.id.charAt(0) == 'r') {               // realDocId + siteId и какой-то мусорный docId
      if (!('docId' in a)) {
        if (isIE) a.href += '#r='+curRubric+';p='+curPage;
        a.realDocId = a.id.substring(1,a.id.indexOf('s'));
        a.siteId = a.id.substring(a.id.indexOf('s')+1,a.id.indexOf('t'));
        a.docId = a.id.substr(a.id.indexOf('t')+1);
        a.docURL = a.href.substr(a.href.indexOf('?')+1);
//        alert("siteId="+a.siteId+" docId="+a.docId+" docURL="+a.docURL);
      }
      docLinks.push(a);
    } 
  }
}

//-- Goto Prev / Next Doc -----------------------------

function showPrevDoc() {
  if (prevDocBtn.isEnabled) {
    var doc = getDocSibling('prev');
    if (doc) {
      loadSnippet(doc, 'doc',undefined,doc.siteId);
      updateAnchor('doc');
    }
  }
}

function showNextDoc() {
  if (nextDocBtn.isEnabled) {
    var doc = getDocSibling('next');
    if (doc) {
      loadSnippet(doc, 'doc',undefined,doc.siteId);
      updateAnchor('doc');
    }
  }
}

function getDocSibling(what) {
  var i, j, d;
  for (i = 0; i < docLinks.length; i++) {
    if (docLinks[i] == lastClickedLink) {
      if (what == 'next') {
        for (j = i+1; j < docLinks.length; j++) {
          d = docLinks[j];
          if (d.offsetHeight > 0) return d;
        }
      } else {
        for (j = i-1; j >= 0; j--) {
          d = docLinks[j];
          if (d.offsetHeight > 0) return d;
        }
      }
      break;
    }
  }
  return '';
}

//-- Notes ------------------------------------------------

var
  addNoteRequest = null;

function addNote() {
  if ((addNoteRequest && addNoteRequest.isBusy) || viewingNotes) return false;
  if (!curDoc) {
    alert('Нечего добавлять.\nCперва кликните на документ.');
    return false;
  }
  if (!addNoteRequest) {
    addNoteRequest = new RemoteFileLoader('addNoteRequest');
    addNoteRequest.onCopyContent = addNoteRequestComplete;
  }
  addNoteBtn.setInProcess(true);
  beginLoad();
  addNoteRequest.isBusy = true;
  addNoteRequest.loadInto('/notepad.html?add='+curDoc+'&query='+queryEscaped, 'add_note');
  return true;
}

function addNoteRequestComplete(docDOM, docText, destId) {
  addNoteRequest.isBusy = false;
  endLoad();
  addNoteBtn.setInProcess(false);
  var infoSentMsg = $('info_sent_msg');
  if (infoSentMsg) {
    infoSentMsg.innerHTML = 'Закладка добавлена.';
    infoSentMsg.afterZoom = msgShownEvent;
    zoom(infoSentMsg, '+');
  }
  return true;
}

function msgShownEvent() {
  this.afterZoom = null;
  setTimeout('zoom("'+this.id+'", "-")', 5000);
}

var
  notesLoader = null,
  notesCount = 0;

function toggleShowNotes() {
  if (showNotesBtn.isDown) showNotes(); else hideNotes();
}

function showNotes() {
  if (!notesLoader) {
    notesLoader = new RemoteFileLoader('notesLoader');
    notesLoader.onCopyContent = notesLoaded;
  } else if (notesLoader.isBusy) {
    warn('notesLoader request is busy.');
    return;
  }
  viewingNotes = true;
  if (!showNotesBtn.isDown) showNotesBtn.setDown(true);
  if (selectedRubric != null) selectedRubric.className = 'visited';
  zoom(searchResults, '-');
  startMovingPagesContainer(0);
  hidePages();
  closeOpinionForm();
  if (showCommentsBtn.isDown) showCommentsBtn.setDown(false);
  updateBtnState('docLoaded = false');
  zoom(snippetBlock, '-');
  if (loadingCount['snippet'] > 0) endLoad('snippet');
  beginLoad('results');
  notesLoader.isBusy = true;
  notesLoader.loadInto('/notepad.html', 'search_results');
}

function notesLoaded(docDOM, docText, destId) {
  notesLoader.isBusy = false;
  endLoad('results');
  if (!viewingNotes) return true;
  searchResults.innerHTML = docText;
  updateUnixTimeBlocks(searchResults, 'SPAN', 'unix_time');
  pagesNum = 0;
  var infoEl = $('content_info');
  if (infoEl) {
    var info = infoEl.innerHTML;  // notes_count
    notesCount = parseInt(info) || 0;
    pagesNum = (notesCount > 0 ? 1 : 0);
    resetPages();
    if (pagesNum > 0) showPages();
  }
  zoom(searchResults, '+');
  resetDocLinks();
  return true;
}

function hideNotes() {
  hidePages();
  loadContent();
}

var
  delNoteRequest = null;
  
function deleteNote(noteId) {
  if (delNoteRequest && delNoteRequest.isBusy) {
    warn('delNoteRequest request is busy.');
    return;
  }
  var noteBox = $('note'+noteId);
  if (!noteBox) {
    alert('Закладка #'+noteId+' не найдена.');
    return;
  }
  noteBox.afterZoom = noteBox_afterZoom;
  zoom(noteBox, '-');
  if (!delNoteRequest) {
    delNoteRequest = new RemoteFileLoader('delNoteRequest');
    delNoteRequest.onCopyContent = delNoteRequestComplete;
  }
  beginLoad();
  delNoteRequest.isBusy = true;
  delNoteRequest.loadInto('/notepad.html?remove='+noteId, 'remove_note');
}

function noteBox_afterZoom() {
  this.afterZoom = null;
  this.parentNode.removeChild(this);
  notesCount--;
  if (notesCount > 0) recountNotes(); else hidePages();
}

function delNoteRequestComplete() {
  delNoteRequest.isBusy = false;
  endLoad();
  return true;
}

function recountNotes() {
  var i, n = 0, d, divs = searchResults.getElementsByTagName('DIV');
  for (i = 0; i < divs.length; i++) {
    d = divs[i];
    if (d.className == 'num') d.getElementsByTagName('SPAN')[0].innerHTML = (++n)+'.';
  }
}


function toggleOpinionForm() {
  if (addCommentBtn.isDown) $('opinion_txt').value = '';
  zoom(opinionFormContainer, (addCommentBtn.isDown ? '+' : '-'));
}

function closeOpinionForm() {
  addCommentBtn.setDown(false); 
  zoom(opinionFormContainer, '-');
}

var
  commentsLoader = null;

function sendOpinion(form, event) {
  if (!commentsLoader) {
    commentsLoader = new RemoteFileLoader('commentsLoader');
  } else if (commentsLoader.isBusy) {
    warn('commentsLoader request is busy.');
    cancelEvent(event);
    return false;
  }
  closeOpinionForm();
  updateBtnState('docLoaded = false');
  zoom(snippetBlock, '-');
  incDocCommentCount();
  $('opinion_doc_id').value = curDoc;
  $('opinion_site_id').value = curDocSite;
  beginLoad('snippet');
  commentsLoader.onload = opinionSent;
  commentsLoader.isBusy = true;
  commentsLoader.submitInto(form, 'snippet_container', event);
}

function opinionSent() {
  commentsLoader.isBusy = false;
  endLoad('snippet');
  loadSnippet(curDoc || docLinks[0], 'hist', true, (curDoc?curDocSite:docLinks[0].siteId));
}

function toggleShowComments() {
  loadSnippet(curDoc || docLinks[0], 'hist', showCommentsBtn.isDown, (curDoc?curDocSite:docLinks[0].siteId));
}

function showCommentsDoc(docId) {
  if (curDoc != docId || !showCommentsBtn.isDown) loadSnippet(docId, 'hist', true);
}

function sendKoo() {
  sendMark('+');
}

function sendKiu() {
  sendMark('-');
}

function sendMark(mark) {
  (mark == '+' ? kiuResultBtn : kooResultBtn).setEnabled(false);
  (mark == '+' ? kooResultBtn : kiuResultBtn).setInProcess(true);
  setTimeout(markSent, 2000);
}

function markSent() {
  (kooResultBtn.inProcess ? kooResultBtn : kiuResultBtn).setInProcess(false);
  (kooResultBtn.isEnabled ? kiuResultBtn : kooResultBtn).setEnabled(true);
  var infoSentMsg = $('info_sent_msg');
  if (infoSentMsg) {
    infoSentMsg.innerHTML = 'Ваша оценка отослана. Спасибо.';
    infoSentMsg.afterZoom = msgShownEvent;
    zoom(infoSentMsg, '+');
  }
}


var
  loadingCount = {};

function beginLoad(what) {
  if (!what) return;
  if (loadingCount[what]) loadingCount[what]++;
  else {
    loadingCount[what] = 1;
    var el = $('loader_'+what);
    if (el) el.style.display = 'block';
  }
}

function endLoad(what) {
  if (!what) return;
  if (loadingCount[what] > 0) {
    loadingCount[what]--;
    if (loadingCount[what] == 0) {
      var el = $('loader_'+what);
      if (el) el.style.display = 'none';
    }
  }
}

var linkVisitedCache = {};

function isLinkVisited(url) {
  var res = linkVisitedCache[url];
  if (res) return true;
  var testLink = document.createElement('A');
  testLink.href = url;
  testLink.innerHTML = 'A';
  testLink.style.position = 'absolute';
  testLink.style.top = '0px';
  testLink.style.left = '0px';
  document.body.appendChild(testLink);
  var w1 = testLink.offsetHeight;
  testLink.className = 'test_visited';
  var w2 = testLink.offsetHeight;
  document.body.removeChild(testLink);
  var res = (w1 != w2);
  if (res) linkVisitedCache[url] = true;
//log3('<a href="' + url + '">' + url + '</a> - ' + res);
  return res;
}




function log(s) {
//if (logBlock) logBlock.innerHTML += s+'<br>';
}

function log2(s) {
//if (logBlock) logBlock.innerHTML += s+'<br>';
}

function log3(s) {
  if (logBlock) logBlock.innerHTML += s+'<br>';
}

if (window.htmlLoaded) init(); else 
  if (window.htmlLoadedSub) subinit(); else searchJsLoaded = true;

var timermarquee=null,
    amarquee=null;
    stoptimertimer=null;

function startTimer(){
  amarquee=document.getElementById('amarquee');
  if (stoptimertimer != null ){
    clearTimeout(stoptimertimer);
    stoptimertimer=null;
  } else {
    if (timermarquee != null)
      return;
    amarquee.style.marginLeft='0px';
    if(amarquee.parentNode.offsetWidth>amarquee.offsetWidth) 
      return;
    timermarquee = window.setTimeout(function(){nextstep();}, 700);
  }
}
function nextstep(){
  ml=amarquee.style.marginLeft;
  ml=ml.substr(0,ml.length-2);
  ml=-1+parseInt(ml);
  amarquee.style.marginLeft=''+ml+'px';
  if((amarquee.offsetWidth+ml)<amarquee.parentNode.offsetWidth)
    timermarquee = window.setTimeout(function(){nextstep2();}, 140);
  else
    timermarquee = window.setTimeout(function(){nextstep();}, 35);
}
function nextstep2(){
  ml=amarquee.style.marginLeft;
  ml=ml.substr(0,ml.length-2);
  ml=+1+parseInt(ml);
  amarquee.style.marginLeft=''+ml+'px';
  if(ml>=0)
    timermarquee = window.setTimeout(function(){nextstep();}, 280);
  else
    timermarquee = window.setTimeout(function(){nextstep2();}, 35);
}
function stopTimer(){
  if (timermarquee == null)
    return;
  if ( stoptimertimer == null )
    stoptimertimer = window.setTimeout(function(){stopTimer();}, 200);
  else {
    clearTimeout(timermarquee);
    amarquee.style.marginLeft='0px';
    timermarquee=null;
    stoptimertimer=null;
  }
}

if(typeof(document.getElementsByClassName) == 'undefined')
  document.getElementsByClassName = function(clsName,tagName) {
    var retVal = [];
    if ( typeof(tagName) == 'undefined' ) tagName="*";
    var elements = document.getElementsByTagName(tagName);
    for (var i = 0, elen = elements.length; i < elen; i++) {
        if (elements[i].className.indexOf(" ") >= 0) {
            var classes = elements[i].className.split(" ");
            for (var j = 0, slen = classes.length; j < slen; j++) {
                if (classes[j] == clsName) {
                    retVal.push(elements[i]);
                    break;
                }
            }
        } else if (elements[i].className == clsName) retVal.push(elements[i]);
    }
    return retVal;
}

function ie_get_nextsibling(n)
{
  x=n.nextSibling;
  while (x!==null&&x.nodeType!=1)
    x=x.nextSibling;
  return x;
}

function img_in_res_fix(){
  if(isIE && ieVersion<9){
    var img_in_res=document.getElementsByClassName('img_in_res','div');
    for (var i=0;i<img_in_res.length;i++){
      img_in_res[i].className='img_in_res_ie';
      img_in_res[i].attachEvent('onmouseover',over_mouse);
      img_in_res[i].attachEvent('onmouseout',out_mouse);
    }
  }
}

/*@cc_on
(function(f){
window.setTimeout = f(window.setTimeout);
window.setInterval = f(window.setInterval);
})(function(f){
return function(c,t){
var a = Array.prototype.slice.call(arguments,2);
if(typeof c != "function")
c = new Function(c);
return f(function(){
c.apply(this, a)
}, t)
}
});
@*/

function over_mouse(){
  var obj = (typeof event == 'undefined') ? this : event.srcElement;
  for(var i=0;i<4&&obj.className!='img_in_res_ie'&&obj.className!='img_in_res_ie_out'&&obj.className!='img_in_res_ie_hover';i++)
    obj=obj.parentNode;
  if(obj.className=='img_in_res_ie'||obj.className=='img_in_res_ie_out')obj.className='img_in_res_ie_hover';
    if(obj.getElementsByTagName('span').length==0){
      var imgs=obj.getElementsByTagName('img');
      for(var j=0;j<imgs.length;j++){
        if(imgs[j].parentNode.className!='img_in_res_ie_hover'&&imgs[j].parentNode.className!='img_in_res_ie'&&imgs[j].parentNode.className!='img_in_res_ie_out'){
          var el=document.createElement('span');
          el.style.position='absolute';
          var vrp=imgs[j].clientWidth;
          if(vrp==0) vrp=imgs[j].width;
          el.style.marginLeft=''+(3-vrp)+'px';
          el.style.width=''+vrp+'px';
          el.style.marginTop='15px';
          el.style.display='block';
          el.style.background='black';
          el.style.border='1px solid #777';
          vrp=imgs[j].clientHeight;
          if(vrp==0)vrp=imgs[j].height;
          el.style.height=''+vrp+'px';
          el.style.overflow='hidden';
          el.style.filter='progid:DXImageTransform.Microsoft.Alpha(opacity=30);'
          el.style.zIndex='1';
          imgs[j].parentNode.insertBefore(el,ie_get_nextsibling(imgs[j]));
          imgs[j].style.position='relative';
          imgs[j].style.zIndex='2';
        }
      }
    }
}

function out_mouse(){
  var obj = (typeof event == 'undefined') ? this : event.srcElement;
  for(var i=0;i<4&&obj.className!='img_in_res_ie'&&obj.className!='img_in_res_ie_out'&&obj.className!='img_in_res_ie_hover';i++)
    obj=obj.parentNode;
  if(obj.className=='img_in_res_ie_hover'){
    obj.className='img_in_res_ie_out';
    window.setTimeout(out2_mouse,10,obj);
  }
}

function out2_mouse(obj){
  if(obj.className=='img_in_res_ie_out')
    obj.className='img_in_res_ie';
}

function autoUpScroll(){
  window.scroll(0,0);
}