
(function($){
$.fn.cximages = function( options ) {

	var defaultOptions = {
		speed:	1500,
		interval: 4500
	};

	var options = $.extend( defaultOptions, options );

	function getImageCount( container ) {
		return $(container).find('img').size();
	};

	function getImages( container ) {
		return $(container).find('img');
	};

	function getState( container ) {
		return $(container).find('.state');
	};
	
	function initImages( container ) {
		var images = $(container).find('img');

		$(images).hide();

		// preload
		var load_image = new Image();
		load_image.src = $(images[0]).attr('src');

		load_image.onload = function(){
			// resize container to fit images:
			$(container).css({
			//	width:  this.width,
				height: this.height
			}); 
		};


		$(images).css('display', 'none');  // hide images
		$(images).css('position', 'absolute');  // overlay images
		$(images).css('border', 'none');
		// $(images[0]).css('display', 'block'); // show first pic.
	
		$(images[0]).fadeIn();

		// save some informations
		$(container).append( '<span class="state" style="display:none;"></span>' );
		var state = getState(container);

		$(state).attr( 'current', 0 );
		$(state).attr( 'max', images.size() );
	};
	
	function crossfade( fromImage, toImage, container ) {
		var images = getImages(container);

		$(images[fromImage]).fadeOut(options.speed);
		$(images[toImage]).fadeIn(options.speed);

		$(container).css('width', $(images[toImage]).width() );
		$(container).css('height', $(images[toImage]).height() );
	};

	function animate( imageNum, container ) {
		var images = getImages( container );
		var image  = $(images[imageNum]);

		var width = $(image).width();
		var height = $(image).height();

		// set start and dir vector
		var canvas  = $('.xhr.room-images');
		var cWidth  = $(canvas).width();
		var cHeight = $(canvas).height();

		var overflowX = width - cWidth;
		var overflowY = height - cHeight;

		// simple...
		$(image).animate({
			left: -overflowX,
			top:  -overflowY
		}, 8000);
	}

	function next( container ) {
		var state   = getState(container);
		var max	    = parseInt($(state).attr('max'));
		var current = parseInt($(state).attr('current'));
		var next    = current + 1;

		if( next == max ) {
			next = 0;
		}
	
		crossfade( current, next, container );	
		// animate( next, container );
		current = next; 
		// save state
		$(state).attr('current', current );
	};

	$.each(this, function() {
	
		if( $(this).find('.state').size() > 0 ) {
			return; // this is allready initialized.
		}

		initImages(this);
		var container = this;
		$(container).css('position', 'relative');

		if( $(container).children().length > 2 ) {
			setInterval( function() {
				next(container);
			},
			options.interval);
		}
			
//		animate( 0, this );
	});
};
	
})(jQuery);


