// 
// Expand/Collapse for lists
// 
// initialize variants:
// new Expandable(labelClass, contentClass);
// new Expandable(labelArray, contentArray);
// new Expandable(labelClass, labelClass, {
// 	effectOptions: {
// 		duration: 1,
// 		beforeStart: function() {}
// 	}
// });
// new Expandable(labelClass, labelClass, {
// 	initialize: function(label, content, options) {},
// 	setElement:function(label, content) {}
// });
// 

Expandable = Class.create({

	initialize: function(label, content, options) {
		// get the labels and contents
		this.labels = label;
		if (Object.isString(label)) this.labels = document.getElementsByClassName(label);

		this.contents = content;
		if (Object.isString(content)) this.contents = document.getElementsByClassName(content);

		// set the options if we have them
		this.options = options || {};
		this.effectOptions = this.options.effectOptions || {};
		
		if (!this.effectOptions.duration) this.effectOptions.duration = .3;

		// if we have a callback
		if (Object.isFunction(this.options.initialize)) this.options.initialize(label, content, options);

		this.setElements();
	},

	setElements: function() {
		for (var i=0; i<this.labels.length; i++) {
			this.labels[i] = $(this.labels[i]);
			this.contents[i] = $(this.contents[i]);

			if (this.contents[i].id) this.contents[i].id = '#'+this.contents[i].id;
			if (document.location.hash) this.setElementInit(this.labels[i], this.contents[i]);
			if (this.labels[i].hasClassName('closed')) this.contents[i].hide();

			// if we have a callback
			if (Object.isFunction(this.options.setElement)) this.options.setElement(this.labels[i], this.contents[i]);

			this.labels[i].observe('click', this.toggle.bind(this, this.labels[i], this.contents[i]), false);
		}
	},

	setElementInit: function(label, content) {
		var id = document.location.hash.toString().replace('#', '');
		if (content.identify().replace('#', '') == id) label.removeClassName('closed');
	},

	toggle: function(label, content, evt) {
		// stop the default action if it's not a hash event
		ADC.cancelEvent(evt);

		// swap the clicked link class
		if (label.hasClassName('closed')) {
			label.removeClassName('closed');
			if (label.match('.button')) label.update(label.innerHTML.replace('More', 'Fewer'));
		} else {
			label.addClassName('closed');
			if (label.match('.button')) label.update(label.innerHTML.replace('Fewer', 'More'));
		}

		// do the expand/collapse effect
		Effect.toggle(content, 'blind', this.effectOptions);
	}

});
