YAHOO.util.Dom.cleanWhitespace = function(el) {
	var el = YAHOO.util.Dom.get(el);
	for (var i = 0; i < el.childNodes.length; i++) {
		var node = el.childNodes[i];
		if (node.nodeType === 3 && !/\S/.test(node.nodeValue)) {
			node.parentNode.removeChild(node);
		}
	}
};

(function() {
  var Y = YAHOO.util,
      Event = Y.Event,
      Dom = Y.Dom,
      Anim = Y.Anim,
      Motion = Y.Motion;
  
  var initCodeCollapse = function() {
    var elements = Dom.getElementsByClassName('code', 'h3', 'main');
    Dom.cleanWhitespace('main');
    if ( elements.length > 0 ) {
      Event.on(elements, 'click', swoop);
      Dom.batch(elements, setHeights);
    }
    function setHeights(el) {
      var target = el.nextSibling;
      target.setAttribute('animheight', target.offsetHeight);
    }
    var start = function() {
      var el = this.getEl();
      el.style.overflow = 'hidden';
    };
    var finish = function() {
      var el = this.getEl();
      el.style.overflow = 'auto';
    };
    function swoop (e) {
      Event.preventDefault(e);
      var target = this.nextSibling;
      var anim, attr;
      if ( Dom.hasClass(this, 'closed') ) {
        attr = {
          height : {
            to : target.getAttribute('animheight')
          },
          paddingTop : {
            to : 1,
            unit : 'em'
          },
          paddingBottom : {
            to : 1,
            unit : 'em'
          }
        };
        Dom.removeClass(this, 'closed');
      }
      else {
        attr = {
          height : {
            to : 0
          },
          paddingTop : {
            to : 1
          },
          paddingBottom : {
            to : 0
          }
        };
        Dom.addClass(this, 'closed');
      }
      anim = new Anim(target, 
        attr, 
        .5, 
        Y.Easing.easeOut
      );
      anim.onStart.subscribe(start);
      anim.onComplete.subscribe(finish);
      anim.animate();
    }
  };
  
  Event.onDOMReady(initCodeCollapse);
})();