/*
 * Lazy Load de imagenes con Mootools http://uninstallme.com/lazy-load-de-imagenes-con-mootools
 * Basado en lazierLoad ñ Javascript Image Lazy Loader for Prototype http://www.bram.us/projects/js_bramus/lazierload/
 */
 
(function(){
    // privadas (Mootools sin conflicto con otras librerias)
    var $ = document.id;
    
    // publicas
    this.Kcmr = this.Kcmr || {};

    Kcmr.MooLazyLoad = new Class({
    	Implements: Options,
    	options: {
    		blank: 'images/blank.gif'
    	},
    	
    	initialize: function(element, options){
    		this.setOptions(options);
    		this.element = element;		
    		this.originalSrc = this.element.src; // guardamos el atributo src original
    		this.hideNotOnViewport(); // ocultacion inicial de las imagenes no visibles
    		this.showOnViewport(); // mostramos imagenes en el area visible de la ventana con el evento scroll
    	},
    	
    	hideNotOnViewport: function(){
    		if(!this.isOnViewport()){
    			this.element.src = this.options.blank;
    			this.element.fade('hide');
    		}
    	},
    	
    	showOnViewport: function(){
    		window.addEvent('scroll', function(){
    			if(this.isOnViewport()){
    				this.element.fade('in');
    				this.element.src = this.originalSrc;				
    			}
    		}.bind(this));
    	},
    	
    	isOnViewport: function(){		
    		// Calcular la posicion Y de un elemento en pantalla http://tinyurl.com/yax5w2o		
    		var a = window.getScroll().y; // espacio no visible por arriba
    		var b = this.element.getCoordinates().top; // posicion top de la imagen respecto a window 
    		var c = window.getSize().y; // altura del area visible de la ventana
    		var d = this.element.height; // altura de la imagen
    		
    		var e = (b - a) + (d / 2);
    		return (e < (c + d));	// esta en el area visible de la ventana?	
    	}
    });  
    
    
    // inicializamos
    window.addEvent('domready', function(){
    	$$('div.post img').each(function(el){
    		new Kcmr.MooLazyLoad(el,{
    		  blank: '/blog/wp-content/themes/coolz/images/blank.gif'
    		});
    	});
    });      
    
})();
