// global submit variable if set to false at any point before submitting, submitting will be halted
var submit = true;
// XMLHTTP Request variable
var req; 
// XMLHTTP Request variable (only used for address validation)
var reqva;
// XMLHTTP Request variable (only used for NA validation)
var reqna;
// Will hold the xml Document
var xmlDoc;
// We have a separte document for the validation of addresses...
var xmlDocva;
// Holds the index in the proposed drop down list of streets
var suggestedIndex = 0;
// Value of the maximum index of the drop down list
var maxList = 0;
// Will hold the user session language for all aoperations within this include
var ajaxlang = "";
// Here we set the status of parsing or not parsing yet
var parsing = false;
// Variable used to check NA
var navalid = false;
// Holds the index in the proposed drop down list of city
var suggestedIndexCity = 0;
// Value of the maximum index of the drop down list for city
var maxListCity = 0;
var minStreetLength4Call = 3;





function checkZipD(event,language) {
// This function will be called only in the "keydown" event to catch the "return" key pressing and 
// Avoid an early submission of the form

 var zipCode = document.getElementById("zipCd");
	// Only do this if we're at four positions and enter is pressed...
	if ((zipCode.value.length>3) && (event.keyCode==13)){	  
		// If this is the case we go to the "normal" check zip function 
		checkZip(event,language);
	}

	// Erase Phone Number
	na = document.getElementById("customerNA");
	na.value ="";

}

function checkCityD(event,language) {
// This function will be called only in the "keydown" event to catch the "return" key pressing and 
// Avoid an early submission of the form
    
 	var  City = document.getElementById("cityNmT");
 	var  CityCd = document.getElementById("cityNm");
	// Clear City Code
	
	//CityCd.value="";
	// Only do this if we're at four or more position and enter is pressed...
	if ((City.value.length>3) && (event.keyCode==13)){	  
		// If this is the case we go to the "normal" check zip function 
		checkCity(event,language);
	}

	// Erase Phone Number
	na = document.getElementById("customerNA");
	na.value ="";

}

function checkCity(event,language) {
// This function will call the check servlet with the ZIP
// code and then prefill the city list with the returned data
 ajaxlang = language;
 var City = document.getElementById("cityNmT");
	// Cancel previous requests  
	if (req != null) req.abort();

	if (City.value.length>2){

	// Url with the servlet that will return the XML

    var url = "../../../../../bwt/check?lang="+language+"&city=" + escape(City.value);
	// Check which type of object we will use (this may and will change between browsers)
	if (window.XMLHttpRequest) {
   		   req = new XMLHttpRequest();
    } else if (window.ActiveXObject) {
   		try {
			req = new ActiveXObject("Microsoft.XMLHTTP");
			} catch (e) {
				try {
		  			req = new ActiveXObject("Msxml2.XMLHTTP");
					} catch (E) {
						xmlhttp = false;
								}
 				}
     
     } 
   // Open the URL
   
    req.open("GET", url, true);
   // tell the request object what function to call if there is a change in its state
   req.onreadystatechange = callbackCity;
   // Send the request without any extra parameters (null)
   req.send(null);

	}else{
  	// Hide the drop down if less than 2  chars
   	hideDropDown("cityNmT");
  }
  if (event.keyCode==8){
	  // Back space pressed, hide all errors of invalid street value
		hideError("cityNmError");  
  }
  if (event.keyCode==40){
	  // Arrow down
	  // Update the drop down list with new highlighted value
	  if(suggestedIndexCity==0) {
		parseMessage("city");
  	  }
	  
	  if(suggestedIndexCity < (maxListCity-1)) suggestedIndexCity++;					
	  updateSuggestionListCity ();	
  }
  if (event.keyCode==38){
	  // Arrow up
	  // Update the drop down list with new highlighted value
	  if(suggestedIndexCity==maxListCity) {
		parseMessage("city");
  	  }
	  if(suggestedIndexCity > 0) suggestedIndexCity--;					
	  updateSuggestionListCity ();	
  }


}

