/*
Script: MooImagePreload.js
	MooImagePreload - Preloads and fades in all (optionally) images on the current page

Version: 
	1.0

License:
	MIT-style license.

Copyright:
	Copyright (c) 2009 [Oskar Krawczyk](http://nouincolor.com/).

Dependencies:
	- MooTools-core 1.2+ or higher [mootools-core.js](http://www.mootools.net/core/)
	- MooTools-more 1.2+ or higher [mootools-more.js](http://www.mootools.net/more/)
	  - Assets
*/

Element.implement({
	cloneProperties: function(source) {
		return this.setProperties(source.getProperties('id', 'width', 'height', 'class', 'alt', 'title', 'style'));
	}
});

var MooImagePreload = new Class({
	Implements: [Options],
	options: {	
		// noImage: $empty
	},
	
	initialize: function(find, options) {
		this.setOptions(options);
		this.base = $type(find) == 'array' ? find : $$(find);
		
		this.findAll();		
	},
	
	findAll: function() {
		this.base.each(this.preload.bind(this));
	},
	
	preload: function(source) {
		source.store('defaut:src', source.get('src')).set('src', '');		

		new Asset.image(source.retrieve('defaut:src'), {
			'styles': 	{opacity: 0},
			'onload': 	this.replaceSource.bind(source),
			'onerror': 	function() {				
				source.set({
					'src': this.options.noImage,
					'styles': {
						opacity: 0
					}
				}).fade('in');
			}.bind(this)
		});
	},
	
	replaceSource: function(source) {
		source.replaces(this).cloneProperties(this).fade('in');
	}
});
