(function($) {
jQuery.fn.searchForm = function() {
    var $form = $(this);
    var locator = new OpenSpace.Gazetteer();
    var $locationsDiv = $("#messageDiv");

    function generateMapURL(aLocation) {
        return "index.php?easting=" + aLocation.location.lon +
                        "&northing=" + aLocation.location.lat;
    }

    $form.submit(function() {
        var locationString = $form.children("#location").val();
        if (locationString.trim() == "") {
            displayError("Please enter a location.");
            return false;
        }
        
        $locationsDiv.html("Loading...");

        locator.getLocations(locationString, setLocation);

        function setLocation(locations) {
            if (locations.length == 0) {
                $locationsDiv.html("No locations found for " + locationString +
                    ". Sorry but only locations in the UK are covered.");
            }
            else if (locations.length == 1) {
                var aLocation = locations[0];
                window.location.href = generateMapURL(aLocation);
            }
            else {                
                var locationsString = "";
                for (var locationsIndex = 0; locationsIndex < locations.length; locationsIndex++) {
                    aLocation = locations[locationsIndex];
                    locationsString += "<a id='location" + locationsIndex + "Link' " +
                        "href='" + generateMapURL(aLocation) + "'>" +
                        aLocation.name + " - " + aLocation.type +
                        "</a><br />";
                }

                $locationsDiv.html(locationsString);
            }
        }
        return false;
    });
};

jQuery.fn.findLocationAccordion = function() {
    this.find('h3').click(function() {
        $(this).next().toggle('slow');
        return false;
    }).next().hide();
}
})(jQuery);
