﻿/*
 * Config options:
 *  - color: Color of the overlay (default: #ffffff)
 *  - opacity: Final opacity of the overlay (range: 0.0 - 1.0, default: 0.5)
 *  - duration: Duration of the fade animation in milliseconds (default: 0)
 */
(function($) {
	jQuery.fn.overlay = function(settings) {
		var config = { 
			color: '#ffffff',
			opacity: 0.5,
			duration: 0,
			left: 'center',
			top: 'center'
		};
		
		if(typeof settings == 'string') {
			if(settings == 'destroy') {
				destroy(this);
				return this;
			}
		} else if(typeof settings == 'object') {
			$.extend(config, settings);
		}
		
		this.each(function() {
			$('#overlay').remove();
			var overlay = $('<div />').attr('id', 'overlay').css({
				backgroundColor: config.color,
				opacity: 0,
				height: '100%',
				width: '100%',
				left: 0,
				top: 0,
				zIndex: 100,
				position: 'fixed'
			});
			var dialog = this;
			overlay.bind('click', function() {
				destroy(dialog);
			});
			$('body').append(overlay);
			
			var dialogLeft, dialogTop;
			if(typeof config.left != 'string') {
				dialogLeft = config.left;
			} else {
				dialogLeft = ($(window).width() - $(dialog).width()) / 2;
			}
			
			if(typeof config.top != 'string') {
				dialogTop = config.top;
			} else {
				dialogTop = ($(window).height() - $(dialog).height()) / 2;
			}
			$(dialog).css({
					left: dialogLeft, 
					top: dialogTop,
					position: 'fixed',
					zIndex: 101,
					opacity: 0,
					display: 'block'
				});
			$(overlay).fadeTo(config.duration, config.opacity);
			$(dialog).fadeTo(config.duration, 1.0);
		});
		
		function destroy(dialog) {
			$(dialog).fadeTo(config.duration, 0);
			$(dialog).css({display: 'none'});
			$('#overlay').fadeTo(config.duration, 0, function() {
				$('#overlay').remove();
			});
		}
		
		return this;
	};
})(jQuery);