var http_request = false;

function validateUSAZipCode(zipCodeElement) {
	if (zipCodeElement.name.indexOf("Agency") > -1) {
		// Agency elements
		validateAgencyUSAZipCode();
	}
	else {
		// Owner elements
		validateOwnerUSAZipCode();
	}
}

function validateOwnerUSAZipCode() {
	if (document.detailform.Owner_Address_Zip_Cd.value.length > 0) {
		validateUSAZipCodeCall(document.detailform.Owner_Address_Zip_Cd.value, 'Owner');
	}
	else {
		document.detailform.Owner_Address_Zip_Cd.value = '';
		document.detailform.Owner_Address_City.value = '';
		document.detailform.Owner_Address_State_Cd.value = '';		
	}
}

function validateAgencyUSAZipCode() {
	if (document.detailform.Agency_Address_Zip_Cd.value.length > 0) {
		validateUSAZipCodeCall(document.detailform.Agency_Address_Zip_Cd.value, 'Agency');
	}
	else {
		document.detailform.Agency_Address_Zip_Cd.value = '';
		document.detailform.Agency_Address_City.value = '';
		document.detailform.Agency_Address_State_Cd.value = '';		
	}
}

function validateUSAZipCodeCall(zipCode, fieldName) {
	// Validate Zip Code
	var url = "/cgi-bin/BlueChipRentals/common/perllet_validateUSAZipCode.pl?letId=" + encodeURIComponent(zipCode) + "&fieldName="  + encodeURIComponent(fieldName) ;
	if (window.XMLHttpRequest) { // Mozilla, Safari,...
          http_request = new XMLHttpRequest();
          if (http_request.overrideMimeType) {
             // set type accordingly to anticipated content type
             // http_request.overrideMimeType('text/xml');
             http_request.overrideMimeType('text/html');
          }
        } else if (window.ActiveXObject) { // IE
          try {
              http_request = new ActiveXObject("Msxml2.XMLHTTP");
          } catch (e) {
             try {
                http_request = new ActiveXObject("Microsoft.XMLHTTP");
             } catch (e) {}
          }
        }
        if (!http_request) {
           alert('Cannot create XMLHTTP instance');
           return false;
        }
	http_request.open("GET", url, true);
	http_request.onreadystatechange = validateUSAZipCodeBack;
	http_request.send(null);
}    
 
function validateUSAZipCodeBack() {
    if (http_request.readyState == 4) {
        if (http_request.status == 200) {
            // extract zip code and other fields
	    var zipCodes = http_request.responseText;
	    var zipReturnValues = zipCodes.split('|');
	    var fieldName = zipReturnValues[1];
	    var returnCode = zipReturnValues[2];
	    var city = zipReturnValues[3];
	    var stateCd = zipReturnValues[4];
	    if (returnCode == 0) {
		// error - null out fields
		if (fieldName == 'Owner') {
			document.detailform.Owner_Address_Zip_Cd.value = '';
			document.detailform.Owner_Address_City.value = '';
			document.detailform.Owner_Address_State_Cd.value = '';
		}
		else {
			document.detailform.Agency_Address_Zip_Cd.value = '';
			document.detailform.Agency_Address_City.value = '';
			document.detailform.Agency_Address_State_Cd.value = '';
		}
		alert('The Zip Code Entered Was Invalid.  Please Try Again.');
	    }
	    else {
		// ok - set fields
		if (fieldName == 'Owner') {
			document.detailform.Owner_Address_City.value = city;
			document.detailform.Owner_Address_State_Cd.value = stateCd;
		}
		else {
			document.detailform.Agency_Address_City.value = city;
			document.detailform.Agency_Address_State_Cd.value = stateCd;
		}
	    }
        }
    }
}

function getOwnerAddressElements(countryId) {
	getAddressElements(countryId);
}

function getAgencyAddressElements(countryId) {
	getAddressElements(countryId, 'Agency');
}

function getAddressElements(countryId, fieldName) {
	// Get Address Elements For Country
	var url = "/cgi-bin/BlueChipRentals/common/perllet_getAddressElements.pl?letId=" + encodeURIComponent(countryId)   + "&fieldName="  + encodeURIComponent(fieldName);
	if (window.XMLHttpRequest) { // Mozilla, Safari,...
          http_request = new XMLHttpRequest();
          if (http_request.overrideMimeType) {
             // set type accordingly to anticipated content type
             // http_request.overrideMimeType('text/xml');
             http_request.overrideMimeType('text/html');
          }
        } else if (window.ActiveXObject) { // IE
          try {
              http_request = new ActiveXObject("Msxml2.XMLHTTP");
          } catch (e) {
             try {
                http_request = new ActiveXObject("Microsoft.XMLHTTP");
             } catch (e) {}
          }
        }
        if (!http_request) {
           alert('Cannot create XMLHTTP instance');
           return false;
        }
	http_request.open("GET", url, true);
	http_request.onreadystatechange = getAddressElementsBack;
	http_request.send(null);
	addressElementsHTML = '<table width="100%" align="center" cellspacing="0" cellpadding="0" class="A-searchTypeFont" valign=top><tr align=center><td><br><br>Please wait, address elements loading .....<br><br><br></td></tr></table>';
	if (fieldName == 'Owner') {
		document.getElementById("owneraddressdata").innerHTML = addressElementsHTML;
	}
	else {
		document.getElementById("agencyaddressdata").innerHTML = addressElementsHTML;
	}
}    

