(function($){
	$.fn.extend({
		ConfirmDiscardChanges: function(options) {
			// stop because there's nothing to do. It's empty.
			if (!this.length) {
				return;
			}
			var $this = $(this),
				hasChanged = false,
				// defaults
				isSpanish = $("form.es").length > 0,
				opts = {
					cancelClass: 'cancelConfirmDiscard',
					confirmTitle: (isSpanish) ? 'Usted tiene cambios a&uacute;n no guardados' : 'You Have Unsaved Changes',
					confirmMessage: (isSpanish) ? '&iquest;Est&aacute; usted seguro de que desea salir de esta p&aacute;gina antes de guardar sus cambios?' : 'Are you sure you want to leave this page before saving your changes?',
					cancelText: (isSpanish) ? 'Eliminar cambios' : 'Discard Changes',
					continueText: (isSpanish) ? 'Quedarse en la p&aacute;gina' : 'Stay on Page'
				},
				// Use this containing .cancelConfirmDiscard element, or else use the document
				changeContainer = ($this.hasClass(opts.cancelClass)) ? $this : document;

			// merge user options with defaults.
			if (options) {
				$.extend(opts, options);
			}

			// set hasChanged to true if field changes are made
			$(changeContainer).change(function(e) {
				hasChanged = true;
			})
			// revert hasChanged on submit
			.find('input[type=submit], input.submit').mouseup(function(e) {
				hasChanged = false;
			});
			var eventHandler = function(e) {
				var $this = $(this);
				// if there are: changes, this obj has the cancel class, or stopConfirm is set on something; return without confirmation.
				if (!hasChanged || $this.hasClass(opts.cancelClass) || $.data(e.target, "stopConfirm") === true) {
					$.data(e.target, "isCancelled", false);
					return;
				}
				// Get parents with the cancel confirm class, or parent is .ui-dialog
				var parents = $this.parents().filter(function() {
					var $this = $(this);
					return $this.hasClass(opts.cancelClass) || $this.hasClass('ui-dialog');
				});
				// stop if a matching parent item is found.
				if (parents.length) {
					return;
				}
				
				// set the cancelClick function for the dialog
				opts.cancelClick = function() {
					var continueFunc = $.data(e.target, "continueFunc");
					if (typeof(continueFunc) == "function") {
						continueFunc();
					} else {
						window.location = e.target.href;
					}
				}
				// Fire the dialog
				$.ConfirmDialog(opts, function() {});
				
				$.data(e.target, "isCancelled", true);
				return false;
			};
			// set up listener on all A tags.
			$("a").live("click", eventHandler);
			//$("div.tabs").bind('tabsselect', eventHandler);
			return this;
		}
	});
	//start this onload so that the DOM load events have already run
	$(window).bind("load", function() {
		$("form.confirmDiscardChanges").ConfirmDiscardChanges();
	});
})(jQuery);
