
// declare a global  XMLHTTP Request object
var XmlHttpObj;
var RackPassed;

// create an instance of XMLHTTPRequest Object, varies with browser type, try for IE first then Mozilla
function CreateXmlHttpObj()
{
	// try creating for IE (note: we don't know the user's browser type here, just attempting IE first.)
	try
	{
		XmlHttpObj = new ActiveXObject("Msxml2.XMLHTTP");
	}
	catch(e)
	{
		try
		{
			XmlHttpObj = new ActiveXObject("Microsoft.XMLHTTP");
		} 
		catch(oc)
		{
			XmlHttpObj = null;
		}
	}
	// if unable to create using IE specific code then try creating for Mozilla (FireFox) 
	if(!XmlHttpObj && typeof XMLHttpRequest != "undefined") 
	{
		XmlHttpObj = new XMLHttpRequest();
	}
}

// called from onChange or onClick event of the continent dropdown list
function StorageListOnChange(RackId) 
{
    var continentList = document.getElementById("storage_local_new");
    
    // get selected continent from dropdown list
    var selectedContinent = continentList.options[continentList.selectedIndex].value;
    
    // url of page that will send xml data back to client browser
    var requestUrl;
    // use the following line if using asp
    //requestUrl = "xml_data_provider.asp" + "?filter=" + encodeURIComponent(selectedContinent);
    // use the following line if using php
	if (RackId){
		RackToFilter=RackId;
	}else{
		RackToFilter=RackPassed;	
	}
     requestUrl = "xml_storage_data_provider.php" + "?filter=" + encodeURIComponent(selectedContinent) + "&filter_rack=" + encodeURIComponent(RackToFilter);
    
	CreateXmlHttpObj();
	
	// verify XmlHttpObj variable was successfully initialized
	if(XmlHttpObj)
	{
        // assign the StateChangeHandler function ( defined below in this file)
        // to be called when the state of the XmlHttpObj changes
        // receiving data back from the server is one such change
		XmlHttpObj.onreadystatechange = BoxListChangeHandler;
		
		// define the iteraction with the server -- true for as asynchronous.
		XmlHttpObj.open("GET", requestUrl,  true);
		
		// send request to server, null arg  when using "GET"
		XmlHttpObj.send(null);		
	}
}


function setRackPassed(val){
	RackPassed = val;
	}

// called from onChange or onClick event of the continent dropdown list
function RackListOnChange() 
{
    
	var continentList = document.getElementById("storage_local_new");
    
    // get selected continent from dropdown list
    var selectedContinent = continentList.options[continentList.selectedIndex].value;
    
    // url of page that will send xml data back to client browser
    var requestUrl;
    // use the following line if using asp
    //requestUrl = "xml_data_provider.asp" + "?filter=" + encodeURIComponent(selectedContinent);
    // use the following line if using php
     requestUrl = "xml_storage_data_provider.php" + "?racklist=1&filter=" + encodeURIComponent(selectedContinent);
    
	CreateXmlHttpObj();
	
	// verify XmlHttpObj variable was successfully initialized
	if(XmlHttpObj)
	{
        // assign the StateChangeHandler function ( defined below in this file)
        // to be called when the state of the XmlHttpObj changes
        // receiving data back from the server is one such change
		XmlHttpObj.onreadystatechange = RackListChangeHandler;
		
		// define the iteraction with the server -- true for as asynchronous.
		XmlHttpObj.open("GET", requestUrl,  true);
		
		// send request to server, null arg  when using "GET"
		XmlHttpObj.send(null);		
	}
}


// this function called when state of  XmlHttpObj changes
// we're interested in the state that indicates data has been
// received from the server
function BoxListChangeHandler()
{
	// state ==4 indicates receiving response data from server is completed
	if(XmlHttpObj.readyState == 4)
	{
		// To make sure valid response is received from the server, 200 means response received is OK
		if(XmlHttpObj.status == 200)
		{			
			PopulateBoxList(XmlHttpObj.responseXML.documentElement);
		}
		else
		{
			alert("problem retrieving data from the server, status code: "  + XmlHttpObj.status);
		}
	}
}