function checkZip(event,language) {
// This function will call the check servlet with the ZIP
// code and then prefill the city list with the returned data
 ajaxlang = language;
 var zipCode = document.getElementById("zipCd");

	// Cancel previous requests  
	if (req != null) req.abort();

	if (zipCode.value.length>3){

	// Url with the servlet that will return the XML
    var url = "../../../../../bwt/check?lang="+language+"&zip=" + escape(zipCode.value);

	// Check which type of object we will use (this may and will change between browsers)
	if (window.XMLHttpRequest) {
   		   req = new XMLHttpRequest();
    } else if (window.ActiveXObject) {
   		try {
			req = new ActiveXObject("Microsoft.XMLHTTP");
			} catch (e) {
				try {
		  			req = new ActiveXObject("Msxml2.XMLHTTP");
					} catch (E) {
						xmlhttp = false;
								}
 				}
     
     } 
   // Open the URL
   
    req.open("GET", url, true);
   // tell the request object what function to call if there is a change in its state
   req.onreadystatechange = callbackZip;
   // Send the request without any extra parameters (null)
   req.send(null);

	}else{
		// In this case the user would have not yet reached the 4 chars in the zip code
		// So we do not need to validate yet, we hide all possible errors
		//Hide errors on the zip code
		hideError("zipCodeError");
		//disable other address fields
	    field = document.getElementById("cityNmT");
	    field.value="";		
	    field = document.getElementById("cityNm");
	    field.value="";		
	    field.disabled = false;
	    field = document.getElementById("streetNm");
		field.value="";
		field.autocomplete = "off"; // We do not want the browser's autocomplete fature
	    							// To ruin our own autocomplete
		
		
	    //field.disabled = true;
		// Hide the div that holds the city information	    
	    hideDiv("cityData");
	
	}
	if (zipCode.value.length>0){
			
		// Erase Phone Number
		na = document.getElementById("customerNA");
		na.value ="";
	}
	// If both NA and ZIP where empty and now zip has at least 1 char it means that it is not more empty
	// So we can hide the "both fields empty" error..
	if (zipCode.value.length>0){
		hideError ("allEmptyError");
		// See if both NA and ZIP are filled in
		checkExclusive();
	}else{
		// On the other hand, if there was an exclusivity error (NA + ZIP filled in), as the length of zip equals
		// zero now, there is no more exclusivity error to show
		hideError ("exclusiveError");
	}


}

function checkStreetD(event,language){
	// This function will be only used when in the display list we select an option via pressing ENTER key
	// This function runs on the keydown event and prevents the form from being submitted
	if (event.keyCode==13){
		// Iterate through all returned street values to see which is the highlighted one
		// This does not make a new request but uses the old returned XML
		var field = document.getElementById("streetNm");
		count = 0;
		for (h=0;h<xmlDoc.length;h++){
			thisNode = xmlDoc.item(h);
			streetName = thisNode.getElementsByTagName("string")[0].childNodes[0].nodeValue
			streetCode = thisNode.getElementsByTagName("code")[0].childNodes[0].nodeValue
			if (streetName.toLowerCase().indexOf(field.value.toLowerCase()) == 0) {
				if(count==suggestedIndex) {
						// When we've reached the highlighted item, change the city code
						updateStreet(escape(streetName),streetCode);
				}
			count++;
			}
		}	
	event.keyCode = 0;
	}
	

}
function checkStreet(event,language){
	// This function is called with the onkeyup event, first ting is to delete the error showing that the
	// street name is valid
	hideError ("emptyStreetNMError");
	// Cancel previous requests
	if (req != null) req.abort();
	// return the street names starting by the letters typed by the user
	var cityName = document.getElementById("cityNm");
	var zipCode = document.getElementById("zipCd");
	var streetName = document.getElementById("streetNm");
  	
  	// We only call the servlet if the length of the filed is greater than 4
  	// this is done to minimize calls and also to comply with the 3 minimum 

	if (streetName.value.length > minStreetLength4Call){
        //alert ('checkStreet.streetName:'+streetName.value);
 		// Create the URL to call
    	var url = "../../../../../bwt/check?lang="+language+"&zip=" + escape(zipCode.value)+"&city="+escape(cityName.value)+"&street="+escape(streetName.value);
		// Select which type of object we'll use
		if (window.XMLHttpRequest) {
   			   req = new XMLHttpRequest();
    	} else if (window.ActiveXObject) {
   			try {
				req = new ActiveXObject("Microsoft.XMLHTTP");
				} catch (e) {
					try {
		  				req = new ActiveXObject("Msxml2.XMLHTTP");
						} catch (E) {
							xmlhttp = false;
									}
 					}
		 }
		 // Do the request

		 parsing = true;
		 req.open("GET", url, true);
  		 req.onreadystatechange = callbackStreet;
  		 req.send(null);
  		
  }else{
  	// Hide the drop down if less than 5 chars
   	hideDropDown("streetNm");
  }
  if (event.keyCode==8){
	  // Back space pressed, hide all errors of invalid street value
		hideError("streetNmError");  
  }
  if (event.keyCode==40){
	  // Arrow down
	  // Update the drop down list with new highlighted value
	  if(suggestedIndex==0) {
		parseMessage("street");
  	  }
	  
	  if(suggestedIndex < (maxList-1)) suggestedIndex++;					
	  updateSuggestionList ();	
  }
  if (event.keyCode==38){
	  // Arrow up
	  // Update the drop down list with new highlighted value
	  if(suggestedIndex==maxList) {
		parseMessage("street");
  	  }
	  if(suggestedIndex > 0) suggestedIndex--;					
	  updateSuggestionList ();	
  }

}


