/*

  MapQuest-based Branch Locator AJAX code Version 1.0
  Copyright (C) 2006 Harding Marketing Communications
  Version   1.0 2/6/2006

  Important Usage Note:
        This file requires that the MapQuest javascript library be
        loaded from the including HTML file. This means that the
        following includes must be present:

        <script src="mapFunctions.js" type="text/javascript"></script>
        <script src="BranchLocatorAjaxLibrary.js" type="text/javascript"></script>

  Debugging note:
        This program will insert the resulting XML into the page if
        there is a section there to receive it. That section looks like
        this:

        <TEXTAREA id="xml" name="xml" rows="20" cols="80">
          xml response goes here.  Debug only, normally hidden.
        </TEXTAREA>
*/

document.write('<script src="BranchLocatorLocalizedStrings.js" type="text/javascript"></script>');

// This global is used to store the active XMLHttpRequest object
// Currently we only have and use one of these at a time.  Because of IE
// this object is destroyed and recreated for every request (you cannot use
// the IE XMLHTTP obect more than once reliably).
var BLAL_http_request = false;

// This global stores the current language ID.  This value defaults to English
// and is set by calling the getLanguageSetting() function.
var BLAL_languageID = "en";

// This global stores the type of query that we are doing. Currently the
// only request types that are valid are "search" and "route".
var BLAL_requestType = null;

// This function is from simpler logger by Philip McCarthy, phil@chimpen.com
function printfire ()
  {
    if (document.createEvent)
      {
        printfire.args = arguments;
        var ev = document.createEvent("Events");
        ev.initEvent("printfire", false, true);
        if (window.dispatchEvent)
          {
            dispatchEvent(ev);
          }
      }
  }

function logMessage(msg)
  {
    printfire("BLAL: " + msg);
  }

function logError(msg)
  {
    printfire("BLAL ERROR: " + msg);
  }

// This method will query the page information to determine what the
// current language is.  Since we don't know yet how this will work, it
// currently looks for a languageID parameter to fake it.
function getLanguageSetting()
  {
    var each_cookie = document.cookie.split(";");

    for (i = 0; i < each_cookie.length; i++)
      {
        var next_cookie = each_cookie[i].trim();

        if (next_cookie.indexOf("woodforestBank=") == 0)
          {
            var one_cookie = unescape(next_cookie.substr(15)).trim();

            var each_variable = one_cookie.split(";");

            for (j = 0; j < each_variable.length; j++)
              {
                var next_variable = each_variable[j].trim();

                if (next_variable.indexOf("languageID") == 0)
                  {
                    return(BLAL_languageID = next_variable.split("=")[1]);
                  }
              }
          }
      }

    return(BLAL_languageID = "en");
  }

function getLocalizedString(stringID)
  {
    var localizedString = localeStrings[getLanguageSetting()][stringID];

    if (localizedString == null)
      {
        return(  "<span style='font-size:xx-large; color: red'>"
               + "Localized String '"
               + stringID
               + "' Not Found in language '"
               + getLanguageSetting()
               + "'!</span>");
      }

    if (getLocalizedString.arguments.length > 1)
      {
        var args = new Array();

        // Copy all but the first argument, which is stringID
        for (x=1; x < getLocalizedString.arguments.length; x++)
          {
            args.push(getLocalizedString.arguments[x]);
          }

        // Now look up the localized string, and use the remaining arguments
        // to format that string.
        return(replaceParams(localizedString, args));
      }

    return(localizedString);
  }

// Initialize an XMLHttpRequest().  Creates and initializes the object
// and stores it in the global BLAL_http_request variable.
function makeRequest(requestType, url)
  {
    BLAL_http_request = false;

    // Set the global state.
    BLAL_requestType = requestType;

    if (window.XMLHttpRequest) // Mozilla, Safari,...
      {
        BLAL_http_request = new XMLHttpRequest();
        if (BLAL_http_request.overrideMimeType)
          {
            BLAL_http_request.overrideMimeType('text/xml');
            // See note below about this line
          }
      }
    else if (window.ActiveXObject) // IE
      {
        try
          {
            BLAL_http_request = new ActiveXObject("Msxml2.XMLHTTP");
          }
        catch (e)
          {
            try
              {
                BLAL_http_request = new ActiveXObject("Microsoft.XMLHTTP");
              }
            catch (e)
              {}
          }
      }

    if (!BLAL_http_request)
      {
        logError('Giving up :( Cannot create an XMLHTTP instance');
        return false;
      }

    // Set the cursor to a wait cursor for the whole document while we
    // are processing the request.
    document.body.style.cursor = "wait";

    // Get the results span and make it visible
    var resultsSection = document.getElementById("resultsSection");
    if (resultsSection)
      resultsSection.style.display = "";

    BLAL_http_request.onreadystatechange = alertContents;
    BLAL_http_request.open('GET', url, true);
    BLAL_http_request.send(null);

  }

