/****************************
PictureFader
Version: 1.0
@author Alvaro Talavera (alvarotala@gmail.com)
*****************************/

var PictureFader = Class.create({
  
  initialize: function(holder, images, images_fx_time) {
	this.holder = holder;
    this.images_array = images;
	this.images_fx_time = images_fx_time;

	this.image_actual_index = 0;
	this.fx_running = false;
	
	this.preloaded_images_array = new Array();
	this.preload_images();
	
	this.load_image();
	
	Event.observe(window, 'keyup', this.key_handler.bindAsEventListener(this));
	
	this.autoupdater();
  },

  autoupdater: function() {
	var obj = this;
	new PeriodicalExecuter(function(pe) {
	  obj.set_image(1);
	}, this.images_fx_time);
  },

  key_handler: function(event) {
    var code = event.keyCode;

    if(code == 39) this.set_image(1); // Right key pressed
	if(code == 37) this.set_image(-1); // Left key pressed
  },

  preload_images: function() {
	var images_len = this.images_array.length;
	
	for(var i=0; i<images_len; i++) {
		this.preloaded_images_array[i] = new Image(this.image_w, this.image_h);
		this.preloaded_images_array[i].src = this.images_array[i];
	}
	
  },

  load_image: function() {
	var fragment = document.createDocumentFragment();
	
	var div_tmp = document.createElement("DIV");
	div_tmp.style.zIndex = 1; // setStyle() dont't work fine in firefox..
	
	var img_tmp = this.preloaded_images_array[this.image_actual_index].cloneNode(true);
	
	div_tmp.appendChild(img_tmp);
	fragment.appendChild(div_tmp);
	$(this.holder).appendChild(fragment);
  },

  set_next_image: function(value) {
	this.image_actual_index += value;

	if(this.image_actual_index == this.images_array.length) {
		this.image_actual_index = 0;
	}

	if(this.image_actual_index < 0) {
		this.image_actual_index = (this.images_array.length - 1);
	}
  },

  set_image: function(value) {
	if(this.fx_running==true) return;
	
	this.fx_running = true;
	var temporal_holder = $(this.holder).down("DIV", 0);
	temporal_holder.style.zIndex = 10; // setStyle() dont't work fine in firefox..

	this.set_next_image(value);
	this.load_image();
	
	var obj = this;
	
	new Effect.Fade(temporal_holder, {
		afterFinish: function() {
			temporal_holder.remove();
			obj.fx_running = false;
		}
	});
	
  }

});
