jQuery.extend({
    BgImageTransitions: []
});

jQuery.fn.extend({
    BgImageTransition: function(src, options) {
		
        if( !src ){ return jQuery; }
		
        //copy css from the element to the helper element function
        function copyCSS( from, to ){
            jQuery(['z-index']).each( function(i,v){
                jQuery(to).css( v, jQuery(from).css( v ) );
            });
        }
		
        //check the bgImageTransition array and see whether there is already a helperElement for the original one. Generate one, if not
        var helperElement = null;
        if( !jQuery.BgImageTransitions[this.attr('id')] ){
			
            helperElement = this.clone();
            copyCSS( this, helperElement );
            helperElement.css('zIndex', 1000);
            helperElement.css('display', 'none');
			helperElement.attr('id', this.attr('id')+'2' );
            helperElement.insertAfter(this);
            jQuery.BgImageTransitions[this.attr('id')] = helperElement;
        }
        else{
            helperElement = jQuery.BgImageTransitions[this.attr('id')];
        }
		

        //load the image file into cache first, so that we get a nice and fast load. Make the transition when the image has been loaded in cache
        var tempImage = new Image();
		
        jQuery(tempImage).load( function(){
            var newImage = ( helperElement.css('display') == 'block' ) ? jQuery(this) : jQuery(helperElement);
            newImage.css('backgroundImage', 'url('+tempImage.src+')');
			helperElement.animate({opacity: 'show'}, 500, 'linear', function() {
				$('div#backgroundRotation').css('background-image',"url("+ tempImage.src +")");
				$('div#backgroundRotation2').css('display','none');
			});
        });
        tempImage.src = src;
        return jQuery;
    }
});
