
//////////////////////////////////////////////////////////////////////////////////////////////////////////////////////
//
//	SYSTEME QUI PERMET D'INCLURE DES FICHIERS HTML CONTENANT DU CODE JS
//	AU MOMENT DE L'APPEL D'UNE FONCTION QU'IL CONTIENT
//
// Améliorations à apporter : essayer d'intégrer le système avec Ajax
//
//////////////////////////////////////////////////////////////////////////////////////////////////////////////////////

var xINCCache = new Object();

function xINC(oParameter)
{
	//Déclaration des propriétés
	this.libraries= new Array();
	this.including = new Object();
	this.cached = 0;
	this.toInclude = 0;
	this.libsTotal = new Array();
	this.libsToLoad = new Array();
	
	if (oParameter == undefined) return false;
	if (oParameter.librairies == undefined || oParameter.librairies == null) return false;
	if (oParameter.librairies.length == 0) return false;
	if (oParameter.callback == undefined)oParameter.callback = null;
	
	this.callBack = oParameter.callback;
	
	// Determine la vraie liste des librairies à charger
	for(i=0;i<oParameter.librairies.length;i++)
	{
		var sLibrary = this.trim(oParameter.librairies[i]);
		if (sLibrary != "")
		{
			this.libsTotal.push(sLibrary);
			this.toInclude++;
			if (this.isCached(sLibrary))
			{
				this.cached++;
			}
			else
			{
				this.libsToLoad.push(sLibrary);
			}
		}
	}

	//Si toutes les librairies sont deja chargees
	if (this.toInclude == this.cached)
	{
		//Launch callback
		if (this.isFunction(this.callBack))
		{
			//this.callBack();
			setTimeout(this.callBack,1300);
			//this.callBack.call();
		}
		if (this.isString(this.callBack))
		{
			setTimeout(this.callBack+"()",1300);
		}
	}
	else
	{
		for(i=0;i<this.libsToLoad.length;i++)
		{
			var myQuery = this;
			xINCLoader.load(this.libsToLoad[i], 
			{
				beginLoading: function(e){myQuery.juststarted(e);},
				endLoading: function(e){myQuery.justfinished(e);}
			});
		}
	}
}


xINC.prototype.trim = function(str)
{
	  if (typeof str == 'string')return str.replace(/^\s*|\s*$/gi,"");
	  else return str;
}

xINC.prototype.isFunction = function(a)
{
	if (a == undefined) return false;
    return typeof a == 'function';
}

xINC.prototype.isString = function(a) {
    return typeof a == 'string';
}

xINC.prototype.juststarted = function(e)
{
	this.including[e] = "1";
}

xINC.prototype.justfinished = function(e)
{
	this.cached++;
	xINCCache[e] = "1";
	if (this.toInclude == this.cached)
	{
		//Launch callback
		if (this.isFunction(this.callBack))
		{
			//this.callBack();
			setTimeout(this.callBack,1300);
			//this.callBack.call();
		}
		if (this.isString(this.callBack))
		{
			setTimeout(this.callBack+"()",1300);
			
		}
	}
}

xINC.prototype.isCached = function(sFile)
{
	var sHash = xINCLoader.hash(sFile);
	if (xINCCache[sHash]!=undefined)return true
	else return false;
}

var xINCLoader = {
		
	getAgent : function(){
		if (this.ua) {
		  return;
		}
		
		var nua = navigator.userAgent, m;
		
		this.ua = {
		  gecko : 0,
		  ie    : 0,
		  webkit: 0
		};
		
		m = nua.match(/AppleWebKit\/(\S*)/);
		
		if (m && m[1]) {
			this.ua.webkit = parseFloat(m[1]);
		} else {
		  m = nua.match(/MSIE\s([^;]*)/);
		
		  if (m && m[1]) {
			 this.ua.ie = parseFloat(m[1]);
		  } else if ((/Gecko\/(\S*)/).test(nua)) {
			 this.ua.gecko = 1;
		
		    m = nua.match(/rv:([^\s\)]*)/);
		
		    if (m && m[1]) {
		    	this.ua.gecko = parseFloat(m[1]);
		    }
		  }
		}
	},	
	hash : function (sFile){
		if (!sFile || sFile=="") return 1;
		var h=0,g=0;
		for (var i=sFile.length-1;i>=0;i--)
		{
	 		var c=parseInt(sFile.charCodeAt(i));
			h=((h << 6) & 0xfffffff) + c + (c << 14);
			if ((g=h & 0xfe00000)!=0) h=(h ^ (g >> 21));
		}
		return h.toString();
	},
    load : function( fileName, options)
    {
        if (typeof(fileName) == 'object')
        {
           for (s in fileName)
                if (typeof(fileName[s]) == 'string')
                	xINCLoader.load(fileName[s],options);
            return;
        }
        if (this.loaded[fileName] || this.loading[fileName])
            return;
        
        //var head = document.getElementsByTagName('head')[0]; 
        //var head = document.getElementById('lazyload'); 
        var head = document.getElementsByTagName('body')[0]; 
        
        
        var dotPosition = fileName.lastIndexOf(".");
        var sExtension = fileName.substr(dotPosition);
		var filehash = xINCLoader.hash(fileName);
		 
		this.getAgent();
		
		fileName += "?rnd="+Math.random();    
        switch(sExtension)
        {
	        case ".css":
	            var obj = document.createElement('link'); 
	            obj.rel = "stylesheet";
	            obj.href = fileName;
	            obj.type = 'text/css';
	            head.appendChild(obj);
	        	break;
	        default:
	            var script = document.createElement('script'); 
	            script.src = fileName;
	            script.type = 'text/javascript';

	            if (this.ua.ie) {
	                // If this is IE, watch the last script's ready state.
	                script.onreadystatechange = function () {
	                  if (this.readyState === 'loaded' ||
	                      this.readyState === 'complete') {
	                	  xINCLoader.endLoading[filehash]();
	                  }
	                };
	              } else if (this.ua.gecko || this.ua.webkit >= 420) {
	                // Firefox and Safari 3.0+ support the load/error events on script
	                // nodes.
	                script.onload  = xINCLoader.endLoading[filehash];
	                script.onerror = xINCLoader.endLoading[filehash];
	              }

	              if (!this.ua.ie && !this.ua.gecko && !(this.ua.webkit >= 420)) {
	                // Try to use script node blocking to figure out when things have
	                // loaded. This works well in Opera, but may or may not be reliable in
	                // other browsers. It definitely doesn't work in Safari 2.x.
	                script = document.createElement('script');
	                script.appendChild(document.createTextNode('xINCLoader.endLoading["'+filehash+'"]();'));
	              }	  
	              document.getElementsByTagName('head')[0].appendChild(script);
	            
	        	break;	        	
        }

        with (xINCLoader)
        {
            options = options || {};
            var emptyFunction = function(){};
            _beginLoading[filehash] = (options.beginLoading || emptyFunction);
            _endLoading[filehash] = (options.endLoading || emptyFunction );
            
            xINCLoader.beginLoading[filehash] = function(e)
                {
                    loading[filehash] = true;
                    _beginLoading[filehash](e);
                };
            xINCLoader.endLoading[filehash] = function(e)
                {
                    loading[filehash] = false;
                    loaded[filehash] = true;
                    _endLoading[filehash](e);
                };
                
            beginLoading[filehash](filehash);
            endLoading[filehash](filehash);
        }
    },
    loading : {},
    loaded : {}, 
    _beginLoading: function(){},
    _endLoading: function(){},
    beginLoading: function(){},
    endLoading: function(){}
};