// This is a simple XML helper function that checks to see if
// the first child of the passed element is a text element and
// if it is, it returns the text element. Otherwise it has no
// children or the child is not text and it returns the second
// parameter (which defaults to "" if not specified). It does
// NOT traverse the element to build a text element.
function TextChildOrDefault(element, defaultValue)
  {
    defaultValue = defaultValue || "";

    // NodeType 3 is text
    if (element && element.firstChild && element.firstChild.nodeType == 3)
        return(element.firstChild.data);

    return(defaultValue);
  }

// This is a simple worker function to translate semicolons in the
// incoming string to <br> HTML.
function semicolonToBreak(inString)
  {
    var parts = new Array();
    var outString = "";

    parts = inString.split(';');
    for (var i=0; i < parts.length; i++)
      {
        outString += parts[i];

        // Don't add a break on the end.
        if (i < parts.length-1)
          outString += "<br />";
      }

    return(outString);
  }


// This function builds the Driving Directions route list starting from
// <maneuvers> in the MapQuest generated XML as a <table> element and
// returns it as a string.
//
// This method uses the following styles:
//   th.resultsTableTitle
//   td.resultsTableMap
//   td.resultsTableNumber
//   td.resultsTableInstructions
//   td.resultsTableDistance
//   span.stepNumber
//   span.stepInstructions
//   span.stepDistance
function BuildRouteList(searchResults)
  {
    var resultList = "";

    var theURL = new URLQuery(window.location.search)

    var showMaps = !(theURL.getValue("maps") && (theURL.getValue("maps") == "0"));

    resultList += "<table cellspacing='0' cellpadding='0' width='100%' summary='" + getLocalizedString("DRIVING_DIRECTIONS") + "' > ";
    resultList += "  <tr>";
    if (showMaps)
      resultList += "    <th class='resultsTableTitle' scope='col' valign='top'>&nbsp;Map</th> ";
    resultList += "    <th colspan='2' class='resultsTableTitle' scope='col' valign='top'>&nbsp;" + getLocalizedString("DRIVING_DIRECTIONS") + "</th> ";
    resultList += "    <th class='resultsTableTitle' scope='col' valign='top'>&nbsp;" + getLocalizedString("MILES") + "</th> ";
    resultList += "  </tr>";

    var maneuvers = searchResults.getElementsByTagName('maneuver');
    logMessage("Found " + maneuvers.length + " steps in the driving directions");
    for (x = 0; x < maneuvers.length; x++)
      {
        nextStep = maneuvers[x];
        stepNumber = nextStep.getElementsByTagName('number').item(0);
        stepInstructions = nextStep.getElementsByTagName('text').item(0);
        stepTime = nextStep.getElementsByTagName('time').item(0);
        stepDistance = nextStep.getElementsByTagName('distance').item(0);
        stepMap = nextStep.getElementsByTagName('request').item(0).firstChild;

        // Check to see if it has a text element.
        stepNumber       = TextChildOrDefault(stepNumber, "0");
        stepInstructions = TextChildOrDefault(stepInstructions);
        stepTime         = TextChildOrDefault(stepTime);
        stepDistance     = TextChildOrDefault(stepDistance);

        logMessage("step number: " + stepNumber);
        logMessage(stepInstructions);
        logMessage(stepTime        );
        logMessage(stepDistance    );
        logMessage(stepMap.data         );

        resultList += "      <tr>";

        if (showMaps)
          {
            resultList += "        <td class='resultsTableMap'>";
            resultList += "          <img width='198' height='119' src='" + stepMap.data + "'>&nbsp;";
            resultList += "        </td>";
          }

        sn = "<span class='stepNumber'>";
        si = "<span class='stepInstructions'>";
        sd = "<span class='stepDistance'>";
        se = "</span>";
        sebr = "</span><br>";

        resultList += "        <td class='resultsTableNumber'>";
        resultList += sn + stepNumber + sd;
        resultList += "        </td>";
        resultList += "        <td class='resultsTableInstructions'>";
        resultList += si + stepInstructions + se;
        resultList += "        </td>";
        resultList += "        <td class='resultsTableDistance'>" + sd + stepDistance + se + "</td>";
        resultList += "      </tr>";
      }

    var totalDistance = searchResults.getElementsByTagName('totalDistance').item(0);

    resultList += "      <tr>";
    if (showMaps)
      resultList += "        <td colspan='3' class='resultsTableInstructions'>";
    else
      resultList += "        <td colspan='2' class='resultsTableInstructions'>";

    resultList += "<span class='stepNumber'>" + getLocalizedString("TOTAL") + "</span>"
               +  "</td>"
               +  "        <td class='resultsTableDistance'>"
               +  "<span class='stepDistance'>" + totalDistance.firstChild.data + "</span>"
               +  "</td>";
    resultList += "      </tr>";

    resultList += "</table>";
    return(resultList);

    return(resultList);
  }

