/*

usage:

$('img').morphImage('/path/to/image.jpg', newWidth, newHeight, callback);

*/
$.fn.imageMorph = (function(src, width, height, callback, SPEED){
    var SPEED = SPEED || 300;


    return this.each(function(){

        var img = $(this),
            newImg = $('<img>'),
            throbber = img.parent().find('.throbber');
        

        if (img.hasClass('morpher')) {
            img.remove();
            return;
        }
                
        if (!throbber.length) {
            throbber = $('<span class="throbber"></span>');
            img.parent().append(throbber);
            throbber.hide();
//            console.log(throbber);
        }
        
           
        var throbberTimeout = setTimeout(function() {
            // if the image is cached, it will load instantly, so we don't want the throbber
            // flickering on and off in that case
            throbber.show();
        }, 60);
        
        newImg.css({
            position: 'absolute',
            top: 0,
            left: 0,
            width: img.width()+'px',
            height: img.height()+'px',
            opacity: 0,
            cursor: 'pointer'
        }).addClass('morpher');
        img.parent().append(newImg).css({
            width: img.width()+'px',
            height: img.height()+'px'
        });
        
        
        newImg.load(function() {
            
            var css = {width:width+'px', height:height+'px', opacity:1};
            img.parent().stop().animate(css, SPEED);
            img.stop().animate(css, SPEED);
            clearTimeout(throbberTimeout);
            throbber.hide();
            newImg.animate(css, SPEED, function() {
                img.remove();
                newImg.removeClass('morpher');
                (callback || function(){})();
            });
        });
        
        newImg.attr('src', src);
    });
});