/*
    LoZooDiVenere / KtCN
	AJAX navigator 1.0b
	
	Copyright 2009 www.lozoodivenere.it, www.ktcn.it
*/
var AJAX_url = {
	getHash: function(){
		var hash = window.location.hash;
		return hash.substring(1); // remove #
	},
	getLinkTarget: function(link) {
		return link.href.substring(link.href.indexOf('#')+1);
	},
	setUrl: function(url){
			//var hash = AJAX_url.getHash();
			window.location.hash = url;//AJAX_url.getHash();
/*			var l = window.location.href;
			//var re = "/\b#[a-z]+\b/g";
			var re = new RegExp("#.*$");
			//var re = "/#.*$/g";
			//var r = re.exec(l);
			//alert(JSON.encode(r));
			//if (r == null) //l = l + "#";
			//if (!l.match(re))
			//alert(r.toString());return;
			if (!l.test(re,"i"))
			 window.location.href = l + '#' + url;
			else
		     //window.location = l.replace(re, "#"+url);
			 window.location.href = l.replace(re, "#"+url);
			//var url_parts = window.location.split('#');
			//if (typeof url_parts[1] == "undefined")
			//return newStr.replace(/_/g, ' ').replace(/#/g, '').capitalize();*/
	},
	
	redirectUrl: function(){
			var hash = AJAX_url.getHash();
			if (hash)
			 window.location.href = hash;
/*			var l = window.location.href;
			var p = l.split("#");
			if (typeof p[1] != "undefined")
			{ window.location.href = p[1];
			}*/
	}
}

var AJAX_nav = new Class({
	options: {
		destination: 'ajax_conteiner',
		ref_class: "ajaxnav",
		ajax_spinner: "ajax_spin",
		//url:this.getProperty('href'),
		temp_update: "ajax_temp",
		//destination_update:$(this.getProperty('rel')),
		fx:true,
		async:false,
		evalScripts:false,
		pre_request:false,
		post_request:false,
		wait_for_pre_request: true,
		pre_request_go_on_flag: false,
		to_top: false,
		link: "cancel"
	},
	
	initialize: function(elements, options) {
		this.setOptions(options);
		this.elements = elements;
		this.req_obj = new Request.HTML(this.options);
		this.req_obj.processHTML=function(text){
			var match = text.match(/<body[^>]*>([\s\S]*?)<\/body>/i);
			text = (match) ? match[1] : text;
			var container = new Element('div');
			return $try(function(){
				var root = '<root><![CDATA[\n' + text + '\n]]></root>', doc;
				if (Browser.Engine.trident){
					doc = new ActiveXObject('Microsoft.XMLDOM');
					doc.async = false;
					doc.loadXML(root);
				} else {
					doc = new DOMParser().parseFromString(root, 'text/xml');
				}
				root = doc.getElementsByTagName('root')[0];
				for (var i = 0, k = root.childNodes.length; i < k; i++){
					var child = Element.clone(root.childNodes[i], true, true);
					if (child) container.grab(child);
				}
				return container;
			}) || container.set('html', text);
		}
		this.req_obj.setOptions({update:this.options.temp_update});
		//alert(JSON.encode(this.elements));
		var o = this;
		this.elements.each(function(el, i){
		 //alert(JSON.encode(el));
		 el.store("ajax_nav_obj",o);
		 el.addEvent("click",function(e){
				e = new Event(e).stopPropagation();
				//alert(this);
				var nav = this.retrieve("ajax_nav_obj");
				var ro = nav.req_obj;
				var d = this.getProperty('rel');
				var dp = d.split('|');
				var h = (this.get("href").split('#'))[0];
				this.set("href",h);
				//if (ro.options.pre_request)
				// ro.options.pre_request(ro);
				ro.setOptions({url:this.getProperty('href'),
								destination_update: dp[0],
								extra_url: "ajax_nav=1"+(typeof dp[1] == "undefined"?"":"&pgobj_keys="+dp[1]),
								//ro: ro,
								onRequest: function(){
									$(this.options.ajax_spinner).setStyle('visibility','visible');
									if (this.options.pre_request)
									 this.options.pre_request(this);
									//if (this.options.wait_for_pre_request)
									// for(;!this.options.pre_request_go_on_flag;){}
								}.bind(ro),
								onComplete: function(){
									//if (!this.options.pre_request_go_on_flag) alert("attenzione, non ho finito!");
									try {
										//var pageTracker = _gat._getTracker("UA-5068288-1");
										//alert(this.options.url);
										pageTracker._trackPageview(this.options.url);
										} catch(err) {}
									}.bind(ro),
								onSuccess: function(responseTree, responseElements, responseHTML, responseJavaScript){
									AJAX_url.setUrl(this.options.url);
									$(this.options.ajax_spinner).setStyle('visibility','hidden');
									if (this.options.fx)
									{ var ta = $(this.options.temp_update);
									  ta.set('html',responseHTML);
									  var coords = ta.getCoordinates();
									  var fx_out = new Fx.Morph(this.options.destination_update,{duration:750, link:'cancel', transition: Fx.Transitions.Quad.easeOut});
									  var fx_in = new Fx.Morph(this.options.destination_update,{duration:750, link:'cancel', transition: Fx.Transitions.Quad.easeOut});
									  fx_out.start({'height':coords.height,'opacity':0}).chain(function(){
																$(this.options.destination_update).set('html',responseHTML);
																$(this.options.update).set('html',"");
																$exec(responseJavaScript);
																fx_in.start({'opacity':1});
																$(this.options.destination_update).setStyle("height","auto");
																if (this.options.to_top)
																 win_top_fx.toElement("top");
															}.bind(this));
									}
									else
									 if (this.options.post_request)
									 { this.options.post_request.periodical(250,this,{'html':responseHTML,'js':responseJavaScript});
									 }
									 else
									 { $(this.options.destination_update).set('html',responseHTML);
									   $exec(responseJavaScript);
									 }
								}.bind(ro)
							 });
				//if (!ro.options.pre_request)
				 ro.send(ro.options.extra_url);
				return false;
			});
		});
	    this.elements.removeClass(this.options.ref_class);
	}
});
AJAX_nav.implement(new Events, new Options);
