;(function($){
    
    $.fn.imgStretcher = function(settings) {
        settings = $.extend({}, $.fn.imgStretcher.defaults, settings);
        $.fn.imgStretcher.settings = settings;

       
       return this.each(function() {
            // this => the object on which this function is called
            var $this = this;
            
            function _build() 
            {
                $(window).resize(_resize);
                _resize();
            };
            
            function _resize() 
            {
                var winW = $(window).width();
                var winH = $(window).height();
                var imgW = 0, imgH = 0;
                
                // Non-proportional resize
                if(!settings.resizeProportionally)
                {
                    imgW = winW;
                    imgH = winH;
                } 
                else 
                {
                    var initW = settings.imageWidth, initH = settings.imageHeight;
                    var ratio = initH / initW;
                    
                    imgW = winW;
                    imgH = imgW * ratio;
                    
                    if(settings.crop || imgH > winH)
                    {
                        imgH = winH;
                        imgW = imgH / ratio;
                    }
                }
                
                if(settings.containerId != '') {
                    // resize container
                    $($this).height($(window).height());
                    $($this).width($(window).width());

                    // Apply new size for images in container
                    $($this).find('img').each(function() {
                        $(this).width(imgW - (2 * settings.xyCorrection));
                        $(this).height(imgH - (2 * settings.xyCorrection));
                        $(this).css('bottom', '0');
                    });
                } else {
                    $($this).width(imgW - (2 * settings.xyCorrection));
                    $($this).height(imgH - (2 * settings.xyCorrection));
                    $($this).css('bottom', '0');                    
                }
            };
            
            /*  Start imgStretcher  */
            _build();
       
       }); /* end each */
        
    }; /* end function */
    
    /*  Default Settings  */
    $.fn.imgStretcher.defaults = {
        resizeProportionally:       true,
        crop:                       false,
        imageWidth:                 300,
        imageHeight:                300,
        xyCorrection:               10,
        containerId:                ''
    };
    
    $.fn.imgStretcher.settings = {};
})(jQuery);
