﻿var timerId;
var oldCookie;
var oldContentUrl = "";
var oldTopHash = "";
var nodeIdHash = {};
var manualGenNodeIdCount = -1;
var selectedContentUrl = null;
var nodeIdRequestAllowed = true;

function Init()
{
  var topHash = window.location.hash;
  if (!(topHash.length >= 3 && topHash.substr(0, 3) == "##?" || topHash == "##!") && topHash.substr(0, 2) == "##") {
    var contentWindow = GetContentFrame().contentWindow;
    SetContentUrl(topHash.substr(2), true);
  }

  timerId = setInterval(CheckContentLoaded, 300);
}

function CheckContentLoaded()
{
  var topHash = window.location.hash;

  //fix Safari URI bug
  topHash = decodeURIComponent(topHash);

  // for Opera
  if (topHash != null && topHash.substr(0, 1) == "#" && topHash.substr(0, 2) != "##")
    topHash = "#" + topHash;

  // redirect to default content
  if (topHash == null || topHash.length == 0)
    if (defaultContentUrl != null && defaultContentUrl.length > 0) {
      topHash = "##" + defaultContentUrl;
      window.location.replace(window.location.href + topHash);
      return;
    }
  if (topHash.length >= 4 && topHash.substr(0, 4) == "##?=" && indexView) {
    var value = topHash.substr(4);
    indexView.setKeywordValue(value);
    tabStrip.activateTab(1);
    window.location.replace(window.location.pathname + window.location.search + "##");
  }
  else if (topHash.length >= 3 && topHash.substr(0, 3) == "##?") {
    var value = topHash.substr(3);
    tabStrip.activateTab(2);
    searchView.search(value);
    window.location.replace(window.location.pathname + window.location.search + "##");
  }

  var contentWindow = GetContentFrame().contentWindow
  if (contentWindow == null)
    return;
  var contentUrl = GetContentUrl();

  var nodeIdFromHash = nodeIdHash[contentUrl];
  if (window.navigator.cookieEnabled) {
    var cookie = document.cookie;
    if (cookie != oldCookie) {
      oldCookie = cookie;
      if (nodeIdFromHash == null) {
        var nodeId = GetCookie("nodeId");
        if (nodeId != null) {
          manualGenNodeIdCount = -1;
          SendNodeIdRequest(contentUrl);
          //nodeIdHash[contentUrl] = nodeId;
          //nodeIdFromHash = nodeId;
          //__HVSyncToc(nodeId);
        }
      }
      var versionId = GetCookie("__versionId");
      if (versionId != null && versionId != "" && versionId != GetVersionID())
        OnSync(versionId);
    }
  }

  nodeIdFromHash = nodeIdHash[contentUrl];
  if (manualGenNodeIdCount != -1)
    manualGenNodeIdCount++;
  if (manualGenNodeIdCount == 2) {
    
    if (selectedContentUrl != contentUrl) {
      // send get nodeId request
      SendNodeIdRequest(contentUrl);
    }
    manualGenNodeIdCount = -1;
  }

  if (contentUrl != null && contentUrl != oldContentUrl) {
    // fix IE sync on back button
    if (nodeIdFromHash != null) {
      manualGenNodeIdCount = -1;
      __HVSyncToc(nodeIdFromHash);
    }
    else
      manualGenNodeIdCount = 0;

    oldContentUrl = contentUrl;
    if (topHash != "##" + contentUrl && topHash != "##" + decodeURIComponent(contentUrl)) {
      topHash = "##" + contentUrl;
      window.location.replace(window.location.pathname + window.location.search + topHash);
    }
  }

  // fix Firefox back button
  if (!(topHash.length >= 3 && topHash.substr(0, 3) == "##?") && topHash != null && topHash != oldTopHash) {
    oldTopHash = topHash;
    if (topHash != "##" + contentUrl && topHash != "##" + decodeURIComponent(contentUrl))
      SetContentUrl(topHash.substr(2), true);
  }
}

function GetVersionID()
{
  var input = document.forms[0]["__VERSIONID"];
  if (input != null)
    return input.value;
}

function SetVersionID(value)
{
  var input = document.forms[0]["__VERSIONID"];
  if (input != null)
    input.value = value;
}

function IsGlobalUrl(url)
{
  return url.indexOf("http://") >= 0 ||
    url.indexOf("https://") >= 0 ||
    url.indexOf("mailto://") >= 0 ||
    url.indexOf("ftp://") >= 0 ||
    url.indexOf("file://") >= 0;
}

function GetContentFrame()
{
  return this.document.getElementById("contentFrame");
}

var prefix = "Content.aspx/";
var contentUrlSaved = null;
function GetContentUrl() {
  var frame = GetContentFrame();
  var contentWindow = frame.contentWindow;
  var url;
  try {
    url = contentWindow.location.href; // this expression can throw an exception
  }
  catch (e) {
    return contentUrlSaved;
  }
  var index = url.indexOf(prefix);
  if (index == -1) {
    if (url == "about:blank")
      return null;
    return url;
  }
  url = url.substr(index + prefix.length);
  var questPos = url.indexOf("?");
  var versionPos = url.indexOf("__versionId", questPos);
  if (versionPos != -1) {
    var firstPart = url.substring(0, versionPos);
    var secondPart = url.substr(versionPos + 11);
    if (secondPart == null || secondPart == "" || secondPart.indexOf("&") == -1)
      url = firstPart.substring(0, firstPart.length - 1);
    else {
      // not implemented
    }
  }
  return url;
}

