(function($) {
    var o;
    $.fn.centerElement = function(options) {
         // build main options before element iteration
        o = $.extend({}, $.fn.centerElement.defaults, options);

        $reference = $(o.reference);
        return this.each(function(){
            $this = $(this);
            $this.css({'position' : 'relative'});

            var width = $this.outerWidth(true) + o.offsetLeft + o.offsetRight;
            var height = $this.outerHeight(true) + o.offsetTop + o.offsetBottom;
            if(o.simulateWidth){
                width = o.simulateWidth;
            }

            if(o.simulateHeight){
                height = o.simulateHeight;
            }

            var refWidth = $reference.width();
            var refHeight = $reference.height();
            if(o.reference != document && o.reference != window){
                refWidth = $reference.outerWidth(o.includeMargin);
                refWidth = $reference.outerHeight(o.includeMargin);
            }

            var newX = (refWidth / 2 - width / 2 + o.offsetLeft / 2 + o.offsetX);
            var newY = (refHeight / 2 - height / 2 + o.offsetTop / 2 + o.offsetY);
            if(o.preventClipping){
                if(newY < 0){
                    newY = 0;
                }
                if(newX < 0){
                    newX = 0;
                }
            }
            if(o.centerX){
                $this.css({'left' : newX + 'px'});
            }

            if(o.centerY){
                $this.css({'top' : newY + 'px'});
            }
        });
    };

    function debug(msg) {
        if (window.console && window.console.log)
            window.console.log('centerDiv debug: ' + msg);
    };

    $.fn.centerElement.defaults = {
        "offsetX" : 0,
        "offsetY" : 0,
        "offsetLeft" : 0,
        "offsetRight" : 0,
        "offsetTop" : 0,
        "offsetBottom" : 0,
        "simulateWidth" : false,
        "simulateHeight" : false,
        "position" : "relative",
        "centerX" : false,
        "centerY" : false,
        "reference" : window,
        "includeMargin" : true,
        "preventClipping" : true
    };
})(jQuery);