// This function builds the POI result list starting from <location> in
// the MapQuest generated XML as a <table> element and returns it as a
// string.
//
// This method uses the following styles:
//   th.resultsTableTitle
//   td.resultsTableAddress
//   td.resultsTableDistance
//   td.resultsTableHours
//   td.resultsTableServices
//   span.branchPrompt
//   span.branchDescription
function BuildResultList(searchResults)
  {
    var resultList = "";

    //Build Results Header Row
    resultList += "<table cellspacing='1' cellpadding='0' width='100%' summary='Search Results'>";
    resultList += "  <tr>";
    resultList += "    <th class='resultsTableTitle' style='WIDTH: 208px' valign='top' scope='col'>&nbsp;" + getLocalizedString("MAP") + "</th> ";
    resultList += "    <th class='resultsTableTitle' valign='top' scope='col'>&nbsp;Location Information</th>";
    resultList += "  </tr>";

    var locations = searchResults.getElementsByTagName('location');
    for (x = 0; x < locations.length; x++)
      {
        nextLoc = locations[x];
        itemNumber = nextLoc.getElementsByTagName('number').item(0);
        branchName = nextLoc.getElementsByTagName('name').item(0);
        branchAddress = nextLoc.getElementsByTagName('address').item(0);
        branchCity = nextLoc.getElementsByTagName('city').item(0);
        branchState = nextLoc.getElementsByTagName('stateProvince').item(0);
        branchZip = nextLoc.getElementsByTagName('postalCode').item(0);
        branchDistance = nextLoc.getElementsByTagName('distance').item(0);
        branchID = nextLoc.getElementsByTagName('user1').item(0);
        branchHours = nextLoc.getElementsByTagName('user2').item(0);
        branchDriveUp = nextLoc.getElementsByTagName('user3').item(0);
        branchDesc = nextLoc.getElementsByTagName('user4').item(0);
        branchATMDesc = nextLoc.getElementsByTagName('user5').item(0);
        branchATMHours = nextLoc.getElementsByTagName('user6').item(0);
        branchPostal = nextLoc.getElementsByTagName('user7').item(0);
        branchTXDOT = nextLoc.getElementsByTagName('user8').item(0);
        branchPhone = nextLoc.getElementsByTagName('user9').item(0);
        branchHolidayHours = nextLoc.getElementsByTagName('user10').item(0);

        recordId = nextLoc.getElementsByTagName('recordId').item(0);
        mapURL = nextLoc.getElementsByTagName('request').item(0).firstChild;

        // Check to see if it has a text element.
        itemNumber         = TextChildOrDefault(itemNumber, "0");
        recordId           = TextChildOrDefault(recordId, getLocalizedString("UNKNOWN"));
        branchName         = TextChildOrDefault(branchName);
        branchAddress      = TextChildOrDefault(branchAddress);
        branchCity         = TextChildOrDefault(branchCity);
        branchState        = TextChildOrDefault(branchState);
        branchZip          = TextChildOrDefault(branchZip);
        branchDistance     = TextChildOrDefault(branchDistance);
        branchID           = TextChildOrDefault(branchID);
        branchHours        = TextChildOrDefault(branchHours);
        branchDriveUp      = TextChildOrDefault(branchDriveUp);
        branchDesc         = TextChildOrDefault(branchDesc);
        branchATMDesc      = TextChildOrDefault(branchATMDesc);
        branchATMHours     = TextChildOrDefault(branchATMHours);
        branchPostal       = TextChildOrDefault(branchPostal, "False");
        branchTXDOT        = TextChildOrDefault(branchTXDOT,  "False");
        branchPhone        = TextChildOrDefault(branchPhone);
        branchHolidayHours = TextChildOrDefault(branchHolidayHours);
        
        var bankLogoType = branchATMDesc;
     		
        //Begin branch results name and header Row
        resultList += "<tr>";
        resultList += " <td class='resultsTableBranchName' colspan='2'>";
        resultList += " <table class='LogoTitleTable' width='100%'>";
        resultList += "<tr>";
        resultList += " <td style='width:200px;'>";
		if(bankLogoType == 1 || bankLogoType == 0)
		{
		resultList += "   <img alt='Bank Logo' src='/Tools/BranchLocator/images/results_" + bankLogoType + "_Logo.gif'>";
		}
        resultList += " </td>";
        resultList += " <td><span class='branchNameHeader'>" + branchName + "</span></td>";
        resultList += "</tr>";
        resultList += "</table>";
        resultList += " </td>";
        resultList += "</tr>";
        
        //BEGIN of Map & Branch Hours & Address Row
        resultList += "<tr>";
        
        //BEGIN results table map container
        resultList += "<td class='resultsTableMap' style='width: 208px'>";
        resultList += "<table class='ResultsTableMapContainer'>";
        resultList += "<tr>";
				resultList += "	<td>";
				resultList += "	<img width='198' height='119' src='" + mapURL.data + "'>";
				resultList += "	</td>";
				resultList += "</tr>";
				resultList += "<tr>";
				resultList += "	<td><span class='branchPrompt'>Distance: </span>";
				resultList += "	<span class='branchDescription'>" + branchDistance + "miles</span></td>";
				resultList += "</tr>";
        resultList += "<tr>";
				resultList += "	<td>";
				
				resultList += "<a class='drivingLink' href='GetDirections.aspx"
                   +  "?destRecordId="      + recordId
                   +  "&address="           + document.getElementById("address").value
                   +  "&city="              + document.getElementById("city").value
                   +  "&state="             + document.getElementById("state").value
                   +  "&zip="               + document.getElementById("zip").value
                   +  "&destName="          + branchName
                   +  "&destAddress="       + branchAddress
                   +  "&destCity="          + branchCity
                   +  "&destStateProvince=" + branchState
                   +  "&destPostalCode=   " + branchZip
                   +  "'>" + getLocalizedString("DRIVING_DIRECTIONS") + "</a>";
                   					
				resultList += "</td>";
				resultList += "</tr>";
        resultList += "</table>";
        resultList += "</td>";
        //END of results table Map Container and cell
        
        resultList += "<td class='resultsTableAddress'>";
        
        //Begin Address & Phone table
        resultList += "   <table class='BranchAddressandPhone'>";
        resultList += "     <tr>";
        resultList += "<td width='50%'>";
        resultList += "   <span class='branchPrompt' style='background-color:#EEEEEE'>"+getLocalizedString("ADDRESS")+":</span>";
        resultList += "   <br>";
				resultList += "		<span class='branchDescription'>" + branchAddress + "<br>" + branchCity + ", " + branchState + " "+ branchZip + "</span><br>";
				resultList += "</td>";
				resultList += "<td valign='top'><span class='branchPrompt' style='background-color:#EEEEEE'>"+ getLocalizedString("PHONE") +":</span>";
				resultList += "   <br>";
				resultList += "		<span class='branchDescription'>" + branchPhone + "</span><br>";
        resultList += "</td>";
        resultList += "</tr>";
        resultList += "</table>";
        
        //BEGIN BRANCH HOURS TABLE
        resultList += "<table class='BranchHoursTable'>";
				resultList += "<tr>";
				resultList += "	<td align='center' bgcolor='#EEEEEE'>";
				resultList += "	<span class='branchPrompt'>Lobby Hours</span></td>";
				resultList += "</tr>";
				resultList += "<tr>";
				resultList += "	<td><span class='branchDescription'>"+semicolonToBreak(branchHours)+"</span></td>";
				resultList += "</tr>";
				resultList += "<tr>";
				resultList += "	<td align='center' bgcolor='#EEEEEE'>";
				resultList += "	<span class='branchPrompt'>" + getLocalizedString("DRIVE_UP_HOURS") + "</span></td>";
				resultList += "</tr>";
				resultList += "<tr>";
				resultList += "	<td><span class='branchDescription'>" + semicolonToBreak(branchDriveUp) + "</span></td>";
				resultList += "</tr>";
        resultList += "</table>";

        
        
        
        
        
        resultList += "</td>";
        resultList += "</tr>"; //END of Map & Branch Hours & Address Row
        

       
        //BEGIN SPACER ROW
        resultList += "<tr>";
        resultList += "<td colspan='2' class='rowSpacer'></td>";
        resultList += "</tr>";
      }
        
      	
    //Closing Tag Main Table
    resultList += "</table>";

    return(resultList);
  }

