$(document).ready(function() {
	$('a').focus(function() {
		$(this).blur();
	});
	$('table.cc_box, img.cc_box').wrap('<div class="cms cc_box"></div>');
	$('#header_images').children('img').each(function() {
		var img = $(this);
		initImage(img);
		setTimeout(function() {
			swapImage(img);	
		}, getInterval());
	});
});

function initImage(img) {
	var id = img.attr('id').split('_')[1];
	img.parent().append('<img id="image_b_' + id + '" class="overlay" />');
	var newimg = img.parent().children('#image_b_' + id);
	newimg.css('position', 'absolute');
	var pos = img.position();
	newimg.css('left', pos.left + 'px');
	newimg.css('top', pos.top + 'px');
	newimg.css('width', img.width() + 'px');
	newimg.css('height', img.height() + 'px');
	newimg.hide();
}

function swapImage(img) {
	var id = img.attr('id').split('_')[1];
	var newimg = img.parent().children('#image_b_' + id);
	newimg.show();
	newimg.attr('src', img.attr('src'));
	img.unbind();
	img.load(function() {
		doSwap(img, newimg)
	});
	img.attr('src', getRndSrc(img.attr('src')));
}

function doSwap(img, newimg) {
	newimg.fadeOut(1500);
	setTimeout(function() {
		swapImage(img);	
	}, getInterval());
}

function getRndSrc(src) {
	var list = Array();
	for (var i=0; i<imagelist.length; i++) {
		list.push(imagelist[i]);
	}
	var osrc = '';
	do {
		osrc = list.splice(Math.floor(Math.random() * list.length), 1);
	} while (osrc == src && list.length);
	return osrc;
}

function getInterval() {
	var d = Math.round(Math.random() * 10000) + 1500;
	d = Math.round(d / 2000) * 2000;
	return d;
}
