﻿(function($) {

    $.fn.simpleModal = function() {

		var $ModalBox = $('<div id="ModalBox" />');
		$ModalBox.hide();
		
		var $ModalBoxBackground = $('<div id="ModalBoxBackground" />');
		var $ModalBoxContentBox = $('<div id="ModalBoxContentBox" />');
		var $ModalBoxContent = $('<div id="ModalBoxContent" />');

		$ModalBox.append($ModalBoxBackground);
		$ModalBoxContentBox.append($ModalBoxContent);
		$ModalBox.append($ModalBoxContentBox);
		$('body').append($ModalBox);
		
		function showModal() {
			$ModalBox.show();
		}
		
		function hideModal () {
			$ModalBox.hide();
		}
		
		$ModalBoxBackground.click(function() {
			hideModal();
			return false;
		});
		
        return this.each(function() {
			$(this).click(function() {
 			    $ModalBoxContent.empty();
				$ModalBoxContent.append($(this).html());

				$(this).children('img').first().each(function(){
					var labelText = $(this).attr('alt');
					$ModalBoxContent.append('<div id="ModalBoxContentLabel">' + labelText + '</div');
				});
				
				if ($.browser.safari){ 
					$bodyElement = $("body");
				} else { 
					$bodyElement = $("html,body");
				} 
				
				var windowTop = $bodyElement.scrollTop();
				var windowLeft = $bodyElement.scrollLeft();
				
				$ModalBoxContentBox.css('top', windowTop + 'px');
				$ModalBoxContentBox.css('left', windowLeft + 'px');
				showModal();
				
				var windowHeight = $(window).height();
				var boxHeight = $ModalBoxContentBox.outerHeight(true);
				if (windowHeight > boxHeight)
				{
					var vOffset = (((windowHeight - boxHeight) / 2) + windowTop);
					$ModalBoxContentBox.css('top', vOffset + 'px');
				}
					
				var windowWidth = $(window).width();
				var boxWidth = $ModalBoxContentBox.outerWidth(true);
				if (windowWidth > boxWidth)
				{
					var hOffset = (((windowWidth - boxWidth) / 2) + windowLeft);
					$ModalBoxContentBox.css('left', hOffset + 'px');
				}
				
				return false;
			});
        });

    };
    
})(jQuery);

