(function($) {
	$(document).ready(function() {
		$('<div id="modal-dialog"></div>').appendTo($('body'));
		var parents = $('.CtrlTip').tipsy({
			gravity : 'sw',
			live    : true,
			opacity : 0.9
		}).parent();
		parents.each(function(i,e) {
			e = $(e);
			e.attr('original-title', e.attr('title')).removeAttr('title');
		});
	});
	

	function openDialogBox(url, box, options)
	{
		try {
			box.dialog('destroy');			
		} catch(e) {}
		if (!url) {
			box.dialog(options);
		}	
		else {
			$.ajax({
				url : url,
				success : function(data) {
					if (jQuery.isPlainObject(data) && data.html)
					{
						box.html(data.html);
					}
					else
					{
						box.html(data);
					}
					box.dialog(options);
				},
				error : function(jqXHR, textStatus, errorThrown) {
					Memberfuse.setPageMessage($(jqXHR.responseText).find('.error').html(), 'error');
				},
				async : false
			});
		}
		// this is here for all of the tinymce boxes if they exist
		Memberfuse.init();
	}
	
	function bindButtons(box)
	{
		box.find('form').die();
		// set up the cancel/submit buttons
		var submit_button = $('#submit_field, #Submit_field, #yes_field, #send_field, .submit_button');
		var cancel_button = $('#cancel_field, #Cancel_field, .cancel_button');
		
		box.bind("dialogclose", function(event, ui) {box.dialog('destroy');});
		
		cancel_button.bind(
				'click', 
				function(event) {
					event.preventDefault(); 
					box.dialog('destroy'); 
					$(this).unbind('click');
					submit_button.die();
				}
			);
		submit_button.live(
				'click', 
				function(event) {
					event.preventDefault();
					submit_button.die();
					var error = false;
					var form = $(this).parents('form');
					$.ajax({
						url: form.attr('action'),
						type: form.attr('method') ? form.attr('method') : 'post',
						data: form.serialize(),
						async: false,
						success: function(data) {
							if (!jQuery.isPlainObject(data))
							{
								data = $.parseJSON(data);
								
							}
							/**
							 *  TODO stop logging this data
							 */ 
							//console.log(data);
							eval(data.dhtml);
							if (error)
							{
								form.replaceWith(data.html);
								Memberfuse.init();
								bindButtons(box);
							}
							else 
							{
								box.dialog('destroy'); 
								form.remove();
							}
						}
					});
				}
			);
	}
	
	function getDialogUrl(caller)
	{
		var href = caller.attr('href');
		return /(^#.*)|(^\..*)/.test(href) ? null : href;
		return url;
	}
	
	$('.CtrlMdl, .CtrlMdlPln').live('click', function(event) {
		event.preventDefault();
		var caller = $(event.currentTarget);
		var url = getDialogUrl(caller);
		var box = !url ? $(caller.attr('href')) : $('#modal-dialog');
		box.dialog('destroy');
		
		var options = $.extend({
			draggable : false,
			modal     : true,
			resizable : false,
			title     : caller.attr('title') || caller.attr('original-title'),
			width     : 'auto',
			zIndex    : 99999,
			hide      : 'fade'
			}, 
			$.parseJSON(caller.attr('rel')));
		
		openDialogBox(url, box, options);


		// bind them to the modal box
		bindButtons(box);
	});
	
	$('.CtrlDrg').live('click', function(event) {
		event.preventDefault();
		var caller = $(event.currentTarget);
		var url = getDialogUrl(caller);
		var box = !url ? $(caller.attr('href')) : $('#modal-dialog');
		box.dialog('destroy');
		
		var options = $.extend({
			draggable : true,
			modal     : true,
			resizable : false,
			title     : caller.attr('title') || caller.attr('original-title'),
			width     : 'auto',
			zIndex    : 99999
			}, 
			$.parseJSON(caller.attr('rel')));
		
		openDialogBox(url, box, options);

		// bind them to the modal box
		bindButtons(box);
	});
	
	$('.CtrlCnfrm').live('click', function(event) {
		// stop from following the link
		event.preventDefault();
		// get the obj that called the event
		var caller = $(event.currentTarget);
		// get the url for the dialog box
		var url = getDialogUrl(caller);
		// define the dialog box based upon the url	
		var box = !url ? $(caller.attr('href')) : $('#modal-dialog');
		
		// setup the options
		var options = $.extend({
			draggable : false,
			modal     : false,
			width     : '200px',
			resizable : false,
			zIndex    : 99999,
			title     : caller.attr('title') || caller.attr('original-title') || "Confirm?"
			}, 
			caller.attr('rel').match(/CtrlCnfrm/) ? {} : $.parseJSON(caller.attr('rel'))
			);

		// set special dialog options that are not normally accessable
		$.ui.dialog.prototype.options.position.my = 'right top';
		$.ui.dialog.prototype.options.position.at = 'left bottom';
		$.ui.dialog.prototype.options.position.of = caller;

		// open the dialog box
		openDialogBox(url, box, options);

		// set the options back the way they were
		$.ui.dialog.prototype.options.position.at = 'center';
		$.ui.dialog.prototype.options.position.my = 'center';
		$.ui.dialog.prototype.options.position.of = $(window);

		// bind buttons to the modal box
		bindButtons(box);
					
	}); 
	
	$(document).ready(function() {
		// for all of those crazy ajax forms that are not in windows
		$('.asyncForm').live(
			'submit', 
			function(event) {
				event.preventDefault();
				var self = $(this);
				$.ajax({
					url: self.attr('action'),
					type: self.attr('method') ? self.attr('method') : 'post',
					data: self.serialize(),
					async: false,
					success: function(data) {
						data = $.parseJSON(data);
						self.replaceWith(data.html);
						setTimeout(data.dhtml, 1);
						Memberfuse.init();
					}
				});
			}
		);
	});
})(jQuery);

