$(document).ready(function () {
	if (banner_images.length < 2)
		return;

	var div = $('div#banner_container');
	var img = $(div.children('img:first'));

	var first_image = img.attr('src');
	
	/*
	 * to avoid repetition of the first image shown
	 * bring it to the tail of the list
	 */
	for (var i in banner_images) {
		if (first_image == banner_images[i]) {
			banner_images.splice(i, 1);
			banner_images.push(first_image);
			break;
		}
	}


	var counter = 0;
	
	function next_img() {
		return banner_images[counter++ % banner_images.length];
	}

	/*
	 * create an <img/> element which is positioned on top of
	 * the alredy present one
	 */
	var overlay = img.clone().hide().attr({
		'src': next_img()
	}).css({
		'position': 'absolute',
		'left': 0,
		'top': 0
	});
	div.append($(overlay)[0]);
	
	/*
	 * Alternatively fadein and fadeout overlay.
	 * If fading out overlay gets the next image,
	 * otherwise "img" gets the next one.
	 * This gives the illusion of crossfade
	 * without messing with z-index
	 * and allows preloading of the next image
	 */
	function update() {
		var fade = 'fadeOut'
		if (counter % 2)
			fade = 'fadeIn';
		
		overlay[fade]('normal', function () {
			var next = overlay;
			if (fade == 'fadeIn')
				next = img;
			next.attr('src', next_img());
			setTimeout(update, 5000);
		});
	};
	setTimeout(update, 5000);
});

