/*
 * jQuery imagefit 1.0
 *
 * resizes an image based on the parent container size
 *
 * Copyright (c) 2010 Andreas John andreas john at noeku at
 * Dual licensed under the MIT and GPL licenses.
 */

(function($) {

    $.fn.imagefit = function(settings, cbReady) {

        var _FITINNER = 'fitInner',
            _FITOUTER = 'fitOuter'
            config = {
                hideUntilReady: true, // Hide the imaddge until it's finished loading
                speed: 2000, // fadeIn speed for background after image loads (e.g. "fast" or 500)
                fillMethode: _FITINNER, //fitInner : fit horizontally and vertically into the parent container,
                                    //fitOuter : resize img proportionally so the whole parent container is filled and eventually the img is clipped
                verticalCenter:false,
                horizontalCenter:false,
                debug:false 
            };

        // Extend the settings with those the user has provided
        if (settings && typeof settings == "object") $.extend(config, settings);

        return this.each(_init);

        function _init() {
            var container = $(this);

            container.imgRatio = new Array();
            container.imgLoaded = new Array();
            container.debugText = $("<p />");
            container.ready = false;
            
            var numImg = $('img',container).length, numImgLoaded=0;

            if (config.hideUntilReady) $(container).css('opacity','0');

            $('img', container).each( function (index, imgObj){

                $(imgObj).bind("load",{index : index}, function(event){
                    var imgObj = $(this);

                    numImgLoaded += 1;

                    container.imgRatio[event.data.index] = $(imgObj).width() / $(imgObj).height();

                    if ( numImgLoaded == numImg ) {
                        container.ready = true;
                        _resizeImg(container, config, true );
                        if(typeof cbReady == "function") cbReady(container);
                    }
                });

                if ($(imgObj).context.complete && typeof(container.imgRatio[index]) =='undefined' )
                {
                    $(imgObj).trigger('load');
                }
            });

            if (config.debug) $(container).after(container.debugText);

            $(window).resize(function (eventObject){
                /* TODO threshhold eventflood */
                _resizeImg(container, config, false );
            });

        }

        function _resizeImg(container, config, init) {
            var ctWidth = $(container).width(),
                ctHeight = $(container).height(),
                ctRatio = ctWidth / ctHeight,
                imgHeight = 0,
                imgWidth = 0,
                imgOffsX = 0,
                imgOffsY = 0,
                margin ='';
                text = '<strong>container:</strong><br/>width: ' + ctWidth + 'px, height: ' + ctHeight + 'px';

            if ( !container.ready ) return;

            $('img', container).each( function (index, imgObj) {
                imgOffsX = 0;
                imgOffsY = 0;

                if ( (config.fillMethode == _FITOUTER  && container.imgRatio[index] < ctRatio ) ||
                     (config.fillMethode == _FITINNER  && container.imgRatio[index] > ctRatio ) )
                {
                    imgWidth = ctWidth;
                    imgHeight = ( imgWidth / container.imgRatio[index] ) | 0;
                    if (config.verticalCenter ) imgOffsY = ( Math.abs(ctHeight - imgHeight) / 2 ) | 0;
                } else {
                    imgHeight = ctHeight;
                    imgWidth = ( imgHeight * container.imgRatio[index] ) | 0;
                    if (config.horizontalCenter ) imgOffsX = ( Math.abs(ctWidth - imgWidth) / 2 ) | 0;
                }
                $(imgObj).width(imgWidth).height(imgHeight)
                if ( config.verticalCenter || config.horizontalCenter ) {
                    margin = (-imgOffsY) + 'px 0 0 ' + (-imgOffsX) + 'px';
                    $(imgObj).css({'margin' :  margin });
                }

                if ( config.debug )
                {
                    text += '<br/>img'+index;
                    text += ' Ratio:' + container.imgRatio[index] + ', width:' + imgWidth +', height:' + imgHeight;
                    text += ', OffsX:' + imgOffsX + ', OffsY:' + imgOffsY;
                    text += ', margin: ' + margin;
                }

            });
            
            if ( init && config.hideUntilReady ) {  $(container).css('opacity','1' ); }

            if(config.debug) $(container.debugText).html(text);
        }
    };

})(jQuery);

