/**
 * jQuery plugin provide zooming an fancyThumbnail image to its original image.
 * Author: Trinh Phuoc Thai <thai.trinh@kmcsoft.com>
 */
(function($) {

    var fancyThumb;

    $.fn.fancyZoom = function(options) {
        var settings = $.extend({
            closeOnClick : true,
            scaleImg : false,
            cssClass : '',
        }, options);
        
        fancyThumb = $(this).find('img');
        var zooming = false;
        
        if ($('#zoom').length == 0) {
            var html = '<div id="zoom" class="' + settings.cssClass + '"><img src="' + $(this).attr('rel') + '" border="0"/></div>';
            $('body').append(html);
            $('#zoom').css({ 
                display: 'none',
                position : 'absolute',
            });
        }
        
        //$('html').click(function(e){if($(e.target).parents('#zoom:visible').length == 0) hide();});
        $(document).keyup(function(event) {
            if (event.keyCode == 27 && $('#zoom:visible').length > 0) hide();
        });
        
        if (settings.closeOnClick) {
            $('#zoom').click(hide);
        }        
        $(this).click (show);
    };

    var show = function() {

        if ($('#zoom:visible').length > 0 ) return;

        var winDim = {
             width: $(window).width(),
             height: $(window).height(),
        };
        
        $('#zoom img').src = $(this).attr('rel');
        fancyThumb = $(this).find('img');

        _fancyOut();
        
    };
    
    var hide = function() {
        if ($('#zoom:hidden').length > 0 ) return;
        
        $('#zoom').animate({
            width : fancyThumb.width(),
            height : fancyThumb.height(),
            top : fancyThumb.offset().top,
            left : fancyThumb.offset().left,
            opacity : 0.0,
        },200,'linear', function() { 
            $('#zoom').css({
                display : 'none',
                width : 'auto',
                height : 'auto',
            });
        });
    }
    
    var _fancyOut = function(img) {
        
        var imgDim = {
            w: $("#zoom").width(),
            h: $("#zoom").height(),
        };
        
        // Set size to current thumg
        $('#zoom').css({
            width : fancyThumb.width(),
            height : fancyThumb.height(),
            top : fancyThumb.offset().top,
            left : fancyThumb.offset().left,
            opacity : 0.0,
        });
        
        
        var winDim = {
            w: $(window).width(),
            h: $(window).height(),
        };

        // Animate to its size and center
        $('#zoom').animate({
            left : (winDim.w - imgDim.w) / 2 + $(document).scrollLeft(),
            top : (winDim.h - imgDim.h) / 2 + $(document).scrollTop(),
            width : imgDim.w,
            height : imgDim.h,
            opacity : 1.0,
        }, 200, 'linear');
    };
    
})(jQuery);
