/*
 * Expandable
 * Requires: jquery.parseclass.js
 */

(function($) {
	$.fn.extend({
		Expandable: function(opts) {
			var _this = this,
			defaultConfig = {
				handle: ".handle",
				content: "div.content",
				showText: "Show",
				hideText: "Hide",
				showClass: "show",
				hideClass: "hide",
				changeText: true,
				animate: true
			};
			$.extend(defaultConfig, opts);
			
			_this.live("expand", function(e, opts) {
				if (opts && opts.handle && $(opts.handle).parents(".expandable:first")[0] !== this) {
					return;
				}
				var $this = $(this),
				config = $.extend({}, defaultConfig, $this.ParseClass(true), opts);
				if (config.changeText === true) {
					$(config.handle, $this).html(config.hideText);
				}
				$this.addClass(config.showClass).removeClass(config.hideClass);
				$this.trigger("expandable", {'type':'expand'});
				var onComplete = function() {
					setTimeout(function() {
						$(config.content, $this).css({display:""});
					}, 10);
				};
				if ((opts && opts.animate === true) || (opts && opts.animate !== false && config.animate) || (!opts && config.animate)) {
					$(config.content, $this).show('blind', {}, 500, onComplete);
				} else {
					$(config.content, $this).show();
					onComplete();
				}
				return false;
			});
			_this.live("collapse", function(e, opts) {
				if (opts && opts.handle && $(opts.handle).parents(".expandable:first")[0] !== this) {
					return;
				}
				var $this = $(this),
				config = $.extend({}, defaultConfig, $this.ParseClass(true), opts),
				onComplete = function() {
					if (config.changeText === true) {
						$(config.handle, $this).html(config.showText);
					}
					$this.addClass(config.hideClass).removeClass(config.showClass);
					$this.trigger("expandable", {'type':'collapse'});
				};
				if (config.animate) {
					$(config.content, $this).hide('blind', {}, 500, onComplete);
				} else {
					$(config.content, $this).hide();
					onComplete();
				}
				return false;
			});
			
			$(defaultConfig.handle).live("click", function(e) {
				var $this = $(this).parents(_this.selector),
				config = $.extend({}, defaultConfig, $this.ParseClass(true));
				if ($this.hasClass(config.hideClass)) {
					$this.trigger("expand", {handle: e.currentTarget});
				} else {
					$this.trigger("collapse", {handle: e.currentTarget});
				}
				e.preventDefault();
			});
		}
	});
	
	$(".expandable").Expandable();
	$(".expandable").Expandable({
		handle: "a.viewmorepayments"
	});
})(jQuery);