// This function processes the search results XMl document.
function processSearchResults(xmldoc, xmltext)
  {
    var search = xmldoc.getElementsByTagName('search').item(0);

    var error = true;
    var status = 99;
    if (search)
      {
        status = search.getAttribute("status");

        logMessage("Search Status = " + status);

        if (status && status == "0")
          error = false;
      }

    // If error, then there is no point in continuing to parse the
    // document.
    errorMessageDiv = document.getElementById("errorMessage");
    errorMessageDiv.innerHTML = "";
    if (error)
      {
        if (status >= 2)
          errorMsg = getLocalizedString("SEARCH_ADDRESS_NOT_FOUND");
        else
          errorMsg = getLocalizedString("SEARCH_ADDRESS_SPECIFIC");

        errorMessageDiv.innerHTML = errorMsg;

        return;
      }

    var primaryMapURL = xmldoc.getElementsByTagName('request').item(0);
    var searchResults = xmldoc.getElementsByTagName('searchResults').item(0);
    var startPage = xmldoc.getElementsByTagName('pageResultsStart').item(0);
    var resultsPerPage = xmldoc.getElementsByTagName('pageResults').item(0);

    // If we have incomplete results, these will contain the parameters
    // to retrieve the next or previous group.
    var previousGroupURL = xmldoc.getElementsByTagName('prevData').item(0);
    var nextGroupURL     = xmldoc.getElementsByTagName('nextData').item(0);

    // We want the second rollover as the first one is the confirmation in the
    // header that we asked for a rollover list.  This is easier than walking
    // the tree to get the right value.  Only slightly unsafe.
    var rolloverList = xmldoc.getElementsByTagName('rollover').item(1);

    if (primaryMapURL)
      {
        overviewMapDiv = document.getElementById("overviewMapHere");
        overviewMapIMG = "<img src='"
                       + primaryMapURL.firstChild.data
                       + "' name='map' id='overview_map' "
                       + "alt='" + getLocalizedString("MAP") + "' border='0'>";
        overviewMapDiv.innerHTML = overviewMapIMG;
      }

    // Now that we have a "real" map, tell the MapQuest
    // map object about it.
    mqaMapInit ('overview_map', 6, '');

    if (startPage)
      {
        startPage = parseInt(startPage.firstChild.data)+1;
      }
    else
      startPage = 1;

    if (resultsPerPage)
      {
        resultsPerPage = parseInt(resultsPerPage.firstChild.data);
      }
    else
      resultsPerPage = 10;

    logMessage("startPage = " + startPage);
    logMessage("resultsPerPage = " + resultsPerPage);

    prevGroupDivider = "";
    var spans = document.getElementsByTagName('span')
    for (var i = 0; i < spans.length; i++)
      {
        if (spans[i].className == 'prevGroup')
          {
            if (previousGroupURL)
              {
                spans[i].innerHTML =
                    "<a class='prevGroupLink'"
                  + "      onclick=\"searchPrevNext('"+ previousGroupURL.firstChild.data + "')\">"
                  + "  " + getLocalizedString("PREVIOUS_GROUP")
                  + "</a>";

                prevGroupDivider = " ------------- ";
              }
            else
              spans[i].innerHTML = "";
          }

        if (spans[i].className == 'prevGroupDivider' && nextGroupURL)
          {
            spans[i].innerHTML = prevGroupDivider;
          }

        if (spans[i].className == 'nextGroup')
          {
            if (nextGroupURL)
              {
                spans[i].innerHTML =
                    "<a class='nextGroupLink'"
                  + "      onclick=\"searchPrevNext('"+ nextGroupURL.firstChild.data + "')\">"
                  + "  " + getLocalizedString("NEXT_GROUP")
                  + "</a>";
              }
            else
              spans[i].innerHTML = "";
          }

        if (spans[i].className == 'numLocs')
          {
            if (searchResults && rolloverList.getAttribute("count") > 1)
              {
                endPage = (resultsPerPage-1) + parseInt(startPage);
                totalItems = (rolloverList.getAttribute("count")-1);

                if (endPage > totalItems) endPage = totalItems;

                message = "";
                if (totalItems > 30)
                  message = "<br><span class='resultsMessage'>"
                          + "(" + getLocalizedString("MAKE_SPECIFIC") + ")"
                          + "</span>";

                spans[i].innerHTML = getLocalizedString("THROUGH", startPage, endPage, totalItems)
                                     + " "
                                     + message;
              }
            else
              spans[i].innerHTML = "<span class='errorMessage'>" + getLocalizedString("NONE_FOUND") + "</span>";
          }
      }

    var locationsDiv = document.getElementById("locations");
    locationsDiv.innerHTML = BuildResultList(searchResults);
  }

