﻿// scripts for GoToLocation control
// - uses global refs to map, showStreetView
// NOTE: _geocodeUrl value must be included in proxy.config
var goToLoc = {
    _geocodeUrl: "http://maps.google.com/maps/api/geocode/json",
    _map: null,
    _locGraphics: null,
    _locSymbol: null,

    findAddress: function () {
        var addr = $.trim($("#txtAddress").val());
        var city = $.trim($("#txtCity").val());
        var state = $("#" + txtStateId).val(); // id in markup page

        if (addr == "" || city == "") {
            $("#geocodeLabel").text("Please enter a street address and city.");
            return;
        }

        // Use utilities.js
        googleGeocoder.findAddressByCityState(addr, city, state, dojo.hitch(this, this.geocodeCallback), dojo.hitch(this, this.geocodeError));

        //        var url = "proxy.ashx?" + this._geocodeUrl + "?address=" + addr + "," + city + "," + state + "&sensor=false";

        //        $.ajax({
        //            type: "GET",
        //            url: url,
        //            contentType: "application/json; charset=utf-8",
        //            dataType: "json",
        //            success: function (data) {
        //                var found = false;
        //                if (data) {
        //                    if (data.status == "OK" && data.results && data.results.length > 0) {
        //                        // Go to first result
        //                        var res = data.results[0];
        //                        $("#geocodeLabel").html("Address found:<br/>" + res.formatted_address);
        //                        var loc = res.geometry.location;
        //                        $("#txtLat").val(loc.lat);
        //                        $("#txtLong").val(loc.lng);
        //                        found = true;
        //                        goToLoc.zoomToPoint();
        //                    }
        //                }

        //                if (!found) {
        //                    $("#geocodeLabel").text("Could not find the address.");
        //                }
        //            },
        //            error: function (jqXHR, status, err) {
        //                $("#geocodeLabel").text("Error occurred finding address. If problem persists, please contact Support.");
        //            }
        //        });
    },

    geocodeCallback: function (data) {
        var found = false;
        if (data) {
            if (data.status == "OK" && data.results && data.results.length > 0) {
                // Go to first result
                var res = data.results[0];
                $("#geocodeLabel").html("Address found:<br/>" + res.formatted_address);
                var loc = res.geometry.location;
                $("#txtLat").val(loc.lat);
                $("#txtLong").val(loc.lng);
                found = true;
                goToLoc.zoomToPoint(true);
            }
        }

        if (!found) {
            $("#geocodeLabel").text("Could not find the address.");
        }
    },

    geocodeError: function (jqXHR, status, err) {
        $("#geocodeLabel").text("Error occurred finding address. If problem persists, please contact Support.");
    },

    zoomToPoint: function (showAddress) {
        var lat = $("#txtLat").val();
        var lng = $("#txtLong").val();
        // convert to Web Mercator
        var wmPt = esri.geometry.geographicToWebMercator(new esri.geometry.Point(lng, lat, new esri.SpatialReference({ wkid: 4326 })));

        this.init();
        var title = (showAddress) ? $("#txtAddress").val() : lat.toString() + ", " + lng.toString();
        var infoTmplt = this.createInfoTemplate(title, lng, lat);
        var graphic = new esri.Graphic(wmPt, this._locSymbol, { lat: lat, long: lng }, infoTmplt);
        this._locGraphics.add(graphic);
        this._map.centerAndZoom(wmPt, 17);
    },

    init: function () {
        if (!this._locGraphics) {
            this._map = map;
            this._locSymbol = new esri.symbol.PictureMarkerSymbol('http://cdn.tierraplan.com/images/mappins/pin-blue.png', 36, 38);
            this._locSymbol.xoffset = 7;
            this._locSymbol.yoffset = 17;

            this._locGraphics = new esri.layers.GraphicsLayer();
            this._map.addLayer(this._locGraphics);
        }
    },

    createInfoTemplate: function (address, x, y) {
        var title = "<div style='margin-left: auto; margin-right: auto;height:20px;'>"
            + "<div style='float:left;'>" + address + "</div> <div style='float:right;'>"
            + "<a href=# onclick='javascript:map.infoWindow.hide();'>Close</a></div><div style='clear: both;'></div></div>";
        var body = "<a href='#' onclick='showStreetView(" + y.toString() + ',' + x.toString() + ");return false;'>Google Street View</a>"
            + "<br/><a href='#' onclick='goToLoc.removeGraphic(" + x.toString() + "," + y.toString() + ");map.infoWindow.hide();return false;'>Remove</a>";
        return new esri.InfoTemplate(title, body);
    },

    removeGraphic: function (x, y) {
        var removeGr = null;
        for (var gr, i = -1; gr = this._locGraphics.graphics[++i]; ) {
            if (gr.attributes.long == x.toString() && gr.attributes.lat == y.toString()) {
                removeGr = gr;
                break;
            }
        }
        if (removeGr)
            this._locGraphics.remove(removeGr);
    }
};
