
/**************************************************************

	Script		: Page Loader
	Version		: 1.0
	Authors		: Samuel Birch
	Desc		: load pages via AJAX.
	Licence		: Open Source MIT Licence

**************************************************************/

var pageLoader = new Class({
							  
	getOptions: function(){
		return {
			links: '.loadMe',
			loadInTo: 'content',
			loadFrom: 'content',
			onStart: Class.empty,
			onRequest: Class.empty,
			onComplete: Class.empty
		};
	},

	initialize: function(options){
	
		var Fade = new Fx.Style('toggler', 'opacity', {
		    duration: 2000,
		    transition: Fx.Transitions.quartInOut
		});
	
		this.setOptions(this.getOptions(), options);
		
		this.links = $$(this.options.links);
		this.links.each(function(el,i){
			el.addEvent('click',function(e){
				if(e != undefined){
					new Event(e).stop();
				}
				Fade.start(1,0);
				
				var link = this;
				window.setTimeout(function(){
					link.start(el);
				}, 3000, true);
				
			}.bind(this));
		}.bind(this));
	},
	
	setContent: function(){
		var temp = new Element('div').setProperties({id:'temp'}).setStyles({display:'none'}).injectInside(document.body);
		temp.setHTML(this.content.response.text);
		var newEl = $('temp').getElement('#'+this.options.loadFrom);
		$(this.options.loadInTo).replaceWith(newEl);
		newEl.setProperties({id:this.options.loadInTo});
		temp.remove();
	},
	
	start: function(el){
		this.options.onStart();
		
		this.content = new Ajax(el, {
								method: 'get',
								onRequest: this.request.bind(this),
								onComplete: this.complete.bind(this),
								autoCancel: true,
								evalScript: true
							}).request();
	},
	
	complete: function(){
		var Fade = new Fx.Style('toggler', 'opacity', {
		    duration: 2000,
		    transition: Fx.Transitions.quartInOut
		});
		
		Fade.start(0,1);
		
		this.setContent();
		this.options.onComplete();
	},
	
	request: function(){
		this.options.onRequest();
	}

});
pageLoader.implement(new Events);
pageLoader.implement(new Options);


/*************************************************************/
