/*global jQuery */
var Squish;

/**
 * An accordion widget.
 * Author: Thomas Peri
 * Modified: 2009-11-16
 */
Squish = function (settings) {
	var $ = jQuery,
		i, items, current, setup;
	
	transitions = settings.transitions || {};

	$(settings.content).css({display: 'none'});
	$(function () {

		$(settings.content).css({display: 'block'});
		
		setup = function (item) {
		
			var curr;
		
			$(item.heading).css({cursor: 'pointer'}).
			click(function () {
			
				// all this weird shuffling with callbacks is for safari
			
				// collaspe the current one
				if (current >= 0) {
					curr = items[current];
					$(curr.item).removeClass(settings.openClass);
					$(curr.content).animate({
						height: 0
					}, function () {
						$(curr.content).css({
							height: curr.height,
							display: 'none'
						});
					});
					if (transitions.close) {
						transitions.close.apply(curr.item);
					}
				} 
				
				// expand the clicked one and make it current,
				// unless it was already current
				if (item.index === current) {
					current = -1;
				} else {
					current = item.index;
					$(item.item).addClass(settings.openClass);
					$(item.content).css({
						height: 0
					}).animate({
						height: item.height
					}, function () {
						$(item.content).css({
							display: 'block'
						});
					});
					if (transitions.open) {
						transitions.open.apply(item.item);
					}
				}
			});
		};
		
		items = [];
		current = -1;
		
		i = 0;
		$(settings.item).each(function () {
			items.push({
				item: this,
				index: i
			});
			i += 1;
		});
		
		i = 0;
		$(settings.content).each(function () {
			items[i].content = this;
			items[i].height = $(this).height();
			$(this).css({
				height: 0,
				overflow: 'hidden'
			});
			i += 1;
		});
		
		i = 0;
		$(settings.heading).each(function () {
			items[i].heading = this;
			i += 1;
		});
		
		for (i = 0; i < items.length; i += 1) {
			setup(items[i]);
		}
	});
};
