//----------------------------------------------------------------------
//globals
//----------------------------------------------------------------------
var m_objAddressForms = 0;
var m_sFormPath = "StreetPerfect/";
var m_bValid = false;
var m_bCorrected = true;
var m_bForeign = false;
var m_bNotCorrect = true;

//----------------------------------------------------------------------
//obect definition
//----------------------------------------------------------------------
function AddressForm( sId, tbxAddress, tbxCity, tbxCode, tbxProvince, tbxCountry, tbxAssumeCorrect, btnSubmit)
{
  this.sId = sId;
  this.tbxCode = tbxCode;
  this.tbxAddress = tbxAddress;
  this.tbxCity = tbxCity;
  this.tbxProvince = tbxProvince;
  this.tbxCountry = tbxCountry;
  this.tbxAssumeCorrect = tbxAssumeCorrect;
  this.btnSubmit = btnSubmit;
}


/////////////////////////////////////////////////////////////////////////
//
// PUBLIC INTERFACE:
//
//    InitDir
//    DisplayProperties
//    InitForms
//    ValidateAddress
//    ValidateAll
//    QuickAddress
//
/////////////////////////////////////////////////////////////////////////


//----------------------------------------------------------------------
//
//  Method:   InitDir
//
//  Purpose:  Let's the script know where the streetperfect pages are
//            relative to the calling page.
//
//----------------------------------------------------------------------
function InitDir( sPath ){
  m_sFormPath = sPath;
}

//----------------------------------------------------------------------
//
//  Method:   DisplayProperties
//
//  Purpose:  By default valid addresses and foreign addresses provide no
//            no indication of the processing. Invalid and corrected addresses
//            do provide indication in the pop up. This method provides an
//            interface for adjusting these properties.
//
//----------------------------------------------------------------------
function DisplayProperties( bValid, bCorrected, bForeign, bNotCorrect) {
  m_bValid = bValid;
  m_bCorrected = bCorrected;
  m_bForeign = bForeign;
  m_bNotCorrect = bNotCorrect;
}

//----------------------------------------------------------------------
//
//  Method:  InitForms
//
//  Purpose:  Sets up current values in forms to assist with validation
//            later, also registers the given address boxes for click
//            events so we can tell if a user has changed the value in
//            the text box
//
//----------------------------------------------------------------------
function InitForms(sId, tbxAddress, tbxCity, tbxCode, tbxProvince, tbxCountry, tbxAssumeCorrect, btnSubmit){

  var index = 0
  if (m_objAddressForms == 0) {
    m_objAddressForms = [new AddressForm];
  } else {
    index = m_objAddressForms.length;
    m_objAddressForms[m_objAddressForms.length] = [new AddressForm];
  }

  m_objAddressForms[index].sId = sId;
  m_objAddressForms[index].tbxCode = tbxCode;
  m_objAddressForms[index].tbxAddress = tbxAddress;
  m_objAddressForms[index].tbxProvince = tbxProvince;
  m_objAddressForms[index].tbxCity = tbxCity;
  m_objAddressForms[index].tbxCountry = tbxCountry;
  m_objAddressForms[index].tbxAssumeCorrect = tbxAssumeCorrect;
  m_objAddressForms[index].btnSubmit = btnSubmit;

  //register the ADDRESS text box for events
  tbxAddress.EIT_sId = sId;
  // save the old onchange event handler
  tbxAddress.orig_onChange_EventHandler=tbxAddress.onchange;
  tbxAddress.onchange=FormChange_EventHandler;

  //register the POSTAL CODE text box for events
  tbxCode.EIT_sId = sId;
  // save the old onchange event handler
  tbxCode.orig_onChange_EventHandler=tbxCode.onchange;
  tbxCode.onchange=FormChange_EventHandler;

  //register the PROVINCE text box for events
  tbxProvince.EIT_sId = sId;
  // save the old onchange event handler
  tbxProvince.orig_onChange_EventHandler=tbxProvince.onchange;
  tbxProvince.onchange=FormChange_EventHandler;

  //register the CITY text box for events
  tbxCity.EIT_sId = sId;
  // save the old onchange event handler
  tbxCity.orig_onChange_EventHandler=tbxCity.onchange;
  tbxCity.onchange=FormChange_EventHandler;

  //register the COUNTRY text box for events
  tbxCountry.EIT_sId = sId;
  // save the old onchange event handler
  tbxCountry.orig_onChange_EventHandler=tbxCountry.onchange;
  tbxCountry.onchange=FormChange_EventHandler;

  //if the user has given you a button then give it a handler
  if (btnSubmit != null) {
    btnSubmit.EIT_sId = sId;
    // save the old onclick event handler;
    btnSubmit.orig_onClick_EventHandler=btnSubmit.onclick;
    btnSubmit.onclick=SubmitButton_EventHandler;
  }

}