// This function processes the route results XMl document.
function processRouteResults(xmldoc, xmltext)
  {
    var route = xmldoc.getElementsByTagName('route').item(0);

    var error = true;
    var status = 99;
    if (route)
      {
        status = route.getAttribute("status");

        logMessage("Status = " + status);

        if (status && status == "0")
          error = false;
      }

    // If error, then there is no point in continuing to parse the
    // document.
    errorMessageDiv = document.getElementById("errorMessage");
    errorMessageDiv.innerHTML = "";
    if (error)
      {
        if (status >= 2)
          errorMsg = getLocalizedString("SEARCH_ADDRESS_NOT_FOUND");
        else
          errorMsg = getLocalizedString("SEARCH_ADDRESS_SPECIFIC");

        errorMessageDiv.innerHTML = errorMsg;

        return;
      }

    var overviewMap = xmldoc.getElementsByTagName('overviewMap').item(0);
    var primaryMapURL = overviewMap.getElementsByTagName('request').item(0);
    var routeResults = xmldoc.getElementsByTagName('maneuvers').item(0);
    var startPage = xmldoc.getElementsByTagName('pageResultsStart').item(0);
    var resultsPerPage = xmldoc.getElementsByTagName('pageResults').item(0);

    var totalTime = xmldoc.getElementsByTagName('totalTime').item(0);
    var totalDistance = xmldoc.getElementsByTagName('totalDistance').item(0);

    // If we have incomplete results, these will contain the parameters
    // to retrieve the next or previous group.
    var previousGroupURL = xmldoc.getElementsByTagName('prevData').item(0);
    var nextGroupURL     = xmldoc.getElementsByTagName('nextData').item(0);

    if (primaryMapURL)
      {
        overviewMapDiv = document.getElementById("overviewMapHere");
        overviewMapIMG = "<img src='"
                       + primaryMapURL.firstChild.data
                       + "' name='map' id='overview_map' "
                       + "alt='" + getLocalizedString("MAP") + "' border='0'>";
        overviewMapDiv.innerHTML = overviewMapIMG;
      }

    // Now that we have a "real" map, tell the MapQuest
    // map object about it.
    mqaMapInit ('overview_map', 6, '');

    var spans = document.getElementsByTagName('span')
    for (var i = 0; i < spans.length; i++)
      {
        if (spans[i].className == 'timeGroup')
          {
            if (totalTime)
              {
                var seconds = totalTime.firstChild.data;

                var timeString = "";

                // Convert the seconds to hours and minutes
                if (seconds > (60 * 60))
                  {
                    timeString += Math.floor(seconds / 3600) + " " + getLocalizedString("HOURS") + " ";
                  }

                timeString += Math.floor((seconds % 3600) / 60) + " " + getLocalizedString("MINUTES");

                spans[i].innerHTML = timeString;
              }
            else
              spans[i].innerHTML = getLocalizedString("UNKNOWN");
          }

        if (spans[i].className == 'distanceGroup')
          {
            if (totalDistance)
              {
                spans[i].innerHTML = totalDistance.firstChild.data;
              }
            else
              spans[i].innerHTML = getLocalizedString("UNKNOWN");
          }
      }

    var locationsDiv = document.getElementById("locations");
    locationsDiv.innerHTML = BuildRouteList(routeResults);
  }

