// http://gisweb.azdeq.gov/arcgis/epanls/
// ADEQ: Arizona Department of Environmental Quality

function GeocodeAddress(address)
{
    // break address into components
    var street = "";
    var city = "";
    var zip = "";
    var split = address.split(",");
    switch (split.length)
    {
        case 1:
            // street, missing city and zip
            ShowError("Enter an address,city,zip or an address,city or an address,zip");
            dojo.byId("address").focus();
            return;
        case 2:
            // street,city or street,zip
            street = split[0];
            isNaN(split[1]) ? city = split[1] : zip = split[1];
            break;
        case 3:
            // street,city,zip
            street = split[0];
            city = split[1];
            if (!isNaN(split[2])) zip = split[2];  // may be state
            break;
        case 4:
            // street,city,state,zip
            street = split[0];
            city = split[1];
            zip = split[3];
            break;
        default:
            ShowError("Invalid address");
            dojo.byId("address").focus();
            return;
    }

    // substitute locator @ for "and" in street intersections
    var and = street.indexOf(" and ");
    if (and < 0) and = street.indexOf(" AND ");
    if (and > 0) street = street.substring(0, and) + " @ " + street.substring(and+5, street.length);

    if (zip.length > 0)
    {
        // drop optional +4
        split = zip.split("-");
        zip = split[0];    

        // validate zipcode
        var z = Number(zip);
        if (z < 85000 || z >= 87000)
        {
            ShowError("Zip limited to 85000-86999");
            return;
        }
    }

    _geocode = { Address: dojo.trim(street), City: dojo.trim(city), State: "AZ", ZIP: dojo.trim(zip), Country: "USA" };

    // send request to server
    var locator = new esri.tasks.Locator(_locatorURL);
    dojo.connect(locator, "onAddressToLocationsComplete", GeocodeAddress2);
    locator.addressToLocations(_geocode, ["Loc_name"]);
}

function GeocodeAddress2(candidates)  // server response
{
    if (candidates.length == 0)
    {
        ShowError("Cannot find address");
        return;
    }
    
    // determine best returned candidate
    var bestScore = _minimumScore - 1;
    var index = -1;
    for (var i = 0; i < candidates.length; i++)
    {
        // limit candidates to street locators
        switch (candidates[i].attributes.Loc_name)
        {
            case "US_Streets":
            case "US_RoofTop":
                if (candidates[i].score > bestScore)
                {
                    // ensure city matches entered value
                    var address = candidates[i].address.split(", ");
                    if (address[1].toLowerCase() == _geocode["City"].toLowerCase())
                    {
                        bestScore = candidates[i].score;
                        index = i;
                    }
                    else
                    {
                        // ensure zip code matches entered value
                        switch (address.length)
                        {
                            case 4:  // street, city, state, zip
                                if (address[3] == _geocode["ZIP"])
                                {
                                    bestScore = candidates[i].score;
                                    index = i;
                                }
                                break;
                            case 3:  // street, city, state zip
                                if (address[2] == _geocode["State"] + " " + _geocode["ZIP"])
                                {
                                    bestScore = candidates[i].score;
                                    index = i;
                                }
                                break;
                        }
                    }
                }
                break;
        }
    }
    if (index < 0)
    {
        ShowError("Cannot find address");
        return;
    }
    _address = candidates[index].address;

    // convert lat/long to utm
    var location = new esri.geometry.Point(candidates[index].location.x, candidates[index].location.y, _WGS_1984);
    var graphic = new esri.Graphic(location);
    var geometryService = new esri.tasks.GeometryService(_geometryURL);
    dojo.connect(geometryService, "onProjectComplete", GeocodeAddress3);
    geometryService.project([graphic], _NAD_1983_UTM_Zone_12N);
}

function GeocodeAddress3(graphics)
{
    _location = graphics[0].geometry;
    
    // stringize extent
    var perimeter = parseInt(_distance * _MetersPerMile * 1.5);
    var extent = EnvelopeFromPoint(_location, perimeter);
    var ext = String(parseInt(extent.xmin));
    ext += ":" + String(parseInt(extent.ymin));
    ext += ":" + String(parseInt(extent.xmax));
    ext += ":" + String(parseInt(extent.ymax));
    
    // go on to results page
    document.location.href = "results.html?distance=" + _distance + "&address=" + _address + "&extent=" + ext;
}

