/**
 * Accordion.js - Collapse and expand items
 * 
 * @author  Webstores <info at webstores dot nl>
 *          Copyright (c) Webstores internet totaalbureau <http://www.webstores.nl/>
 * 
 * @param {Mixed} el The CSS selector or object reference of the accordion element
 * @param {Object} options Optional parameters object
 */
function Accordion(el, options) {
	this.el = $(el);
	this.options = options;
	this.init();
};

Accordion.prototype = {
	
	/**
	 * Constructor
	 */
	init: function() {
		if(this.el.length) {
			var self = this;
						
			this.options = $.extend({
				togglerCls: 'toggler',
				collapsedCls: 'collapsed',
				expandedCls: 'expanded',
				onBeforeCollapse: null,
				onAfterCollapse: null,
				onBeforeExpand: null,
				onAfterExpand: null
			}, this.options || {});
			
			this.el.find('.' + this.options.togglerCls).each(function(i, el) {
				var target = $('#' + el.href.split('#')[1]).get(0);
				
				(target.id == window.location.hash.split('#')[1]) ? self.expand(target) : self.collapse(target);
				
				$(el).click(function(e) {
					e.preventDefault();
					self.itemClickHandler(target);
				});
			});
		}
	},
	
	/**
	 * When an item is clicked
	 * 
	 * @param {Object} item The CSS selector or object reference of the accordion item
	 */
	itemClickHandler: function(item) {
		this.isExpanded(item) ? this.collapse(item) : this.expand(item);
	},
	
	/**
	 * Is the item expanded?
	 * 
	 * @param {Mixed} item The CSS selector or object reference of the accordion item
	 */
	isExpanded: function(item) {
		return $(item).hasClass(this.options.expandedCls);
	},
	
	/**
	 * Collapse an item
	 * 
	 * @param {Mixed} item The CSS selector or object reference of the accordion item
	 */
	collapse: function(item) {
		if(typeof this.options.onBeforeCollapse == 'function') {
			this.options.onBeforeCollapse(item);
		}
		
		$(item).removeClass(this.options.expandedCls);
		$(item).addClass(this.options.collapsedCls);
		
		if(typeof this.options.onAfterCollapse == 'function') {
			this.options.onAfterCollapse(item);
		}
	},
	
	/**
	 * Expand an item
	 * 
	 * @param {Mixed} item The CSS selector or object reference of the accordion item
	 */
	expand: function(item) {
		if(typeof this.options.onBeforeExpand == 'function') {
			this.options.onBeforeExpand(item);
		}
		
		$(item).removeClass(this.options.collapsedCls);
		$(item).addClass(this.options.expandedCls);
		
		if(typeof this.options.onAfterExpand == 'function') {
			this.options.onAfterExpand(item);
		}
	}
};

