/**
 * gallery.js
 * PB 14/04/08
 * Simple gallery with preloader;
 *
 * Depends:
 * ===================================
 * base.js  http://dean.edwards.name/weblog/2006/03/base/
 * jQuery.js http://http://jquery.com/
 * preloader.js 
 */

var Gallery = Base.extend({

    preloader: null,    // ref to preloader;
    image: null,        // current image;
    gif: null,          // preloader visual representation;     
    $: null,            // shorthand for jQuery;        

    constructor: function() {
        // requires jQuery;
        if( ! jQuery ){
            return false;
        }
	},
	
	init: function( root, $ ){
	    this.$ = $;
	    this.gif = root + "loader.gif";
        // get gallery;
	    var gallery = jQuery( "#gallery" );
	    var self = this;
	    if( ! gallery || gallery.length == 0 ){
		    return false;
		};
	    //bind mouse events for interaction;
	    gallery.each(function(){
	        var links = self.$( "a", gallery );
	        links.bind("click", function( e ){
	            self.loadContent.call( self, e );
	            return stopDefault( e );
	        });
	    });
        // add preloader;
		var div = this.$( "#gallery-image", gallery );
		var img = this.$( "img", div ); 
		img.before( this.getPreloader() );   
	},
	
	getPreloader: function(){
	    if( ! this.preloader ){
	        this.setPreloader( this.gif );
		}
		return this.preloader.getHTML();
	},
	
	setPreloader: function( image ){
	    if( image ){
	        this.preloader = new Preloader();
	        this.preloader.init( image, 50, 50 );
		    return this.$( this.preloader.getHTML() )
		            .css( "margin", "70px 0 0 123px" );
	    }
	    return false;
	},
	
	loadContent: function( e ){
	    var elem, path;
	    e = e || window.event;
	    elem = e.target || e.srcElement;
	    this.cleanGallery(); 
		path = elem.parentNode.href;
		this.preloader.load( path, this.contentLoaded, this );
		this.$( this.getPreloader() ).show();                  
	},
	
	cleanGallery: function(){
		var div = this.$( "#gallery-image" );
		var img = this.$( "img:last", div ); 
		if( img ) img.remove();
	},
	
	contentLoaded: function( img ){    
	    var self = this;
	    
	    this.image = img;
	    this.image.width = "297";
	    this.image.height = "195";
	    
        setTimeout( function(){
               self.showContent();
            }, 500 );
	},
	
	showContent: function(){
	    this.$( this.getPreloader() ).hide();
	    
	    var div = this.$( "#gallery-image" );
		this.$( "#mask", div ) 
	        .before( this.image );
	        
	    this.$( "img:last", div )
	        .css( "opacity", 0 )
	        .fadeTo( "slow", 1 );
	}
});