// jModal Plugin (Custom Plugin by Richard Brum, Exclusive to DineBestForLess.com)

/*

USAGE:

$('#element_to_make_modal').jModal(true);	// "true" to show it, "false" to hide it

*/

(function( $ ){
	$.fn.jModal = function(show_or_hide) {
		var $popup = this;
		if (show_or_hide === true) {
			// First, create the overlay (background of modal pop-up)
			if ($('#jmodal_overlay').length == 0) {
				// This doesn't yet exist, so create it
				$('<div id="jmodal_overlay" />').appendTo('body');
			}
			$('#jmodal_overlay').css({
				'background': 'none #000',
				'cursor'	: 'not-allowed',
				'display'	: 'none',
				'height'	: '100%',
				'left'		: 0,
				'opacity'	: 0.8,
				'position'	: 'fixed',
				'top'		: 0,
				'width'		: '100%',
				'z-index'	: 1100
			}).click(function() {
				$popup.jModal(false);
			});
			// Take the pop-up ("this") and re-attach it to the main document
			$popup.appendTo('body');
			// Assign it pop-up styles + center it
			var left = ( $(window).width()  - $popup.width()  ) / 2;
			var top  = ( $(window).height() - $popup.height() ) / 2;
			$popup.css({
				'display'	: 'none',
				'left'		: left + 'px',
				'position'	: 'fixed',
				'top'		: top + 'px',
				'z-index'	: 1105
			});
			// Look for any cancel buttons ('.modal_cancel', '.cancel') and apply click script
			$popup.find('.modal_cancel, .cancel').each(function() {
				$(this).click(function(e) {
					$popup.jModal(false);
					e.preventDefault();
					return false;
				});
			});
			// Finally, look for a '.titlebar' class within the popup and add an "X" icon within it
			var $titlebar = $popup.find('.titlebar');
			if ($titlebar.length > 0) {
				$titlebar.css({
					'position'	: 'relative',
					'cursor'	: 'move'
				});
				var $icon = $('<img id="popup_close" src="/images/icon_popup_close.gif" />');
				$icon.appendTo($titlebar).css({
					'cursor'	: 'pointer',
					'position'	: 'absolute',
					'right'		: 0,
					'top'		: 0
				}).attr('title', 'Click to close this pop-up').click(function() {
					$popup.jModal(false);
				});
			}
			// Now show the modal pop-up
			$('#jmodal_overlay').fadeIn();
			$popup.fadeIn();
			if ($titlebar.length > 0) {
				$popup.draggable({
					handle		: $titlebar
				});
			}
		} else {
			// Hide the modal pop-up
			$('#jmodal_overlay').fadeOut();
			$popup.find('form')[0].reset();
			$popup.fadeOut();
		}
	};
})( jQuery );
