$(function() {
	$('div.image_cross_fade').each(function() {
		var img, display_type, i;
		var metadata				= $(this).metadata();
		var image_cross_fade_data	= metadata.image_cross_fade;
		var that					= $(this);
		var options					= {
										'index'			: 0, 
										'showTime'		: 5000, 
										'transitionTime': 1000, 
										'doHoverPause'	: true, 
										'maxZIndex'		: 100 
									  };
		if (image_cross_fade_data.options) {
			$.extend(options, image_cross_fade_data.options);
		}
		var extension_filters = image_cross_fade_data.ef.split('-').join(',');
		var url = '/component/json/file_bucket/' + image_cross_fade_data.fb + '/' + extension_filters;
		$.getJSON(url, function(json){
			if (json.files.length === 0) {
				// aborting! no img to show
			} else if(json.files.length === 1) {
				that.css('overflow', 'hidden');
				img = new Image();
				$(img)
					.load(function () {
						that.html('').append(this);
					})
					.attr('src', json.files[0].url);
			} else {
				that.html('').css('position', 'relative').css('overflow', 'hidden');
				for (i = 0; i < json.files.length; i++) {
					img = new Image();
					$(img).attr('src', json.files[i].url.replace(' ', '%20'));
					if (i === 0) {
						display_type = 'block';
					} else {
						display_type = 'none';
					}
					$('<div/>')
						.addClass('to-fade')
						.css('position', 'absolute')
						.css('top', 0)
						.css('left', 0)
						.css('display', display_type)
						.append($(img))
						.appendTo(that);
				}
				that.children('div').children('img').preload({
					enforceCache	: true,
					onFinish		: function() { 
													var apply_to = that.children('.to-fade');
													apply_to.dumbCrossFade(options);
												  }
				});
			}
		});
	});
});