function callbackZip(){
	// This function is called when there is a change in the request status when retrieving the zip codes
    if (req != null){
       if (req.readyState == 4) {
		try{
        if (req.status == 200) {
		    xmlDoc = req.responseXML.getElementsByTagName("city");
			// Check if we have answers
			
			
			if (xmlDoc.length>0){
				// We do have, hide errors and show whole address form
				hideError("zipCodeError");
				// Retrieve all possible zip codes (only one actually)
				parseMessage("zip");
				showDiv("cityData");
			}else{
				// TODO ---> PARSE ERRORS!!!
			    xmlDoc = req.responseXML.getElementsByTagName("error");
				error = xmlDoc.item(0).childNodes[0].nodeValue;
				if (error=="1"){
					// Invalid address error
					showError("zipCodeError");
				}else if (error =="2"){
				
				}else{	
					// Default error
					showError("zipCodeHubError");
				}
				hideDiv("cityData");
			}
        }
        }catch(e){
        }
    }
	}
}

function callbackAddress(){
	// This function is called when there is a change in the request status for the address validation
    if (reqva.readyState == 4) {
    	if (reqva.status == 200) {
			parsing = false;
		    xmlDocva = reqva.responseXML.getElementsByTagName("street");
		    //alert (xmlDocva);
			// Check if the answer is corect
			var submitme = false;
			hideError("invalidAddressError");
			// It can happen that we get 2 different addresses for the same street (specially on zip 1000)
			if ((xmlDocva.length>0) && (xmlDocva.length<2)){
				// We've got a valid address ... DO SUBMIT FORM
				// But first update the street code value!!!
				var field = document.getElementById("streetCode");
				//alert ("+++"+xmlDocva.length);
				for (h=0;h<xmlDocva.length;h++){
					thisNode = xmlDocva.item(h);
					// Get street name and code
					streetName = thisNode.getElementsByTagName("string")[0].childNodes[0].nodeValue;
					streetCode = thisNode.getElementsByTagName("code")[0].childNodes[0].nodeValue;
					// If data typed equals one of the returned values there is no need to show options
					// It is a _VALID_ street
					//alert ("["+streetCode.toLowerCase() +"==="+field.value.toLowerCase()+"]");
					
					if (streetCode == field.value) {
						updateStreet(streetName,streetCode);
						submitme = true;
					}
				}
					
					//alert ("-------"+submitme);
					if (submitme){
					     document.forms[0].onsubmit="return true;";					     
						 document.forms[0].submit();
					}else{
						showError("invalidAddressError");
					}
			}else{
				// TODO ---> PARSE ERRORS!!!
			    xmlDoc = reqva.responseXML.getElementsByTagName("error");
				if (xmlDoc.length>0){
					error = xmlDoc.item(0).childNodes[0].nodeValue;
					if (error=="1"){
						// Invalid address error
						showError("invalidAddressError");
					}else if (error =="2"){
						showError("invalidStreetError");
		
					}else{	
						// Default error
						showError("invalidStreetError");
					}
				}else{
						// If we're here it means that we had several addresses for just a single address!!
						showError("invalidAddressError");
				}
			}
        }
    }

}

