if (typeof(Unleash) == 'undefined') Unleash = {};

Unleash.Communicate = function()
{
	var that = this;
	
	this.init = function(args)
	{
		this.sel = args.selector;
		this.ajax_url = args.ajax_url;
		this.$form = $(this.sel);
		this.inputs = $(this.sel+' :input');
		
		$(this.sel).submit(function(event)
		{
			// prevent the default form submision
			event.preventDefault();
			
			// and call our send method
			that.send();
		});
	};
	
	this.send = function()
	{
		var sending = $('<p>')
			.text('Your message is being sent...')
			.addClass('sending')
			.hide();

		this.$form
		.ajaxStart(function()
		{
			that.inputs.attr('disabled', 'disabled');
			
			$(this).append(sending);
			$(sending).fadeIn('slow');
		})
		.ajaxStop(function()
		{
			that.inputs.attr('disabled', '');
			
			$(sending).fadeOut('slow', function()
			{
				$(this).remove();
			});
		});
		
		$.post(
			this.ajax_url,
			this.$form.serialize(),
			function(data, textStatus)
			{
				// I'm not sure why, but the callback is
				// never called :(
				that.handleResponse(data, textStatus);
			},
			'json'
		);
	};
	
	this.handleResponse = function(d, t)
	{
		if (t == 'success' && d.sent == '1')
			this.good();
		else
			this.bad();
	};
	
	this.good = function()
	{
		var msg = $('<p>')
			.text('Thanks! We\'ll get back with you as soon as possible.')
			.addClass('success');
		
		// Show the success message
		this.$form.prepend(msg);
		
		// Get rid of the success message
		$(msg).click(function() { $(this).fadeOut('fast'); });
		setTimeout(function() {
			if ($(that.sel+' .success'))
				$(that.sel+' .success').fadeOut('fast');
		}, 7000);
		
		// Remove the error message if it exists
		if ($(that.sel+' .error'))
			$(that.sel+' .error').empty();
	};
	
	this.bad = function()
	{
		var msg = $('<p>')
			.text('We were unable to send your message. Please try again later.')
			.addClass('error');
		
		this.$form.prepend(msg);
	};
	
};

