﻿$.fn.imageFlyout = function(options) {
    /// <summary>Flys out an image to the centerof the browser window. Takes into account scroll position.
    /// The triggering element should be a hyperlink with the href (NavigateUrl) set to the image you want to open.
    /// Use this function in the jQuery ready handler so it can attach the click event appropriately.
    /// </summary>    
    /// <param name="fn" type="Function">Optional function called when centering is complete. Passed DOM element as parameter</param>    
    /// <param name="closeFlyoutText" type="String">Optional title text for the image. Defaults to 'Click to Close'</param>
    /// <param name="flyoutClassName" type="String">Optional class for the flyout if additional styling is desired.</param>
    /// <param name="closeImgClass" type="String">Optional class for the close image.</param>
    /// <returns type="jQuery" />
    var opt = { closeFlyoutText: 'Click to close',
        flyoutClassName: '',
        closeImgClass: '',
        minWidth: 10,
        minHeight: 10,
        completeHandler: null
    };
    $.extend(opt, options);

    return this.each(function(i) {
        $(this).click(function(e) {
            e.preventDefault(); // prevents actually navigating to the target img
            $('#flyoutImg').remove(); // closes any existing flyouts
            var jWin = $(window);
            var ImgDiv = document.createElement('div');
            $(ImgDiv)
            .attr({ 'id': 'flyoutImg', 'title': opt.closeFlyoutText, 'class': opt.flyoutClassName })
            .html('<span class="' + opt.closeImgClass + '"></span><img src="' + $(this).attr('href') + '" />')
            .css({ 'position': 'absolute', 'left': e.pageX, 'top': e.pageY, 'z-index': 80, 'cursor': 'pointer', 'display': 'none' })
            .insertAfter($('form'))
            .click(function() {
                $(ImgDiv).fadeOut('normal', function() {
                    $(this).remove();
                });
            });
            var finalHeight = $('#flyoutImg').height();
            var finalWidth = $('#flyoutImg').width();
            finalHeight = opt.minHeight > finalHeight ? opt.minHeight : finalHeight;
            finalWidth = opt.minWidth > finalWidth ? opt.minWidth : finalWidth;
            $(ImgDiv)
            .css({ 'width': 1, 'height': 1 })
            .animate({ 'width': finalWidth, 'height': finalHeight, 'top': (jWin.scrollTop() + (jWin.height() / 2) - (finalHeight / 2)), 'left': (jWin.scrollLeft() + (jWin.width() / 2) - (finalWidth / 2)) }, 'normal', 'swing', function() {
                // if specified make callback and pass element
                if (opt.completeHandler)
                    opt.completeHandler(this);
            });
        });
    });
}