function callbackStreet(){
	// This function is called when there is a change in the request asking for street names
  try{
	 if (req.readyState == 4) {
        if (req.status == 200) {
		    parsing = false;
		    xmlDoc = req.responseXML.getElementsByTagName("street");
			// Create the drop down item (if not existing)
	   	    createDropDown("streetNm");
	   	    // And parse the street names
			parseMessage("street");
        }
    }
	}catch(e){
	
}
}

function callbackCity(){
	// This function is called when there is a change in the request asking for street names
  try{
	 if (req.readyState == 4) {
        if (req.status == 200) {
		    parsing = false;
		    xmlDoc = req.responseXML.getElementsByTagName("address");
			// Create the drop down item (if not existing)
	   	    createDropDown("cityNmT");
	   	    // And parse the street names
			parseMessage("city");
        }
    }
	}catch(e){
	
}
}

function parseMessage(which) {

	// See what kind of information we're trying to parse
    if (which=="zip") {
    	// Parse through all answers and get the zip code for them
		var fielda = document.getElementById("cityNmT");
		// clear existing options first
		fielda.value = "";		
		var fieldb = document.getElementById("cityNm");
		fieldb.autocomplete = "off"; // We do not want the browser's autocomplete fature
	    								// To ruin our own autocomplete
		
		// clear existing options first
		fieldb.value = "";		
		// Iterate through answers, Actually there is only 1
		for (h=0;h<xmlDoc.length;h++){
			thisNode = xmlDoc.item(h);
			// Get the city name
			cityName = thisNode.getElementsByTagName("string")[0].childNodes[0].nodeValue;
			// Get the city Code (ID)
			cityCode = thisNode.getElementsByTagName("code")[0].childNodes[0].nodeValue;

			// Add options to the city drop down list
			addOption(fielda,cityName,fieldb,cityCode);
    	}
    }
   // Prefill the street name
    if (which=="street") {
		updateSuggestionList();
		if (!parsing){
		if (maxList > 0 ){
			 // Show drop down if options are available
			 showDropDown("streetNm")
		}else{
			// Tell the user the street name is invalid
			showError("streetNmError");
		}
		}
	}
    if (which=="city") {
		updateSuggestionListCity();
		if (!parsing){
		if (maxListCity > 0 ){
			 // Show drop down if options are available
			 showDropDown("cityNmT")
		}else{
			// Tell the user the street name is invalid
            if (maxListCity==0) hideError("cityNmError");
			else showError("cityNmError");
		}
		}
	}
}

function addOption(fielda,value,fieldb,id){
	// create new options in a drop down
	fielda.value=value;
	fieldb.value=id;

}

function deleteDropDown(fieldId){
		// self explanatory
		nfield = document.getElementById("DD-" + fieldId);
		nfield.innerHTML ="";
}

function createDropDown(fieldId){
		// Create markup for drop-down list of suggestions

		ifield = document.getElementById(fieldId);
		nfield = document.getElementById("DD-" + fieldId);
		// if the div doesn't exist, create it
		if(!nfield) {
			newdiv = document.createElement('DIV');
			newdiv.id = "DD-" + fieldId;
			newdiv.className = "THHideDropDown";
			newdiv.style.top =  (getTop(ifield) + ifield.offsetHeight + 2).toString() + "px";
			newdiv.style.left =  getLeft(ifield).toString() + "px";
 			newdiv.style.width = ifield.offsetWidth.toString() + "px";
			document.body.insertBefore(newdiv,document.body.firstChild);
			
		}							
}

