/*
* Funcion para precargar imagenes
* Solo es necesario poner a la imagen a precargar 
* la clase preload 
*  Edison Suárez Fuentes - I2B Technologies
*/

var PCS = PCS || {};

PCS.cargaSecuencial = Class.create();
PCS.cargaSecuencial.prototype = {
	options: null,
	fotos: null,
	initialize : function(options) {
		// encuentra las imagenes y las comienza  a poner en modo cargando
		var fotos = [];
		$$('.preload').each(function(image) {
			fotos.push (new PCS.cargaImagenes(image, (options || {} ) ) );
		})
		this.fotos=fotos;
		this.comenzar(this.options);
	},
	comenzar: function(options){
		// comienza a car
		this.fotos.each(function(miImagen) {

			var newImage 	= null;
			newImage 		= new Image();
			newImage.src 	= miImagen.element.origSrc;

			// image is in cache (IE6 & IE7 ... Firefox can handle the onload well even file was in cache);
			if (newImage.complete) {
					miImagen.element.src 	= newImage.src;
			// image not in cache
			} else {
				newImage.onload = function() {
					miImagen.element.src 	= newImage.src;
				}.bind(this);
			}
		});
		this.fotos=null;
	}
}

PCS.cargaImagenes = Class.create();
PCS.cargaImagenes.prototype = {
	options		: null,// options
	element		: null,// the img element

	initialize: function(image, options) {
		// set the options
		this.options				= options || {};
		this.options.treshold		= this.options.treshold || 100;
		this.options.replaceImage	= this.options.replaceImage || "./medios/blank.gif";
		this.options.loadingImage	= this.options.loadingImage || "./medios/spinner.gif";
		// set blank and loading image
		this.element		= image;
		this.element.origSrc 	= this.element.src;
		this.element.src 		= this.options.replaceImage;
		this.element.setStyle({ backgroundImage: 'url(' + this.options.loadingImage + ')', backgroundPosition: '50% 50%', backgroundRepeat: 'no-repeat' });
	}
}

//Prototype 1.6 lo solucionara :(
//function initcargaSecuencial() { myCS = new PCS.cargaSecuencial(); }
//Event.observe(document, 'contentloaded', initcargaSecuencial, false);
function Preload_init() {
	// quit if this function has already been called
	if (arguments.callee.done) return;
	
	// flag this function so we don't do the same thing twice
	arguments.callee.done = true;
	
	// kill the timer
	if (_timer) {
		clearInterval(_timer);
		_timer = null;
	}
	
	// create the "page loaded" message
	myCS = new PCS.cargaSecuencial();
};