//----------------------------------------------------------------------
//
//  Method:  ValidateAddress
//
//  Purpose: Validate address call only be called on forms that were
//           previously registered with a call to initforms. The id
//           assigned during InitForms is used here to indicate which
//           form is to be validated with StreetPerfect.
//
//----------------------------------------------------------------------
function ValidateAddress( sId ){

  var lFormToValidate = GetFormById( sId );
  var bValidStatus = ConvertToBool (lFormToValidate.tbxAssumeCorrect.value)

  //you told me to assume this one is correct
  if ( bValidStatus == true) {
    return "V"
  }
  
  //Get the Address results
  PageToLoad = m_sFormPath + "ValidateAddress.aspx?sCode=" + escape(lFormToValidate.tbxCode.value) +
               "&sStreetAddress=" + escape(lFormToValidate.tbxAddress.value) +
               "&sCity=" + escape(lFormToValidate.tbxCity.value) +
               "&sProv=" + escape(lFormToValidate.tbxProvince.value) +
               "&sCountry=" + escape(lFormToValidate.tbxCountry.value) +
               "&bValid=" + m_bValid +
               "&bCorrected=" + m_bCorrected +
               "&bForeign=" + m_bForeign +
               "&bNotCorrect=" + m_bNotCorrect +
               "&sFormName=" + sId;

  lResults = window.showModalDialog( PageToLoad, "Address Validation " + sId , "dialogHeight: 250px; dialogWidth: 600px; status:off;");

  //If the address is correct than set assumecorrect so that we don't try and validate again later.
  lsStatus = RandomAccess("sStatus",lResults);

  if (lsStatus == "V"){                     //valid address
    lFormToValidate.tbxAssumeCorrect.value = true;
  } else if (lsStatus == "C") {             //corrected address
    lFormToValidate.tbxAssumeCorrect.value = true;
  } else if (lsStatus == "F") {             //foreign address
    lFormToValidate.tbxAssumeCorrect.value = true;
  } else if (lsStatus == "I") {             //ignore address address
                                            //Note that 'I' means you will get no values
    lFormToValidate.tbxAssumeCorrect.value = false;
  } else if (lsStatus == "S") {             //correct and save address
    lFormToValidate.tbxAssumeCorrect.value = true;
  }


  PopulateForm(lResults, lFormToValidate.tbxAddress, lFormToValidate.tbxCity, lFormToValidate.tbxCode, lFormToValidate.tbxProvince, lFormToValidate.tbxCountry);
  return lsStatus;
}


//----------------------------------------------------------------------
//
//  Method:  ValidateAll
//
//  Purpose: Validate all addresses
//
//----------------------------------------------------------------------
function ValidateAll( ){
  for (i = 0; i < m_objAddressForms.length; i++) {
    ValidateAddress(m_objAddressForms[i].sId);
  }
}


//----------------------------------------------------------------------
//
//  Method:  QuickAddress
//
//  Purpose:  Makes use of the QuickAddress form to get address information
//            then distributes it to the local form.
//
//----------------------------------------------------------------------
function QuickAddress( tbxAddress, tbxCity, tbxCode, tbxProvince, tbxCountry){

  //Get the Address results
  PageToLoad = m_sFormPath + "QuickAddress.aspx?sCode=" + tbxCode.value;
  lResults = window.showModalDialog( PageToLoad, "Address Look Up", "dialogHeight: 250px; dialogWidth: 600px; status:off;");
  PopulateForm(lResults, tbxAddress, tbxCity, tbxCode, tbxProvince, tbxCountry);
}



/////////////////////////////////////////////////////////////////////////
// PRIVATE
/////////////////////////////////////////////////////////////////////////



