﻿window.wscnt = 0;

window.wait = function() {
    window.wscnt++;

    $("body").css("cursor", "wait");
    $("input").css("cursor", "wait");
    $("select").css("cursor", "wait");
    $("a").css("cursor", "wait");
}

window.ready = function() {
    window.wscnt--;

    if (window.wscnt <= 0) {
        $("body").css("cursor", "default");
        $("input").css("cursor", "default");
        $("input[type=\"text\"]").css("cursor", "text");
        $("select").css("cursor", "default");
        $("a").css("cursor", "pointer");
    }
}

String.prototype.replaceAll = function(a, b) {
    var t = this;
    var i = t.indexOf(a);
    while (i > -1) {
        t = t.replace(a, b);
        i = t.indexOf(a, i + b.length + 1);
    }
    return t;
};

String.prototype.isNumeric = function() {
    return parseFloat(this) + "" == parseFloat(this);
};

function Locator(map, table, premier, premiertext, additionaltext) {
    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._premierText = (premiertext) ? premiertext : "Featured Retailers:";
    this._additionalText = (additionaltext) ? additionaltext : "Additional Retailers:";

    this.resetTables = function() {
        if (this._mapTable != null) {
            this.resetTable(this._mapTable.id);
        }
        if (this._mapPremier != null) {
            this.resetTable(this._mapPremier.id);
        }
    };

    this.resetTable = function(id) {
        $("#" + id).html("<table class=\"locator-table\" cellspacing=\"0\"></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 > 300) {
                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");
        wait();
    };

    this.getLocationsByLatLon = function (b, lat, lon, r) {
        this._currentZip = lat + "," + lon;
        this.getJson("http://locator.hhbrown.com/LocationsByLatLon/" + b + "/" + lat + "/" + lon + "/" + r + "/json/" + this._name + ".gotLocations");
        wait();
    };

    this.gotLocations = function(result) {
        ready();
        this.resetBounds();
        this.resetMarkers();
        this.resetTables();

        if (result.Locations.length == 0 && result.Premier_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_arrow.png");

        if (this._mapTable != null) {
            if (result.Locations.length != 0) {
                $("#" + this._mapTable.id + " table").before("<h4>" + this._additionalText + "</h4>");
            }

            for (var i = result.Locations.length - 1; i >= 0; i--) {
                var l = result.Locations[i];
                l.Address = (l.Address2) ? l.Address2 + " " + l.Address1 : l.Address1;

                this.addMarker(l, false, i);
            }

            $("#" + this._mapTable.id + " table tr:odd").addClass("alt");
            $("#" + this._mapTable.id + " table tr:first td").addClass("tb-header");
            $("#" + this._mapTable.id + " table tr:last td").addClass("tb-footer");
        }

        if (this._mapPremier != null) {
            if (result.Premier_Locations.length != 0) {
                $("#" + this._mapPremier.id + " table").before("<h3>" + this._premierText + "</h3>");
            }

            for (var i = result.Premier_Locations.length - 1; i >= 0; i--) {
                var l = result.Premier_Locations[i];
                l.Address = (l.Address2) ? l.Address2 + " " + l.Address1 : l.Address1;

                this.addMarker(l, true, i);
            }

            $("#" + this._mapPremier.id + " table tr:odd").addClass("alt");
            $("#" + this._mapPremier.id + " table tr:first td").addClass("tb-header");
            $("#" + this._mapPremier.id + " table tr:last td").addClass("tb-footer");
        }
    };

    this.addMarker = function (loc, featured, letter) {
        var o = window[this._name];
        var l = this._markers;
        var r = this._mapPremier;
        var mt = this._mapTable;
        var t = (featured) ? r : mt;
        var b;
        var a1 = (loc.Address1) ? loc.Address1 + "<br />" : "";
        var a2 = (loc.Address2) ? loc.Address2 + "<br />" : "";
        var n = "<strong>" + loc.Name + "</strong><br />" + a1 + a2 + loc.City + ", " + loc.State + " " + loc.Zip;
        n = (loc.Phone == "" || loc.Phone == null) ? n : n + "<br />" + loc.Phone;
        var nn = a1 + a2 + loc.City + ", " + loc.State + " " + loc.Zip;
        nn = (loc.Phone == "" || loc.Phone == null) ? nn : nn + "<br />" + loc.Phone;
        var g = this._mapObj;

        if (loc.G_Address != null) {
            b = (featured) ? "http://locator.hhbrown.com/images/red_balloon_" + letter + ".png" : "http://locator.hhbrown.com/images/blue_balloon_" + letter + ".png";

            var d = (loc.G_Coder == "G") ? "http://maps.google.com/?daddr=" + loc.G_Address + "&saddr=" + this._currentZip : "http://maps.yahoo.com/dd_result?taddr=" + loc.G_Address + "&newaddr=" + 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); var nm = new GMarker(p); g.addOverlay(nm); nm.setImage(b); l.push(nm); });

            if (!loc.Url) {
                g.addOverlay(m);
            }

            m.setImage(b);
            l.push(m);

            if (!loc.Url) {
                this._bounds.extend(p);
            }

            if (featured) {
                $("#" + t.id + " table").prepend("<tr></tr>");
                $("#" + t.id + " table tr:first").append("<td class=\"marker\"></td>");
                $("#" + t.id + " table tr:first").append("<td class=\"info\"></td>");
                $("#" + t.id + " table tr:first").append("<td class=\"directions\"></td>");

                var online = false;
                if (loc.Url) {
                    if (loc.Url.length > 4) online = true;
                }

                if (online) {
                    n = "<a href=\"" + loc.Url + "\" target=\"_blank\"><strong>" + loc.Name + "</strong></a>";
                    $("#" + t.id + " table tr:first .directions").append("<a href=\"" + loc.Url + "\" target=\"_blank\">Shop Online</a>");
                } else {
                    $("#" + t.id + " table tr:first .marker").append("<img class=\"png\" alt=\"\" src=\"" + b + "\" />");
                    $("#" + t.id + " table tr:first .marker img").css("cursor", "pointer").click(function () { g.setCenter(p, 15); var nm = new GMarker(p); g.addOverlay(nm); nm.setImage(b); l.push(nm); });
                    if (loc.G_Coder != "N") {
                        $("#" + t.id + " table tr:first .directions").append("<a class=\"png\" target=\"_blank\" href=\"" + d + "\" ></a>");
                        $("#" + t.id + " table tr:first .directions").append("<div class=\"miles\">" + loc.Distance + " Miles</div>");
                        $("#" + t.id + " table tr:first .directions a").prepend("Directions");
                    } else {
                        $("#" + t.id + " table tr:first .directions").append("<div class=\"miles\">" + loc.Distance + " Miles</div>");
                    }
                }

                $("#" + t.id + " table tr:first .info").append(n);

            } else {
                $("#" + t.id + " table").prepend("<tr></tr>");
                $("#" + t.id + " table tr:first").append("<td class=\"marker\"></td>");
                $("#" + t.id + " table tr:first").append("<td class=\"store-name\"></td>");
                $("#" + t.id + " table tr:first").append("<td class=\"address\"></td>");
                $("#" + t.id + " table tr:first").append("<td class=\"miles\"></td>");
                $("#" + t.id + " table tr:first").append("<td class=\"directions\"></td>");

                if (loc.Address1 == "" && loc.Address2 == "") {
                    $("#" + t.id + " table tr:first .store-name").append("<a href=\"" + loc.Url + "\" target=\"_blank\">" + loc.Name + "</a>");
                    $("#" + t.id + " table tr:first .directions").append("<a href=\"" + loc.Url + "\" target=\"_blank\">Shop Online</a>");
                } else {
                    $("#" + t.id + " table tr:first .marker").append("<img class=\"png\" alt=\"\" src=\"" + b + "\" />");
                    $("#" + t.id + " table tr:first .marker img").css("cursor", "pointer").click(function () { g.setCenter(p, 15); var nm = new GMarker(p); g.addOverlay(nm); nm.setImage(b); l.push(nm); });
                    $("#" + t.id + " table tr:first .store-name").append(loc.Name);
                    $("#" + t.id + " table tr:first .address").append(nn);
                    $("#" + t.id + " table tr:first .miles").append("<div class=\"miles\">" + loc.Distance + " Miles</div>");

                    if (loc.G_Coder != "N") {
                        $("#" + t.id + " table tr:first .directions").append("<a class=\"png\" target=\"_blank\" href=\"" + d + "\" ></a>");
                        $("#" + t.id + " table tr:first .directions a").prepend("Directions");
                    }
                }
            }

            this.bestFitWithCenter(this._mapObj, this._bounds, this._mapObj.getCenter());
        } else {
            b = (featured) ? "http://locator.hhbrown.com/images/red_balloon_" + letter + ".png" : "http://locator.hhbrown.com/images/blue_balloon_" + letter + ".png";

            $("#" + t.id + " table tr:first .marker").append("<img class=\"png\" alt=\"\" src=\"" + b + "\" />");
            $("#" + t.id + " table tr:first .info").append(n);
        }
    };

    this.invalidZip = function(z) { alert("I'm sorry " + z + " is not a valid zipcode."); this.resetTables(); this.centerMap(); this.resetMarkers(); ready(); return false; };
    this.invalidRadius = function(r) { alert("I'm sorry " + r + " is not a valid radius. Please enter a number between 0 and 300."); this.resetTables(); this.centerMap(); this.resetMarkers(); ready(); return false; };
    this.noResults = function(r) { alert("I'm sorry there were not results found please try a larger radius."); this.resetTables(); this.centerMap(); this.resetMarkers(); ready(); return false; };
}
