
if ( window.addEventListener ) window.addEventListener( 'load', doLoad, 0 );
else window.attachEvent( 'onload', doLoad );

var loader = new Preloader();
function doLoad(){ loader.execute(); }

function Preloader()
{
	this.counter, this.bar;
	this.images = 0;
	
	this.initialize = function( id ) 
	{     
		this.bar 	= document.getElementById( id );
		
		if (!this.bar) 
		{
			this.bar 				= document.createElement('div');
			this.bar.id 			= id;			
			this.bar.innerHTML 	= 'loading';
			
			this.bar.style.color           = '#fff';
			this.bar.style.position        = 'absolute';
			this.bar.style.top             = 0;
			this.bar.style.right           = 0;
			this.bar.style.backgroundColor = '#f00';
			this.bar.style.border          = '1px solid #f99';
			this.bar.style.width           = '80px';
			this.bar.style.padding         = '4px';
			this.bar.style.fontFamily      = 'Arial, Helvetica, sans';
			this.bar.style.display         = 'block';
			
			document.body.insertBefore( this.bar, document.body.firstChild );
		}		
	},
	
	this.setStatus = function()
	{
		var ctr = 0;
		
		if( this.images < document.images.length ) 
		{
			this.images = document.images.length;
		}
		
		for( var i=0; i < this.images; i++ ) 
		{
			if(document.images[i] && document.images[i].complete) 
			{
				ctr++;
			}
			else if(document.images[i].complete == null) 
			{
				ctr++;
			}
		}
	
		var buff 	= 100/this.images;
		var len 	= Math.round(ctr * buff);
		
		if( len > 100 ) 
		{
			len = 100;
		}
		
		this.bar.innerHTML = len + ' % loaded';
		
		window.status = ctr + ' / ' + this.images;
		
		if( ctr >= this.images ) 
		{
			if( this.counter ) 
			{
				clearInterval( this.counter );
			}
			
			this.counter = setInterval( "loader.setComplete()", 100 );
		}
	},
	
	this.setComplete = function() 
	{
		window.status = 'Done';
		
		this.bar.style.display = 'none';;	
	},
	
	this.execute = function() 
	{     
		this.initialize( "loaderBox" );
		
		if( document.images && document.images.length ) 
		{
			if( this.counter ) 
			{
				clearInterval( this.counter );
			}
			
			this.counter = setInterval( "loader.setStatus()", 100 );
		}
		else 
		{
			this.setComplete();
		}
	} 
};