// Creates a simple reveal/hide toggle for anchors that target an ID on the current page

var TIAccordion = new Class({
	Implements: [Options, Events],
	Binds: ['toggle', 'toggle_all', 'open_all', 'close_all'],
	options: {
		triggerSelector: 'a.trigger',
		openClass: 'open',
		revealOptions: {}
	},
	parent: null,
	triggers: [],
	
	initialize: function(target, options) {
		this.setOptions(options);
		
		if ($type(target) == 'element') {
			// No work on our part
			this.parent = target;
		} else if ($type(target) == 'string') {
			// Lookup parent, because it's presumably an ID
			var el = $(target);
			if (el)
				this.parent = el;
		} else if ($type(target) == 'array') {
			// An array of the trigger elements or IDs
			target.each(function(item) {
				if ($type(item) == 'element') {
					this.triggers.push(item);
				} else if ($type(item) == 'string') {
					var el = $(item);
					if (el)
						this.triggers.push(el);
				}
			});
		}
		// Populate the triggers array if we haven't already
		if (this.triggers.length == 0) {
			if (this.parent !== null) {
				this.triggers = this.parent.getElements(this.options.triggerSelector);
			}
		}
		// If we have triggers, process them; otherwise fail silently
		if (this.triggers.length > 0) {
			this.triggers.each(function(trigger) {
				var href = trigger.get('href');
				var el = href.substr(href.lastIndexOf('#') + 1);
				el = $(el);
				if (el) {
					trigger.accordion_target = el;
					trigger.accordion = this;
					var hash = (location.hash.indexOf('#') != -1 ? location.hash.substr(1) : location.hash);
					
					if ((hash != el.get('id') && hash != '') || (hash == '' && !el.hasClass(this.options.openClass))) {
						el.hide();
					}
					trigger.addEvent('click', function(e) {
						if ($chk(e)) e.stop();
						this.accordion.toggle(this.accordion_target);
					});
				}
			}.bind(this));
		}
	},
	
	// Action is optional; valid options: toggle, reveal, dissolve
	toggle: function(el, action) {
		var action = ($type(action) ? action : 'toggle');
		el.get('reveal', $merge({
			onComplete: function(el) {
				if (el.isDisplayed)
					el.addClass(this.options.openClass);
				else
					el.removeClass(this.options.openClass);
			}.bind(this)
		}, this.options.revealOptions))[action]();
	},
	
	// animate is optional and defaults to true
	toggle_all: function(action, animate) {
		var animate = ($chk(animate) ? animate : true);
		this.triggers.each(function(trigger) {
			if (!animate)
				trigger.accordion_target.show();
			else
				this.trigger(trigger.accordion_target, action);
		});
	},
	
	open_all: function(animate) {
		var animate = ($chk(animate) ? animate : true);
		this.toggle_all('reveal', animate);
	},
	
	close_all: function(instant) {
		var animate = ($chk(animate) ? animate : true);
		this.toggle_all('dissolve', animate);
	}
});