﻿
function httpRequest_v2()
{
    var m_str_idElmt_forWaitingMsg = ""; 
    var m_str_txtErreur = "";
    
    // chemin vers la page qui nous interesse
    var m_str_file = "";
    var m_str_param = "";
    var m_str_method = "";
    var m_bool_isAsynchrone = true;
    var m_obj_xmlHttp = null;
    var m_str_waitingMessage = "";
	var m_str_tagId = "";
	var m_str_moreAction = "";
    var m_objHtml_forNv = null;
    var m_objTimer  = null;
    var m_str_curHash; 
    var m_str_locationHash_forIe = ""
    
    var pv_onReadyStateFunction_loadContent = function()
    { 
        if (!m_bool_isAsynchrone || m_obj_xmlHttp.readyState == 4) 
		{ 
		 
			    if (m_str_waitingMessage.length > 5)
				{pv_hideWaitingMessage()}
    					
    			// on charge le div on l'on va afficher la réponse
				var objMain=document.getElementById(m_str_tagId);
				if (objMain){objMain.innerHTML = m_obj_xmlHttp.responseText;}
			
				// on execute le script qui est demandé en plus
				 eval(m_str_moreAction);
				
				// initialisation des liens de type xhr
				 initXHR();  
				 m_str_curHash = pv_getLocationHash();
				 
				// on check si l'ancre actuel correspond à l'ancre chargé
                  if (setTimeout) m_objTimer = setTimeout(pv_check_hash, 900);
		 
	    }
    }
	
	var pv_getLocationHash = function()
	{
	    if (location.hash.indexOf("#_") < 0 && m_str_locationHash_forIe.indexOf("#_") < 0)
	    { 
    	    return ""
	    }
	    if (navigator.userAgent.match(/MSIE (\d+\.\d+)/) && navigator.userAgent.match(/MSIE (\d+\.\d+)/)[1] >= 5.5)
        { 
            return  m_str_locationHash_forIe;
        }
        else
        {
            return location.hash
        }
	}
	
	
 	var pv_check_hash = function()
 	{  
 	    // on stop l'horloge
 	    if (m_objTimer){ clearTimeout(m_objTimer);}
 	    // si le hash est différent, l'utilisateur a cliqué sur précédent, alors il va falloir rechargé la page !!!!!
 	    if (pv_getLocationHash().length > 0 && m_str_curHash != pv_getLocationHash())
 	    { 
 	        var tmpHash;
 	        m_str_param = '';
 	        
 	       
 	        
            // on recupere le bon hash 
            m_str_curHash = pv_getLocationHash(); 
 	        // on zappe le '#'
 	        tmpHash = m_str_curHash.substr(2);
 	        
 	        
 	        var tabValue = tmpHash.split('&');
 	        
 	        for (var i=0; i<tabValue.length; i++) 
 	        {
 	            var curLine = tabValue[i];
 	            
 	            if (curLine.indexOf('file') > -1)
 	            {
 	                m_str_file = curLine.split('=')[1];
 	            }
 	            else if (curLine.indexOf('target') > -1)
 	            {
 	                m_str_tagId = curLine.split('=')[1];
 	            }
 	            else if (m_str_param  == '')
 	            {
 	                m_str_param = curLine;
 	            }
 	            else
 	            {
 	                m_str_param = m_str_param + '&' + curLine;
 	            }
 	        }
 	        
 	        if (m_str_waitingMessage.length > 5)
		    {pv_ShowWaitingMessage(m_str_waitingMessage)}

        
          
             
		    // Préparation de l'envoi en fonction de la method !
		    if (m_str_method == "GET"){pv_sendGetReq();}
		    else{pv_sendPostReq();}
             if (m_bool_isAsynchrone)
            {m_obj_xmlHttp.onreadystatechange = pv_onReadyStateFunction_loadContent;}
		     if (!m_bool_isAsynchrone)
		    {pv_onReadyStateFunction_loadContent()}
     	         
 	        
 	    }
 	    else
 	    {
 	        // on check si l'ancre actuel correspond à l'ancre chargé
            if (setTimeout) m_objTimer = setTimeout(pv_check_hash, 300);
 	    }
 	}
 	
 	this.forIE = function(tmpHash)
 	{
 	   m_str_locationHash_forIe = tmpHash;
 
 	}
 	
 	this.initPage = function(waitingMessage)
 	{
 	    m_str_waitingMessage = waitingMessage;
 	  
 	  
 	    pv_check_hash();
 	}
 	
    //=====================================================================================
	// charge le contenu dynamique d'une page et l'ecrit dans un div à l'aide de l'objet XHR() 
	this.LoadContent = function(pathToScript, params ,method, TAGID,waitingMsg,MoreAction, isNotAsynchrone) 
	{ 
	    pv_constructor(pathToScript, params ,method, isNotAsynchrone);
	 
	    clearInterval(m_objTimer);
		
		// Récupération du message d'attente
		m_str_waitingMessage = waitingMsg;
		m_str_tagId = TAGID;
		m_str_moreAction = MoreAction;
		
	    
	    if (navigator.userAgent.match(/MSIE (\d+\.\d+)/) && navigator.userAgent.match(/MSIE (\d+\.\d+)/)[1] >= 5.5) 
	    { 
	        var tmpHash = "#_target=" + m_str_tagId + "&" + m_str_param + "&file=" + m_str_file;

	        with (frames["__nv_form_XHR"].document) 
	        {
	           
				open("text/html");
				write("<html><head></head><body onl",
					'oad="parent.nv_xhr_v2.forIE(\'' + tmpHash + '\');">',
					tmpHash+"</body></html>");
				close();
			}
	    }
	    else
	    {
	    
         
	          
	        //on met à jour notre Hash !
            m_objHtml_forNv.setAttribute("action",   "#_target=" + m_str_tagId + "&" + m_str_param + '&file=' + m_str_file)
		    m_objHtml_forNv.submit();
		}
		 
		// on check si l'ancre actuel correspond à l'ancre chargé
        if (setTimeout) m_objTimer = setTimeout(pv_check_hash, 300);
	}
    
    
    
    /********************************************************************************
 	 * Fonction qui permet d'envoyer une requete http de type : POST 				*
 	 ********************************************************************************/
	var pv_sendGetReq = function() 
	{
  		m_obj_xmlHttp.open('POST', m_str_file + "?" + m_str_param, m_bool_isAsynchrone);
  		m_obj_xmlHttp.setRequestHeader("Content-type", "application/x-www-form-urlencoded");
  		m_obj_xmlHttp.send("?" + m_str_param);
	}
    
    /********************************************************************************
 	 * Fonction qui permet d'envoyer une requete http de type : POST				*
 	 ********************************************************************************/
	 var pv_sendPostReq = function() 
	{
		m_obj_xmlHttp.open("POST", m_str_file, m_bool_isAsynchrone);
		m_obj_xmlHttp.setRequestHeader("Content-type", "application/x-www-form-urlencoded");
		m_obj_xmlHttp.send(m_str_param);
	}
    
    
    /********************************************************************************
 	 * Fonction qui traite le status apres utilisation du xmlHttpRequest			*
 	 * PARAM : status , integer, code de retour HTTP								*
 	 * RETURN: boolean, a true si aucune erreur, false si probleme, ecriture de		*
 	 *									l'erreur dans this.error					*
 	 ********************************************************************************/
 	var pv_gestionStatus = function(status)
 	{
 	 	var reussite = true;
 	 	if (status >= 300 && status < 400)
 	 	{
 	 		m_str_txtErreur = "erreur http numéro : " + status + " \n Code de redirection !" ;
 	 		reussite = false;
 	 	}
 	 	else if(status >= 400 && status < 500)
 	 	{
 	 		m_str_txtErreur = "erreur http numéro : " + status + " \n Code erreur client !" ;
 	 		reussite = false;
 	 	}
 	 	else if (status >= 500 )
 	 	{
 	 		m_str_txtErreur = "erreur http numéro : " + status + " \n Code erreur serveur !" ;
 	 		reussite = false;
 	 	}
 	 	
 	 	
 	 	if (!reussite && isDebug)
 	 	{
	//		ShowDebugMsg(this.txtErreur + "<br/><br/><br/>" + this.xmlHttp.responseText)
 	 	
 	 	}
 	 	return reussite;
 	}	
 	
    /* ################################################################################################
	* Affiche un message d'attente pendant qu'une recherche est effectuée de maniere asynchrone 
	* ################################################################################################ */
	var pv_ShowWaitingMessage= function(message)
	{
		if (document.getElementById("overlay_white"))
		{this.hideWaitingMessage()}
	
	
		// récupération du body
		var elmt_Body = document.getElementsByTagName("body").item(0); // récupération
		
		// création du div qui va "cacher" un peu tout
		var elmt_divObscure = document.createElement("div");
		elmt_divObscure.setAttribute("id","overlay_white");// on lui ajoute une belle Id ;)
		elmt_divObscure.className = "overlay_for_hidden waitingColor";
		
		var elmt_divToWrite = document.createElement("div");
		elmt_divToWrite.setAttribute("id","overlay_white_write")
		elmt_divToWrite.className = "overlay_to_write";
		elmt_divToWrite.style.position = "absolute";
		
		// écriture de l'image
		var elmt_imgWaiting = document.createElement("img");
		 
		// SI ON DOIT CACHER SEULEMENT UN ELEMENT !
		if (m_str_idElmt_forWaitingMsg && m_str_idElmt_forWaitingMsg.length > 0)
		{
			forElmt = document.getElementById(m_str_idElmt_forWaitingMsg)
			
			var topAndLeft = findPos(forElmt)
			
			elmt_imgWaiting.setAttribute("src", "/_assets/i/download.gif");
			elmt_divToWrite.style.top = topAndLeft[1] + "px";
			elmt_divToWrite.style.left = topAndLeft[0] + "px";
			
			elmt_divObscure.style.top = topAndLeft[1] + "px";
			elmt_divObscure.style.left = topAndLeft[0] + "px";
					
			elmt_divToWrite.style.height = forElmt.offsetHeight  +"px";
			elmt_divToWrite.style.width = forElmt.offsetWidth + "px";
			
			elmt_divObscure.style.height = forElmt.offsetHeight  +"px";
			elmt_divObscure.style.width = forElmt.offsetWidth + "px";
		}
		else
		{
			elmt_imgWaiting.setAttribute("src", "/ds/i/loading.gif");
	 		nv_dimensionAndScroll = new structure_dimensionAndScrol();

			elmt_divToWrite.style.top = (nv_dimensionAndScroll.height / 3) + nv_dimensionAndScroll.scroll_y + "px";
			elmt_divToWrite.style.left = "0px";
			elmt_divToWrite.style.height =  nv_dimensionAndScroll.max_height - (nv_dimensionAndScroll.height / 3) + nv_dimensionAndScroll.scroll_y + "px";
			elmt_divToWrite.style.width  = nv_dimensionAndScroll.max_width + "px";
			
			elmt_divObscure.style.height = nv_dimensionAndScroll.max_height + "px";
			elmt_divObscure.style.width = nv_dimensionAndScroll.max_width + "px";
			
			// Il va falloir positioner contenablement not "image d'attente"
		}
		
		
		var elmt_divContent = document.createElement("div"); // création
		elmt_divContent.className = "waitingMessage";// on lui ajoute une belle Id ;)
		
		elmt_divContent.innerHTML = message ; // <img src='/i/loading.gif'>	

		elmt_Body.appendChild(elmt_divObscure);
		elmt_Body.appendChild(elmt_divToWrite);
		elmt_divToWrite.appendChild(elmt_imgWaiting);;
		elmt_divToWrite.appendChild(elmt_divContent)

		setOpacity(elmt_divObscure, 60);
	}


	/* ####################################################################################### */
	var pv_hideWaitingMessage = function()
	{
		if (! document.getElementById("overlay_white")) return false;
	
		var topAndLeft = [0,0];
		var widthAndHeight = [0,0];
		
		var forElmt = document.getElementsByTagName('body')
		if (m_str_idElmt_forWaitingMsg && m_str_idElmt_forWaitingMsg.length > 0)
		{
			forElmt = document.getElementById(m_str_idElmt_forWaitingMsg)
			
			var topAndLeft = findPos(forElmt)
		//	document.getElementById(this.idElmt_forWaitingMsg).removeChild(document.getElementById('overlay_white'))	
		}

		document.getElementsByTagName('body').item(0).removeChild(document.getElementById('overlay_white'))	
		document.getElementsByTagName('body').item(0).removeChild(document.getElementById('overlay_white_write'))	
		
	}
    
    
    // le constructeur ! (appelé en derniere ligne ;)
    var pv_constructor= function (thisPathToScript, thisParams, thisMethod, thisIsNotAsynchrone)
    {
        var posOf_charInterogation = -1;
        
        // on nettoie le chemion de la section "http://" si elle est présente
        m_str_file = thisPathToScript.replace(/http:\/\/[^\/]*/, '');
        
        // on rempalce les & encodé par des "&" pas encodé
        m_str_file = m_str_file.replace(/&amp;/g, '&'); 
        
        posOf_charInterogation = m_str_file.indexOf('?')
        
        // on va tronqué, et remplir le param !
        if (posOf_charInterogation > 0)
        {m_str_param = m_str_file.substr(posOf_charInterogation + 1) + '&' + thisParams;m_str_file =  m_str_file.substr(0, posOf_charInterogation);}
        else
        {m_str_param = thisParams;}
        
        // on ajoute un parametre pour savoir si xhr ou pas
        if (m_str_param.length > 0)
        {m_str_param = m_str_param + "&isXHR=1";}
        else
        {m_str_param = "isXHR=1";}
        
        // la méthod demandé (Post ou get en grosà
        m_str_method = thisMethod;
        
        // mode asynchrone ou pas ?
        if (thisIsNotAsynchrone) {m_bool_isAsynchrone = false}
        
          
        // si il n'existe pas on le cré
        if (!m_objHtml_forNv)
        {
            pv_createHtml_historyMethod();
        }
    } 
    
    var pv_createHtml_historyMethod = function()
    {
        if (navigator.userAgent.match(/MSIE (\d+\.\d+)/) && navigator.userAgent.match(/MSIE (\d+\.\d+)/)[1] >= 5.5) 
        { 
			m_objHtml_forNv = document.createElement("iframe");
			m_objHtml_forNv.setAttribute("name", "__nv_form_XHR");
			m_objHtml_forNv.setAttribute("id", "__nv_form_XHR");
		
		
			m_objHtml_forNv.setAttribute("src", 'javascript:;');
			m_objHtml_forNv.style.position = "absolute";
			m_objHtml_forNv.style.top    = "-900px";
			m_objHtml_forNv.style.left   = "-900px";
			m_objHtml_forNv.style.width  = "1px";
			m_objHtml_forNv.style.height = "1px";
			
        }
        else
        {
            m_objHtml_forNv = document.createElement("form");
            m_objHtml_forNv.setAttribute("id","__nv_form_XHR");
            m_objHtml_forNv.setAttribute("method", "get");
        }
         
	       
	       
	       
        document.getElementsByTagName("body").item(0).appendChild(m_objHtml_forNv);
    }
    
 
    
    // initialisation de l'objet httpRequest
    if (window.ActiveXObject)
    {m_obj_xmlHttp = new ActiveXObject("Microsoft.XMLHTTP");}

    // on detecte si il supporte l'objet XMLHttpRequest
    else if (window.XMLHttpRequest)
    {m_obj_xmlHttp = new XMLHttpRequest();}

    
    // on recupere le form ajax   
    m_objHtml_forNv = document.getElementById("__nv_form_XHR");
  
}
