﻿//XMLHttpRequest functions
//
// All rights are reserved. Reproduction or transmission in whole or in part, in 
// any form or by any means, electronic, mechanical or otherwise, is prohibited 
// without the prior written consent of the copyright owner.
// 
// Filename: AJAX.js


//HTTP handlers for MWS Services
var proxyName = "FindAddressProxy.ashx";
var routeProxyName = "FindProxy.ashx";
var findNearbyProxyName = "FindNearbyProxy.ashx";

//HTTP handler for zooming in, uses States.xml
var zoomAlgorithmProxyName = "ZoomAlgorithm.ashx";

//XMLHttpRequest object
var xmlhttp = false;

//polygon datasources
var EAFlights = "False";
var OAFlights = "False";

//for driving directions: Start, End or Both
var GeocodeType="";

function FindAddressByLatLong( latlong, ea, oa )
{
	HideFindAddressErrorLabel();
    // Check to see which category was checked off to see which polygon file to check
	EAFlights=ea;
    OAFlights=oa;
    
    // Validate for at least one category and one address field
    if (EAFlights == "False" && OAFlights == "False")
    {
       // map.ShowMessage('You must select a Category to perform a search.');
       ShowFindAddressErrorLabel('You must select a Category.');
    }
    else
    {    
        polyzipSearchFlag=true;

        // Call Find Address Proxy   
        InitXmlHttp();
        xmlhttp.onreadystatechange=searchHandler;
        xmlhttp.open("GET", "" + findNearbyProxyName + "?EAFlights="+EAFlights+"&OAFlights="+OAFlights+"&latitude="+latlong[0]+"&longitude="+latlong[1], true );
        xmlhttp.send(null);
        ShowPanel("eRecruitingPanel");
        startExpand("eRecruitingPanel");
    }
}

// Find Address call
function FindAddress()
{
	ResetParams();
	HideFindAddressErrorLabel();
	HideFindResults();
	map.Clear();
	
	
    // Check to see which category was checked off to see which polygon file to check
    if (document.getElementById("chkEnlistedRecruiting").checked)
    {
        EAFlights="True";
    }
    else
    {
		EAFlights = "False";
	}
    if (document.getElementById("chkHealthProfessions").checked )
    {
        OAFlights="True";
    }
    else
    {
		OAFlights = "False";
	}
    
    // Validate for at least one category and one address field
    if (EAFlights == "False" && OAFlights == "False")
    {
       // map.ShowMessage('You must select a Category to perform a search.');
       ShowFindAddressErrorLabel('You must select a Category.');
    }
    else if ((document.getElementById("address").value=="") && (document.getElementById("zip").value==""))
    {
        ShowFindAddressErrorLabel('You must enter a zip code.');
    }
    else if ((document.getElementById("address").value=="") && (document.getElementById("city").value=="") && (document.getElementById("state").value=="") && (document.getElementById("zip").value==""))
    {
        //map.ShowMessage('You must enter an address to perform a search.');
        ShowFindAddressErrorLabel('You must enter an address.');
    }
    else if ((document.getElementById("address").value=="") && (document.getElementById("city").value=="") && !(document.getElementById("state").value=="") && (document.getElementById("zip").value==""))
    {
        ShowFindAddressErrorLabel('You must enter a city or zip code.');
    }
    else
    {    
        polyzipSearchFlag=true;
        
        var address = document.getElementById('address').value;
        var city = document.getElementById('city').value;
        var zipCode =document.getElementById('zip').value;
        var state =document.getElementById('state').value;
        
        var zipRegex=/^[0-9][0-9][0-9][0-9][0-9]$/;        
        
        //Validate the entered postalcode or clear if invalid:
       
        if(!zipRegex.test(zipCode)){
           zipCode = "";
        } 
                
        
        var addressLine="";

        if(address != ""){
            addressLine+=address;
            addressLine+=",";
        }
        
        // Search using zip code only as per PO 54867
        //if(city != ""){
        //    addressLine+=city;
        //    addressLine+=",";
        //}
        
        //if(state != ""){
        //    addressLine+=state;
        //    addressLine+=",";
        //}
        
        if(zipCode != ""){
            addressLine+=zipCode;
            addressLine+=",";
        }
        
        if (state.toUpperCase() == "PUERTO RICO" || state.toUpperCase() =="PR")
            addressLine+= "Puerto Rico";
        else if(address != "" || city != "" || state != "" || zipCode != "")
            addressLine+="US";
        
        if(addressLine != ""){
            try{
                map.Find(null,addressLine,null,null,null,null,null,null,true,null,onFoundResults); //Call VE to geocode address
            }
            catch(e){
                alert(e.message);
            }
        }        
    }
}

//The callback function. Called after the search result is returned.
function onFoundResults(a, b, resultsArray, d, e)
{
    if (resultsArray.Length < 1)
    {
        NoResultsError();
    }
    else
    {
        // Call Find Address Proxy   
        InitXmlHttp();
        xmlhttp.onreadystatechange=searchHandler;
        xmlhttp.open("GET", "" + proxyName + "?latitude=" + resultsArray[0].LatLong.Latitude + "&longitude=" + resultsArray[0].LatLong.Longitude + "&zip="+ document.getElementById("zip").value+"&EAFlights="+EAFlights+"&OAFlights="+OAFlights, true );
        xmlhttp.send(null);
    }
}

// Zoom Algorith proxy
function GetIconReference()
{
    // Retrieve center latlong of map
    var centerMap="";
    centerMap = map.GetCenter();

    // Call Zoom Proxy
    InitXmlHttp();
    xmlhttp.onreadystatechange=searchHandler;
    xmlhttp.open("GET", "" + zoomAlgorithmProxyName + "?zoomLevel="+xZoomLevel+"&xCenterMap="+ centerMap+"&er="+ ERChecked+"&hp="+ HPChecked+"&ot="+ OTChecked+"&globalState="+ globalState+"&globalCity="+ globalCity, true );
    xmlhttp.send(null);
}


function NoResultsError()
{
    //map.ShowMessage('No results found');
    ShowFindAddressErrorLabel( 'No Results Found' );
}


/* This function is used to initialize the xmlHttp object */
function InitXmlHttp() {
    // Attempt to initialize xmlhttp object
    try
    {
        xmlhttp = new ActiveXObject("Msxml2.XMLHTTP");
    }
    catch (e)
    {
        // Try to use different activex object
        try
        {
            xmlhttp = new ActiveXObject("Microsoft.XMLHTTP");
        }
        catch (E)
        {
            xmlhttp = false;
        }
    }
    
    // If not initialized, create XMLHttpRequest object
    if (!xmlhttp && typeof XMLHttpRequest!='undefined')
      {     
            xmlhttp = new XMLHttpRequest();
      }
      // Define function call for when Request obj state has changed
      xmlhttp.onreadystatechange=searchHandler;
}


/* Handles and evals the Response from Proxy page */
function searchHandler()
{
    if (xmlhttp.readyState==4)
    {
        try
        {
            eval( xmlhttp.responseText );
        }
        catch (E)
        {            
            map.ShowMessage( "An internal error occured" );
        }
    }
}

