var searchType = "";
var searchFor = "";
var firstSearch = false;
function doSearch(name, location) {
    searchType = "rides";
    if (name && name != "") {
        // Find ride by name.
        findRoutesByName(name);
    } else if (location && location != "") {
        // Do proximity search by location.
        doLocationSearch(location);
    } else {
        // No search term was entered.
        alert("Please enter a search term.");
    }
}
function locationSearch(location) {
    searchType = "search";
    searchFor = (isUK(location)) ? "UK" : (isPostcode(location) ? "postcode" : "place");
    doLocationSearch(location);
}

function doLocationSearch(address) {
    if (!isUK(address))
        address = address + ",UK";

    firstSearch = true;
    // Pass address to VE map.Find method and invoke callback function on completion.
    map.Find(
        null,           // what
        address,        // where
        null,           // VEFindType (always VEFindType.Businesses)
        null,           // VEShapeLayer (base by default)
        null,           // start index for results (0 by default)
        null,           // max number of results (default is 10)
        null,           // show results? (default is true)
        null,           // create pushpin for what results? (ignored since what is null)
        false,          // use default disambiguation? (default is true)
        true,           // set best map view? (default is true)
        processAddressSearch // callback function.
    );
}

function processAddressSearch(shape, results, places, hasMore, veErrorMessage) {
    // Clear any previous search results shapes.
    searchResultsShapeLayer.DeleteAllShapes();

    if (places == null || places.length == 0) {
        // No results found.
        alert("Search returned no results");
        return;
    }

    if (places.length == 1) {
        clearMapControl();
        // Found unique match.
        var place = places[0];
        var location = place.LatLong;
        
        // get rides
        if (searchType == "rides") {
            findRoutesByLocation(location.Longitude, location.Latitude);
        }
    } else {
        clearMapControl();
    
        // Process ambiguous result.
        var resultCoords = new Array();
        var ol = document.createElement('ol');
        for (var p = 0; p < places.length; p++) {
            var place = places[p];
            var location = place.LatLong;
            resultCoords.push(new VELatLong(location.Latitude, location.Longitude));

            // Create a pin at that location, list the latitude & longitude
            var pin = new VEShape(VEShapeType.Pushpin, location);
            var html = "<div class='searchResultPushpin'>"+(p+1)+"</div>";
            pin.SetCustomIcon(html);

            // Add pushpin to shapelayer.
            searchResultsShapeLayer.AddShape(pin);

            // Results list
            var li = document.createElement('li');
            var a = document.createElement('a');
            a.setAttribute('href', '#mapView');
            if (searchType == "search") {
                a.onclick = new Function('gotoLocation(' + location.Longitude + ',' + location.Latitude + ');');
            } else {
                a.onclick = new Function('findRoutesByLocation(' + location.Longitude + ',' + location.Latitude + ');');
            }
            a.innerHTML = place.Name;
            li.appendChild(a);
            ol.appendChild(li);
        }
        // Autoscale map to show all results.
        //map.SetMapView(resultCoords);
        searchResultsShapeLayer.Show();

        // Display list of locations.
        var searchResults = document.getElementById('searchResults');

        if (searchResults.firstChild != null) {

            searchResults.removeChild(searchResults.firstChild);
            
            if (searchResults.firstChild != null) {
                searchResults.removeChild(searchResults.firstChild);
            }
        }
        var title = document.createElement('h2');
        title.innerHTML = "Multiple Search Results";
        searchResults.appendChild(title);
        searchResults.appendChild(ol);
        searchResults.style.display = "block";
        alert("Multiple locations found, showing first location\n\nSee list below map for more locations.");
    }
}

function searchClusteringCallback(clusters) {
    // This function is called when a group of icons are clustered.
    for (var i = 0; i < clusters.length; ++i) {
        // Customise the icon and mouse-over infobox for each cluster.
        var cluster = clusters[i];
        var shape = cluster.Shapes[0];
        var id = shape.GetID();
        
        var clusterShape = cluster.GetClusterShape();
        clusterShape.SetTitle("There are " + cluster.Shapes.length + " search result locations here...");
        clusterShape.SetDescription("<br /><a href=\"#\" onClick='searchClusterClick(\"" + id + "\");'>Click here to search in this area</a>");
        clusterShape.SetCustomIcon('<div class=\"pin\"><img src=\"/images/emagin/pin_multi_white.gif\" /><div class=\"pinText\">&nbsp;</div></div>');
    }
}
function searchClusterClick(ID) {
    var shape = map.GetShapeByID(ID);
    var latlong = shape.GetIconAnchor();
    
    if (searchType == "search") {
        gotoLocation(shape.Longitude, shape.Latitude);
    } else {
        findRoutesByLocation(shape.Longitude, shape.Latitude);
    }
}
function gotoLocation(longitude, latitude, zoom) {
    if (zoom == null) zoom = 12;
    var coord = new VELatLong(latitude, longitude);
    map.SetCenterAndZoom(coord, zoom);
}
function isPostcode(search) {
    var test = /^([A-PR-UWYZ0-9][A-HK-Y0-9][AEHMNPRTVXY0-9]?[ABEHMNPRVWXY0-9]?)\s*?([0-9][ABD-HJLN-UW-Z]{2}|GIR 0AA)?$/i.test(search);
    return (test) ? true : false;
}
function isUK(search) {
    if (search.toLowerCase() == "uk" || search.toLowerCase() == "united kingdom")
        return true;
    else
        return false;
}

