﻿(function($) {

	$.fn.productModal = function() {

		var $ModalBox = $('<div id="Modals" />');
		$ModalBox.hide();

		var $ModalBoxBackground = $('<div id="ModalBackground" />');
		var $ModalBoxContentBox = $('<div id="ModalContentBox" />');
		var $ModalBoxContent = $('<div id="ModalContent" />');
		var $LoadingImage = $('<img src="/assets/img/loading.gif" alt="Loading..." width="32" height="32" />');
		var $CloseButton = $('<a id="CloseButton" href="#" />');

		$ModalBox.append($ModalBoxBackground);
		$ModalBoxContentBox.append($ModalBoxContent);
		$ModalBoxContentBox.append($CloseButton);
		$ModalBoxContent.append($LoadingImage);
		$ModalBox.append($ModalBoxContentBox);
		$('body').append($ModalBox);

		function showModal() {
			$ModalBox.show();
		}

		function hideModal() {
			$ModalBox.hide();
		}
		
		$ModalBoxBackground.click(function() {
			hideModal();
			return false;
		});
		
		$CloseButton.click(function() {
			hideModal();
			return false;
		});

		function getBodyElement() {
			if ($.browser.safari)
			    return $("body");
		    else
			    return $("html,body");
		}
		
		function getTopOffset() {
		    var windowTop = getBodyElement().scrollTop();
		    
		    var windowHeight = $(window).height();
		    var boxHeight = $ModalBoxContentBox.outerHeight(true);
		    
		    if (windowHeight > boxHeight) {
			    var vOffset = (((windowHeight - boxHeight) / 2) + windowTop);
			    return vOffset;
		    }
		    else
				return windowTop;
		}
		
		function getLeftOffset() {
		    var windowLeft = getBodyElement().scrollLeft();
		    
		    var windowWidth = $(window).width();
		    var boxWidth = $ModalBoxContentBox.outerWidth(true);
		    
		    if (windowWidth > boxWidth) {
			    var hOffset = (((windowWidth - boxWidth) / 2) + windowLeft);
			    return hOffset;
		    }
		    else
				return windowLeft;
		}

		return this.each(function() {
			$(this).click(function() {
				$ModalBoxContent.empty();
				$ModalBoxContent.append($LoadingImage.show());
			    $ModalBoxContentBox.css('top', getTopOffset() + 'px');
			    $ModalBoxContentBox.css('left', getLeftOffset() + 'px');
				showModal();
				
				var $image = $('<img src="' + $(this).attr('href') + '" />');
				$image.hide();
				$ModalBoxContent.append($image);

				$image.load(function() {
					$LoadingImage.hide();
					$image.show();
					$ModalBoxContentBox.css('top', getTopOffset() + 'px');
					$ModalBoxContentBox.css('left', getLeftOffset() + 'px');
				});

				return false;
			});
		});

	};

})(jQuery);

