var ComplimentaryChecker = Class.create(
	{
		initialize: function (form)
		{
			this.usgbcId = null;
			
			this.form = $(form);
			
			this.container = $(this.form.up());
			
			this.form.observe('submit', this.onFormSubmit.bind(this));
			this.loading = this.form.up(1).down('#loading');
		},
		
		onFormSubmit: function (evt)
		{
			evt.stop();
			
			this.showLoading();
			
			new Ajax.Request(
				this.form.readAttribute("action"),
				{
					method: 'post',
					parameters: this.form.serialize(),
					evalJSON: true,
					onSuccess: function (tx)
					{
						this.onAjaxSuccess(tx).bind(this);
					}.bind(this),
					onFailure: function (tx)
					{
						this.onAjaxFailure.bind(this);
					}.bind(this)
				}
			);
		},
		
		showLoading: function ()
		{
			this.loading.show();
		},
		
		hideLoading: function ()
		{
			this.loading.hide();
		},
		
		onAjaxSuccess: function (tx)
		{
			if(!tx.responseJSON || !tx.responseJSON.content)
			{
				alert("An unknown error occurred.  Please try again later.");
				if(typeof console !== "undefined" && console.debug)
				{
					console.debug(tx);
					return;
				}
			}
			
			this.container.update(tx.responseJSON.content);
			
			this.container.select('a[class~="ajax"]').each(
				function (link)
				{
					link.observe('click', this.onLinkClick.bind(this))
				}.bind(this)
			);
			
			if(tx.responseJSON.usgbcId)
			{
				this.usgbcId = tx.responseJSON.usgbcId;
			}
			
			if(tx.responseJSON.links)
			{
				Element.replace($$('ul[class~="links"]')[0], tx.responseJSON.links);
			}
			
			this.hideLoading();
		},
		
		onAjaxFailure: function (tx)
		{
			alert("An error occurred checking your eligibility.  Please try again later.");
			
			if(typeof console !== "undefined" && console.debug)
			{
				console.debug(tx);
				return;
			}
			
			this.hideLoading();
		},
		
		onLinkClick: function (evt)
		{
			evt.stop();
			
			var elem = Event.element(evt);
			
			this.showLoading();
			
			new Ajax.Request(
				'/usgbc/complimentary/' + elem.readAttribute("rel"),
				{
					method: 'post',
					parameters: { usgbcId: this.usgbcId },
					onSuccess: function (tx)
					{
						this.onAjaxSuccess(tx).bind(this);
					}.bind(this),
					onFailure: function (tx)
					{
						this.onAjaxFailure.bind(this);
					}.bind(this)
				}
			);
		}
	}
);

ComplimentaryChecker.bindAll = function ()
{
	$$('form[class~="complimentary-checker"]').each(
		function (form)
		{
			var trash = new ComplimentaryChecker(form);
		}
	);
};

document.observe(
	"dom:loaded",
	function ()
	{
		ComplimentaryChecker.bindAll();
	}
);
