/*!
 * jQuery CAPTCHA-verified plugin
 * 
 * In-browser component of CATPCHA-verified content plugin.
 */
;(function($) {
	var defaults = {
		dialog: {
			title: 'Verification',
			width: 300,
			resizable: false,
		},
		buttonText: {
			ok: 'OK',
			cancel: 'Cancel'
		}
	};
	
	$.fn.captchaVerified = function(options) {
		var settings = $.extend(true, {}, defaults, options);

		return $(this).click(function() {
			var setupForm = function() {
				$(this).find('form').ajaxForm({
					target: $dialog,
					success: setupForm
				}).find('input[type=submit], input[type=reset], button[type=submit], button[type=reset]').hide();
			};

			var submitForm = function() {
				$dialog.find('form').submit();
			};

			var closeDialog = function() {
				$dialog.dialog('close', function() {
					$dialog.remove();
				});
			};

			var dialogHasForm = function() {
				return ($dialog.find('form').length > 0);
			};

			var okayButton = function() {
				if (dialogHasForm()) {
					submitForm();
				} else {
					closeDialog();
				}
			};

			var $dialog = $('<div>').load($(this).attr('href'), function() {
				var buttons = {};
				buttons[settings.buttonText.ok] = okayButton;
				if (dialogHasForm()) {
					buttons[settings.buttonText.cancel] = closeDialog;
				}
				$(this).dialog($.extend({
					buttons: buttons,
					open: setupForm
				}, settings.dialog));
			});

			return false;
		});
	};
})(jQuery);