//----------------------------------------------------------------------
//
//  Method:   GetFormById
//
//  Purpose:  Returns the form in the global array of initialized forms.
//
//----------------------------------------------------------------------
function GetFormById( sId ){
  for (i = 0; i < m_objAddressForms.length; i++) {
    if (m_objAddressForms[i].sId == sId) {
      return m_objAddressForms[i];
    }
  }
}


//----------------------------------------------------------------------
//
//  Method:  RandomAccess
//
//  Purpose: Provides random access to a set of attribute value pairs by attribute
//
//----------------------------------------------------------------------
function RandomAccess( attribute, valueArray)
{
  for (i=0; i< valueArray.length; i++)
  {
    lTemp = valueArray[i].split("=");
    lsAttribute = lTemp[0];         //first value of array is attribute
    lsValue = lTemp[1];             //second value of array is value

    if (attribute == lsAttribute){
      return lsValue;
    }
  }
  return null;
}


//----------------------------------------------------------------------
//
//  Method:   PopulateForm
//
//  Purpose:  Takes an array of '=' delimited attribute value pairs that match
//            values from the StreetPerfect Webservice CompleteAddressStruct
//            and populates the form
//
//----------------------------------------------------------------------
function PopulateForm(Results, tbxAddress, tbxCity, tbxCode, tbxProvince, tbxCountry)
{
  if (Results == null) {
    return;
  }
  //Distribute the results to the form

  //check for street info.
  if (RandomAccess("sStreetAddress", Results) != null) {
      tbxAddress.value = RandomAccess("sStreetAddress", Results);
  }

  //check for the city info
  if (RandomAccess("sCity", Results) != null) {
    tbxCity.value = RandomAccess("sCity", Results);
  }

  //check for the postal/zip code info
  if (RandomAccess("sCode", Results) != null) {
    tbxCode.value = RandomAccess("sCode", Results);
  }

  //check for the province/state info
  if (RandomAccess("sProv", Results) != null) {
    tbxProvince.value = RandomAccess("sProv", Results);
  }

  //check for the country info
  if (RandomAccess("sCountry", Results) != null) {
    tbxCountry.value = RandomAccess("sCountry", Results);
  }

  //Set the Address field as the next with focus
  tbxAddress.focus();
}

//----------------------------------------------------------------------
//
//  Method:    ConvertToBool
//
//  Purpose:  Javascript converts to booleans weirdly. Better to write your
//            own casting function that works like someone would expect.
//
//----------------------------------------------------------------------
function ConvertToBool(inBool){
  if (inBool == 1) {
    return true;
  }else if (inBool.toLowerCase() == "true"){
    return true;
  }else{
    return false;
  }
}

/////////////////////////////////////////////////////////////////////////
// EVENT HANDLERS
/////////////////////////////////////////////////////////////////////////


//----------------------------------------------------------------------
//
//  Event:    FormChanged_EventHandler
//
//  Purpose:  Update the status of the form as changed so we know to
//            validate the address again later.
//
//----------------------------------------------------------------------
function FormChange_EventHandler( ){
  var sId = window.event.srcElement.EIT_sId;      //the id of the form that has been changed
  lobjFormChanged = GetFormById( sId );       //the actual form

  // Call the Original Handler
  if (window.event.srcElement.orig_onChange_EventHandler != null) {
    window.event.srcElement.orig_onChange_EventHandler();
  }

  lobjFormChanged.tbxAssumeCorrect.value = false;
}


//----------------------------------------------------------------------
//
//  Event:    SubmitButton_EventHandler
//
//  Purpose:  Handle determining what to return when the user presses the button
//            that is associated with the address form
//
//----------------------------------------------------------------------
function SubmitButton_EventHandler( ){
  var sId = window.event.srcElement.EIT_sId;  //the id of the form that has been changed
  lobjSubmitPressed = GetFormById( sId );     //the actual form

  // Call the Original Handler
  if (lobjSubmitPressed.btnSubmit.orig_onClick_EventHandler != null) {
    lobjSubmitPressed.btnSubmit.orig_onClick_EventHandler();
  }

  lobjSubmitPressed.btnSubmit;                //the button
  sStatus = ValidateAddress(sId)

  //if the form return Corrected/Foreign/or Valid then it's okay to continue
  if (sStatus=="F" || sStatus=="V" || sStatus=="I" || sStatus=="S" ){
    return true;
  } else {
    return false;
  }

}

