﻿function handleElement(containerElem, containerList, objectType) {
  this.m_containerElem = containerElem;
  this.m_info = containerList;
  this.m_objType = objectType;
  var that = this;

  this.expandElement = function() {
    if(that.m_info.previousContainer !== that.m_containerElem) {
      var lastContainer = that.m_info.getPreviousContainer();
      if(lastContainer) lastContainer.className = that.m_objType.containerClass;
      that.m_containerElem.className = that.m_objType.selectedClass;
      that.m_info.setPreviousContainer(that.m_containerElem);
    }
  }
}

function elementInfo() {
  var m_previousContainer = null;
  this.setPreviousContainer = function(value) { m_previousContainer = value; }
  this.getPreviousContainer = function() { return m_previousContainer; }
}
elementInfo.containerClass = 'unselected';
elementInfo.selectedClass = 'selected';

function registerElements(containerName, initElem) {
  var containerElem = document.getElementById(containerName);
  if(containerElem) {
    var children = containerElem.childNodes;
    var listHolder = new elementInfo();
    var currElem = 0;
    for(var i = 0; children && i < children.length; ++i) {
      if(children[i].className === elementInfo.containerClass) {
        var handler = new handleElement(children[i], listHolder, elementInfo);
        children[i].onmouseover = handler.expandElement;
        if(initElem === currElem++) handler.expandElement();
      }
    }
  }
}

var isSetup = false;
function pageLoad() {
  // Apparently this function may be called several times
  if(isSetup) return; else isSetup = true;
  var newsHandler = registerElements('newsitems', 0);
  var feedHandler = registerElements('feeditems', 0);
}

/* From http://simonwillison.net/2004/May/26/addLoadEvent/ */
function addLoadEvent(func) {
  var oldonload = window.onload;
  if (typeof window.onload != 'function')
    window.onload = func;
  else {
    window.onload = function() {
      if (oldonload) oldonload();
      func();
    }
  }
}

// Register the list handlers
addLoadEvent(pageLoad);