function RackListChangeHandler()
{
	
	// state ==4 indicates receiving response data from server is completed
	if(XmlHttpObj.readyState == 4)
	{
		// To make sure valid response is received from the server, 200 means response received is OK
		if(XmlHttpObj.status == 200)
		{			
			PopulateRackList(XmlHttpObj.responseXML.documentElement);
		}
		else
		{
			alert("problem retrieving data from the server, status code: "  + XmlHttpObj.status);
		}
	}
}

// populate the contents of the country dropdown list
function PopulateBoxList(countryNode)
{
    var countryList = document.getElementById("box_select");
	// clear the country list 
	for (var count = countryList.options.length-1; count >-1; count--)
	{
		countryList.options[count] = null;
	}

	var countryNodes = countryNode.getElementsByTagName('box');
	var idValue;
	var textValue; 
	var optionItem;
	// populate the dropdown list with data from the xml doc
	for (var count = 0; count < countryNodes.length; count++)
	{		
		textValue = GetInnerText(countryNodes[count]);
		idValue = countryNodes[count].getAttribute("id");
		styleValue = countryNodes[count].getAttribute("style");
		optionItem = new Option( textValue, idValue,  false, false);
		countryList.options[countryList.length] = optionItem;
		if (styleValue){
		countryList.options[countryList.length-1].style.backgroundColor = "#F60";
		countryList.options[countryList.length-1].style.color = "white";
		countryList.options[countryList.length-1].style.fontWeight = "bold";
		}
	}
	countryList.style.visibility='visible';
}

function PopulateRackList(countryNode)
{
    //alert("passed2: "+ValPassed);
	var countryList = document.getElementById("rack_select");
	// clear the country list 
	for (var count = countryList.options.length-1; count >-1; count--)
	{
		countryList.options[count] = null;
	}

	var countryNodes = countryNode.getElementsByTagName('rack');
	var idValue;
	var textValue; 
	var optionItem;
	// populate the dropdown list with data from the xml doc
	for (var count = 0; count < countryNodes.length; count++)
	{		
		textValue = GetInnerText(countryNodes[count]);
		idValue = countryNodes[count].getAttribute("id");

		optionItem = new Option( textValue, idValue,  false, false);
		countryList.options[countryList.length] = optionItem;
		
		if (RackPassed && RackPassed==idValue){
			
			countryList.options[count].selected = true;

		}

	}
	countryList.style.visibility='visible';
}

// returns the node text value 
function GetInnerText (node)
{
	 return (node.textContent || node.innerText || node.text || node.firstChild.nodeValue || node.data) ;
//	 	 return (node.textContent || node.innerText || node.text) ;
}



function BoxListOnChange()
{
	// turn image selector visible
	var PointIcon = document.getElementById("grid_selector");
	PointIcon.style.visibility='visible';
	//var PointIcon2 = document.getElementById("grid_selector_db");
	//PointIcon2.style.visibility='hidden';
	var hiddenDetailsView = document.getElementById("box_details_view");
	hiddenDetailsView.style.visibility='visible';
	var hiddenDetails = document.getElementById("box_details");
	hiddenDetails.style.visibility='visible';		
}
function BoxListOnChange2()
{
	// turn image selector visible
	var PointIcon = document.getElementById("grid_selector");
	PointIcon.style.visibility='visible';
	var PointIcon2 = document.getElementById("current_storage");
	PointIcon2.style.display='none';
	var hiddenDetailsView = document.getElementById("box_details_view2");
	hiddenDetailsView.style.visibility='visible';
	var hiddenDetails = document.getElementById("box_details2");
	hiddenDetails.style.visibility='visible';		
}

