jQuery(function($){
	
	var $links, $warpper, $popin;
	var options = {
		fade : 500,
		wrapperBg : '#000',
		wrapperOpacity : 0.7,
		append : ''
	};
	
	$.fn.zoomBox = function(o)
	{
		$.extend(options, o);
		$links = $(this);
		
		initZoomBox();
		
		$links.each(initLink);
	}
	
	var initZoomBox = function()
	{
		$wrapper = $('<div id="popin-wrapper"></div>').appendTo($(document.body));
		$wrapper.css({
			position:'absolute',
			top:0,
			right:0,
			bottom:0,
			left:0,
			'z-index':100,
			'background':options.wrapperBg
		}).hide();
		$popin = $('<div id="popin"></div>').appendTo($(document.body));
		$popin.css({
			position:'absolute',
			top:-9999,
			left:-9999,
			'z-index':101
		});
	}
	
	var initLink = function()
	{
		var $a = $(this);
		
		if(options.append.length>0)
		{
			$(options.append).appendTo($a);
		}
		
		$a.click(function(e){
			showPopin($a.attr('href'));	
			e.preventDefault;
			return false;
		});
	}
	
	var showPopin = function(img)
	{
		$popin.html('<img src="'+img+'" alt="" />');
		var $img = $('img', $popin);
		$img.css({
			'max-width':$(window).width()-50,
			'max-height': $(window).height()-50
		});
		$popin.css({
			width: $img.width(),
			height: $img.height(),
			top:Math.round( ($(window).height()-$img.height()) /2 ),
			left:Math.round( ($(window).width()-$img.width()) /2 )
		}).hide();
		
		$(document.body).css('overflow', 'hidden');
		
		if(options.fade !== false)
		{
			$wrapper.fadeTo(options.fade, options.wrapperOpacity);
			$popin.fadeTo(options.fade, 1);
		}
		else
		{
			$wrapper.fadeTo(0, options.wrapperOpacity);
			$popin.show();
		}
		
		
		
		$(document.body).keypress(function(e){
			if(e.keyCode == 27)
				hidePopin();
		});
		
		$wrapper.click(hidePopin);
	}
	
	var hidePopin = function()
	{
		if(options.fade !== false)
		{
			$popin.fadeTo(options.fade, 0, function(){
				$popin.hide().text('').css({
					top:-9999,
					left:-9999,
					width:null,
					height:null
				}).show();
			});
			$wrapper.fadeTo(options.fade, 0, function(){
				$wrapper.hide();
				$wrapper.die();
				$(document.body).die();
			});
		}
		else
		{
			$popin.hide().text('').css({
				top:-9999,
				left:-9999,
				width:null,
				height:null
			}).show();
			$wrapper.hide();
			$wrapper.die();
			$(document.body).die();
		}
		
		$(document.body).css('overflow', 'auto');
	}
	
});