/**
 * Created by JetBrains PhpStorm.
 * User: thomaskasper
 * Date: 21.10.11
 * Time: 12:34
 * To change this template use File | Settings | File Templates.
 */

$(function(){
    var resizeBackground = new ResizeBackground();
});


function ResizeBackground() {
    var self = this;
    this.$backgroundWrap = $('img.background');
    this.backgroundHeight = this.$backgroundWrap.height();
    this.backgroundWidth = this.$backgroundWrap.width();

    this.$backgroundWrap.hide();
//  IE doesn't fire the load because of cached images
    if($.browser.msie) {
        this.$backgroundWrap.attr('src',$(this.$backgroundWrap).attr('src') + '?' + Math.random());
    }
    this.$backgroundWrap.load( function() {

        self.backgroundHeight = self.$backgroundWrap.height();
        self.backgroundWidth = self.$backgroundWrap.width();

        $(window).trigger("resize");
        self.$backgroundWrap.fadeIn(
            "normal"

        );
    });
    this.registerEventListener();
}

ResizeBackground.prototype.registerEventListener = function() {
    var self = this;

    $(window).resize(function(eventObject) {
        self.snapImage(eventObject);
    });
};

ResizeBackground.prototype.snapImage = function(eventObject) {
    if(this.isSnapToHeight(eventObject)) {
        this.snapToHeight();
    } else {
        this.snapToWidth();
    }
};

ResizeBackground.prototype.isSnapToHeight = function(eventObject) {
    var $window = $(eventObject.currentTarget);
    var heightFactor = $window.height() / this.backgroundHeight;
    var widthFactor  = $window.width()  / this.backgroundWidth;

    return (heightFactor > widthFactor);
};

/**
 *
 * Sets full height and width to auto to resize background image proportional
 */
ResizeBackground.prototype.snapToHeight = function() {
    this.$backgroundWrap.css({
        height  :   '100%',
        width   :   'auto'
    });
};

/**
 *
 * Sets full width and height to auto to resize background image proportional
 */
ResizeBackground.prototype.snapToWidth = function() {
    this.$backgroundWrap.css({
        height  :   'auto',
        width   :   '100%'
    });
};