// This is the Ajax callback function.  This is where the work of
// loading the result XML starts.
function alertContents()
  {
    if (BLAL_http_request.readyState == 4)
      {
        // Set the cursor back to auto since we either got a result or
        // an error.
        document.body.style.cursor = "auto";

        if (BLAL_http_request.status == 200)
          {
            // document.write(BLAL_http_request.responseText);
            var xmldoc  = BLAL_http_request.responseXML;
            var xmltext = BLAL_http_request.responseText;


//document.getElementById('showResult').innerHTML = xmltext;

            logMessage("Request Type = " + BLAL_requestType);

            if (BLAL_requestType == "search")
              {
                processSearchResults(xmldoc, xmltext);
              }
            else
              {
                processRouteResults(xmldoc, xmltext)
              }

            // Debugging code
            xmlField = document.getElementById("xml");
            if (xmlField != null)
              xmlField.value = xmltext;
          }
        else
          {
            logError('There was a problem with the request.');
          }
      }
  }

// This function walks through the elements on the page and builds the
// end of a search URL for MapQuest. It makes assumptions about the
// names of the fields on the page, so if you change those field names
// (or add some) you will need to modify this function.
function buildSearchValues()
  {
    var srchBranch        = document.getElementById("srchBranch");
    var srchATM           = document.getElementById("srchATM");
    var srchExtHours      = document.getElementById("srchExtHours");
    var srch24Hours       = document.getElementById("srch24Hours");
    var srchWeekendHours  = document.getElementById("srchWeekendHours");
    var srchInStore       = document.getElementById("srchInStore");
    var srchTDOT          = document.getElementById("srchTDOT");
    var srchUSPS          = document.getElementById("srchUSPS");
    var srchDriveThru     = document.getElementById("srchDriveThru");

    if (srchBranch == null)
      return("");

    var searchValues = "";

    if (srchBranch.checked && srchATM.checked)
      {
        // If both are checked, then neither are searched for
      }
    else
      {
        if (srchBranch.checked)       searchValues += "&Search1=1";
        if (srchATM.checked)          searchValues += "&Search1=0";
      }
    if (srchExtHours.checked)     searchValues += "&Search2=1";
    if (srch24Hours.checked)      searchValues += "&Search3=1";
    if (srchWeekendHours.checked) searchValues += "&Search4=1";
    if (srchInStore.checked)      searchValues += "&Search5=1";
    if (srchTDOT.checked)         searchValues += "&Search6=1";
    if (srchUSPS.checked)         searchValues += "&Search7=1";
    if (srchDriveThru.checked)    searchValues += "&Search8=1";

    return(searchValues);
  }

