/*
* HYPERBOX
*/

var Hyperbox = function(oSettings) {
	
	if (!oSettings) {
		oSettings = {};
	}
	var oConfig = $.extend({}, Hyperbox.s_oDefaults, {
		iAnimationDuration: 500
	}, oSettings);

	this.each(function() {
		
		var dThis = this;
		
		dThis.m_oOptions = oConfig;
		dThis.m_jHeader;
		dThis.m_iAnimationDuration = 0;
		
		dThis._Constructor = function() {
			if ($(dThis).is('.non-collapsible')) {
				return;
			}
			$(dThis).css('margin-bottom', 0).wrap('<div class="box-wrapper"/>');
			dThis.m_jHeader = $(dThis).find('.box-header').click(dThis.OnClick).css('cursor', 'pointer');
			if (Hyperbox.GetState($(dThis).attr('id'))) {
				dThis.Collapse();
			}
			dThis.m_iAnimationDuration = dThis.m_oOptions.iAnimationDuration;
		};
		
		dThis.OnClick = function(eEvent) {
			if ($(this).closest('.box-wrapper').is('.layout-box-collapsed')) {
				dThis.Uncollapse();
			}
			else {
				dThis.Collapse();
			}
			return false;
		};
		
		dThis.Collapse = function() {
			var iCollapsedHeight = dThis.m_jHeader.height();
			$(dThis).closest('.box-wrapper').stop(true, true).animate({
				height: iCollapsedHeight
			}, {
				duration: dThis.m_iAnimationDuration,
				complete: function() {
					$(this).addClass('layout-box-collapsed').children('.layout-box');
					dThis.SaveState(true);
				}
			});
		};
		
		dThis.Uncollapse = function() {
			var jBox = $(dThis).closest('.box-wrapper');
			dThis.SaveState(false);
			var iCollapsedHeight = jBox.stop(true, true).css('height');
			jBox.removeClass('layout-box-collapsed').css('height', 'auto');
			var iUncollapsedHeight = jBox.height();
			jBox.css('height', iCollapsedHeight).animate({
				height: iUncollapsedHeight
			}, {
				duration: dThis.m_iAnimationDuration,
				complete: function() {
					$(this).css('height', 'auto');
				}
			});
		};
		
		dThis.SaveState = function(bCollapsed) {
			Hyperbox.SaveState($(dThis).attr('id'), bCollapsed);
		};
		
		dThis._Constructor();
		
	});

	return this;

};

Hyperbox.SetDefaults = function(oDefaults) {
	Hyperbox.s_oDefaults = oDefaults;
};

Hyperbox.GetState = function(sId) {
	Hyperbox.LoadStates();
	if (Hyperbox.s_oStates[$('body').attr('id')] != undefined) {
		return Hyperbox.s_oStates[$('body').attr('id')][sId] ? true : false;
	}
	return false;
};

Hyperbox.SaveState = function(sId, bCollapsed) {
	Hyperbox.LoadStates();
	if (Hyperbox.s_oStates[$('body').attr('id')] == undefined) {
		Hyperbox.s_oStates[$('body').attr('id')] = {};
	}
	Hyperbox.s_oStates[$('body').attr('id')][sId] = bCollapsed;
	$.cookie(Hyperbox.COOKIE_NAME, JSON.stringify(Hyperbox.s_oStates), {expires: 7});
};

Hyperbox.s_oStates;

Hyperbox.LoadStates = function() {
	if (Hyperbox.s_oStates == undefined) {
		Hyperbox.s_oStates = $.parseJSON($.cookie(Hyperbox.COOKIE_NAME));
		if (Hyperbox.s_oStates == undefined) {
			Hyperbox.s_oStates = {};
		}
	}
};

Hyperbox.COOKIE_NAME = 'hyperbox_layout';

(function($) {
	$.fn.Hyperbox = Hyperbox;
})(jQuery);


