var Image_Rotator = Class.create();
Image_Rotator.prototype = {
	initialize: function(img_location, options) {
		this.options = Object.extend({ 
			prefix: 'image_rotator_',
			max_images: 5,
			currentClass: 'current',
			targetName: 'target',
			listName: 'counter',
			ajaxLoader: '/ajax/main/image_loader',
			param: 'img'
		},
		options || {});
		this.cache = new Hash();
		this.img_location = img_location;
		this.current_image = 1;
		this.target = $(this.options.prefix + this.options.targetName);
		this.list_numbers = $(this.options.prefix + this.options.listName);
	},
	startRotation: function() {
		new Ajax.Request(this.options.ajaxLoader + '?' + this.options.param + '=1', {
			method: 'get',
			onSuccess: this.loadImage.bind(this)
		});
	},
	nextImage: function() {
		this.current_image++;
		if(this.current_image > this.options.max_images) {
			this.current_image = 1;
		}
		if(this.cache[this.current_image] == undefined) {
			new Ajax.Request(this.options.ajaxLoader + '?' + this.options.param + '=' + this.current_image, {
				method: 'get',
				onSuccess: this.loadImage.bind(this)
			});
		}else{
			this.target.update(this.cache[this.current_image]);
			//this.target.writeAttribute('src', this.img_location + this.options.prefix + this.current_image + '.jpg');
			this.activateCounter(this.current_image);
			this.cur_call = window.setTimeout(this.nextImage.bind(this), 10000);
		}
	},
	loadImage: function(transport) {
		code = transport.responseText;
		if(this.cache[this.current_image] == undefined) {
			this.cache[this.current_image] = code;
		}
		this.target.update(code);
		this.activateCounter(this.current_image);
		this.cur_call = window.setTimeout(this.nextImage.bind(this), 10000);
	},
	activateCounter: function(current_image) {
		var last_img = current_image - 1;
		if(last_img == 0) {
			last_img = this.options.max_images;
		}
		$$('#' + this.options.prefix + this.options.listName + ' li').each(function(it) {
			it.removeClassName(this.options.currentClass);
		}.bind(this));
		$(this.options.prefix + this.options.listName + '_' + current_image).addClassName(this.options.currentClass);
	},
	setCurrentImage: function(number) {
		if(number > this.options.max_images) {
			return false;
		}
		this.current_image = number;
		window.clearTimeout(this.cur_call);
		if(this.cache[this.current_image] == undefined) {
			new Ajax.Request(this.options.ajaxLoader + '?' + this.options.param + '=' + this.current_image, {
				method: 'get',
				onSuccess: this.loadImage.bind(this)
			});
		}else{
			this.target.update(this.cache[this.current_image]);
			//this.target.writeAttribute('src', this.img_location + this.options.prefix + this.current_image + '.jpg');
			this.activateCounter(this.current_image);
			this.cur_call = window.setTimeout(this.nextImage.bind(this), 10000);
		}
	}
};
