/*
	Imager preloader v.1
	* Copyright 2011, Leysam Rosario
	* Dual licensed under the MIT or GPL Version 2 licenses.
*/

//script configuration
var image_options = {
	loadDelay: 1000,//Delay of loading, default 1000(1000 is equal 1 sec)
	fadeDuration: 1000,//fade duration time. default 1000
	OneByOne: true,//image load 1 by 1
	OneByOneDuration: 1000,//image load 1 by 1
	errorMessage: 'Can\'t load image'//Error that will be show if the image is not load or if it has a error
}

var imageLoader = function(images,options){
	var images = images;
	var options = options;
	this.construct = function(img){
		for(i=0;i<img.length;i++){
			if(options.OneByOne){
				this.init(img[i]);
			}else{
				this.init(img[i]);
			}
		}
	}
	this.init = function(imgElem){
		var target = imgElem;
		var parent = $(target).parent();
		var img = new Image();
		img.src = $(target).attr('src');
		img.onload = function(){
				setTimeout(closeParent,options.loadDelay);//For some reason we need to use this process rather than use the .delay function XD
				function closeParent(){
				 parent.attr('class','img-holder');
				};
				$(target).css({visibility:'visible',opacity:0}).delay(options.loadDelay)
					.animate({opacity:1},options.fadeDuration,function(){
				});
		}
		
		$(target)
			.load(function(){ 
				setTimeout(closeParent,options.loadDelay);//For some reason we need to use this process rather than use the .delay function XD
				function closeParent(){
				 parent.attr('class','img-holder');
				};
				$(target).css({visibility:'visible',opacity:0}).delay(options.loadDelay)
					.animate({opacity:1},options.fadeDuration,function(){
				});
				
			}).css({visibility:'hidden'})
			.error(function(){
				setTimeout(closeParent,options.loadDelay);//For some reason we need to use this process rather than use the .delay function XD
				function closeParent(){parent
				.css({opacity:0})
				.attr('class','img-holder-error')
				.text(options.errorMessage)
				.animate({opacity:1});
				};
			})
			.attr('src',target.src)
			.parent()
				.attr('class','img-holder-loading')
				.width($(target).width())
				.height($(target).height());
	}
	this.construct(images);
}
