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 = document.body.clientWidth-25;
  divIndex.style.width = (divWidth>0) ? divWidth+"px" : "0px";
  
  var divHeight = document.body.clientHeight-60;
  divIndex.style.height = (divHeight>0) ? divHeight+"px" : "0px";
}
function Index_OnLoad()
{
  window.onresize = OnResize;
  Index_LoadFromCookie();
  divIndex = document.getElementById("divIndex");
  if (!isNetscape) {
    Index_LoadIndexChunk(document.all("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)'>Loading...</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;
}

// 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; 
  table = document.getElementById("indexTable");
  var rowCount = table.rows.length
  if( rowCount == 0)
  {
     alert(rowCount);
  }
  
  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 / div.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'>Loading</a>";
  }

  // Shows "Loading" link if we are moving down
  if( _scrollTop + div.clientHeight > chunkBottom && _scrollTop + div.clientHeight < div.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'>Loading</a>";
  }


  if( bSearchForString )
    return;
  if( _scrollTop < chunkTop - rowHeight*2
     || _scrollTop > chunkBottom - div.clientHeight - rowHeight )
  {
    if( estimateLowBorder < _scrollTop && _scrollTop < estimateHighwBorder)
    {
      return;
    }

    var estimateSize = chunkBottom - chunkTop;
    estimateLowBorder = _scrollTop - estimateSize/2;
    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)
{
  // alert(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;
  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 );
    }
    if (lastHighlitedRow != null)
      lastHighlitedRow = "";
    if( searchForString ) {
      firstRow.style.backgroundColor="silver";
      lastHighlitedRow = firstRow;
    }
  }
  bCanScroll = true;
}

// Posts load extra data request to server
function Index_LoadIndexChunk(sRequest, nPosition, nHeight)
{
  var url = appPath + "/IndexActionServer.aspx";
  if (sRequest != null) {
    Index_SaveToCookie();
    url = url + "?a="+ encodeURI(sRequest) + "&h=" + nHeight;
  }
  else
    url = url + "?p="+nPosition + "&h=" + nHeight;
  
  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)
{
    Index_ShowPopup(link, e);
}

function Index_ShowPopup(link, e)
{
  if (e==null)
    return;
  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">' + 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.pageY + top/2;
    indexPopupDiv.style.top = (calculatedPos + popupHeight) > parentHeight ? calculatedPos - popupHeight : calculatedPos;
    indexPopupDiv.style.left = e.pageX;
    e.stopPropagation();
  } else {
    var calculatedPos = e.y + top/2;
    indexPopupDiv.style.top = (calculatedPos + popupHeight) > parentHeight ? calculatedPos - popupHeight : calculatedPos;
    indexPopupDiv.style.left = e.x;
    e.cancelBubble=true;
  }

  var child = indexPopupTable.firstChild;
  while( child.tagName != "A" ) {
      child = child.firstChild;
  }
  child.focus();

  indexPopupDiv.setAttribute("sender", link.id);
}

function ShowTopic(e)
{
  util.CancelEvent(e);
  searchLink = document.getElementById("_searchLink");
  if( searchLink )  {
    var content = top.GetContentFrame();
    content.contentWindow.location = 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(2010,0,1);
    document.cookie = "searchKeyword="+document.all("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);
}

