/**
 * 	Campaign Monitor 0.1 - jQuery plugin
 *	written by Tony Milne (Inlight Media)
 *	http://inlight.com.au
 *
 *	Copyright (c) 2009 Tony Milne (http://inlight.com.au)
 *	Dual licensed under the MIT (MIT-LICENSE.txt)
 *	and GPL (GPL-LICENSE.txt) licenses.
 *
 *	Built for jQuery library
 *	http://jquery.com
 */

(function($) {
	$.fn.campaignMonitor = function(options) {
		
		// Define the default settings. Will be used unless overridden by the user's options.
		var defaults = {						
			before_submit_callback: null,
			after_submit_callback: null,
			success_message: '<p><strong>NOTE:</strong> A confirmation email has been sent to your email account.</p><p>Please complete the instructions in order to complete the subscription process.</p>',
			success_message_class: 'campaign_monitor_success',			
			form_fadeout_speed: 'slow',
			success_message_fadein_speed: 'slow',
			proxy_url: 'campaign-monitor.php'			
		};
			
		
		this.each(function() {
			
			var obj = $(this);
			var id = obj.attr("id");
			var original_action = obj.attr("action");
			var settings = $.extend(defaults, options);
			
			
			// Insert a hidden field to store the original form action.									
			var original_action_html = "<input name='action' type='hidden' value='"+original_action+"' />";			
			obj.append(original_action_html);
			
			
			// Modify the form's action to point to our campaign monitor proxy.			
			obj.attr("action", settings.proxy_url);
			
			
			// Attach the form submit handler.
			obj.submit(function() {
				// Call the before_submit_callback if defined, and abort submitting the form if it returns false.
				if (settings.before_submit_callback != null) {
					if (settings.before_submit_callback() == false) { return false; }					
				}
				
				// All good. Submit the form via AJAX.
				$.ajax({
					type: "POST",
					url: settings.proxy_url,
					data: obj.serialize(),
					success: function(result) {						
						if (settings.after_submit_callback != null) {
							settings.after_submit_callback();
						}
						else {
							default_after_submit();
						}
					}
				});
				
				// Return false to prevent the default form submission.
				return false;
			});
			
			
			// Insert the success message directly after the form.			
			var success_message_html = "<div class='"+settings.success_message_class+"' style='display: none;'>"+settings.success_message+"</div>";
			obj.after(success_message_html);
			
			function default_after_submit() {
				// Fade the form out and fade in the subscription success message.			
				obj.fadeOut("slow", function() {
					obj.next("'."+settings.success_message_class+"'").fadeIn("slow");
				});
			}
		});
	};
})(jQuery);
