/*
 * imgPreview jQuery plugin
 * Copyright (c) 2009 James Padolsey
 * j@qd9.co.uk | http://james.padolsey.com
 * Dual licensed under MIT and GPL.
 * Updated: 09/02/09
 * @author James Padolsey
 * @version 0.22
 */
(function($){
    
    $.expr[':'].linkingToImage = function(elem, index, match){
        // This will return true if the specified attribute contains a valid link to an image:
        return !! ($(elem).attr(match[3]) && $(elem).attr(match[3]).match(/\.(gif|jpe?g|png|bmp)$/i));
    };
    
    $.fn.imgPreview = function(userDefinedSettings){
        
        var s = $.extend({
            
            /* DEFAULTS */
            
            // CSS to be applied to image:
            imgCSS: {},
            // Distance between cursor and preview:
            distanceFromCursor: {top:0, left:10},
            // Boolean, whether or not to preload images:
            preloadImages: false,
            // Callback: run when link is hovered: container is shown:
            onShow: function(){},
            // Callback: container is hidden:
            onHide: function(){},
            // Callback: Run when image within container has loaded:
            onLoad: function(){},
            // ID to give to container (for CSS styling):
            containerID: 'imgPreviewContainer',
            // Class to be given to container while image is loading:
            containerLoadingClass: 'loading',
            // Prefix (if using thumbnails), e.g. 'thumb_'
            thumbPrefix: '',
            // Where to retrieve the image from:
            srcAttr: 'href'
            
        }, userDefinedSettings),
        
        $container = $('<div/>').attr('id', s.containerID)
                        .append('<img/>').hide()
                        .css('position','absolute')                          
                        .appendTo('body'),
            
        $img = $('img', $container).css(s.imgCSS),
        
        // Get all valid elements (linking to images / ATTR with image link):
        $collection = this.filter(':linkingToImage(' + s.srcAttr + ')');
        
        // Re-usable means to add prefix (from setting):
        function addPrefix(src) {
            return src.replace(/(\/?)([^\/]+)$/,'$1' + s.thumbPrefix + '$2');
        }
        
        // Вмещаем в экран
        function screenHeight(){                  
            return $.browser.opera? window.innerHeight : $(window).height(); 
        } 
        
        function screenWidth(){                  
            return $.browser.opera? window.innerWidth : $(window).width(); 
        } 
        
        function ResizeBlock(ttop) {   
            t_height = $("div#"+s.containerID).height();               
            scrTop = $(window).scrollTop();  
            
            scrHeight = screenHeight();             
            scrSum = ttop + t_height - scrTop - s.distanceFromCursor.top; 
                                       
            if(scrHeight > scrSum) {                 
                return ttop - s.distanceFromCursor.top;  
            } else { 
                scrShift = ttop - t_height - scrTop - s.distanceFromCursor.top; 
                if(scrShift < 0) {  
                    return scrTop + s.distanceFromCursor.top;    
                } else {
                    return scrTop + scrShift;
                }    
            } 
        }
        
        function ResizeBlockWidth(tleft) {              
            t_width = $("div#"+s.containerID).width();   
            scrLeft = $(window).scrollLeft();    
            
            scrWidth = screenWidth();
            scrSum = tleft + t_width - scrLeft - s.distanceFromCursor.left; 
            
            if(scrWidth > scrSum) {                 
                return tleft + s.distanceFromCursor.left;  
            } else { 
                scrShift = tleft - t_width - scrLeft - s.distanceFromCursor.left - 80; 
                if(scrShift < 0) {
                    return scrLeft + s.distanceFromCursor.left;    
                } else { 
                    return scrLeft + scrShift;
                }    
            } 
        }
            
        
        if (s.preloadImages) {
            (function(i){
                var tempIMG = new Image(),
                callee = arguments.callee;
                tempIMG.src = addPrefix($($collection[i]).attr(s.srcAttr));
                tempIMG.onload = function(){
                    $collection[i + 1] && callee(i + 1);
                };
            })(0);
        }
        
        $collection
            .mousemove(function(e){                  
                $container.css({
                    top: ResizeBlock(e.pageY),      
                    left: ResizeBlockWidth(e.pageX)
                });   
            }) 
            .hover(function(e){
                
                var link = this;  
                $img
                    .load(function(){
                        $container.removeClass(s.containerLoadingClass);
                        $img.show();
                        s.onLoad.call($img[0], link);
                        $container.css({
                            top: ResizeBlock(e.pageY),      
                            left: ResizeBlockWidth(e.pageX)       
                        });  
                        
                        var img_w = $img.width(); 
                        $container.css({'width':img_w+'px'});
                    })
                    .attr( 'src' , addPrefix($(link).attr(s.srcAttr)) );
                s.onShow.call($container[0], link); 
                
                $container
                    .addClass(s.containerLoadingClass).show();                        
                
            }, function(){
                
                $container.hide();
                $img.unbind('load').attr('src','').hide();
                s.onHide.call($container[0], this);
                
            });
        
        // Return full selection, not $collection!
        return this;
        
    };
    
})(jQuery);

