var CollapsiblePanelController = function(){
	var $ = function(id){ var el = id.style ? id : document.getElementById(id); el.setStyle = function(p, v){ this.style[p] = v; return this; }; return el; }
    var panels = [];

    var CollapsiblePanel = function(handle, panel){
        this.handle = $(handle); this.panel = $(panel);

		this.panel.setStyle('display', 'none');
		$(this.panel.parentNode).setStyle('borderColor', '#fff');

		this.handle.setStyle('cursor', 'pointer').onclick = function(e){
			if (!e) var e = window.event;

			var handle = e.target ? $(e.target) : $(e.srcElement);
			handle.blur();
			var panel = CollapsiblePanelController.getPanelByHandle(handle.parentNode);
			CollapsiblePanelController.togglePanel(panel);
		};
    }

    return {
        init: function(){
            var els = document.getElementsByTagName('*');

            for(var i=0, len=els.length; i<len; i++){
                var el = els[i];

                if(el.className == 'collapsible'){
					var handle=null, panel=null;

					for(var j=0,len2=el.childNodes.length; j<len2; j++){
						var child = el.childNodes[j];

						if(child.className){
							child.className.indexOf('handle') > -1 ? handle = child : null;
							child.className.indexOf('panel') > -1 ? panel = child : null;
						}
					}

					if(handle && panel){
						panels.push(new CollapsiblePanel(handle, panel));
					}
                }
            }
		},
		togglePanel: function(panel){
			var handle = panel.handle;
			var panel = panel.panel;

			return panel.style.display == 'none' ? $(panel.setStyle('display', 'block').parentNode).setStyle('borderColor', '#ccc') : $(panel.setStyle('display', 'none').parentNode).setStyle('borderColor', '#fff');
		},
		getPanelByHandle: function(handle){
			var panel;
			for(var i=0, len=panels.length; i<len; i++){
				if(panels[i].handle == handle){
					panel = panels[i];
					break;
				}
			}
			return panel;
		}
    };
}();
