﻿var DierbergsMap = function(id, lat, lng, zoom, formMode, sidebar, textbox, button) {
    if (!GBrowserIsCompatible()) return null;

    var mapElem = document.getElementById(id);
    this._map = new GMap2(mapElem);

    this._map.setCenter(new GLatLng(lat, lng), zoom);
    this._map.addControl(new GSmallMapControl());
    this._map.addControl(new GHierarchicalMapTypeControl());
    this._map.enableScrollWheelZoom();
    this._map.enableContinuousZoom();

    this._locationsJsonUrl = "/about/locations.aspx?json=1";
    this._locations = null;
    this._selectedLocation = null;
    this._queryCoordinates = null;
    this._geocodeRequestPending = false;
    this._locationsRequestPending = false;
    this._formMode = formMode;

    if (undefined === sidebar) this._sidebar = null;
    else this._sidebar = document.getElementById(sidebar);

    if (undefined === textbox) this._textbox = null;
    else this._textbox = document.getElementById(textbox);

    if (undefined === button) this._button = null;
    else {
        this._button = document.getElementById(button);
        GEvent.bindDom(this._button, "click", this, this.submitLocationSearch);
    }
}

DierbergsMap.prototype = {
    submitLocationSearch: function() {
        if (undefined !== this._textbox && null != this._textbox && "" != this._textbox.value)
            this.locationSearch(this._textbox.value);
    },

    addSingleLocation: function(lat, lng, desc) {
        var marker = new GMarker(new GLatLng(lat, lng));
        this._map.addOverlay(marker);
        GEvent.addListener(marker, "click", function() { marker.openInfoWindowHtml(desc); });
    },

    addSearchResultLocation: function(index) {

        this._locations[index].html = StringFormat(
            "<strong>{0}</strong><br/>{1}<br/>{2}, {3} {4}<br/>{5}<br/>{6} miles",
            this._locations[index].locationName,
            this._locations[index].address.street,
            this._locations[index].address.city,
            this._locations[index].address.state,
            this._locations[index].address.zipCode,
            this._locations[index].phone,
            this._locations[index].distance
            );

        if (!this._formMode) {
            this._locations[index].html += StringFormat("<br/><a href=\"{0}\" class=\"BulletedLink\">View Details</a>", this._locations[index].url);
        }

        var icon = new GIcon(G_DEFAULT_ICON);
        icon.image = DierbergsMap.letterIcons[index];

        var latLng = new GLatLng(this._locations[index].coordinates[0], this._locations[index].coordinates[1]);

        this._locations[index].marker = new GMarker(latLng, { icon: icon });
        this._map.addOverlay(this._locations[index].marker);

        var sidebarRadioButton = this.addSidebarEntry(index);

        var thisSurrogate = this;
        GEvent.addListener(this._locations[index].marker, "click", function() {
            thisSurrogate._locations[index].marker.openInfoWindowHtml(thisSurrogate._locations[index].html);
            if (null != sidebarRadioButton) sidebarRadioButton.checked = true;
            thisSurrogate._selectedLocation = thisSurrogate._locations[index];
        });
    },

    addSidebarEntry: function(index) {
        if (null == this._sidebar) return null;

        var table = document.createElement("table");
        table.className = "DierbergsMapSidebarEntry";

        var tableBody = document.createElement("tbody");
        table.appendChild(tableBody);

        var row = document.createElement("tr");
        tableBody.appendChild(row);

        var leftCell = document.createElement("td");
        leftCell.className = "EntryLeftColumn";
        row.appendChild(leftCell);

        var icon = document.createElement("img");
        icon.setAttribute("src", this._locations[index].marker.getIcon().image)
        leftCell.appendChild(icon);

        if (this._formMode) {
            var radioDiv = document.createElement("div");
            radioDiv.className = "EntryRadioButtonContainer";
            leftCell.appendChild(radioDiv);

            var radioButton = document.createElement("input");
            radioButton.setAttribute("type", "radio");
            radioButton.setAttribute("name", "SelectedStore");
            radioButton.setAttribute("id", "radio" + this._locations[index].guid);
            radioButton.setAttribute("value", this._locations[index].guid);
            radioDiv.appendChild(radioButton);
            radioDiv.appendChild(document.createElement("br"));
            radioDiv.appendChild(document.createTextNode("SELECT"));
        }
        //        else
        //        {
        //            var linkDetails = document.createElement("a");
        //            linkDetails.setAttribute("href", this._locations[index].url);
        //            linkDetails.appendChild(document.createTextNode("DETAILS"));
        //            leftCell.appendChild(document.createElement("br"));
        //            leftCell.appendChild(document.createElement("br"));
        //            leftCell.appendChild(linkDetails);
        //        }

        var rightCell = document.createElement("td")
        rightCell.className = "EntryRightColumn";
        rightCell.innerHTML = this._locations[index].html;
        row.appendChild(rightCell);

        var thisSurrogate = this;
        GEvent.addDomListener(table, 'click', function() {
            GEvent.trigger(thisSurrogate._locations[index].marker, 'click');
            if (radioButton != undefined) {
                radioButton.checked = true;
            }
            thisSurrogate._selectedLocation = thisSurrogate._locations[index];
        });

        this._sidebar.appendChild(table);

        var separator = document.createElement("div");
        separator.className = "DierbergsMapSidebarSeparator";
        this._sidebar.appendChild(separator);

        return radioButton;
    },

    locationSearch: function(zipCode) {
        var i;
        var thisSurrogate = this;

        this._map.clearOverlays();
        for (i = this._sidebar.childNodes.length - 1; i >= 0; i--) {
            this._sidebar.removeChild(this._sidebar.childNodes[i]);
        }
        this._queryCoordinates = null;

        if (undefined !== zipCode) {
            var geocoder = new GClientGeocoder();
            geocoder.getLocations(zipCode, function(response) {
                thisSurrogate._geocodeRequestPending = false;
                if (!response || response.Status.code != 200) {
                    alert("Sorry, we were unable to geocode that zip code");
                } else {
                    thisSurrogate._queryCoordinates = new GLatLng(response.Placemark[0].Point.coordinates[1], response.Placemark[0].Point.coordinates[0]);
                    thisSurrogate.completeLocationSearch(zipCode);
                }
            });
        }

        if (null == this._locations) {
            this._locationsRequestPending = true;
            GDownloadUrl(this._locationsJsonUrl, function(data, responseCode) {
                thisSurrogate._locationsRequestPending = false;
                if (200 == responseCode) {
                    thisSurrogate._locations = eval(data);
                    for (i = 0; i < thisSurrogate._locations.length; i++) {
                        thisSurrogate._locations[i].latLng = new GLatLng(thisSurrogate._locations[i].coordinates[0], thisSurrogate._locations[i].coordinates[1]);
                    }
                    thisSurrogate.completeLocationSearch(zipCode);
                } else if (-1 == responseCode) {
                    alert("The request for location data timed out.  Please try again.");
                } else {
                    alert("Error: could not retrieve location data");
                }
            });
        }
        else thisSurrogate.completeLocationSearch(zipCode);
    },
    
    completeLocationSearch: function(zipCode) {
        if (null == this._locations) return;
        if (undefined !== zipCode && null == this._queryCoordinates) return;
        
        var bounds = new GLatLngBounds();
        
        if (null != this._queryCoordinates) {
            for (i = 0; i < this._locations.length; i++) {
                this._locations[i].distance = this.getDistance(this._queryCoordinates, this._locations[i].latLng);
            }
            
            this._locations.sort(function(x, y) { return x.distance - y.distance; });
            
            if (this._locations[0].distance < 50) {
                var homeIcon = new GIcon(G_DEFAULT_ICON);
                homeIcon.image = "http://maps.google.com/mapfiles/arrow.png";
                homeIcon.shadow = "http://maps.google.com/mapfiles/arrowshadow.png";
                homeIcon.iconSize = new GSize(39, 34);
                homeIcon.shadowSize = new GSize(39, 34);
                homeIcon.iconAnchor = new GPoint(11, 30);
                var homeMarker = new GMarker(this._queryCoordinates, { icon: homeIcon });
                this._map.addOverlay(homeMarker);
                bounds.extend(this._queryCoordinates);
            }
        }
    
        for (i = 0; i < this._locations.length; i++) {
            this.addSearchResultLocation(i);
            bounds.extend(this._locations[i].latLng);
        }
        
        this._map.setCenter(bounds.getCenter(), this._map.getBoundsZoomLevel(bounds));

        this._queryCoordinates = null;
    },
    
    selectLocation: function(id) {
        if (null != this._locations) {
            for (i = 0; i < this._locations.length; i++) {
                if (id == this._locations[i].guid) {
                    GEvent.trigger(this._locations[i].marker, 'click');
                }
            }
        }
    },

    getDistance: function(point1, point2) {
        var dMeters = point1.distanceFrom(point2)
        // return distance in miles rounded to two decimal places
        return Math.round(dMeters * 0.062137) / 100;
    },

    checkResize: function() {
        var thisSurrogate = this;
        setTimeout(function() { thisSurrogate._map.checkResize(); }, 1000);
    }
}