function getAddressElementsBack() {
    if (http_request.readyState == 4) {
        if (http_request.status == 200) {
            // extract address elements and other fields
	    var addressElements = http_request.responseText.split(':');
	    var numElements = addressElements.length;
	    var fieldName = addressElements[1].split('|')[0];
	    var returnCode = addressElements[1].split('|')[1];
	    var telCode = addressElements[1].split('|')[2];
	    if (fieldName == 'Owner') {
		    document.detailform.Owner_Home_Tel_Country_Cd.value = telCode;
	    }
	    else {
		    document.detailform.Agency_Tel_Country_Cd.value = telCode;
	    }
	    if (returnCode == 0) {
		// error no address found so set to default
		setAddressElementsToDefault(fieldName);
	    }
	    else {
		    addressElementsHTML = '<table width="100%" align="center" cellspacing="0" cellpadding="0" class="A-searchTypeFont" valign=top>';
		    var htmlStartLabel = '<tr><td width="33%" align=right class=A-searchTypeFont>';
		    var htmlStartField ='';
		    if (fieldName == 'Owner') {
			    var htmlStartField = '<td width="67%" align=left class=A-searchTypeFont><input type=text name=Owner_';
		    }
		    else {
			    var htmlStartField = '<td width="67%" align=left class=A-searchTypeFont><input type=text name=Agency_';
		    }
		    var valueSize = ' value="" size=';
		    var valueMaxLength = ' maxlength=';
		    var valueOther = '';
		    var htmlRequired = '<font color=red>*</font>';
		    var htmlEndLabel = '&nbsp;:&nbsp;</td>';
		    var htmlEndField = '></td></tr>';
		    for (var x = 1; x<numElements; x++) {
			var y= x-1;
		        var elementAttributes = addressElements[x].split('|');
			var elementLabel = elementAttributes[3];
			var elementName = elementAttributes[4];
			var elementType = elementAttributes[5];
			var elementLength = elementAttributes[6];
			var elementEnterableLength = elementAttributes[7];
			var elementRequiredFl = elementAttributes[8];
			// Check if readonly
			if (elementRequiredFl == 'R') {
				valueOther = ' readonly=readonly';
			}
			else {
				valueOther = '';
			}
			// Find other validation parameters
			var elementValidation = elementAttributes[9].toString();
			var elementValidationAction = '';
			var elementValidationFl = '';
			var elementRequiredText = '';
			// Combine for validation string
			var elementValidationString = '';
			if (elementRequiredFl == 'Y') {
				elementValidationString = 'R';
				elementRequiredText = htmlRequired;
			}
			if (elementValidation.length > 0) {
				if (elementValidation.length > 5) {
					// Validation is a call to a routine
					elementValidationAction = elementValidation;
				}
				else {
					// Validation is general validation
					elementValidationFl = elementValidation;
				} 
			}
			elementValidationString = elementValidationString + elementValidationFl;
		        addressElementsHTML = addressElementsHTML + htmlStartLabel + elementRequiredText + elementLabel + htmlEndLabel + htmlStartField + elementName + valueSize + elementLength + valueMaxLength + elementEnterableLength + valueOther + elementValidationAction + htmlEndField;
		    }
		    addressElementsHTML = addressElementsHTML + '</table>';
		    if (fieldName == 'Owner') {
			    document.getElementById("owneraddressdata").innerHTML = addressElementsHTML;
		    }
		    else {
			    document.getElementById("agencyaddressdata").innerHTML = addressElementsHTML;
		    }
	    }
        }
    }
}

