function getDescendantNode(parent, className) {	
	if (parent.className == className)
		return parent;
		
	var list = parent.childNodes;
	if (list == null) return null;
	for (var i=0; i<list.length; i++) {
		var child = list.item(i);
		if(child.className == className)
			return child;
		
		child = getDescendantNode(child, className);
		if (child != null)
			return child;
	}
  
	return null;
}

function RegisterEvent(obj, evType, fn, useCapture){
  if (obj.addEventListener){
    obj.addEventListener(evType, fn, useCapture);
    return true;
  } else if (obj.attachEvent){
    var r = obj.attachEvent("on"+evType, fn);
    return r;
  } else {
    alert("Handler could not be attached");
  }
  return true;
};

// Walks a form to hook up all slide panels
function TSlidePanels() {
}

TSlidePanels.prototype.Init = function() {
  document.getElementsByClassName('TSlidePanel').each(function(element) {  
    var aGlyphOpen = '';
    var aGlyphClose = '';
    var aSlider = getDescendantNode(element, 'TSlideContent');
    var aToggle = getDescendantNode(element, 'TSlideToggle');
    var aGlyph = getDescendantNode(element, 'TSlideGlyph');
    
    if (aGlyph != null) {
      aGlyphOpen = aGlyph.id + '-open';
      aGlyphClose = aGlyph.id + '-close';
      
      aGlyph.id = aGlyphOpen;
    }
        
    aToggle.SlidePanel = new TSlidePanel();
    aToggle.SlidePanel.Init(aSlider, aGlyph, aGlyphOpen, aGlyphClose);

    RegisterEvent(aToggle, 'click', aToggle.SlidePanel.Toggle, true);
  });
}

// Creates a collapsing panel.
function TSlidePanel() {
  this.effectObject = null;
  this.sliderElement = null;
  this.glyphElement = null;
  this.openClass = null;
  this.closeClass = null;
  this.opened = false;
};

TSlidePanel.prototype.Init = function(aSlider, aGlyph, aOpen, aClose) {
  this.sliderElement = aSlider;
  this.glyphElement = aGlyph;
  this.openClass = aOpen;
  this.closeClass = aClose;
};

TSlidePanel.prototype.Toggle = function(e) {
  var self = (e.target) ? e.target : e.srcElement;
    
  if (self.SlidePanel.effectObject == null) {
    self.SlidePanel.effectObject = new fx.Height(self.SlidePanel.sliderElement , {duration: 500, onComplete: function() {
        if (self.SlidePanel.glyphElement) {         
          if (parseInt(self.SlidePanel.sliderElement.style.height) == 0) {
            self.SlidePanel.glyphElement.id = self.SlidePanel.openClass;
          } else {
            self.SlidePanel.glyphElement.id = self.SlidePanel.closeClass;  
          }
        }
      }
    });
  }
  self.SlidePanel.effectObject.toggle();    
};

