

/**
 * JS Modul für Hintergrund
 *
 * @author		Florian Ilch <post@florianilch.de>
 * @link		http://florianilch.de
 * @package		de_florianilch
 * @version		0.6
*/
(function($){
	
    $.backdrop = function(el, options){
        // To avoid scope issues, use 'base' instead of 'this'
        // to reference this class from internal events and functions.
        var base = this;
        
        // Access to jQuery and DOM versions of element
        base.$el = $(el);
        base.el = el; 
        
        // Add a reverse reference to the DOM object
        base.$el.data("instanceBackdrop", base);
        
        var
        scale = 1,
        ratio = 0,
        $window	= $(window),
    	$img	= base.$el.find('img:first');
        
        /**
         * Initialisierung
         */
        base.init = function(){
            base.options = $.extend({},$.backdrop.defaultOptions, options);
            ratio = base.options.width / base.options.height;
            $window.resize(base.resize);
           	base.resize();
        };
        
        base.resize = function(){
        	if( !base.resizable() )
        		return false;
        	if( $window.width()/ratio < $window.height() ) {
        		base.setScale( $window.height() / base.options.height );
        		$img.parent().css({left: -(($img.attr('width') - $window.width()) / 2), top: 0});
        	} else {
        		base.setScale( $window.width() / base.options.width );
        		//$img.parent().css({left: 0, top: -(($img.attr('height') - $window.height()) / 2)});
			$img.parent().css({left: 0, top: -(($img.attr('height') - $window.height()) / 2)});
        	}
        	return true;
        };

        base.resizable = function () {
        	if( base.options.minWidth != null && base.options.minHeight != null ) {
        		return $window.width() > base.options.minWidth || $window.height() > base.options.minHeight;
        	} else {
        		return true;
        	}
        };
        
        base.setScale = function ( value ) {
        	scale = value;
        	base.updateDimensions();
        };
        
        base.getScale = function () {
        	return scale;
        };
        
        base.updateDimensions = function () {
        	$img.attr({
        		width: base.options.width * base.getScale(),
        		height: base.options.height * base.getScale()
        	});
        };
        
        base.init();
    };
	
    $.backdrop.defaultOptions = {
        width:	1020,
        height: 765,
        minWidth: null,
        minHeight: null
    };

    $.fn.backdrop = function(options){
        return this.each(function(){
            (new $.backdrop(this, options));
        });
    };

	
    // This function breaks the chain, but returns
    // the sample if it has been attached to the object.
    $.fn.getInstanceBackdrop = function(){
        return this.data("instanceBackdrop");
    };
	
})(jQuery);
