var HeaderSwitch = Class.create({
	images: [],
	pointer: 0,
	overlay: null,
	
	initialize: function(images) {
		this.images = images;
		this.detectCurrentImage();
		this.createOverlay();
		window.setTimeout(function() { this.startInterval(); }.bind(this), 5000);
	},
	
	createOverlay: function() {
		var header = $('header');
		header.insert((this.overlay = new Element('img').setStyle({ 
			width: header.getWidth() + 'px',
			height: header.getHeight() + 'px',
			src: '', alt: '',
			overflow: 'hidden',
			display: 'none' //,
			//position: 'absolute'
		})));
	},
	
	detectCurrentImage: function() {
		var i = 0, bg = $('header').getStyle('background-image');
		if(bg) {
			this.pointer = this.images.indexOf(parseInt((bg.replace(/[^\d]+/g, '')).charAt(1)));
			if(++this.pointer >= this.images.length)
				this.pointer = 0;
		}
	},
	
	startInterval: function() {
		var iv = this.startInterval.bind(this);
		var ov = this.overlay;
		var i = new Image();
		i.onload = function() {
			ov.src = i.src;
			Effect.Appear(ov, {
				afterFinish: function() {
					$('header').style.backgroundImage = 'url(' + i.src + ')';
					(function() {
						ov.hide();
						window.setTimeout(iv, 5000);
					}).defer();
				},
				duration: 2
			});
		};
		
		i.src = 'images/A4M_' + this.images[this.pointer] + '.png';
		if(++this.pointer >= this.images.length)
			this.pointer = 0;
	}
});

HeaderSwitch.start = function() { new HeaderSwitch(HeaderSwitch.getImages()); };
HeaderSwitch.addImages = function(images) { HeaderSwitch.getImages = function() { return images; } };