function updateSuggestionList (){

		// Update the list of suggestions, this is a inner HTML that will go into the drop down div
		var htmlList="";
		// get the field where the user has already typed some values
		var field = document.getElementById("streetNm");
		// Width of the div
		var bigSize = 0;
		// Boolean to test equality
		var equalToInput = false;
		// Parse through all nodes
		count = 0;
		for (h=0;h<xmlDoc.length && (!equalToInput);h++){
			thisNode = xmlDoc.item(h);
			// Get street name and code
			streetName = thisNode.getElementsByTagName("string")[0].childNodes[0].nodeValue
			streetCode = thisNode.getElementsByTagName("code")[0].childNodes[0].nodeValue
			// If data typed equals one of the returned values there is no need to show options
			// It is a _VALID_ street
			if (streetName.toLowerCase() == field.value.toLowerCase()) equalToInput = true;
			
			// If we found the street do not bother checking further
			if (!equalToInput){
				// If street returned starts as the input
				if (streetName.toLowerCase().indexOf(field.value.toLowerCase()) != -1) {
					// change the width of div if bigger
					if (streetName.length > bigSize){
						bigSize = streetName.length;
					}
					// If this is the selected option, "hover-it"
					if(count==suggestedIndex) {
						htmlList += "<li class='THLIHover' onclick='updateStreet(\""+escape(streetName)+"\",\""+streetCode+"\")'>"+streetName+"</li>";
					}else{
						// Else show it as normal
						htmlList += "<li onclick='updateStreet(\""+escape(streetName)+"\",\""+streetCode+"\")'>"+streetName+"</li>";
   		         	}
					count++;
        	    } 			
       		}
       	 }	
		// If there are options to show (meaning not equal to input)
		if (!equalToInput){
		// Set number of options
		maxList=count;
		// get the drop down div object
		divItem = document.getElementById("DD-streetNm");
		// If it exists
		if (divItem){
			// And list is not empty
	        if (htmlList != ""){
	        	// Set up inner HTML with the list
		        divItem.innerHTML = "<ul>"+htmlList+"</ul>";	
		    }else{
		    	// Otherwise set list options to zero
		        maxList=0;
	    		bigSize =20;
		    }
			// Set proper wifth for div
			divItem.style.width=bigSize*7;	    
		}

		if(count==0){
			hideDropDown("streetNm");
			deleteDropDown("streetNm");
		}

		}else{
			// We've typed the correct address
			updateStreet(streetName,streetCode);
			maxList=0;
		}

}

function updateSuggestionListCity (){

		// Update the list of suggestions, this is a inner HTML that will go into the drop down div
		var htmlList="";
		// get the field where the user has already typed some values
		var field = document.getElementById("cityNmT");
		// Width of the div
		var bigSize = 0;
		// Boolean to test equality
		var equalToInput = false;
		// Parse through all nodes
		count = 0;
		for (h=0;h<xmlDoc.length;h++){
			thisNode = xmlDoc.item(h);
			// Get street name and code
			childNodes = thisNode.getElementsByTagName("city");
			cityName = childNodes[0].getElementsByTagName("string")[0].childNodes[0].nodeValue;
			cityCode = childNodes[0].getElementsByTagName("code")[0].childNodes[0].nodeValue;
			zipCode= thisNode.getElementsByTagName("zip")[0].childNodes[0].nodeValue;

			// If data typed equals one of the returned values there is no need to show options
			// It is a _VALID_ street
			if (cityName.toLowerCase() == field.value.toLowerCase()) equalToInput = true;
			
			// If we found the street do not bother checking further
			if (!equalToInput){
				// If street returned starts as the input
				//if (cityName.toLowerCase().indexOf(field.value.toLowerCase()) == 0) {
					// change the width of div if bigger
					if (cityName.length > bigSize){
						bigSize = cityName.length;
					}
					// If this is the selected option, "hover-it"
					if(count==suggestedIndexCity) {
						htmlList += "<li class='THLIHover' onclick='updateCity(\""+escape(cityName)+"\",\""+cityCode+"\",\""+zipCode+"\")'>"+cityName+"</li>";
					}else{
						// Else show it as normal
						htmlList += "<li onclick='updateCity(\""+escape(cityName)+"\",\""+cityCode+"\",\""+zipCode+"\")'>"+cityName+"</li>";
   		         	}
					count++;
        	    //} 			
       		}
       	 }	
		// If there are options to show (meaning not equal to input)
		if (!equalToInput){
		// Set number of options
		maxListCity=count;
		// get the drop down div object
		divItem = document.getElementById("DD-cityNmT");
		// If it exists
		if (divItem){
			// And list is not empty
	        if (htmlList != ""){
	        	// Set up inner HTML with the list
		        divItem.innerHTML = "<ul>"+htmlList+"</ul>";	
		    }else{
		    	// Otherwise set list options to zero
		        maxListCity=0;
	    		bigSize =20;
		    }
			// Set proper wifth for div
			divItem.style.width=bigSize*7;	    
		}
		}else{
			// We've typed the correct address
			updateCity(cityName,cityCode,zipCode);
			maxListCity=0;
		}

}


