/**
 * @author tom
 */

function MSAccordeon(rootElementID) {
	this.rootElement = '#' + rootElementID;
	this.transitionTime = 0.5;
	this.openItemNum = -1;
	this.openItemId = '';
}

MSAccordeon.prototype.setTransitionTime = function(value) {
	this.transitionTime = parseFloat(value);
};

MSAccordeon.prototype.setOpenItemNum = function(num) {
	this.openItemNum = parseInt(num);
	//alert(num);
}

MSAccordeon.prototype.setOpenItemId = function(id) {
	this.openItemId = id;
}

MSAccordeon.prototype.hideAllItems = function() {
	// closure
	var scope = this;
	$$(this.rootElement +' span').each(
		function(element) {
			element.next().hide();
		}
	)
};

// you can pass a number from 1 to items.length in order to have an item opened by default when the page loads
// non functional so far.
MSAccordeon.prototype.assignItemToggleLinks = function() {
	
	var scope = this;
	var expandedItem = null;
	var transition = Effect.Transitions.linear;
	var itemCnt = 0;
	this.hideAllItems();
	
	$$( this.rootElement + " span" ).each(
		// create Links within H3s
		function(el) {
			el.contents = el.firstChild.nodeValue;
			el.update('<a href="javascript:;">' + el.contents + '</a>');
		}
	);
	
	// assign Link functionality
	$$(this.rootElement + ' span a').each(
				
		function(link) {
					
			link.setAttribute('href', 'javascript:;');
			link.item = link.parentNode.next();
			link.item.isOpen = false;
			
			link.item.addClassName('accordeon-item');
			
			link.onclick = function() {
								
				if (null != expandedItem) {
					new Effect.BlindUp( 
						expandedItem, 
						{ 
							duration	: scope.transitionTime, 
							delay		: 0, 
							transition	: transition,
							from		: 0,
							to			: 1		 
						} 
					);
					// reset link class of item's link
					expandedItem.up().down().down().className = '';
				}
				
				if (this.item == expandedItem) {
					expandedItem = null;
					return;
				}
				
				var effectType = 'BlindDown';
				new Effect[effectType]( 
					this.item, 
					{ 
						duration	: scope.transitionTime, 
						delay		: 0, 
						transition	: transition,
						from		: 0,
						to			: 1
					} 
				);
				// activate clicked item's links
				this.item.up().down().down().className = 'open';
				expandedItem = this.item;
				return false;
			}
		
			if (itemCnt == scope.openItemNum) {
				link.onclick();
			}
			
			if ( link.up().up().id == scope.openItemId ) {
				link.onclick();
			}
		
		itemCnt++;			
		}
			
	)
};
	
MSAccordeon.prototype.init = function() { 
	
	document.observe(
		'dom:loaded',
		this.assignItemToggleLinks.bind(this)
	);
	
};
