var divIndex;
var originalInnerHTML = null;
var skipScrollTime = 500;
var Index_XmlHttpRequest = null;
var previousText = "";
var bCanScroll = true;
var bSearchForString = false;
var estimateLowBorder = 0;
var estimateHighwBorder = 0;
var lastScrollTop = 0;
var lastPosition = 0;
var lastDiv = null;
var bNeedNextTimer = false;
var bTimerSet = false;
var lastHighlitedRow = null;
var bNeedScrollToInitialPos = true;

function OnResize()
{
  if (!divIndex)
    return;

  var divWidth;
  var divHeight;
  if (isNetscape || isOpera) {
    divWidth = document.body.clientWidth - 28;
    divHeight = document.body.clientHeight - 90;
  }
  else {
    divWidth = document.body.clientWidth-25;
    divHeight = document.body.clientHeight-60;
  }

  if (divWidth>0 && divHeight>0) {
    divIndex.style.width = divWidth+"px";
    divIndex.style.height = divHeight+"px";
  }
  else if (isNetscape || isOpera) {
    divIndex.style.width = "0px";
    divIndex.style.height = "0px";
  }
}

function ActivateIndexInput() {
  var textBox = document.getElementById("tbSearchString");
  if (textBox != null)
    try {
    textBox.focus();
    if (isIE) {
      if (textBox.createTextRange!=null) {
        var r = textBox.createTextRange();
        r.collapse(false);
        r.select();
      }
    }
    else {
      if (textBox.selectionStart!=null) {
        var end = textBox.value.length;
        textBox.setSelectionRange(end, end);
        textBox.focus();
      }
    }
  }
  catch (e) { }
}

function Index_OnLoad()
{
  window.onresize = OnResize;
  Index_LoadFromCookie();
  divIndex = document.getElementById("divIndex");
  Index_LoadIndexChunk(document.getElementById("tbSearchString").value, null);
  OnResize();
}

// Adds extra "Loading..." etries into index.
function FillBorders()
{
  try {
    table = document.getElementById("indexTable");
    for( i = 0; i < maxAdditionalRows; i++ )
      table.insertRow().insertCell().innerHTML = "<a href='javascript:void(0)'>"+loadingMessage+"</a>";
   }
  catch(e) {}
}

function _OnKeyDown(e)
{
  if(e.keyCode==13) {
    util.CancelEvent(e);
    ShowTopic(e);
  }
}

function _OnKeyUp(searchText)
{
  if (searchText!=previousText)
    Index_LoadIndexChunk(searchText, null);
  previousText = searchText;
}

function SetIndexValue(searchText)
{
  if (searchText!=previousText) {
    document.getElementById("tbSearchString").value = searchText;
    Index_LoadIndexChunk(searchText, null, null, true);
    previousText = searchText;
  }
}

// Sets position on the index entry starting with <searchText>.
function OnTextChange(searchText)
{
  if (window.event) {
    if(window.event.propertyName=="value")
      Index_LoadIndexChunk(searchText, null);
  }
  else
    Index_LoadIndexChunk(searchText, null);
}


function ScrollToLast()
{
  Index_DoScroll(lastDiv, lastPosition);
  if (bNeedNextTimer) {
    bNeedNextTimer = false;
    window.setTimeout("ScrollToLast()", skipScrollTime);
  }
  else
    bTimerSet = false;
  bCanScroll = true;
}

