﻿window.$cE = document.createElement;

String.prototype.replaceAll = function(v1, v2) {
    var t = this;
    var i = t.indexOf(v1);
    while (i > -1) {
        t = t.replace(v1, v2);
        i = t.indexOf(v1, i + v2.length + 1);
    }
    return t;
};

String.prototype.isNumeric = function() {
    return parseFloat(this) + "" == parseFloat(this);
};

function Locator(map, table, premier) {
    this._name = map.id.replaceAll("-", "") + table.id.replaceAll("-", "");
    window[this._name] = this;
    this._mapDiv = map;
    this._mapObj = new GMap2(map);
    this._mapObj.addControl(new GSmallMapControl());
    this._mapGeoCoder = new GClientGeocoder();
    this._bounds = new GLatLngBounds();
    this._mapTable = table;
    this._mapPremier = premier;
    this._markers = new Array();
    this._currentZip = "00000";

    this.resetTable = function() {
        $("#" + this._mapTable.id + " table").remove();
        $("#" + this._mapTable.id).append("<table cellspacing='0'></table>");
        $("#" + this._mapTable.id + " table").addClass("locator-table");
    };

    this.resetBounds = function() {
        this._bounds = new GLatLngBounds();
    };

    this.centerMap = function() {
        this._mapObj.setCenter(new GLatLng(39.90973623453719, -98.61328125), 3);
    };

    this.bestFitWithCenter = function(map, bounds, mapCenter) {
        var swLL = bounds.getSouthWest();
        var neLL = bounds.getNorthEast();
        var marginRatio = 0.001;
        var minLat = Math.min(2 * mapCenter.lat() - neLL.lat(), swLL.lat());
        var maxLat = Math.max(2 * mapCenter.lat() - swLL.lat(), neLL.lat());
        var minLng = Math.min(2 * mapCenter.lng() - neLL.lng(), swLL.lng());
        var maxLng = Math.max(2 * mapCenter.lng() - swLL.lng(), neLL.lng());
        var minLatLng = new GLatLng(minLat - marginRatio, minLng - marginRatio);
        var maxLatLng = new GLatLng(maxLat + marginRatio, maxLng + marginRatio);
        bounds.extend(maxLatLng);
        bounds.extend(minLatLng);
        map.setZoom(map.getBoundsZoomLevel(bounds));
        map.setCenter(mapCenter);
    };

    this.resetMarkers = function() {
        for (var i = 0; i < this._markers.length; i++) {
            this._mapObj.removeOverlay(this._markers[i]);
        }

        this._markers = new Array();
    };

    this.centerMap();

    this.getJson = function(u) {
        var s = document.createElement("script");
        s.setAttribute("type", "text/javascript");
        s.setAttribute("src", u);
        s.setAttribute("id", +(new Date()).getTime());
        $("head").get(0).appendChild(s);
    };

    this.validateLocatorQuery = function(b, z, r) {
        if (!z.isNumeric()) {
            this.invalidZip(z);
            return false;
        }

        if (!r.isNumeric()) {
            this.invalidRadius(r);
            return false;
        } else {
            if (r > 100) {
                this.invalidRadius(r);
                return false;
            }
        }

        return true;
    };

    this.getLocations = function(b, z, r) {
        if (!this.validateLocatorQuery(b, z, r)) {
            return false;
        }

        this._currentZip = z;
        this.getJson("http://locator.hhbrown.com/Locations/" + b + "/" + z + "/" + r + "/json/" + this._name + ".gotLocations");
    };

    this.gotLocations = function(result) {
        this.resetBounds();
        this.resetMarkers();
        this.resetTable();

        if (result.Locations.length == 0) { this.noResults(); return false; }

        var p = new GLatLng(result.Latitude, result.Longitude);
        this._bounds.extend(p);
        this._mapObj.setCenter(p, 12);

        var m = new GMarker(p);
        this._mapObj.addOverlay(m);
        this._markers.push(m);
        
        m.setImage("http://locator.hhbrown.com/images/green_baloon.png");

        for (var i = 0; i < result.Locations.length; i++) {
            var l = result.Locations[i];
            l.Address = (l.Address2) ? l.Address2 + " " + l.Address1 : l.Address1;

            $("#" + this._mapTable.id + " table").append("<tr></tr>");
            $("#" + this._mapTable.id + " table tr:eq(" + i + ")").append("<td class=\"marker\"></td>");
            $("#" + this._mapTable.id + " table tr:eq(" + i + ")").append("<td class=\"info\"></td>");
            $("#" + this._mapTable.id + " table tr:eq(" + i + ")").append("<td class=\"directions\"></td>");

            this.addMarker(l, i, 0);
            if (i >= 25) break;
        }

        $("#" + this._mapTable.id + " table tr:odd").addClass("alt");
    };

    this.addMarker = function(loc, i, tries) {
        var o = window[this._name];
        var t = this._mapTable;
        var l = this._markers;
        var b;
        var a1 = (loc.Address1) ? loc.Address1 + "<br />" : "";
        var a2 = (loc.Address2) ? loc.Address2 + "<br />" : "";
        var n = loc.Name + "<br />" + a1 + a2 + loc.City + ", " + loc.State + " " + loc.Zip
        var g = this._mapObj;

        if (loc.G_Address != null) {
            b = "http://locator.hhbrown.com/images/red_balloon_" + i + ".png";

            var d = "http://maps.google.com/?daddr=" + loc.G_Address + "&saddr=" + this._currentZip;
            var p = new GLatLng(loc.G_Latitude, loc.G_Longitude);
            var m = new GMarker(p);

            GEvent.addListener(m, "click", function() { g.setCenter(p, 15); });

            this._bounds.extend(p);
            this._mapObj.addOverlay(m);
            m.setImage(b);

            this._markers.push(m);

            $("#" + t.id + " table tr:eq(" + i + ")").innerHTML = "";
            $("#" + t.id + " table tr:eq(" + i + ") .marker").append("<img class=\"png\" alt=\"\" src=\"" + b + "\" />");
            $("#" + t.id + " table tr:eq(" + i + ") .marker img").css("cursor", "pointer").click(function() { g.setCenter(p, 15); });
            $("#" + t.id + " table tr:eq(" + i + ") .info").append(n);
            $("#" + t.id + " table tr:eq(" + i + ") .directions").append("<a class=\"png\" target=\"_blank\" href=\"" + d + "\" ></a>");
            $("#" + t.id + " table tr:eq(" + i + ") .directions").append("<div class=\"miles\" style=\"text-align: center;\">" + loc.Distance + " Miles</div>");
            $("#" + t.id + " table tr:eq(" + i + ") .directions a").prepend("Directions");

            this.bestFitWithCenter(this._mapObj, this._bounds, this._mapObj.getCenter());
        } else {
            b = "http://locator.hhbrown.com/images/blue_balloon_" + i + ".png";

            $("#" + t.id + " table tr:eq(" + i + ")").innerHTML = "";
            $("#" + t.id + " table tr:eq(" + i + ") .marker").append("<img class=\"png\" alt=\"\" src=\"" + b + "\" />");
            $("#" + t.id + " table tr:eq(" + i + ") .info").append(n);
        }
    };

    this.invalidZip = function(z) { alert("I'm sorry " + z + " is not a valid zipcode."); this.resetTable(); this.centerMap(); this.resetMarkers(); return false; };
    this.invalidRadius = function(r) { alert("I'm sorry " + r + " is not a valid radius. Please enter a number between 0 and 100."); this.resetTable(); this.centerMap(); this.resetMarkers(); return false; };
    this.noResults = function(r) { alert("I'm sorry there were not results found please try a larger radius."); this.resetTable(); this.centerMap(); this.resetMarkers(); return false; };
}