/*global jQuery */
var Squish;

/**
 * An accordion widget.
 * Author: Thomas Peri
 * Version: 2009-05-11
 */
Squish = function (settings) {
	var $ = jQuery,
		i, items, current, setup, show, toggle, ids,
		goTo;
		
	show = function (href) {
		$(function () {
			var id, item;
			id = href.split('#')[1];
			item = ids[id];
			if (item.index !== current) {
				toggle(item);
			}
		});
		return false;
	};
	
	toggle = function (item) {
		var curr;

		// 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'
				});
			});
		} 
		
		// 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'
				});
			});
		}
		
	};

	$(settings.content).css({display: 'none'});
	$(function () {

		ids = {};
		$(settings.content).css({display: 'block'});
		
		setup = function (item) {
			ids[item.item.id] = item;
			$(item.heading).css({cursor: 'pointer'}).
			click(function () {
				toggle(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]);
		}
	});
	
	this.show = show;
};



