/*
 * Center an element that is positioned absolutely.
 * Intended for elements positioned with the body as the offset,
 * therefore, not intended to be used within positioned elements 
 * other then the body.
 */
(function($){ 

    $.fn.getCssParams = function(measurements){
        var cssParams = {
                position: 'absolute',
                top: ($(window).height() / 2) + measurements.scrollTop - measurements.halfHeight,
                left: ($(window).width() / 2) + measurements.scrollLeft - measurements.halfWidth
            };
                        
            return cssParams;
    };

    $.fn.getMeasurements = function(){
        var el = $(this),
            m = {
                elHeight: el.height(),
                elWidth: el.width(),
                scrollTop: parseInt($(window).scrollTop(), 10),
                scrollLeft: parseInt($(window).scrollLeft(), 10)
            };
      
        m.elTotalHeight = parseInt(el.css('padding-top').replace('px', ''), 10) + 
                          parseInt(el.css('padding-bottom').replace('px', ''), 10) + 
                          /*parseInt(el.css('border-top-width').replace('px', ''), 10) + 
                          parseInt(el.css('border-bottom-width').replace('px', ''), 10) + */
                          m.elHeight;
        m.elTotalWidth = parseInt(el.css('padding-left').replace('px', ''), 10) + 
                         parseInt(el.css('padding-right').replace('px', ''), 10) + 
                         /*parseInt(el.css('border-left-width').replace('px', ''), 10) + 
                         parseInt(el.css('border-right-width').replace('px', ''), 10) +*/ m.elWidth;
       
        m.halfHeight = parseInt((m.elTotalHeight / 2), 10);
        m.halfWidth = parseInt((m.elTotalWidth / 2), 10);
        
        return m;
    };

    $.fn.center = function(options){
        //private vars
        var el = $(this),
            measurements = $(el).getMeasurements(),
            cssParams = $().getCssParams(measurements);
        
        //set the default popup options
        var defaults = {
            centerOnScroll: true,
            centerOnResize: true
        };
        
        //extend options with defaults
        var options = $.extend(defaults, options);
        
        $('body').css('position', 'relative');
        
        $(el).css(cssParams);
        
        if(options.centerOnScroll){
            $(window).scroll(function(){
                measurements = $(el).getMeasurements();
                cssParams = $().getCssParams(measurements);
                el.css(cssParams);
            });
        }
        
        if(options.centerOnResize){
            $(window).resize(function(){
                measurements = $(el).getMeasurements();
                cssParams = $().getCssParams(measurements);
                el.css(cssParams);
            });
        }

        
    };
    
})(jQuery);