function OpenBoxGrid(passed_query){
    var boxList = document.getElementById("box_select");
    // get selected box from dropdown list
    var selectedBox = boxList.options[boxList.selectedIndex].value;
	if (document.getElementById("box_details2")){
		var selectedPos = document.getElementById("box_details2").value;
	}else{
		var selectedPos = document.getElementById("box_details").value;
	}
	
	//open boxgrid page
	var linkstr="boxgrid.php?cleanstart=1&box_details="+selectedPos+"&box_id="+selectedBox+"&"+passed_query;
	popUpWindowBoxGrid(linkstr,650,600);
}

function OpenBoxGridEdit(passed_query){
	var linkstr="boxgrid.php?"+passed_query;
	popUpWindowBoxGrid(linkstr,650,600);
}

var popUpWin=0;
function popUpWindowBoxGrid(URLStr, width, height) {
  if(popUpWin) {
    if(!popUpWin.closed) popUpWin.close();
  }
  var left = (screen.width/3) - width/3;
  var top = (screen.height/3) - height/3;
  popUpWin = open(URLStr, 'popUpWin', 'toolbar=no,location=no,directories=no,status=no,menubar=no,scrollbars=yes,resizable=yes,copyhistory=yes,width='+width+',height='+height+',left='+left+', top='+top+',screenX='+left+',screenY='+top+'');
}


function envoieRequete(url,id) 
{ 
    var xhr_object = null; 
    var position = id; 
     if(window.XMLHttpRequest)  // Firefox 
	 	xhr_object = new XMLHttpRequest();
     else if (window.ActiveXObject){ // Internet Explorer 
		 //xhr_object = new ActiveXObject("Microsoft.XMLHTTP"); 
		 try {
xhr_object=new ActiveXObject("Msxml2.XMLHTTP");
} 
catch (e){
try{
xhr_object=new ActiveXObject("Microsoft.XMLHTTP");
}
catch (e){}
}
}
	 else { // XMLHttpRequest non supporté par le navigateur 
   alert("Votre navigateur ne supporte pas les objets XMLHTTPRequest..."); 
   return; 
	} 
  
    // On ouvre la requete vers la page désirée 
    xhr_object.open("GET", url, true); 
	//xhr_object.open("GET", "utf8_ajax.php?ajaxpage="+url, true); 
    xhr_object.onreadystatechange = function(){ 
    if ( xhr_object.readyState == 4 ) 
    { 
        // j'affiche dans la DIV spécifiées le contenu retourné par le fichier 
        document.getElementById(position).style.display = '';
		document.getElementById(position).innerHTML = xhr_object.responseText; 
		//setInnerHTML(document.getElementById(position), xhr_object.responseText)
		 
    } 
    } 
    // dans le cas du get 
    xhr_object.send(null); 
 
 // cas d'un POST
// xhr_object.open("POST", file, true);
// xhr_object.onreadystatechange = ... .. .
// xhr_object.send("mavar1=pwet&mavar2=plop&mavar3=blurp..."); (pense à échapper les caractères spéciaux)
  
} //end envoieRequete

function envoieRequete2(url,id) 
{ 
    var xhr_object = null; 
    var position = id; 
     if(window.XMLHttpRequest)  // Firefox 
	 	xhr_object = new XMLHttpRequest();
     else if (window.ActiveXObject){ // Internet Explorer 
		 //xhr_object = new ActiveXObject("Microsoft.XMLHTTP"); 
		 try {
xhr_object=new ActiveXObject("Msxml2.XMLHTTP");
} 
catch (e){
try{
xhr_object=new ActiveXObject("Microsoft.XMLHTTP");
}
catch (e){}
}
}
	 else { // XMLHttpRequest non supporté par le navigateur 
   alert("Votre navigateur ne supporte pas les objets XMLHTTPRequest..."); 
   return; 
	} 
  
    // On ouvre la requete vers la page désirée 
    xhr_object.open("GET", url, true); 
	//xhr_object.open("GET", "utf8_ajax.php?ajaxpage="+url, true); 
    xhr_object.onreadystatechange = function(){ 
    if ( xhr_object.readyState == 4 ) 
    { 
        // j'affiche dans la DIV spécifiées le contenu retourné par le fichier 
        document.getElementById(position).style.display = '';
		//document.getElementById(position).innerHTML = xhr_object.responseText; 
		setInnerHTML(document.getElementById(position), xhr_object.responseText)
		 
    } 
    } 
    // dans le cas du get 
    xhr_object.send(null); 
 
 // cas d'un POST
// xhr_object.open("POST", file, true);
// xhr_object.onreadystatechange = ... .. .
// xhr_object.send("mavar1=pwet&mavar2=plop&mavar3=blurp..."); (pense à échapper les caractères spéciaux)
  
} //end envoieRequete

