// Bibliothèque pour le modèle de page Ajax.
// Tuto : http://www.clever-age.com/veille/blog/comment-gerer-une-navigation-en-ajax.html
//
// Les URL doivent être des URL normales, sans ancre, accessibles directement.
//
// Toutes les URL a réécrire douvent avoir le rel 'ajx'
// Les pages appelées par un robot sont appelées sur leur URL normales.
// Pourles navigateurs possédant js, l'URL devrat petre redirigée vers la racine + ancre
// Ex : http://serveur.tld/cat1/page1.html -> http://serveur.tld/#/cat1/page1.html

// Nécessite la librairie JQuery

// Pour appeler la réécriture, inclure ce fichier dans le head, puis initialiser :
// window.phpkod.plugins.ajaxUrl.serverUrl = 'http://www.monserveur.tld/';
// window.phpkod.plugins.ajaxUrl.ajaxFunc = xajax_get;
// window.phpkod.plugins.ajaxUrl.init();

var AjaxUrlController = function(){
	this.init.apply(this,arguments);
	return this;
}

AjaxUrlController.prototype = {
};
window.phpkod = window.phpkod || {};
window.phpkod.plugins = window.phpkod.plugins || {};
window.phpkod.plugins.ajaxUrl = 	{

		// L'adresse racine du serveur pour la redirection si besoin.
		serverUrl : null,
		
		// La fonction callback qui appelle les nouvelles données en ajax.
		ajaxFunc : null,
		
		relName : 'ajxurl',
		relRegex : /ajxurl/,
		
		// Initialise une nouvelle instance
		init : function()
			{
				if(!window.location.hash)
					{
						var u = window.location.href;
						u = u.replace(this.serverUrl,'');
						hash = '#/'+ ( u ? u : '') ;
						window.location = this.serverUrl + hash;
					}
				$(document).ready(function(){
					$.historyInit(window.phpkod.plugins.ajaxUrl.pageload);
				});
				this.rewriteUrl();
				
			},
			
		pageload : function( hash )
			{
				if(hash) {
					hash = hash.replace('/', '');
				    window.phpkod.plugins.ajaxUrl.ajaxFunc(hash);
				}
			},
		
		rewriteUrl : function()
			{

				$("a[rel='ajxurl']").click(function(){
					   //suppression du mot cle history, pour que les liens ne soient surchargés qu'une seule fois
					   this.rel = this.rel.replace(window.phpkod.plugins.ajaxUrl.relName, ''); 
					   // mise à jour de l'ancre
					   var hash = this.href;
					   hash = hash.replace(window.phpkod.plugins.ajaxUrl.serverUrl, ''); 
					   // suppression du caractère #
					   hash = hash.replace(/^.*#/, ''); 
					   // chargement dans l'historique et appel de pageload
					   // ! Must adding a slash first for home / blank page.
					   $.historyLoad('/'+hash); 
					   // trés important : désactivation du clic du lien a
					   return false; 
				 });
			}

};
