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

function getTextContent(node) {
  var text = '';
  if(node) {
    if(node.children) {
      text = GetTextContent(node.firstChild);
    } else {
      if(node.nodeValue) {
        // ie
        text = node.nodeValue;
      } else {
        // firefox
        text = node.textContent;
      }
    }
  }
  return text;
}

function mediumvoteClassAutoAttach() {
  var vdb = [];
  var spans = document.getElementsByTagName('span');
  for (var i = 0; span = spans[i]; i++) {
    if (span && (hasClass(span, 'vote_pos') || hasClass(span, 'vote_neg') ||
                 hasClass(span, 'vote-on')  || hasClass(span, 'vote-off'))) {
      // Read in the path to the PHP handler
      uri = span.getAttribute('title');
      // Read in the id
      id  = span.getAttribute('id');
      // Remove the title, so no tooltip will display
      span.removeAttribute('title');

      // remove href link
      if (document.getElementById)
        var elem = document.getElementById(id);
      else if (document.all)
        var elem = document.all[id];
      else if (document.layers)
        var elem = document.layers[id];

      elem.innerHTML = getTextContent(elem);

      // Create an object with this uri. Because
      // we feed in the span as an argument, we'll be able
      // to attach events to this element.
      var parentID = span.parentNode.id;

      if (!vdb[uri]) {
        vdb[uri] = new VDB(span, uri, parentID);
      }
    }
  }
}

/**
 * A Vote DataBase object
 */
function VDB(elt, uri, id) {
  var db = this;
  // By making the span element a property of this object,
  // we get the ability to attach behaviours to that element.
  this.elt = elt;
  this.uri = uri;
  this.id  = id;
  this.elt.onclick = function() {
    HTTPGet(db.uri, db.receive, db);
  }
}

/**
 * HTTP callback function. Updates vote count display
 */
VDB.prototype.receive = function(string, xmlhttp, vdb) {
  if (xmlhttp.status != 200) {
    return alert('An HTTP error '+ xmlhttp.status +' occured.\n'+ vdb.uri);
  }

  // update the display
  document.getElementById(vdb.id).innerHTML = string;
  if (document.getElementById)
    document.getElementById(vdb.id).innerHTML = string;
  else if (document.all)
    document.all[vdb.id].innerHTML = string;
  else if (document.layers)
    document.all[vdb.id].innerHTML = string;
}
