﻿//AJAX Interaction 
//For server side validation 
function AJAXInteraction(url, callback) {

    var req = init();
    req.onreadystatechange = processRequest;
  
    function init() {
      if (window.XMLHttpRequest) {
        return new XMLHttpRequest();
      } else if (window.ActiveXObject) {
        return new ActiveXObject("Microsoft.XMLHTTP");
      }
    }
    
    function processRequest () {
      // readyState of 4 signifies request is complete
      if (req.readyState == 4) {
	  // status of 200 signifies sucessful HTTP call
        if (req.status == 200) {
            eval(callback + '(\'' + req.responseText + '\')');
        }
      }
    }

    this.doGet = function() {
      // make a HTTP GET request to the URL asynchronously
      req.open("GET", url, true);
      req.send(null);
    }
}

function validateThis(sourceClientID, descriptionClientID, webserviceURL, callbackFunctionName) {
    
    var target = document.getElementById(sourceClientID);
    var url = webserviceURL +  encodeURIComponent(target.value);
    var ajax = new AJAXInteraction(url, callbackFunctionName);
    if (target.value != '') {
        document.getElementById(descriptionClientID).innerHTML = 'Validating . . . ';
        document.getElementById(descriptionClientID).className = 'validate_wait';    
        ajax.doGet();
    }
}

function validatePostie(street1ClientID, street2ClientID, cityClientID, stateClientID, postcodeClientID, countryClientID, streetonly, descriptionClientID, webserviceURL, callbackFunctionName) {
    
    var street1Target = document.getElementById(street1ClientID);
    var street2Target = document.getElementById(street2ClientID);
    var cityTarget = document.getElementById(cityClientID);
    var stateTarget = document.getElementById(stateClientID);
    var postcodeTarget = document.getElementById(postcodeClientID);
    var countryTarget = document.getElementById(countryClientID); 

    var url = webserviceURL + 
              'street1=' + encodeURIComponent(street1Target.value) + '&' + 
              'street2=' + encodeURIComponent(street2Target.value) + '&' +
              'city=' + encodeURIComponent(cityTarget.value) + '&' +
              'state=' + encodeURIComponent(stateTarget.value) + '&' + 
              'postcode=' + encodeURIComponent(postcodeTarget.value) + '&' + 
              'streetonly=' + streetonly;    
    var ajax = new AJAXInteraction(url, callbackFunctionName);
    
    // Only validate if country value is blank (which means country = Australia) 
    if (countryTarget.value == '') {
        document.getElementById(descriptionClientID).innerHTML = 'Validating . . . ';
        document.getElementById(descriptionClientID).className = 'validate_wait';    
        ajax.doGet();
    }
}
 
