/*
ContentUpdater 1.0 

Source code by Luca Reghellin - http://www.reghellin.com - email@reghellin.com
Required: mootools 1.2

//TODO
- Valutare se rendere disponibile anche la selezione dei link via # (id) o . (classe), per poter istanziare 
  pi ContentUpdater con diverse requestOptions
- Valutare se condensare le azioni di onload in un unico metodo utilizzato sia da sendAjaxRequest che da loadImage


*/

//var u = new Utils();


var ContentUpdater = new Class({

	Implements:Options,
	/*se non c' menuId, sono controllati i rel*/
	/*se non c' loaderId, il loader  istanziato nel #content, il content avr position:relative. */
	/*contentBox: obbligatorio. */
	/*contentId: opzionale. L'id che verr usato per il div content istanziato in contentBox */
	options:{
		menuId:'menu2',
		contentBox:'cuContentBox',
		contentId:'cuContent',
		loaderImage:null,
		loaderId:/*'cuLoader'*/null,
		loaderZIndex:1500,
		loaderOpacity:0.5,
		fadeFx:false,
		auxFunction:null,
		requestOptions:{
			method:'get',
			autoCancel:true
		}
	},

	initialize:function(options){
		
		this.setOptions(options);
		this.o = this.options;
		
		this.menu = null;
		this.content = null;
		this.contentBox = null;
		this.loaderBox = null;
		this.loaderSize = null;
		this.loader = null;
		//this.showLoader = false;
		
		this.currentRequest = null;
		this.currentResponse = null;
		//this.currentRespon
		
		var init = this.preparePlayers();
		if(!init){ return; }
		this.prepareEffects();
		this.prepareEvents();
		
	},//end initialize();

	sendAjaxRequest:function(location,vars){
		
		var opt = { url:location,
					onRequest:function(){
						this.showLoader();
					}.bindWithEvent(this),
					onSuccess:function(text,xml){
						//u.report(text)
						this.currentResponse = text;
						this.hideLoader();
						this.showContent();
					}.bindWithEvent(this),
					onFailure:function(transport){ /*TODO*/ }.bindWithEvent(this)
				   };

		var rOptions = $merge(this.o.requestOptions,opt);

		this.currentRequest = new Request(rOptions);
		this.currentRequest.send();
	},
	
	loadImage:function(location){
		this.showLoader();
		var img = new Asset.image(location,{
			onload:function(img){
				this.currentResponse = img;
				this.hideLoader();
				this.showContent();
			}.bindWithEvent(this)
		});
	},
	
	//if tweenOpacity.onComplete && content.opacity == 0
	resetContent:function(){
		this.content.empty();
		if(this.currentResponse){ 
			if($type(this.currentResponse) == 'element'){ this.content.grab(this.currentResponse); }
			else if($type(this.currentResponse) == 'string'){ this.content.set('html',this.currentResponse); }
		}
	},
	
	showContent:function(){
		this.content.retrieve('tweenOpacity').start(0).start(1);
	},
	
	showLoader:function(){
		if(!this.loader){ return; }
		this.loader.setStyles({
			'left':this.loaderBox.getSize().x/2,
			'top':this.loaderBox.getSize().y/2
		});
		this.loader.tween('opacity',this.o.loaderOpacity);
	},
	
	hideLoader:function(){
		if(!this.loader){ return; }
		this.loader.tween('opacity',0);
	},
	
	prepareEffects:function(){
		//TODO: test se non c'
		if(this.loader){ this.loader.set('tween',{ duration:'short',link:'cancel' }); }
		
		
		this.content.set('tween',{ link:'chain' });
		
		//TODO
		//sistemare getter/setter fx per 1.2 - 'opacity' dovrebbe essere passata come propriet.
		this.content.store('tweenOpacity',new Fx.Tween(this.content,{property:'opacity',duration:500,link:'chain'}));
	},
	
	
	prepareEvents:function(){
		//console.log('ok')
		$$(this.menu).addEvent('click',function(e){
				var button=($(e.target).match('a')) ? $(e.target) : $(e.target).getParent('a');
				e.preventDefault();
				if(this.o.auxFunction){  this.o.auxFunction(); }
				this.checkLink(button.getProperty('href'));
				//alert(this.o.auxFunction);
				
				//console.log('click')
			}.bindWithEvent(this)
		);
		
		this.content.retrieve('tweenOpacity').addEvent('onComplete',function(){
			if(this.content.getStyle('opacity') == 0){ this.resetContent(); }
		}.bindWithEvent(this));
	},
	
	checkLink:function(url){
		var splitted = url.split('?');
		var location = splitted[0];
		if(location.indexOf('#') == location.length-1){ return; }//no link
		var vars = splitted[1];
		var ext = location.substring(location.length-4);
		//TODO: l'estensione pu essere anche maiuscola. Prendere codice dalla milkbox
		if(ext == '.jpg' || ext == '.gif' || ext == '.png'){ 
			this.loadImage(location); 
		} else {
			this.sendAjaxRequest(location,vars);
		}
	},

	preparePlayers:function(){
		this.menu = (this.o.menuId) ? this.buildMenuFromId(this.o.menuId) : this.buildMenuFromRel();
		this.contentBox = $(this.o.contentBox);
		//console.log(this.menu.length,this.content)
		if(this.menu.length == 0 || !this.contentBox){ return false; }
		this.content = new Element('div',{ 'id':this.o.contentId, 'styles':{ 'opacity':0, 'visibility':'hidden' } });
		this.contentBox.grab(this.content);
		this.buildLoaderHTML();
		return true;
	},
	
	buildMenuFromId:function(id){
		return $(id).getElements('a');//valutare se racchiudere in un $$
	},
	
	buildMenuFromRel:function(){
		var cuLinks = $$('a').map(function(a){ if(a.rel && a.rel.test(/^cu/i)){ return a; } });
		return cuLinks;
	},
	
	buildLoaderHTML:function(){
		if(this.o.loaderImage){
			//uso asset in modo da poter controllare se effettivamente l'immagine c'.
			var img = new Asset.image(this.o.loaderImage, { 
				onload:function(img){
					this.loaderSize = $H(img.getProperties('width','height')).map(function(item, index){
						return item.toInt();
					});
					//se il path dell'immagine  sbagliato:
					if(this.loaderSize.height == 0 && this.loaderSize.width == 0){ /*this.showLoader = false;*/ return; }
					//setta il contenitore del loader
					this.loaderBox = (this.o.loaderId) ? $(this.o.loaderId) : this.contentBox;
					this.loaderBox.setStyle('position','relative');
					
					this.loader = new Element('div',{
							'styles':{
								'position':'absolute',
								'z-index':this.o.loaderZIndex,
								'width':this.loaderSize.width,
								'height':this.loaderSize.height,
								'marginLeft':-this.loaderSize.width/2,
								'marginTop':-this.loaderSize.height/2,
								'opacity':0,
								'backgroundColor':'#000000',
								'background':'url('+this.o.loaderImage+') center no-repeat'
							}
					});
					
					this.loaderBox.grab(this.loader);
					
				}.bindWithEvent(this)//fine onload
			});//fine asset
		}//fine if	
	}//fine buildLoaderHTML();
	
});//FINE CLASSE

//istanza
window.addEvent('domready',function(){
	
	function aux(){
		if($('cuContentBox').hasClass('spacer')){
			$('cuContentBox').removeClass('spacer');
		}
// 		var h = ($('cuContentBox').getStyle('height').toInt() == 0);
// 		var ov = ($('cuContentBox').getStyle('overflow') == 'hidden');
// 		if(h && ov){
// 			$('cuContentBox').setStyles({ 'height':'auto','overflow':'auto'})
// 		}
	}

	cu = new ContentUpdater({ auxFunction:aux });

});