//////////////////////////////////////////////////////////////////////////////
//Basic Ajax Routine- Author: Dynamic Drive (http://www.dynamicdrive.com)
//Last updated: Jan 15th, 06'

function createAjaxObj(){
var httprequest=false
if (window.XMLHttpRequest){ // if Mozilla, Safari etc
httprequest=new XMLHttpRequest()
if (httprequest.overrideMimeType)
httprequest.overrideMimeType('text/xml')
}
else if (window.ActiveXObject){ // if IE
try {
httprequest=new ActiveXObject("Msxml2.XMLHTTP");
} 
catch (e){
try{
httprequest=new ActiveXObject("Microsoft.XMLHTTP");
}
catch (e){}
}
}
return httprequest
}

var ajaxpack=new Object()
ajaxpack.basedomain=window.location.protocol+"//"+window.location.hostname
ajaxpack.ajaxobj=createAjaxObj()
ajaxpack.filetype="txt"
ajaxpack.divname="content_preview2"
ajaxpack.addrandomnumber=0 //Set to 1 or 0. See documentation.

ajaxpack.getAjaxRequest=function(url, parameters, callbackfunc, filetype){
ajaxpack.ajaxobj=createAjaxObj() //recreate ajax object to defeat cache problem in IE
if (ajaxpack.addrandomnumber==1) //Further defeat caching problem in IE?
var parameters=parameters+"&ajaxcachebust="+new Date().getTime()
if (this.ajaxobj){
this.filetype=filetype
this.ajaxobj.onreadystatechange=callbackfunc
this.ajaxobj.open('GET', url+"?"+parameters, true)
this.ajaxobj.send(null)
}
}

ajaxpack.postAjaxRequest=function(url, parameters, callbackfunc, filetype, divname){
ajaxpack.ajaxobj=createAjaxObj() //recreate ajax object to defeat cache problem in IE
if (this.ajaxobj){
this.filetype=filetype
this.divname=divname
this.ajaxobj.onreadystatechange = callbackfunc;
this.ajaxobj.open('POST', url, true);
//this.ajaxobj.setRequestHeader("Content-type", "application/x-www-form-urlencoded; charset=iso-8859-1");
this.ajaxobj.setRequestHeader("Content-type", "application/x-www-form-urlencoded; charset = UTF-8");
//this.ajaxobj.setRequestHeader("Content-type", "text/html; charset = UTF-8");
//this.ajaxobj.setRequestHeader("Accept-Charset","UTF-8");
this.ajaxobj.setRequestHeader("Content-length", parameters.length);
this.ajaxobj.setRequestHeader("Connection", "close");
this.ajaxobj.send(parameters);
}
}