function SetContentUrl(url, quiet)
{
  var contentUrl = GetContentUrl();

  if (contentUrl == url || decodeURIComponent(contentUrl) == url)
    return;

  contentUrlSaved = url;
  if (!IsGlobalUrl(url)) {
    if (quiet == null || !quiet)
      url = prefix + url;
    else
      url = appPath + prefix + url;
  }
  var versionID = GetVersionID();
  if (versionID != null) {
    if (url.indexOf("?") == -1)
      url = url + "?";
    else
      url = url + "&";
    url = url + "__versionId=" + versionID;
  }
  if (quiet == null || !quiet)
    GetContentFrame().src = url;
  else {
    GetContentFrame().contentWindow.location.replace(url);
  }
}

function OnTreeNodeClick(event, node)
{
  if (node.data.ID.indexOf("showNext") != -1) {
    var parentNode = treeView.getParentNode(node);
    treeView.removeNode(node);

    var childNodes = treeView.getChildNodes(parentNode);

    Xtensive.HelpServer.Web.TreeNodeProvider.Load(parentNode.data.ID, childNodes.length, null, function(data) {
      treeView.load(parentNode.data.ID, data);
    });
  }
  else {
    if (node.data.Url == null || node.data.Url.length == 0)
      return;

    selectedContentUrl = node.data.Url;
    nodeIdHash[selectedContentUrl] = node.data.ID;
    SetContentUrl(node.data.Url);
  }
}

function GetCookie(cookieName)
{
  var cookie = document.cookie;
  var result = null;
  var len = cookieName.length + 1;
  var i = cookie.indexOf(cookieName + "=");
  if (i != -1) {
    var endIndex = cookie.indexOf(";", i + len);
    if (endIndex == -1)
      result = cookie.substring(i + len);
    else
      result = cookie.substring(i + len, endIndex);
  }
  return result;
}

function __HVSyncToc(nodeId)
{
  treeView.activateNode(nodeId, tabStrip.getActiveTab()==0);
}

function SendNodeIdRequest(contentUrl)
{
  if (contentUrl == null || contentUrl.length == 0)
    return;
  if (!nodeIdRequestAllowed) {
    setTimeout(function() { SendNodeIdRequest(contentUrl); }, 50);
    return;
  }
  if (nodeIdHash[contentUrl] != null)
    return;
  nodeIdRequestAllowed = false;
  Xtensive.HelpServer.Web.TreeNodeProvider.GetPath(contentUrl, function(path) {
    var notLoaded = [];
    var count = [];
    for (var i = 0; i < path.length; i++) {
      var node = treeView.getNode(path[i]);
      if (node == null) {
        if (i < path.length - 1) {
          var id = path[i + 1];
          notLoaded.push(id);
          var childNodes = treeView.getChildNodes(id);
          if (childNodes != null) {
            var length = childNodes.length;
            for (var j = 0; j < childNodes.length; j++) {
              var childNode = childNodes[j];
              if (childNode.data.ID.indexOf("showNext") != -1) {
                treeView.removeNode(childNode);
                length--;
              }
            }
            count.push(length);
          }
          else
            count.push(null);
        }
        else {
          notLoaded.push(null);
          count.push(null);
        }
      }
      else
        break;
    }
    if (notLoaded.length > 0)
      Xtensive.HelpServer.Web.TreeNodeProvider.LoadPath(notLoaded, count, path[0], function(data) {
        for (var i = notLoaded.length - 1; i >= 0; i--) {
          var node = notLoaded[i];
          if (node != null)
            treeView.expandNode(node, data[i]);
          else
            treeView.load(null, data[i]);
        }
        nodeIdHash[contentUrl] = path[0];
        __HVSyncToc(path[0]);
        nodeIdRequestAllowed = true;
      },
      function() {
        nodeIdRequestAllowed = true;
        manualGenNodeIdCount = 0;
      });
    else {
      nodeIdHash[contentUrl] = path[0];
      __HVSyncToc(path[0]);
      nodeIdRequestAllowed = true;
    }
  },
  function() {
    nodeIdRequestAllowed = true;
    manualGenNodeIdCount = 0;
  });
}

function OnTabActivate(event, tabIndex)
{
  if (tabIndex == 0) {
    treeView.initialize();
    if (indexView != null)
      indexView.hideTopicList(false);
  }
  else if (tabIndex == 1) {
    if (indexView!=null)
      indexView.initialize();
    else if (searchView!=null)
      searchView.initialize();
  }
  else if (tabIndex == 2) {
    indexView.hideTopicList(false);
    searchView.initialize();
  }
}

function OnPrintButtonClick() {
  var contentWindow = GetContentFrame().contentWindow;
  if ($.browser.opera || (/chrome/.test(navigator.userAgent.toLowerCase()))) {
    var href = contentWindow.location.href;
    href = href.indexOf("?") > -1 ? href + "&print=1" : href + "?print=1";
    var printWindow = window.open(href, "printWindow", "scrollbars=yes");
    printWindow.focus();
  }
  else {
    contentWindow.focus();
    contentWindow.print();
  }
}

function OnSync(newVersionId)
{
  if (newVersionId != null)
    SetVersionID(newVersionId);
  nodeIdHash = {};
  RefreshTree();
  indexView.refresh();
}

function RefreshTree()
{
  if (nodeIdRequestAllowed) {
    nodeIdRequestAllowed = false;
    treeView.refresh(function() { nodeIdRequestAllowed = true; });
  }
  else
    setTimeout(RefreshTree, 50);
}

function OnLoadContent()
{
  if (searchView != null) {
    var contentWindow = GetContentFrame().contentWindow;
    searchView.onContentLoaded(contentWindow.document, tabStrip.getActiveTab()==2);
  }
}