// Sets scroll position.
function OnScroll(div)
{
  var _scrollTop = div.scrollTop;
  var _scrollHeight = div.scrollHeight-div.clientHeight;
  table = document.getElementById("indexTable");
  var rowCount = table.rows.length;

  var rowHeight = table.rows[1].scrollHeight;
  // Counts sizes of index chunk currently visible
  var chunkTop = table.rows[1].offsetTop;
  var chunkBottom = table.rows[rowCount-1].offsetTop;

  var position = _scrollTop / _scrollHeight;

  // Shows "Loading" link if we are moving up
  if (_scrollTop<chunkTop && _scrollTop>rowHeight*2) {
    var cell = table.rows[0].cells[0];
    cell.style.verticalAlign="top";
    cell.innerHTML = "<a href='javascript:LoadChunk()' style='position:relative;top:"+
    Math.floor((_scrollTop+ Math.min(chunkTop,_scrollTop+div.clientHeight) - rowHeight)/2)+
    "px'>"+loadingMessage+"</a>";
  }

  // Shows "Loading" link if we are moving down
  if (_scrollTop+div.clientHeight>chunkBottom && _scrollTop+div.clientHeight<_scrollHeight-rowHeight*2) {
    var cell = table.rows[rowCount-1].cells[0];
    cell.style.verticalAlign="top";
    cell.innerHTML = "<a href='javascript:LoadChunk()' style='position:relative;top:"+
    (Math.floor( (_scrollTop+div.clientHeight + Math.max(_scrollTop,chunkBottom) - rowHeight)/2)- chunkBottom)+
    "px'>"+loadingMessage+"</a>";
  }


  if (bSearchForString)
    return;
  if (_scrollTop<chunkTop || (_scrollTop>chunkBottom-div.clientHeight-rowHeight && _scrollTop<_scrollHeight)) {
    if (estimateLowBorder<_scrollTop && _scrollTop<estimateHighwBorder)
      return;
      
    var estimateSize = chunkBottom - chunkTop;
    estimateLowBorder = _scrollTop - estimateSize/2 + div.clientHeight;
    estimateHighwBorder = _scrollTop + estimateSize/2 - div.clientHeight;

    lastScrollTop = _scrollTop;
    lastPosition = position;
    lastDiv = div;
    if (!bCanScroll) {
      if (!bTimerSet)
        window.setTimeout("ScrollToLast()", skipScrollTime);
      else
        bNeedNextTimer = true;
      bTimerSet = true;
      return;
    }
    bCanScroll = false;
    Index_DoScroll(div, lastPosition);
  }
}

function Index_DoScroll(div, position)
{
  Index_LoadIndexChunk(null, position);
}

// Fill index with data
function Index_Internal_OnResponse(s)
{
  bCanScroll = false;
  table = document.getElementById("indexTable");
  // Microsoft's bug
  if (isNetscape)
    table.innerHTML = s;
  else {
    table.outerHTML = '<table id="indexTable">' + s + '</table>'; 
    table = document.getElementById("indexTable");
  }

  var infoRow = table.rows[1];
  var firstRow = null;
  var searchForString = false;
  var openItem = false;
  if (infoRow!=null) {
    firstRow = document.getElementById(infoRow.getAttribute("activeItem"));
    searchForString = infoRow.getAttribute("searchForString")=="1";
  }

  var div = document.getElementById("divIndex");
  if (firstRow!=null) {
    if (!bTimerSet)
      div.scrollTop = firstRow.offsetTop+table.offsetTop;
    if (bNeedScrollToInitialPos)
      document.body.setAttribute("rowToScroll", firstRow.id);
    if (lastHighlitedRow != null)
      lastHighlitedRow = "";
    if (searchForString) {
      firstRow.style.backgroundColor="silver";
      lastHighlitedRow = firstRow;
    }
  }
  var searchLink = document.getElementById("_searchLink");
  if (searchLink!=null && searchLink.getAttribute("openItem") == "1")
    ShowTopic();
  bCanScroll = true;
}

// Posts load extra data request to server
function Index_LoadIndexChunk(sRequest, nPosition, nHeight, directLink)
{
  var url = "IndexActionServer.aspx";
  if (sRequest!=null) {
    Index_SaveToCookie();
    url = url + "?a="+encodeURIComponent(sRequest)+"&h="+nHeight;
  }
  else
    url = url + "?p="+nPosition+"&h="+nHeight;
  if (directLink)
    url = url+"&d=1";

  d = new Date();
  url += "&t=" + d.getUTCMilliseconds();

  if (Index_XmlHttpRequest==null)
    Index_XmlHttpRequest = util.CreateXmlHttpRequest();
  else
    Index_XmlHttpRequest.abort();
  Index_XmlHttpRequest.open("GET", url, true);
  Index_XmlHttpRequest.onreadystatechange = function() {
    if (Index_XmlHttpRequest.readyState==4 && Index_XmlHttpRequest.responseText)
      Index_Internal_OnResponse(Index_XmlHttpRequest.responseText);
  }
  Index_XmlHttpRequest.send(null);
}