// This stores the path to the web service.
//
// We use this to build URLs based on the current form settings. This
// web service takes our parameters, adds authentication information for
// MapQuest and some parameter defaults and passes the request on to
// MapQuest.
var BLAL_webServiceURL = "GetTheMap.aspx?";

// This function queries our web service for the current address on the
// page.
function searchAddress()
  {
    var address    = document.getElementById("address");
    var city       = document.getElementById("city");
    var state      = document.getElementById("state");
    var zip        = document.getElementById("zip");
    var srchRadius = document.getElementById("srchRadius");


    makeRequest("search",
                BLAL_webServiceURL + 'address=' + address.value
                                   + '&city=' + city.value
                                   + '&state=' + state.value
                                   + '&zip=' + zip.value
                                   + '&radius=' + srchRadius.value
                                   + buildSearchValues());
  }

// This function queries our web service using only the Zip Code on the
// page.
function searchZip()
  {
    var zip   = document.getElementById("zip");
    var srchRadius = document.getElementById("srchRadius");

    makeRequest("search",
                BLAL_webServiceURL + 'zip=' + zip.value
                                   + '&radius=' + srchRadius.value
                                   + buildSearchValues());
  }

// This is a helper function used to query MapQuest using the pre-built
// URL that hey provide in the XML for reading the previous list of
// items or the next list of items on the page.
function searchPrevNext(params)
  {
    makeRequest("search",
                BLAL_webServiceURL + params);
  }

// This function queries our web service for driving directions
function getDirections()
  {
    var address      = document.getElementById("address");
    var city         = document.getElementById("city");
    var state        = document.getElementById("state");
    var zip          = document.getElementById("zip");
    var destRecordId = document.getElementById("destRecordId");

    makeRequest("route",
                BLAL_webServiceURL + 'address=' + address.value
                                   + '&city=' + city.value
                                   + '&state=' + state.value
                                   + '&zip=' + zip.value
                                   + '&destRecordId=' + destRecordId.value
                                   + '&routeLanguage=' + getLanguageSetting());
  }


// Page URL Query Object.
//   This object parses the passed Key Value List into key value pairs.
//   You can pass any KV list into this, but the most common use is to
//   pass in window.location.search like this:
//
//   x = new URLQuery(window.location.search);
//
// Members:
//   getKeyValuePairs() - Return an associative array of the items in the URL.
//   getKeys() - Returns an array of the keys
//   getValue(key) - Returns the value for the passed key.
//   getLength() - Returns the number of key value pairs in the URL.
function URLQuery(kvList)
  {
    if (kvList.length > 1)
      this.kvList = kvList.substring(1, kvList.length);
    else
      this.kvList = null;

    // KeyValuePairs holds the associative array
    this.keyValuePairs = new Array();

    // Since I couldn't find an easy way to retrieve a list of the keys
    // in the associative array, we'll store them separately.
    this.keyList = new Array();

    if (kvList)
      {
        kvPairList = this.kvList.split("&");
        for (var i=0; i < kvPairList.length; i++)
          {
            nextPair = kvPairList[i];
            splitPair = nextPair.split("=");
            this.keyValuePairs[splitPair[0]] = unescape(splitPair[1]);
            this.keyList.push(splitPair[0]);
          }
      }

    this.getKeyValuePairs = function()
           {
             return this.keyValuePairs;
           }

    this.getKeys = function()
           {
             return(this.keyValuePairs.getKeys());
           }

    this.getValue = function(key)
           {
             return(this.keyValuePairs[key]);
           }

    this.getLength = function()
           {
             return this.keyValuePairs.length;
           }
  }