function showDropDown(fieldId){
	// show drop down , foreseen like this in case more drop downs where to be shown
	thisdiv = document.getElementById("DD-" + fieldId);
	// If it exists, show it (change class)
	if (thisdiv) thisdiv.className = "THShowDropDown";

}
function hideDropDown(fieldId){
	// hide drop down , foreseen like this in case more drop downs where to be hidden
	thisdiv = document.getElementById("DD-" + fieldId);
	// If it exists, hide it (change class)
	if (thisdiv) thisdiv.className = "THHideDropDown";

}

function showError(fieldId){
	// this function is used to show error divs
	thisdiv = document.getElementById(fieldId);
	// If it exists, show the error
	if (thisdiv) thisdiv.className = "errorShown";
	// As there is an error, we cancel the submit
	submit = false;

}
function hideError(fieldId){
	// this function is used to hide error divs
	thisdiv = document.getElementById(fieldId);
	// If it exists, hide it
	if (thisdiv) thisdiv.className = "errorHidden";
	// and as there is no mor error, allow for submissions
	// Note: everytime a submit is requestd, all fields are re-checked,
	// We do not allow sending solely based on this value
	submit = true;

}
	// 2 following functions are merely to get coordinates of "drop down - able" field

	function getTop(obj) {
		var cur = 0;
		if(obj.offsetParent) {		
			while(obj.offsetParent) {
				cur+=obj.offsetTop;
				obj = obj.offsetParent;
			}
		}
		return cur;
	}
	function getLeft(obj) {
		var cur = 0;
		if(obj.offsetParent) {		
			while(obj.offsetParent) {
				cur+=obj.offsetLeft;
				obj = obj.offsetParent;
			}
		}
		return cur;
	}


function updateStreet(name,code){
		// Update the hidden street code field with the proper value	
		streetField = document.getElementById("streetNm");
		streetCode  = document.getElementById("streetCode");
		//alert ('streetField:'+streetField.value+',streetCode:'+streetCode.value+']');
		
		
		streetField.value=unescape(name);
		streetCode.value = code;
		// And hide drop down, as this usually is called when a value from the drop down is selected
		hideDropDown("streetNm");	
		// as this could come also from a non drop down selection (user has typed the whole street by himself)
		// We have to validate the street
		checkValidStreet();	
		
	}

function updateCity(name,code,zip){
		// Update the hidden street code field with the proper value	
		cityField = document.getElementById("cityNmT");
		cityCode  = document.getElementById("cityNm");
		zipCode  = document.getElementById("zipCd");
		
		cityField.value=unescape(name);
		cityCode.value = code;
		zipCode.value = zip;
		// And hide drop down, as this usually is called when a value from the drop down is selected
		hideDropDown("cityNmT");	
		// as this could come also from a non drop down selection (user has typed the whole street by himself)
		// We have to validate the street
		showDiv("cityData");
		//checkValidStreet();	
		
	}
	
function showDiv(fieldId){
	// Function to show any div
	thisdiv = document.getElementById(fieldId);
	if (thisdiv) thisdiv.className = "divShown";

}
function hideDiv(fieldId){
	// Function to hide any div

	thisdiv = document.getElementById(fieldId);
	if (thisdiv) thisdiv.className = "divHidden";

}

function checkWholeInfo(){
	// function to check if all the fields are completed as required

	na = document.getElementById("customerNA").value;
	
	
	if (na==""){
	a = (document.getElementById("zipCd").value == "");
	//alert ("a=="+a);
	b = (document.getElementById("cityNmT").value == "");
	//alert ("b=="+b);
	c = (document.getElementById("streetNm").value == "") ;
	//alert ("c=="+c);
	d = (document.getElementById("houseNb").value == "" );
	//alert ("d=="+d);
	e =  !(document.getElementById("houseNb").value.match(/^\d*$/));
	//alert ("e=="+e);
	//f =  !(document.getElementById("alphaHouseNb").value.match(/^\D*$/));
	f =  !(document.getElementById("alphaHouseNb").value.match(/^\D*$/) || (document.getElementById("alphaHouseNb")=="") );
	//alert ("f=="+f);
	
	if (!a){
		if (b) {
		showDiv("cityData");
		return false;
		}
		if (c) {
		showError ("emptyStreetNMError");
		return false;
		}
		if (d) {
		showError ("emptyhouseNbError");
		return false;
		}
		if (e) {
		showError ("invalidhouseNbError");
		return false;
		}
		if (f) {
		showError ("invalidAlphaNumber");
		return false;
		}
	return true;
	}
	
	}else{
		return true;
	}
}