function setAddressElementsToDefault(fieldName) {
	if (fieldName == 'Owner') {
		addressElementsHTML = '<table cellspacing="0" cellpadding="0" width="100%" align="center" class="A-searchTypeFont" valign=top><tr><td width="33%" align=right class="A-searchTypeFont"><font color=red>*</font>Street Address :&nbsp;</td><td width="67%" align=left class="A-searchTypeFont"><input type=text name="Owner_Address_Ln1" value="" size="55" maxlength="50"></td></tr><tr><td width="33%" align=right class="A-searchTypeFont"><font color=red>*</font>City/Town :&nbsp;</td><td width="67%" align=left class="A-searchTypeFont"><input type=text name="Owner_Address_City" value="" size="45" maxlength="40"></td></tr><tr><td width="33%" align=right class="A-searchTypeFont"><font color=red>*</font>Locality/Province/County :&nbsp;</td><td width="67%" align=left class="A-searchTypeFont"><input type=text name="Owner_Address_State_Cd" value="" size="45" maxlength="40"></td></tr><tr><td width="33%" align=right class="A-searchTypeFont"><font color=red>*</font>Post Code :&nbsp;</td><td width="67%" align=left class="A-searchTypeFont"><input type=text name="Owner_Address_Zip_Cd" value="" size="20" maxlength="10"></td></tr></table>';
		document.getElementById("owneraddressdata").innerHTML = addressElementsHTML;
	}
	else {
		addressElementsHTML = '<table cellspacing="0" cellpadding="0" width="100%" align="center" class="A-searchTypeFont" valign=top><tr><td width="33%" align=right class="A-searchTypeFont"><font color=red>*</font>Street Address :&nbsp;</td><td width="67%" align=left class="A-searchTypeFont"><input type=text name="Agency_Address_Ln1" value="" size="55" maxlength="50"></td></tr><tr><td width="33%" align=right class="A-searchTypeFont"><font color=red>*</font>City/Town :&nbsp;</td><td width="67%" align=left class="A-searchTypeFont"><input type=text name="Agency_Address_City" value="" size="45" maxlength="40"></td></tr><tr><td width="33%" align=right class="A-searchTypeFont"><font color=red>*</font>Locality/Province/County :&nbsp;</td><td width="67%" align=left class="A-searchTypeFont"><input type=text name="Agency_Address_State_Cd" value="" size="45" maxlength="40"></td></tr><tr><td width="33%" align=right class="A-searchTypeFont"><font color=red>*</font>Post Code :&nbsp;</td><td width="67%" align=left class="A-searchTypeFont"><input type=text name="Agency_Address_Zip_Cd" value="" size="20" maxlength="10"></td></tr></table>';
		document.getElementById("agencyaddressdata").innerHTML = addressElementsHTML;
	}
}

function MM_findObj(n, d) { //v4.0
   var p,i,x;  if(!d) d=document; if((p=n.indexOf("?"))>0&&parent.frames.length) {
     d=parent.frames[n.substring(p+1)].document; n=n.substring(0,p);}
   if(!(x=d[n])&&d.all) x=d.all[n]; for (i=0;!x&&i<d.forms.length;i++) x=d.forms[i][n];
   for(i=0;!x&&d.layers&&i<d.layers.length;i++) x=MM_findObj(n,d.layers[i].document);
   if(!x && document.getElementById) x=document.getElementById(n); return x;
 }
 
 function MM_validateForm() { //v4.0
   var i,p,q,nm,test,num,min,max,errors='',args=MM_validateForm.arguments;
   for (i=0; i<(args.length-2); i+=3) { 
     test=args[i+2];
     val=MM_findObj(args[i]);
     if (val) { 
 	nm=args[i+1]; 
 	if ((val=val.value)!="") {
         	if (test.indexOf('isEmail')!=-1) { 
 			p=val.indexOf('\@');
 	        	if (p<1 || p==(val.length-1))  {
 				errors+='- '+nm+' must contain an e-mail address.';
 			}
         	}
 		else { 
			if (test.charAt(1) == 'N' || test.charAt(1) == 'P') {
         	 		if (isNaN(val)) {
					errors+='- '+nm+' must contain a number.';
			  	}
				if (test.charAt(1) == 'P' && val.length < 10) {
					errors+='- '+nm+' must be a 10 digit number.';
				}
			}
 			else {
 		        	if (test.indexOf('inRange') != -1) { 
 					p=test.indexOf(':');
 	        			min=test.substring(8,p); max=test.substring(p+1);
         	  			if (val<min || max<val) {
 						errors+='- '+nm+' must contain a number between '+min+' and '+max+'.\n';
 					}
 				}
 				else {
 					if (test.charAt(1) == 'T') {
          			 		if (isTime(val)) {
 							errors+='- '+nm+' must be a valid time in the format HH:MM.';
 			  			}
 					}
 					else {
 						if (test.charAt(1) == 'D') {
          				 		if (isDate(val)) {
 								errors+='- '+nm+' must be a date in the format YYYY-MM-DD.';
 				  			}
 						}
 					}
 				}
 			}
 		}
      	}
      	else {
 		if (test.charAt(0) == 'R') {
 			errors += '- '+nm+' is required.\n'; 
 		}
 	}
      }
   } 
   if (errors) alert('The following error(s) occurred:\n'+errors);
   document.MM_returnValue = (errors == '');
 }
 
 function isTime(testTime)
 {
 	// check testtime is a time
 	p=testTime.indexOf(':');
 	if (p == -1 || p == 0) {
 		return 1;
 	}
 	hours=testTime.substring(0,p); mins=testTime.substring(p+1);
 	if (isNaN(hours) || isNaN(mins)) {
 		return 1;
 	}
 	if (hours<0 || hours > 23) {
 		return 1;
 	}
 	if (mins<0 || mins > 59) {
 		return 1;
 	}
 
 	return 0;
 }