// Prefill the fields on the page from the URL. If we have complete
// search terms, run an initial search. This method allows us to use any
// incoming URL values to pre-fill the page as if the user had typed the
// values in. This allows this AJAX page to also act like a server-side
// GET style search.
//
// Note that this function makes assumptions about the names of fields
// on the page, so if you change (or add) fields on the page you will
// need to edit this function as well.
//
// This method cannot be called until the page is fully loaded, so the
// recommended approach is onLoad:
//
//   <body onLoad="prefill()">
//
function prefill()
  {
    var theURL = new URLQuery(window.location.search)

    // Preload form fields
    var addressValue           = theURL.getValue("address");
    var cityValue              = theURL.getValue("city");
    var stateValue             = theURL.getValue("state");
    var zipValue               = theURL.getValue("zip");
    var srchBranchValue        = theURL.getValue("srchBranch");
    var srchATMValue           = theURL.getValue("srchATM");
    var srchExtHoursValue      = theURL.getValue("srchExtHours");
    var srch24HoursValue       = theURL.getValue("srch24Hours");
    var srchWeekendHoursValue  = theURL.getValue("srchWeekendHours");
    var srchInStoreValue       = theURL.getValue("srchInStore");
    var srchTDOTValue          = theURL.getValue("srchTDOT");
    var srchUSPSValue          = theURL.getValue("srchUSPS");
    var srchDriveThruValue     = theURL.getValue("srchDriveThru");
    var srchRadiusValue        = theURL.getValue("radius");
    var destRecordIdValue      = theURL.getValue("destRecordId");
    var destNameValue          = theURL.getValue("destName");
    var destAddressValue       = theURL.getValue("destAddress");
    var destCityValue          = theURL.getValue("destCity");
    var destStateProvinceValue = theURL.getValue("destStateProvince");
    var destPostalCodeValue    = theURL.getValue("destPostalCode");

    var address           = document.getElementById("address");
    var city              = document.getElementById("city");
    var state             = document.getElementById("state");
    var zip               = document.getElementById("zip");
    var srchBranch        = document.getElementById("srchBranch");
    var srchATM           = document.getElementById("srchATM");
    var srchExtHours      = document.getElementById("srchExtHours");
    var srch24Hours       = document.getElementById("srch24Hours");
    var srchWeekendHours  = document.getElementById("srchWeekendHours");
    var srchInStore       = document.getElementById("srchInStore");
    var srchTDOT          = document.getElementById("srchTDOT");
    var srchUSPS          = document.getElementById("srchUSPS");
    var srchDriveThru     = document.getElementById("srchDriveThru");
    var srchRadius        = document.getElementById("srchRadius");
    var destRecordId      = document.getElementById("destRecordId");
    var destName          = document.getElementById("destName");
    var destAddress       = document.getElementById("destAddress");
    var destCity          = document.getElementById("destCity");
    var destStateProvince = document.getElementById("destStateProvince");
    var destPostalCode    = document.getElementById("destPostalCode");

    if (addressValue)
      address.value = addressValue;

    if (cityValue)
      city.value = cityValue;

    if (stateValue)
      state.value = stateValue.toUpperCase();

    if (zipValue)
      zip.value = zipValue;

    if (srchRadius)
      {
        if (srchRadiusValue)
          srchRadius.value = srchRadiusValue;
        else
          srchRadius.value = "20";
      }

    // If the current page has one search boolean field, it probably has
    // them all.
    if (srchBranch)
      {
        // We can only have one or the other, not both
        if (srchBranchValue == 1)
          {
            srchBranch.checked = true;
            srchATM   .checked = false;
          }

        // We can only have one or the other, not both
        if (srchATMValue          == 1)
          {
            srchBranch.checked = false;
            srchATM   .checked = true;
          }

        if (srchExtHoursValue     == 1) srchExtHours     .checked = true;
        if (srch24HoursValue      == 1) srch24Hours      .checked = true;
        if (srchWeekendHoursValue == 1) srchWeekendHours .checked = true;
        if (srchInStoreValue      == 1) srchInStore      .checked = true;
        if (srchTDOTValue         == 1) srchTDOT         .checked = true;
        if (srchUSPSValue         == 1) srchUSPS         .checked = true;
        if (srchDriveThruValue    == 1) srchDriveThru    .checked = true;

        // If we have complete search values, go ahead and do a search.
        if (zipValue)
          searchZip();

        if (cityValue && stateValue)
          searchAddress();
      }

    // If it has the destRecordId then it probably has all of the other
    // destination fields
    if (destRecordId)
      {
        if (destRecordIdValue)
          destRecordId.value = destRecordIdValue;

        if (destNameValue)
          destName.value = destNameValue;

        if (destAddressValue)
          destAddress.value = destAddressValue;

        if (destCityValue)
          destCity.value = destCityValue;

        if (destStateProvinceValue)
          destStateProvince.value = destStateProvinceValue;

        if (destPostalCodeValue)
          destPostalCode.value = destPostalCodeValue;

        // If we have a destination record ID, do a route search
        getDirections();
      }

  }
