(function($){
	$.fn.extend({
		lightBox: function() {
		    
		    //Our function for hiding the lightBox
			function lightBoxHide() {
				$(document).unbind("keydown", handleEscape);
				var remove = function() { $(this).remove(); };
				lightBoxOverlay.fadeOut(remove);
				lightBoxWindow
					.fadeOut(remove)
					.empty();
			}
			
			//Our function that listens for escape key.
			function handleEscape(e) {
				if (e.keyCode == 27) {
					lightBoxHide();
				}
			}
			
			//Create our overlay object
			var lightBoxOverlay = $("<div id='lightBoxOverlay'></div>");
			//Create our lightBox window
			var lightBoxWindow = $("<div id='lightBoxWindow'></div>");
			var lightBoxClose = $("<div id='lightBoxClose'></div>");
			
			return this.each(function() {
				//Listen for clicks on objects passed to the plugin
				$(this).click(function(e) {
					
					if (typeof document.body.style.maxHeight === "undefined") { //if IE 6
						$("body","html").css({height: "100%", width: "100%"});
					}
					
					//Append the overlay to the document body
					$("body").append(lightBoxOverlay.click(function() { lightBoxHide(); }));
					//Add a loader to our page
					$("body").append("<div id='lightBoxLoad'></div>");
					
					//Set the css and fade in our overlay
					lightBoxOverlay.css("opacity", 0.8);
					lightBoxOverlay.show();
					
					//Prevent the anchor link from loading
					e.preventDefault();
					
					//Activate a listener 
					$(document).keydown(handleEscape);	
					var arg =  $(this).attr('rel');
					var isSale =  $(this).hasClass('sale');
					//Load the image
					var img = new Image();
					$(img).load(function () {
						var imageWidth = img.width / 2;
						var imageHeight = img.height / 2;
						lightBoxWindow.css({
							"margin-left": -imageWidth
						});
						
						if ( !(jQuery.browser.msie && jQuery.browser.version < 7)) { // take away IE6
    						lightBoxWindow.css({
    							"margin-top": -imageHeight
    						});
                		}
                        
						$("#lightBoxLoad").remove();
						lightBoxWindow.append(lightBoxClose.click(function() { lightBoxHide(); }));
						if (arg != '')
						{
							lightBoxWindow.append('<div id="lightBoxArg">€ ' + arg + '</div>');
						}
						if (isSale)
						{
							var saleOverlay = $("<div></div>");
							saleOverlay.css({ 'width': '104px', 'height': '104px', 'bottom': '15px',
											'right': '15px', 'position': 'absolute', 
											'background': 'url(/images/sale-large.png) top left no-repeat'});
							lightBoxWindow.append(saleOverlay);
						}
						lightBoxWindow.append(img);
						$(this).addClass("lightBoxImage");
						$("body").append(lightBoxWindow);
						lightBoxWindow.fadeIn(50);
					})
					.attr({ src: this.href }).click(function() {
						lightBoxHide();
					});
				});
			});
		}
	});
})(jQuery);

$(function() {
	$('a.lightBox').lightBox();		
});