function OnContentLoaded()
{
}

function S(link, e)
{
  if (e!=null)
    util.CancelEvent(e);
  Index_ShowPopup(link, e);
}

function Index_ShowPopup(link, e)
{
  var s = link.innerHTML;
  var si = s.indexOf("<!--");
  var ei = s.lastIndexOf("-->");
  sInnerData = s.substring(si+"<!--".length, ei);

  indexPopupDiv   = parent.document.getElementById("divIndexPopup");
  indexPopupTable = parent.document.getElementById("tIndexPopup");
  if (isNetscape)
    indexPopupTable.innerHTML = sInnerData;
  else {
    indexPopupTable.outerHTML = '<table id="tIndexPopup" style="width:auto;">' + sInnerData + '</table>';
    indexPopupTable = parent.document.getElementById("tIndexPopup");
  }
  var node = window.frameElement;
  var top = 0;
  while (node.parentNode!=null) {
    top+=node.offsetTop;
    node=node.parentNode;
  }

  var parentHeight = parent.document.body.clientHeight;  
  var popupHeight  = 150;
  indexPopupDiv.style.display = "block";
  if (isNetscape) {
    var calculatedPos = (e==null ? 32 : e.pageY) + top/2;
    indexPopupDiv.style.top = (calculatedPos + popupHeight) > parentHeight ? calculatedPos - popupHeight : calculatedPos;
    indexPopupDiv.style.left = e==null ? 32 : e.pageX;
    if (e!=null)
      e.stopPropagation();
  }
  else {
    var calculatedPos = (e==null ? 32 : e.y) + top/2;
    indexPopupDiv.style.top = (calculatedPos + popupHeight) > parentHeight ? calculatedPos - popupHeight : calculatedPos;
    indexPopupDiv.style.left = e==null ? 32 : e.x;
    if (e!=null)
      e.cancelBubble=true;
  }

  var child = indexPopupTable.firstChild;
  while (child.tagName!="A")
    child = child.firstChild;
  child.focus();
}

function ShowTopic(e)
{
  if (e!=null)
    util.CancelEvent(e);
  var searchLink = document.getElementById("_searchLink");
  if (searchLink) {
    if (searchLink.getAttribute("multiple") == "1") {
      Index_ShowPopup(searchLink);
    }
    else {
      var content = parent.GetContentFrame();
      content.contentWindow.location.replace(searchLink.href);
    }
  }
}

function Index_ClosePopups()
{
  indexPopupDiv = parent.document.getElementById("divIndexPopup");
  indexPopupDiv.style.display = "none";
}

function Index_SaveToCookie()
{
  if (window.navigator.cookieEnabled) {
    var cookieDate = new Date();
    cookieDate.setFullYear(cookieDate.getFullYear() + 1);
    document.cookie = "searchKeyword="+document.getElementById("tbSearchString").value+";expires="+cookieDate.toGMTString();
  }
}

function Index_LoadFromCookie()
{
  if (!window.navigator.cookieEnabled)
    return;
    
  var cookie = document.cookie;
  var i = cookie.indexOf("searchKeyword=");
  if (i!=-1) {
    var endIndex = cookie.indexOf(";", i+14);
    if (endIndex == -1){
      document.getElementById("tbSearchString").value = cookie.substring(i+14);
    }
    else {
      document.getElementById("tbSearchString").value = cookie.substring(i+14, endIndex);
    }
  }
}

function Index_Refresh()
{
  Index_LoadIndexChunk(document.getElementById("tbSearchString").value, null);
}

