// $Id: 

if (isJsEnabled()) {
  addLoadEvent(activemenuAutoAttach);
}

function activemenuAutoAttach() {
  var jsam = [];
  var container = activemenuCreateContainer();
  // The menu blocks supported. Each can designate a different uri. We're starting with one.
  var menus = {'block-user-1': '?q=activemenu/js'};
  var path = activemenuBasePath();
  for (menu in menus) {
    var menuDiv = document.getElementById(menu);

    if (menuDiv) {
      var uri = menus[menu];
      var lis = menuDiv.getElementsByTagName('li');
      for (var i = 0; li = lis[i]; i++) {
        if (li && hasClass(li, 'collapsed') || hasClass(li, 'expanded')) {
          var pos = absolutePosition(li);
          var div = document.createElement('div');
          div.className = 'activemenuPointer';
          div.style.left = (pos.x - 20) + 'px';
          div.style.top = pos.y + 'px';
          div.owner = li;
          if (hasClass(li, 'collapsed') && !hasClass(li, 'populated')) {
            // The second argument is to get around an IE bug of returning absolute URLs
            var href = li.firstChild.getAttribute('href', 2);
            // Get just the part of the path used by menus.
            href = href.substring(path.length, href.length);
            if (!jsam[href]) {
              jsam[href] = new jsAM(div, uri, href);
            }
          }
          else {
            addClass(div.owner, 'populated');
            div.onclick = function() {
              toggleClass(this.owner, 'collapsed');
              toggleClass(this.owner, 'expanded');
              activemenuAutoAttach();
            }
          }
          container.appendChild(div);
        }
      }
    }
  }
}

function activemenuCreateContainer() {
  if (document.getElementById('activemenuContainer')) {
    // Remove all children from element
    var container = document.getElementById('activemenuContainer');
    while (container.firstChild) {
      container.removeChild(container.firstChild);
    }
  }
  else {
    var container = document.createElement('div');
    container.setAttribute('id', 'activemenuContainer');
    document.getElementsByTagName('body')[0].appendChild(container);
  }
  return container;
}

/**
 * An activemenu object
 */
function jsAM(elt, uri, href) {
  var db = this;
  this.elt= elt;
  this.uri = uri;
  this.href = href;
  this.elt.onclick = function() {
    var ul = document.createElement('ul');
    var li = document.createElement('li');
    li.appendChild(document.createTextNode('loading'));
    ul.appendChild(li);
    db.elt.owner.appendChild(ul);
    db.target = ul;
    removeClass(db.elt.owner, 'collapsed');
    addClass(db.elt.owner, 'expanded');
    addClass(db.elt.owner, 'populated');
    HTTPPost(db.uri, db.receive, db, {'href' : db.href});
  }
}

/**
 * HTTP callback function.
 */
jsAM.prototype.receive = function(string, xmlhttp, jsam) {
  if (xmlhttp.status != 200) {
    return alert('An HTTP error '+ xmlhttp.status +' occured.\n'+ jsam.uri);
  }
  // Parse back result
  var items = parseJson(string);
  if (typeof items['status'] == 'undefined' || items['status'] != 0) {
    var ul = document.createElement('ul');
    for (key in items) {
      // IE seems to add an undefined item at the beginning of the array
      if (typeof(items[key].path) != 'undefined') {
        var li = document.createElement('li');
        li.className = items[key].children ? 'collapsed' : 'leaf';
        var a = document.createElement('a');
        a.setAttribute('href', activemenuBasePath() + items[key].path);
        a.appendChild(document.createTextNode(items[key].title));
        li.appendChild(a);
        ul.appendChild(li);
      }
    }
    jsam.elt.owner.replaceChild(ul, jsam.target);
    activemenuAutoAttach();
  }
}

function activemenuBasePath() {
  var path = location.pathname;
  // We don't yet support clean urls. We need to load data to determine if we are in a clean url environment.
  path += '?q=';
  return path;
}

/**
 * All functions from here to end are here temporarily to fix issues in drupal.js.
 */

/**
 * Parse a JSON response.
 *
 * The result is either the JSON object, or an object with 'status' 0 and 'data' an error message.
 */
function parseJson(data) {
  if ((data.substring(0, 1) != '{') && (data.substring(0, 1) != '[')) {
    return { status: 0, data: data.length ? data : 'Unspecified error' };
  }
  return eval('(' + data + ');');
}

/**
 * Like the String object's indexOf method, returns the index of an array element, or -1 if the element is not in the array
 */
Array.prototype.indexOf = function (el) {
  for (var i = 0; i < this.length; i++) {
    if (this[i] == el) {
      return i;
    }
  }
  return -1;
}

/**
 * Returns true if an element has a specified class name
 */
function hasClass(node, className) {
  var classes = node.className.split(' ');
  return classes.indexOf(className) != -1 ? true : false;
}

/**
 * Adds a class name to an element
 */
function addClass(node, className) {
  var classes = node.className.split(' ');
  if (classes.indexOf(className) == -1) {
    classes.push(className);
    node.className = classes.join(' ');
    return true;
  }
  return false;
}

/**
 * Removes a class name from an element
 */
function removeClass(node, className) {
  var classes = node.className.split(' ');
  if (classes.indexOf(className) != -1) {
    classes.splice(classes.indexOf(className), 1);
    node.className = classes.join(' ');
    return true;
  }
  return false;
}

/**
 * Toggles a class name on or off for an element
 */
function toggleClass(node, className) {
  if (!removeClass(node, className) && !addClass(node, className)) {
    return false;
  }
  return true;
}