DierbergsMap.letterIcons = [
    "http://www.google.com/mapfiles/markerA.png",
    "http://www.google.com/mapfiles/markerB.png",
    "http://www.google.com/mapfiles/markerC.png",
    "http://www.google.com/mapfiles/markerD.png",
    "http://www.google.com/mapfiles/markerE.png",
    "http://www.google.com/mapfiles/markerF.png",
    "http://www.google.com/mapfiles/markerG.png",
    "http://www.google.com/mapfiles/markerH.png",
    "http://www.google.com/mapfiles/markerI.png",
    "http://www.google.com/mapfiles/markerJ.png",
    "http://www.google.com/mapfiles/markerK.png",
    "http://www.google.com/mapfiles/markerL.png",
    "http://www.google.com/mapfiles/markerM.png",
    "http://www.google.com/mapfiles/markerN.png",
    "http://www.google.com/mapfiles/markerO.png",
    "http://www.google.com/mapfiles/markerP.png",
    "http://www.google.com/mapfiles/markerQ.png",
    "http://www.google.com/mapfiles/markerR.png",
    "http://www.google.com/mapfiles/markerS.png",
    "http://www.google.com/mapfiles/markerT.png",
    "http://www.google.com/mapfiles/markerU.png",
    "http://www.google.com/mapfiles/markerV.png",
    "http://www.google.com/mapfiles/markerW.png",
    "http://www.google.com/mapfiles/markerX.png",
    "http://www.google.com/mapfiles/markerY.png",
    "http://www.google.com/mapfiles/markerZ.png",
];

function StringFormat(str) {
    if (undefined === str) return null;

    for (var i = 1; i < arguments.length; i++) {
        var re = new RegExp('\\{' + (i - 1) + '\\}', 'gm');
        str = str.replace(re, arguments[i]);
    }
    return str;
}