function checkValidAddress(){
	//debugger;
	// Cancel any previous requests
	if (req != null) req.abort();
	if (reqva != null) reqva.abort();
	// We will check the whole address form now
	var cityCode = document.getElementById("cityNm");
	var zipCode = document.getElementById("zipCd");
	var houseNb = document.getElementById("houseNb");
	var alphaHouseNb = document.getElementById("alphaHouseNb");
	var boxNb = document.getElementById("boxNb");
	var blockNb = document.getElementById("blockNb");
	var appartNb = document.getElementById("appartNb");
	var floorNb = document.getElementById("floorNb");
	//var streetName = document.getElementById("streetNm");
	var streetName = document.getElementById("streetCode");	
	
  	// create the URL to call
	
   	var url = "../../../../../bwt/check?lang=" + ajaxlang + 
   	"&zip=" + escape(zipCode.value) + 
   	"&city=" + escape(cityCode.value) + 
   	"&street=" + escape(streetName.value) +
   	"&houseNb=" + escape(houseNb.value) + 
   	"&alphaHouseNb=" + escape(alphaHouseNb) +
   	"&boxNb=" + escape (boxNb) + 
   	"&blockNb=" + escape (blockNb) +
   	"&appartNb=" + escape (appartNb) +
   	"&floorNb=" + escape (floorNb);
	// and the XMLHTTP request object
	if (window.XMLHttpRequest) {
   			   reqva = new XMLHttpRequest();
    	} else if (window.ActiveXObject) {
   			try {
				reqva = new ActiveXObject("Microsoft.XMLHTTP");
				} catch (e) {
					try {
		  				reqva = new ActiveXObject("Msxml2.XMLHTTP");
						} catch (E) {
							xmlhttp = false;
									}
 					}
  	}	
 	// call the servlet
	
	reqva.open("GET", url, true);
  	reqva.onreadystatechange = callbackAddress;
  	reqva.send(null);
	// Always return false, because check is not yet doen, remember that we're waiting for a response
  	// from the server, which will trigger the callbackAddress function.
	return  false;
}



function checkForm(){
    var streetName = document.getElementById("streetNm"); //
	
	// Check if exclusive fields are completed
	if (submit) submit = checkExclusive();
	//alert ("1 "+streetName.value);
	// Check if all fields are empty	
	if (submit) submit = checkEmpty();
	//alert ("2 "+streetName.value);
	// Check mandatory fields
	if (submit) submit = checkWholeInfo();
	//alert ("3 "+streetName.value);
	// Check if phone is empty, if not empty we do not chekc address
	na = document.getElementById("customerNA").value;
	if (na == ""){
		// validate address
     	//alert ("4 "+streetName.value);
		if (submit) checkValidAddress();
     	//alert ("5 "+streetName.value);
		// we will always return false as we do not do the final check
		// until we've got a valid XML response back from check servlet
	}else{
		var goodNA =  phoneExists(na);
		if (!goodNA){
			// Show invalid number error
			// showError ("customerNAError");
		}
		return true;
	}
	return false;
}

function checkExclusive(){
	// NA or ZIP, not both!
	na = document.getElementById("customerNA").value;
	zc = document.getElementById("zipCd").value;
	
	if ((na!="") && (zc!="")){
		showError ("exclusiveError");
		return false;	
	}else{
		return true;
	}
}

function checkEmpty(){	
	// On of NA or ZIP should be complete
	na = document.getElementById("customerNA").value;
	zc = document.getElementById("zipCd").value;
	if ((na=="") && (zc=="")){
		showError ("allEmptyError");
		return false;	
	}else{
		return true;
	}
}