function processGetPost(){
var myajax=ajaxpack.ajaxobj
var myfiletype=ajaxpack.filetype
var mydivname=ajaxpack.divname
//alert('myajax ... :' + myfiletype + ' & DIV=' + divname)
if (myajax.readyState == 4){ //if request of file completed
if (myajax.status==200 || window.location.href.indexOf("http")==-1){ //if request was successful or running script locally
if (myfiletype=="txt")
//alert(myajax.responseText)
//alert('txt => POSITION again:' + position + document.getElementById(position).innerHTML)
        // j'affiche dans la DIV spécifiées le contenu retourné par le fichier 
        document.getElementById(mydivname).innerHTML = myajax.responseText; 
else
alert(myajax.responseXML)
}
}
}

    // SetInnerHTML Sécurisé
    function setInnerHTML(divContent, HTML) {
      divContent.innerHTML=HTML; 
      var All=divContent.getElementsByTagName("*");
      for (var i=0; i<All.length; i++) {
        All[i].id=All[i].getAttribute("id")
        All[i].name=All[i].getAttribute("name")
        //All[i].className=All[i].getAttribute("class")
		var elementClass = All[i].getAttribute("class");
		if (elementClass == null) {
		elementClass = All[i].getAttribute("className");
		}
		All[i].className=elementClass;
      }
      var AllScripts=divContent.getElementsByTagName("script")
      for (var i=0; i<AllScripts.length; i++) {
         var s=AllScripts[i];
         if (s.src && s.src!="") {
            // Précédement asynchrone, mis en synchrone pour éviter des problèmes de dépendances de scripts
            eval(getFileContent(s.src))
         }
         else {
            eval(s.innerHTML)
         }
      }
    }
 
    // Renvoie le texte de l'objet ActiveXObject le plus récent depuis une liste
    var pickRecentProgID = function (idList){
	    // found progID flag
        var bFound = false;
        for(var i=0; i < idList.length && !bFound; i++){
            try{
                var oDoc = new ActiveXObject(idList[i]);
                o2Store = idList[i];
                bFound = true;
            }catch (objException){
                // trap; try next progID
            };
        };
        if (!bFound)
		    throw ("Aucun ActiveXObject n'est valide sur votre ordinateur, pensez à mettre à jour votre navigateur");
        idList = null;
        return o2Store;
    }
 
    // Retourne un nouvel objet XmlHttpRequest
    var GetXmlHttpRequest_AXO=null
    var GetXmlHttpRequest=function () {
	    if (window.XMLHttpRequest) {
		    return new XMLHttpRequest()
	    }
	    else if (window.ActiveXObject) {
		    if (!GetXmlHttpRequest_AXO) {
			    GetXmlHttpRequest_AXO=pickRecentProgID(["Msxml2.XMLHTTP.5.0", "Msxml2.XMLHTTP.4.0", "MSXML2.XMLHTTP.3.0", "MSXML2.XMLHTTP", "Microsoft.XMLHTTP"]);
		    }
		    return new ActiveXObject(GetXmlHttpRequest_AXO)
	    }
	    return false;
    }
 
    function getFileContent(url) {
       var Xhr=GetXmlHttpRequest();
       Xhr.open("GET",url,false);
       Xhr.send(null);
       return Xhr.responseText;
    }
	
function createpoststring_lots(){
//var namevalue=document.getElementById("relatives").innerHTML //get value to post from a DIV
var lot_validity_value=document.getElementById("add_lot_form").lot_validity.value //get value to post from a form field
var lot_number_value=document.getElementById("add_lot_form").lot_number.value
var lot_comments_new_value=document.getElementById("add_lot_form").lot_comments_new.value
var lot_quantity_value=document.getElementById("add_lot_form").lot_quantity.value
var lot_unit_value=document.getElementById("add_lot_form").lot_unit.value
var action2_value=document.getElementById("add_lot_form").action2.value
var chem_id_value=document.getElementById("add_lot_form").chem_id.value
var div_value=document.getElementById("add_lot_form").div.value
var lot_id_value=document.getElementById("add_lot_form").lot_id.value

var poststr = "lot_number=" + encodeURI(lot_number_value) + "&lot_validity=" + encodeURI(lot_validity_value) + "&lot_comments_new=" + escape(lot_comments_new_value) + "&lot_quantity=" + encodeURI(lot_quantity_value) +"&lot_unit=" + encodeURI(lot_unit_value) + "&div=" + encodeURI(div_value) + "&chem_id=" + encodeURI(chem_id_value) + "&lot_id=" + encodeURI(lot_id_value) + "&action2=" + encodeURI(action2_value)
return poststr
}	
