// Some initialization
var sTocActive = null,
    sTocCurrent = '',
    _sPrevLocation = '',
    _aTocArray = [],
    oTocRequest = window.XMLHttpRequest ? new XMLHttpRequest : new ActiveXObject("Microsoft.XMLHTTP");

// Handles click on group of articles
function onTocToggle(oEvent, sId) {
  var oNode = document.getElementById(sId);
  var oBook = document.getElementById('img_' + sId);
  var oToc = document.getElementById('toc_' + sId);

  if (oNode.style.display == 'none') {
    oBook.src = oBook.src.replace('close', 'open');
    oToc.src = oToc.src.replace('close', 'open');
    oNode.style.display = '';
  } else {
    oBook.src = oBook.src.replace('open', 'close');
    oToc.src = oToc.src.replace('open', 'close');
    oNode.style.display = 'none';
  }

  oEvent.cancelBubble = true;
}

// Puts link to history
function putToHistory(_s) {
  var d = window.historyFrame.contentWindow.document;
  d.open();
  d.write('<sc' + 'ript>top.location.href = "' + _s + '";</sc' + 'ript>');
  d.close();
}

// Sends request to server
function loadTocPage (_s) {
  oTocRequest.open("GET", _s, true);
  oTocRequest.onreadystatechange = onTocRequest;
  oTocRequest.setRequestHeader("X-Requested-With", "XMLHttpRequest");
  oTocRequest.send(null);
}

// Handles click on article
function handleTocClick(oNode) {
  sTocCurrent = oNode.href.replace(/^.+\?/, '');

  // Deselect previously active
  if (sTocActive)
    document.getElementById(sTocActive).className = "";

  // Select new active
  sTocActive = oNode.id;
  oNode.className = "active";

  //
  if (window.urchinTracker)
    setTimeout(function(){urchinTracker('/reference' + sTocCurrent)}, 1);

  // DISQUS reload comments
  setTimeout(function(){
	  // Remove old comments
	  document.getElementById("disqus_thread").innerHTML	= "";
	  // Load new comments
	  disqus_url	= 'http://www.amplesdk.com/reference/?' + sTocCurrent;
	  fAmpleSDK_loadComments();
  }, 1);
}

function onTocSearch(sQuery) {
	  // Removed old comments
	  document.getElementById("disqus_thread").innerHTML	= "";
	  //
	putToHistory("#/query=" + sQuery.replace(/"/g, '\\"'));
	  //
	  if (window.urchinTracker)
	    setTimeout(function(){urchinTracker('/reference/search/' + sQuery)}, 1);
}

function onTocClick(oEvent, oNode) {
  // Put to
  putToHistory(oNode.href.replace('?', '#'));
  // Stop event propagation
  oEvent.cancelBubble = true;

  // Prevent following link
  return false;
}

// Handles article success load
function onTocRequest() {
  if (oTocRequest.readyState == 4) {
    // Render content
    var oReference = document.getElementById("reference");
    oReference.innerHTML = oTocRequest.responseText;

    // Force javascript execution
    var oScripts = oReference.getElementsByTagName('script');
    for (var i = 0; i < oScripts.length; i++) {
      eval(oScripts[i].innerHTML);
    }

    // Adjust title
    document.title = String(document.title).replace(/:\/.*$/, ':/' + sTocCurrent);
  }

  // Toggle loading message
  document.getElementById("loading").style.display = oTocRequest.readyState == 4 ? "none" : "";
  prettyPrint();
}

// Init page to work with reference
function initBook() {
  var o = document.getElementById('root_node').getElementsByTagName('a'),
      oIframe = document.createElement('iframe');
  for (var i = 0; i < o.length; i++) {
    o[i].onmouseover = handleOver;
    if (o[i].href && !o[i].href.match(/^javascript\:/i)) {
      _aTocArray.push(o[i]);
    }
  }
  oIframe.id = 'historyFrameId';
  oIframe.style.display = 'none';
  window.historyFrame = document.body.appendChild(oIframe);
  var oTooltip = document.createElement('div');
  oTooltip.id = 'tooltip';
  window.tooltip = document.body.appendChild(oTooltip);
  window.tooltip.onmouseout = handleOut;
  watchLocationChange();
}

// Timer that watches location change
function watchLocationChange() {
  var o, p, s;
  if (_sPrevLocation != document.location.href) {
    for (var i=0; i<_aTocArray.length; i++) {
      if (_aTocArray[i].href.replace('?', '#') == document.location.href) {
        p = _aTocArray[i];
        o = _aTocArray[i];
        break;
      }
    }
    if (o) {
      while (o.className != 'toc') {
        if (o.nodeName == 'UL' && o.id && o.style.display == 'none') {
          onTocToggle({}, o.id);
        }
        o = o.parentNode;
      }
      handleTocClick(p);
      loadTocPage(p.href);
    }
    else {
    	if (document.location.href.match(/#\/query=(.*)/)) {
    		  if (sTocActive)
    			    document.getElementById(sTocActive).className = "";
    		loadTocPage("?query=" + encodeURIComponent(RegExp.$1));
    	}
    }
    _sPrevLocation = document.location.href;
  }
  window.setTimeout(watchLocationChange, 100);
}

// Mouseover handler for TOC
function handleOver(e) {
  e ? 0 : e = event;
  var oTarget = e.srcElement || e.target;
  var p = getPos(oTarget);
  window.tooltip.innerHTML = oTarget.innerHTML;
  window.tooltip.className = oTarget.className;
  window.tooltip.onclick = function (event) {
    if (oTarget.onclick) {
      oTarget.onclick.apply(oTarget, arguments);
      window.tooltip.className = 'active';
    } else if (oTarget.parentNode.onclick) {
      oTarget.parentNode.onclick.apply(oTarget.parentNode, arguments);
    }
  };

  with (window.tooltip.style) {
    top = p.y + 'px';
    left = (p.x - 1) + 'px';
    display = 'block';
  }
};

// Mouseout hides tooltip
function handleOut() {
  window.tooltip.style.display = 'none';
}

// Gets poisiton of input element
function getPos(o) {
  var r = {x:0, y:0};
  while (o.offsetParent) {
    r.x += o.offsetLeft;
    r.y += o.offsetTop;
    o = o.offsetParent;
  }
  return r;
}

window.attachEvent ? window.attachEvent("onload", initBook) : window.addEventListener("load", initBook, false);