function checkValidStreet(){
	// Call the servlet to see if the street is valid, usual AJAX stuff (see functions above to understand)
	sc = document.getElementById("streetCode");
    zipCode = document.getElementById("zipCd");
    cityName = document.getElementById("cityNm");
    streetName = document.getElementById("streetNm");
	// cancel any previous requests!
	if (req != null) req.abort();
	
	if (sc.value != "ERROR"){
	hideDropDown("streetNm");
		// first we recover the new XML with the complete value of the street
	   	var url = "../../../../../bwt/check?lang="+ajaxlang+"&zip=" + escape(zipCode.value)+"&city="+escape(cityName.value)+"&street="+escape(streetName.value);
	   	//prompt('url',url);
			if (window.XMLHttpRequest) {
   				   req = new XMLHttpRequest();
    	} else if (window.ActiveXObject) {
   			try {
				req = new ActiveXObject("Microsoft.XMLHTTP");
				} catch (e) {
					try {
		  				req = new ActiveXObject("Msxml2.XMLHTTP");
						} catch (E) {
							xmlhttp = false;
									}
 					}
 		}
		 req.open("GET", url, true);
  		 req.onreadystatechange = checkStreetName;
  		 req.send(null);
	}
}

function checkStreetName(){
	try {
   if (req.readyState == 4) {
        if (req.status == 200) {
		    xmlDoc = req.responseXML.getElementsByTagName("street");
			sn = document.getElementById("streetNm");
			correct = false;
			for (h=0;h<xmlDoc.length;h++){
				thisNode = xmlDoc.item(h);
				streetName = thisNode.getElementsByTagName("string")[0].childNodes[0].nodeValue;
				streetCode = thisNode.getElementsByTagName("code")[0].childNodes[0].nodeValue;
				// the street exists, update the streetCode hidden value
				if (sn.value.toUpperCase() == streetName.toUpperCase()){
					sc = document.getElementById("streetCode");
					sc.value = streetCode;
					correct = true
					// and hide erros!
					hideError("streetNmError");
				}
			}		
			if (!correct){
				// Street does not exist
				sc = document.getElementById("streetCode");
				// Reset street code value to empty
				sc.value = "";
				// Show error (Invalid street)
				showError("streetNmError");
			}
		
	    }
    }
    }catch(e){
	
    }
 }
  
function checkPhone (){
	// Check if the phone is a valid phone in the DB
	na = document.getElementById("customerNA");
	zc = document.getElementById("zipCd");
	cn = document.getElementById("cityNmT");
	cc = document.getElementById("cityNm");

	if (na.value.length > 0){
		zc.value="";
		cn.value="";
		cc.value="";
	    hideDiv("cityData");
	}
	if (na.value.length == 9){
		// TODO we should check if the phone exists on the DB
		phoneExists(na.value);
	}else{
		hideError ("customerNAError");
	}
	// If NA is completed, hide error showing that fields are empty
	if (na.value.length>0){
		hideError ("allEmptyError");
		// See if the zip is also with data
		checkExclusive();
	}else{
		// Otherwise, hide excluisve errors (NA empy!).
		hideError ("exclusiveError");
	}

}

function phoneExists(na){

	// Cancel previous requests  
	if (reqna != null) reqna.abort();


	if (na.length==9){

	// Url with the servlet that will return the XML
 /*   var url = "../../../../../bwt/check?na="+na;

	// Check which type of object we will use (this may and will change between browsers)
	if (window.XMLHttpRequest) {
   		   reqna = new XMLHttpRequest();
    } else if (window.ActiveXObject) {
   		try {
			reqna = new ActiveXObject("Microsoft.XMLHTTP");
			} catch (e) {
				try {
		  			reqna = new ActiveXObject("Msxml2.XMLHTTP");
					} catch (E) {
						xmlhttp = false;
								}
 				}
     
     } 
   // Open the URL
   reqna.open("GET", url, true);
   // tell the request object what function to call if there is a change in its state
   reqna.onreadystatechange = callbackPhone;
   // Send the request without any extra parameters (null)
   reqna.send(null);
	}else{
	// Phone number is not proper length - Return error
	return false;
*/
	return true;
	}
}


function callbackPhone(){
 /*  try {
   if (reqna.readyState == 4) {
        if (reqna.status == 200) {
		    xmlDoc = reqna.responseXML.getElementsByTagName("phone");
			// Check if we have answers
			if (xmlDoc.length>0){
				// NA is valid
				navalid = true;
				hideError ("customerNAError");
			}else{
				navalid = false
				showError ("customerNAError");
			}
		}
	}
	}catch(e){
		
	}
*/

}
