;(function($) {
    
    
    // fit algorithm
    var _getFitDimensions = function(objectWidth, objectHeight, containerWidth, containerHeight){
        
        if((containerWidth - objectWidth) < (containerHeight - objectHeight)){
            objectHeight = objectHeight * (containerWidth / objectWidth);
            objectWidth = containerWidth;
        }
        else {
            objectWidth = objectWidth * (containerHeight / objectHeight);
            objectHeight = containerHeight;
        }
        return {
            width: objectWidth,
            height: objectHeight
        }
    }, _count = 0, objectContainer = [];
    
    $.fn.extend({
        toast : function(){

            var pos, img, dims, innerHeight, innerWidth, wrap, _imgCount, 
                _imgLoadedCount = 0, wrapper = "<div></div>", _selObj,
                container, target, 
                
                _onImagesLoaded = function(){
                    _bindEvents();
                },
                
                _fitImage = function(img, _target){
                    var containerId = "toast-bubble-container-" + (_count).toString();
                    var imgDims = {
                        width: img.width(),
                        height: img.height()
                    };
           
                    _count++;
                    
                    _imgLoadedCount++;
                            
                    img.wrap(wrapper);
                    img.css({"display":"block"});
                    
                    wrap = img.parent();
                    wrap.wrap("<div id='"+containerId+"'></div>")
                    container = wrap.parent();
                    container.css({"position":"absolute"});
                    var html = container.wrap("<div></div>").parent().html();
                    
                    $('#toast-bubble-working').append(html);
                    
                    container.parent().remove();
                    
                    var newImg = $('#' + containerId).find('img');
                    newImg.width(imgDims.width);
                    newImg.height(imgDims.height);
                    
                    objectContainer.push({target:_target, containerId:containerId, bound:false});
                    
                    img.css({
                        border: 0
                    });
                
                    innerWidth = wrap.width() - (parseInt(wrap.css('padding-left')) + parseInt(wrap.css('padding-right')));
                    innerHeight = wrap.height() - (parseInt(wrap.css('padding-top')) + parseInt(wrap.css('padding-bottom')));
                    
                    dims = _getFitDimensions(newImg.width(), newImg.height(), innerWidth, innerHeight)


                    newImg.width(dims.width);
                    newImg.height(dims.height);
                    
                                                            
                    if(innerWidth > img.width()){
                        
                        newImg.css({"margin-left": ((innerWidth - newImg.width()) / 2).toString() + "px"});
                    }
                    if(innerHeight > img.height()){
                        newImg.css({"margin-top": ((innerHeight - newImg.height()) / 2).toString() + "px"});
                    }
                    
                    if(_imgLoadedCount >= _imgCount){
                        _onImagesLoaded();
                    }
                },
                
                _fitImages = function(){
                    _selObj.each(function(){
                        var _target;
                        img = $(this).find("img");
                        _target = $(this);
                        
                        
                        if(img.width() == 0){                            
                            img.bind('load', function(){                                
                               _fitImage($(this), _target);
                            });
                        }
                        else {
                            _fitImage(img, _target);
                        }
                        
                    });
                },
                
                
                _getObjByContainerId = function(containerId){
                    for(var i = 0; i < objectContainer.length; i++){
                        if(objectContainer[i].containerId == containerId){
                            return objectContainer[i];
                        }
                    }
                    return null;
                },
                
                _getContainerByTarget = function(target){
                    for(var i = 0; i < objectContainer.length; i++){
                        if(objectContainer[i].target.attr('id') == target.attr('id')){
                            return $('#' + objectContainer[i].containerId);
                        }
                    }
                    return null;
                },
                
                _getFirstHeight = function(obj){
                    for(var i = 0; i < $(obj).find("*").length; i++){
                        if($($(obj).find("*")[i]).height() > 0){
                            return $($(obj).find("*")[i]).height();
                        }
                    }
                    return 0;
                },
                
                _hide = function(img){
                    $('#toast-bubble-working').css("visibility","hidden");
                    img.removeClass("toastShown").addClass("toastHidden");
                },
                
                _show = function(img){
                    $('#toast-bubble-working').css("visibility","visible");
                    img.removeClass("toastHidden").addClass("toastShown");
                },

                _onMouseOver = function(img){
                    _show(img);
                },

                _onMouseOut = function(img){
                    _hide(img);
                },
                
                _bindEvents = function(){
                    
                    $('#toast-bubble-working > div').each(function(i){
                        var img = $(this);
                        var obj = _getObjByContainerId($(this).attr('id'));
                        var target = obj.target;
                        
                        if(!target.bound){
                            target.bind('mouseover', function(){                 
                                var container = _getContainerByTarget($(this));
                                var pos = $(this).position();
                                var off = $(this).offset();
                                
                                img.css({
                                    "left":(off.left+$(this).width()).toString() + "px",         
                                    "top":(off.top - _getFirstHeight(container) / 2).toString() + "px"
                                });
                                
                                _onMouseOver(img);
                                
                            })
                            target.bind('mouseout', function(){
                                _onMouseOut(img);
                            });
                            
                            img.bind('mouseover', function(){
                                _onMouseOver(img);
                            });
                            img.bind('mouseout', function(){
                                _onMouseOut(img);
                            });
                            
                            var targetHTML = target.html();
                            target.html("");
                            
                            img.find("*:first").wrap(target.wrap("<div></div>").parent().html());
                            target.html(targetHTML);
                            
                            if($(this).find('a').length > 0){
                                var href = $(this).find('a').attr("href");
                                img.bind("click", function(){
                                    location.href = href;
                                })
                            }
                            
                            target.unwrap("<div></div>");                         
                            
                            
                            img.addClass("toastHidden");
                            target.bound = true;
                        }
                    });
                }
            ;
                            
            if(arguments.length){
                if(typeof arguments[0] == 'object')
                    wrapper = arguments[0].wrapper == undefined ? "<div></div>" : arguments[0].wrapper;
                else if(typeof arguments[0] == 'string')
                    wrapper = arguments[0];
            }
            
            if(!$('#toast-bubble-working').length){
                $('body').append("<div id='toast-bubble-working' style='visibility: hidden; position: absolute; top:0; left: 0;'></div>");
            }
            
            _selObj = this;
            _imgCount = this.find('img').length;
            
            _fitImages(this);
            
            return this;

        }
    });

})(jQuery);



