google.load("search", "1");
google.load("maps", "2");

(function($) {

    google.setOnLoadCallback(function() {

        var homeIcon = new GIcon();
        homeIcon.image = 'http://maps.google.com/mapfiles/arrow.png';
        homeIcon.shadow = 'http://www.google.com/intl/en_us/mapfiles/arrowshadow.png';
        homeIcon.iconSize = new GSize(39, 34);
        homeIcon.iconAnchor = new GPoint(9, 31);
        homeIcon.infoWindowAnchor = new GPoint(9, 31);
        homeIcon.shadowSize = new GSize(39, 34);

        var sitaIcon = new GIcon();
        sitaIcon.image = "/images/locator/sita-pointer.png";
        sitaIcon.shadow = "/images/locator/sita-pointer-shadow.png";
        sitaIcon.iconSize = new GSize(86, 60);
        sitaIcon.shadowSize = new GSize(86, 60);
        sitaIcon.iconAnchor = new GPoint(0, 60);
/*
        sitaIcon.image = "http://www.google.com/mapfiles/marker.png";
        sitaIcon.shadow = "http://www.google.com/mapfiles/shadow50.png";
        sitaIcon.iconSize = new GSize(20, 34);
        sitaIcon.shadowSize = new GSize(37, 34);
        sitaIcon.iconAnchor = new GPoint(10, 34);
*/

        var map;
        var localSearch = new google.search.LocalSearch();


        var flash = function(type, message) {
            $("#result")
                .empty()
                .css("display", "none")
                .removeClass("failure")
                .removeClass("success");
                $("#result")
                    .addClass(type)
                    .html(message);
                $("#result").fadeIn();
        }

        var usePointFromPostcode = function(postcode, callback) {
            var re = new RegExp("^[a-zA-Z]{1,2}[0-9][0-9A-Za-z]{0,1} {0,1}[0-9][A-Za-z]{2}$");
            if(postcode.match(re)) {
            localSearch.setSearchCompleteCallback(null, function() {
                if (localSearch.results[0]) {
                    callback(new google.maps.LatLng(
                        localSearch.results[0].lat,
                        localSearch.results[0].lng
                    ));
                } else {
                    flash("failure", "Postcode not found!");
                }
            });

            localSearch.execute(postcode + ", UK"); } else { flash("failure", "Invalid postcode"); }
        }

        var locateNearest = function(point) {
            var bounds = new GLatLngBounds();

            var marker = new GMarker(point, homeIcon);
            map.addOverlay(marker);
            bounds.extend(point);

            $.getJSON("/Locator/Lookup", { lat: point.lat(), lng: point.lng() }, function(data) {

                for (var i = 0; i < data.length; i++) {
                    var location = data[i];
                    point = new google.maps.LatLng(location.lat, location.lng);
                    marker = new GMarker(point, sitaIcon);
                    GEvent.addListener(marker, "click", function() {
                        var html = data[0].landfill + ",<br/>" + data[0].site;
                        map.openInfoWindowHtml(marker.getLatLng(), html);
                    });
                    map.addOverlay(marker);
                    bounds.extend(point);
                }
                map.setCenter(bounds.getCenter(), map.getBoundsZoomLevel(bounds));

                $("#result")
                    .empty()
                    .css("display", "none")
                    .removeClass("failure")
                    .removeClass("success");
                if (data.length > 0) {
                    flash("success",
                              "Congratulations, your location is eligible for funding. It is in the funding zone " +
                              "for the SITA " + data[0].site + " location (" + data[0].dist.toFixed(3) + " miles), your assigned landfill " + 
                              "site is " + data[0].landfill + ".<br><br><a href='http://www.sitatrust-applications.org.uk/Form2/init.pl'>Apply: Small Grant</a> | <a href='http://www.sitatrust-applications.org.uk/Form1/init.pl'>Apply: Large Grant</a>");
                } else {
                    flash("failure", "Sorry, your location is not eligible for funding.");
                }
            });
        }

        $(function() {
            if (GBrowserIsCompatible()) {
                map = new google.maps.Map2(document.getElementById("map"));
                map.addControl(new GLargeMapControl());
                map.addControl(new GMapTypeControl());
                map.setCenter(new google.maps.LatLng(54.622978, -2.592773), 5, G_HYBRID_MAP);

                $("#locateNearest").bind("submit", function() {
                    usePointFromPostcode($("#postcode").val(), locateNearest);
                    return false;
                });

                /*
                var i = 0;
                var first = true;
                var geoLookup = function(point) {
                if (!first) {
                $("#debug").append(postcodes[i] + "," + point.lat() + "," + point.lng() + "\n");
                if (i > postcodes.length) { return; }
                i++;
                }
                first = false;
                usePointFromPostcode(postcodes[i], geoLookup);
                }
                geoLookup();
                */
            }
        });

        $(window).unload(GUnload);

    });

})(jQuery);
