/**
 * @constructor
 * @param {Object} wrapper
 */
function Accordion(){
	this.sections = [];
	this.animateLoop = GEvent.callback(this,this.animateSwap);
}
Accordion.prototype.init = function(wrapper, height){
	//alert('initacc');
	for(var i = 0; i < wrapper.childNodes.length; i++){
		if(wrapper.childNodes[i].nodeType !== 1) continue;
		for(var j = i + 1; j < wrapper.childNodes.length; j++){
			if(wrapper.childNodes[j].nodeType !== 1) continue;
			
			var list = wrapper.childNodes[j].getElementsByTagName('ul')[0];
			list.style.display = 'none';

			this.sections.push({
				heading:wrapper.childNodes[i],
				body:wrapper.childNodes[j],
				list:list});
			height -= wrapper.childNodes[i].offsetHeight;
			height -= wrapper.childNodes[j].offsetHeight;
			i = j;
			break;
		}
	}
	this.available = height;
	this.active = this.sections[0];
	this.active.list.style.display = 'block';
	this.active.body.style.height = this.available + 'px';
	this.active.body.style.lineHeight = '1.5em'; //twitchy layout problems with IE 6,7 without this 
	this.active.list.style.overflowY = 'auto';
	this.active.list.style.height = this.available + 'px';
	this.growingSize = 0;
	this.animating = false;
}

Accordion.prototype.swap = function(next,callback){
	if(this.animating) return;
	this.callback = callback;
	var growing;
	for (var i = 0; i < this.sections.length && growing == null; i++){
		if(this.contains(this.sections[i].heading,next)) growing = this.sections[i];
	}
	if(this.active == growing) return;
	this.growing = growing;
	this.animating = true;
	this.growing.list.style.display = 'block';
	this.active.list.style.overflowY = 'hidden';
	this.active.list.style.height = '0px';
	this.growing.list.style.height = this.available + 'px';
	this.growing.body.style.lineHeight = '1.5em';
	this.animateSwap();
}

Accordion.prototype.animateSwap = function(){
	if(this.growingSize > this.available){
		this.active.body.style.height = '0px';
		this.growing.body.style.height = this.available + 'px';		
		this.active = this.growing;
		this.active.list.style.overflowY = 'auto';	
		this.animating = false;
		this.growingSize = 0;
		setTimeout(this.callback,1);
	}else{
		this.active.body.style.height = (this.available - this.growingSize) + 'px';		
		this.growing.body.style.height = this.growingSize + 'px';
		this.growingSize += 90;
		setTimeout(this.animateLoop,50);
	}
}

Accordion.prototype.contains = function(haystack, needle){
	if(haystack == needle) return true;
	if(haystack.nodeType != 1 || !haystack.hasChildNodes()) return false;
	for(var i = 0;  i < haystack.childNodes.length; i++){
		if(this.contains(haystack.childNodes[i], needle)) return true;
	}
	return false;
}
