(function($)
{
	$.fn.quicklook = function(options)
	{
        // defaults in case they are ever needed
		var defaults = {
		};
		
		var options = $.extend(defaults, options);
	
		return this.each(function()
		{
            // setup click function
			$(this).click(function()
            {
                var id = "#quick_popup_"+$(this).parent().attr('id');
                if ($(id).length > 0)
                { 
                    startPopup();
                    showPopup(id); 
                }
                else
                {   
                    // grab the html to render
                    $.get('/ajax/quicklook/id/' + $(this).parent().attr('id'), function(data)
                    {
                        // add in overlay div, only if it doesn't exist yet
                        if ($("#overlay").length == 0)
                        { 
                            // throw in overlay div
                            $('body').append('<div id="overlay"></div>'); 
                            // add click handler to overlay
                            $("#overlay").click(function()
                            {
                                $('.quick_popup').hide();
                                finishClose();
                            });
                            // throw in loading div
                            $('body').append('<div id="loading"><img src="/images/loading.gif" /><span>Loading...</span></div>');
                        }
                    
                        // build jquery elements from returned html
                        var quicklook_div = $(data);
                        startPopup();
                        
                        // preload quicklook image
                        // so the height and width is correct when div is shown
                        var imgPreloader = new Image();
                        imgPreloader.onload = (function()
                        {   
                            // add quicklook div to the DOM
                            $('body').append(quicklook_div);
                            
                            showPopup(id); 
                                                                       
                            // attach close click handler     
                            $(id).find(".quick_popup_close").click(function()
                            {
                                $(this).parent().hide();
                                finishClose();
                            });
                        });
                        // kick off the image preloader
                        imgPreloader.src = $('img[class=quick_popup_image]', quicklook_div).attr('src');
                    });
                }
            });
		});
	};
})(jQuery);

