/*
	WPAJAX v0.9a - Ajax Wrapper for Wordpress
	by Luca Di Bella (http://www.handsonweb.it) - MIT-style license.
	Relay on Mootools r381
	Backbutton support by Daniel Mota
	
	CLASS needs the basepath of your blog
	you can use <?php bloginfo("url") ?>
	
	ADDED SUPPORT FOR GOOGLE ANALYTICS
	ADDED SUPPORT FOR BACKBUTTON (Stil buggy IE, for ie FALSE is forced)
	ADDED SUPPORT FOR LIGHTBOX (Without modifyng the core slimbox library)
	
	TODO: Resolve flickering issue in IE
	TODO: Changing Document Title
	TODO: Check for newer version of mootools for reenabling AJAX onStateChange Event (NOW IS NOT WORKING);
	TODO: Profile link checks and optimize code on checklightbox (maybe we don't need it anymore)
*/

var wpajax = new Class({
	
	/*
	Private attribute for "State Manage"
	*/ 
	currentStatus: null,
	
	/*
	CONSTRUCTOR:
		Options:
			ajaxurl: point to the "main function" file
			ajaxUpdater: id of the element to be updated
			noAjaxClass: class a link should have in order to prevent an ajax call
			mainFxElem: id of the element Effect will be abblied to
			mainFxType: don't change this - at least for now
			globalAjax: a little tricky - id of the element to use as ajax message collector
			useAnalytics:
			historySupport:
	*/
	initialize: function(baseUrl, options){
		this.setOptions({
			ajaxUrl: 'wp-custom-functions/ajaxmanager.php',
			ajaxUpdater: 'content',
			noAjaxClass: 'noajax', // Classe da assegnare ai link per un redirect NO AJAX (internamente al sito)
			mainFxElem: 'content',
			mainFxType: 'opacity',
			globalAjax: null,
			useAnalytics: true, // Supporto per google analytics
			historySupport: false // Supporto history
		}, options);
		
		
		// DEFINISCO LE VARIABLI GLOBALI
		this.baseUrl = baseUrl;
		this.mainFx = new Fx.Style(this.options.mainFxElem, this.options.mainFxType, {duration: 600});
		this.mainFx.hide();
		
		// FUNZIONI DI INIT
		this.checkLinks();
		this.createGlobalAjaxDiv();
		
		// MAIN EVENTS
		this.addEvent('onRefresh', this.refresh.bind(this));
		
		// HISTORY SUPPORT
		if(window.gecko || window.khtml || window.ie7){
			this.options.historySupport = true;
		}
		if(this.options.historySupport == true){	
			window.addEvent('backbutton', this.historyListener.bind(this))
		}
		
	},
	
	historyListener: function(event){
		//console.log('history: ' + event.hash);
		//console.log(this.currentStatus);
		if((event.hash != this.currentStatus) && (event.hash != '')) this.loadContent(event.hash, false);
	},
	
	/* Effettua le operazioni di rewrite sui link sull'onclick */
	checkLinks: function(){
		$$('a').each(function(el){
			el.onclick = function(){
				if((this.isBlog(el) == true) && (this.checkLightbox(el) == true) && (this.checkMoodalbox(el) == true) && (el.id != 'closeme') && ($(el).hasClass(this.options.noAjaxClass) == false) && (el.href.test(/^jpg/i) == false)){
					this.loadContent(el.href, true);
					return false;
				} else if(el.id == 'closeme'){
					//console.log('chiuditi');
					this.fade().chain(function(){ $(this.options.ajaxUpdater).setHTML("")}.bind(this));
					this.mainFx.removeEvent('onComplete');
					return false;
				} else if(el.href.test(/^jpg/i) == true){
					//console.log('test: ' + el.href.test(/^jpg/i));
					return false;
				} else if(el.rel.test('^moodalbox', 'i') == true){
					console.log('open moodal');
					if(!window.gecko){
						MOOdalBox.open( // case matters
						el.href, // the link URL
						"Diario del Centenario", // the caption (link's title) - can be blank
						"800 500" // width and height of the box - can be left blank
						);
					} else {
						var w = 800;
						var h = 500;
						var l = (screen.width) ? (screen.width-w)/2 : 0;
						var t = (screen.height) ? (screen.height-h)/2 : 0;
						window.open(el.href, '', 'width='+w+',height='+h+',left='+l+',top='+t+',resizable=no,menubar=no,toolbar=no, scrollbars=no,locations=no,status=no');
					}
					return false;
				}
				
				//BLOCK ALL LINK (Fot test only)
				//return false;
				
			}.bind(this);
		}, this);
	},
	
	/* WRAPPER FOR AJAX CLASS */
	ajaxLoad: function(url, saveHistory){
		var querystring = url.substring(url.indexOf('?') + 1);
		querystring = '?' + querystring;
		
		var newurl = this.options.ajaxUrl + querystring;
		new Ajax(newurl, {
			method: 'get', 
			update: this.options.ajaxUpdater, 
			onComplete: function(){ 
				this.appear(); 
				this.fireEvent('onRefresh', [querystring]);
				
				// SUPPORTO GOOGLE ANALYTICS
				if(this.options.useAnalytics == true){ urchinTracker(url); };
				
				// SUPPORTO HISTORY
				this.currentStatus = querystring;
				if(this.options.historySupport == true){
					if(saveHistory){
						window.hash(querystring);
					}
				}
			}.bind(this),
			onStateChange: this.globalAjaxListener.bindAsEventListener(this), 
			evalScripts: true}).request();
	},
	
	loadContent: function(url, saveHistory){
		//console.log('loadContent fired: ' + saveHistory)
		this.fade().chain(this.ajaxLoad.pass([url, saveHistory], this));
	},
	
	refresh: function(q){
		//console.log('refresh q: '+ q);
		this.checkLinks();
		this.prepareForLightbox();
		Lightbox.init();
	},
	
	prepareForLightbox: function(){
		$$('div.onecolumn').each(function(el){
			$$('#'+el.id +' a').each(function(ael){
				if(ael.href.test('jpg$','i')){
					//adding Lightbox Gallery Support
					if($E('img', ael)){
						ael.rel = 'lightbox['+el.id+']';
						$(ael).addClass("imagelink");
					} else {
						$(ael).addClass("textimagelink");
						ael.rel = 'lightbox';
					}
				}
			})
		})
	},
	
	// VISUAL
	fade: function(){
		return this.mainFx.start(0);
	},
	
	appear: function(){
		this.mainFx.start(1);
	},
	
	
	// UTILS
	/* Controlla se il link appartiene al blog */
	isBlog: function(el){
		var link = el.href
		if(link.indexOf(this.baseUrl) == 0){
			return true;
		} else {
			return false;
		}
	},
	
	/* Controlla se il link fa il trigger di un lightbox */
	checkLightbox: function(el){
		//console.log('rel test: ' + el.rel.test('^lightbox', 'i'))
		//console.log('has class: ' + $(el).hasClass('imagelink'))
		return true;
		if((el.rel.test('^lightbox', 'i') == true) || ($(el).hasClass('imagelink')) == true){
			return false;
		}
			return true;

	},
	
	/* Controlla se il link fa il trigger di un moodalbox */
	checkMoodalbox: function(el){
		//console.log('modalbox rel test: ' + el.rel.test('$moodalbox', 'i'))
		//console.log('has class: ' + $(el).hasClass('imagelink'))
		//return true;
		if(el.rel.test('^moodalbox', 'i') == true){
			return false;
		}
			return true;

	},
	
	/* VISUAL DEL LOADING - NOT WORK!! */
	globalAjaxListener: function(e){
		//console.log('eccomi');
		var status = e.readyState;
		gbFx = new Fx.Style(this.options.globalAjax, 'opacity', {duration: 250, wait: true});
		
		switch(status){
			case 1:
				//console.log('starting');
				gbFx.start(1);
				break;
			case 2:
				//console.log('started');
				break;
			case 3:
				//console.log('in progress');
				break;
			case 4:
				//console.log('completed');
				gbFx.start.delay(20, gbFx, 0);
				break;
			default:
				//console.log('something is wrong...');
				break
		}
	},
	
	createGlobalAjaxDiv: function(){
		if(this.options.globalAjax == null){
			var gbAjax = new Element('div');
			gbAjax.id = 'gbAjax';
			$(gbAjax).setStyles({'position': 'absolute', 'top': 0, 'right': 0 , 'width': '120px', 'height': '32px', 'z-index': 100}).setHTML('Loading').injectInside(document.body);
			this.options.globalAjax = gbAjax;
			$(gbAjax).effect('opacity').hide();
		}
	}

})

wpajax.implement(new Options);
wpajax.implement(new Events);