﻿
var GMap = false;
var GMarkerManager;
var GMapGeoCoder;
var GMapLocations = {
    Controls: {        
        Textbox: 'txtPostalCode',
        Select: 'selRadius',
        Button: 'btnPostalCodeGo'
        
    },
    ResultLocationNode: 'Location',
    ActiveLocation: false,
    Icons: {
        _base: false,
        _type: 'dot',
        Type: {
            _letter: function(l) { return 'http://maps.google.com/mapfiles/icon_green'+l+'.png' },
            _dot: function(c) { return 'http://maps.google.com/mapfiles/ms/icons/'+c+'-dot.png'; },
            Set: function(t) { GMapLocations.Icons._type = t; },
            Get: function(o) { 
                    if (GMapLocations.Icons._type == 'letter' && o && o.letter)
                        return GMapLocations.Icons.Type._letter(o.letter);
                    else if (GMapLocations.Icons._type == 'dot' && o && o.color)
                        return GMapLocations.Icons.Type._dot(o.color.toLowerCase());
                    else if (o && o.dot && o.color)
                        return GMapLocations.Icons.Type._dot(o.color);
                    else
                        return GMapLocations.Icons.Type._dot('navy');
            }
        },
        Base: function() {
            if (! GMapLocations.Icons._base)
            {
                var icon    = new GIcon(G_DEFAULT_ICON);
                /*
                icon.shadow = "http://www.google.com/mapfiles/shadow32.png";
                if ('dot' == this._type)
                {
                    icon.iconSize   = new GSize(32, 32); //icon.shadowSize        = new GSize(32, 32);                        
                    //icon.iconAnchor = new GPoint(0, 0); //icon.infoWindowAnchor = new GPoint(12, 8);
                }
                else
                {
                    icon.iconSize   = new GSize(20, 34); icon.shadowSize       = new GSize(37, 34);                        
                    icon.iconAnchor = new GPoint(9, 32); icon.infoWindowAnchor = new GPoint(9, 2);
                }
                */
                GMapLocations.Icons._base = icon;
            }
            return GMapLocations.Icons._base;
        }
    },
    Bounds: {
        Points: [],
        NorthEast: { Lat:0, Lng:0 },
        SouthWest: { Lat:0, Lng:0 },
        
        Set: function(bounds) {
            bounds = GMapLocations._parse_lat_lng_from_string(bounds);
            GMapLocations.Bounds.SouthWest.Lng = bounds[0].lat; GMapLocations.Bounds.SouthWest.Lat = bounds[0].lng;
            GMapLocations.Bounds.NorthEast.Lng = bounds[1].lat; GMapLocations.Bounds.NorthEast.Lat = bounds[1].lng;                    
        }
    },
    Origination: { 
        data: { postalcode: false, radius: 0 },
        marker: false,
        point: false
    },
    Markers: [],
    _init: function () {
        if (GBrowserIsCompatible()) {
            GMap = new GMap2(document.getElementById('map_canvas'));
            GMapGeoCoder = new GClientGeocoder();
            GMap.setUIToDefault();

            $('#'+GMapLocations.Controls.Textbox)
                .css('color','silver')
                .bind('focus', function() { if (!$(this).val().match(/\d+/)) $(this).val('').css('color','black'); })
                .bind('keypress', function(e) { 
                    if ((e.which && e.which == 13) || (e.keyCode && e.keyCode == 13)) {  
                        $('#'+GMapLocations.Controls.Button).click();return false;
                    }
                    return true;
                });
           $('#'+GMapLocations.Controls.Button)
                .bind('click', function() {
                    if ( $('#'+GMapLocations.Controls.Textbox).val().match(/\d{5}/)) GMapLocations.Locate(this);
                });
        }
    },
    _get_xml: function(xml) {
        if (!jQuery.support.htmlSerialize) { //If IE 6+
            var xmlDoc = new ActiveXObject("Microsoft.XMLDOM");  xmlDoc.loadXML(xml); xml = xmlDoc;
        }
        return xml;        
    },
    _parse_lat_lng_from_string: function(data) {
        data = data.toString().replace(/[\(\)]/g,''); data = data.split(', ');
        var latlng = [];
        for (var i = 0; i < data.length; i+=2)
            latlng.push( {lat:data[i], lng:data[i+1]} );
        if (latlng.length == 1) return latlng[0];
        return latlng;
    },
    Init: function() {
        this._init();
    },
    LocateAll: function() {
    	/*
        BranchLocation.LocateAll(GMapLocations.Locate_OnComplete, BranchLocation_MSAjax_OnError, BranchLocation_MSAjax_OnTimeOut);
	   */

        var webservicehost = document.location.protocol + "//" + document.location.hostname;
        $.ajax({
           type: "GET",
           url: webservicehost + "/_layouts/WECO/BranchLocationServices.aspx",
           error: BranchLocation_MSAjax_OnError,
           success: GMapLocations.Locate_OnComplete
         });
       
        $('#'+GMapLocations.Controls.Textbox).val('Enter Zip Code').css('color','silver');
        $('#'+GMapLocations.Controls.Select).val('25')
        if (GMapLocations.Origination.marker)
            GMap.removeOverlay(GMapLocations.Origination.marker);
        GMapLocations.Origination.data.postalcode = GMapLocations.Origination.data.radius = false;
    },
    Locate: function(o) {      
        var postalcode = jQuery.trim($('#'+GMapLocations.Controls.Textbox).val());
        var radius = $('#'+GMapLocations.Controls.Select).val();
        
        GMapLocations.LocateByZip(postalcode, radius);
    },
    LocateByZip: function(postalcode, radius) {      

        // Assigning this back into the TextBox, in the case where this method is called from ASPX page
        $('#'+GMapLocations.Controls.Textbox).val(postalcode).css('color','black');
        
        if (GMapLocations.Origination.data.postalcode != postalcode ||
            GMapLocations.Origination.data.radius     != radius)
        {        
            if (GMapLocations.Origination.marker)
                GMap.removeOverlay(GMapLocations.Origination.marker);
            
            GMapLocations.Origination.data.postalcode = postalcode;
            GMapLocations.Origination.data.radius     = radius;
                
            GMapGeoCoder.getLatLng(postalcode + ' US', 
                function(point) {
                    if (!point)
                        alert(postalcode + " not found");
                    else {
                        var iconMarker = new GIcon(GMapLocations.Icons.Base());
                        iconMarker.image = GMapLocations.Icons.Type.Get({'dot':true, 'color':'yellow'});
                        var marker = new GMarker(point, {icon:iconMarker});
                        GMap.addOverlay(marker);                  
                        GMapLocations.Origination.marker = marker;
                        GMapLocations.Origination.point  = point;

               			/*
                        BranchLocation.Locate(point.y, point.x, GMapLocations.Origination.data.radius,
                            GMapLocations.Locate_OnComplete, BranchLocation_MSAjax_OnError, BranchLocation_MSAjax_OnTimeOut);
            			*/

                        var webservicehost = document.location.protocol + "//" + document.location.hostname;
			            var requestStr = "latitude=" + point.y + "&longitude=" + point.x + "&radius=" + GMapLocations.Origination.data.radius;
                        $.ajax({
                           type: "POST",
                           url: webservicehost + "/_layouts/WECO/BranchLocationServices.aspx",
                           data: requestStr,
                           error: BranchLocation_MSAjax_OnError,
                           success: GMapLocations.Locate_OnComplete
                           });
                    }
                }
            );
        }            
    },

    Locate_OnComplete: function(locationXml) {
        if (locationXml != null && locationXml.length > 0)
        {
            GMapLocations.PlotXml(locationXml);
        }
    },

    PlotXml: function(xml) {        
        xml = this._get_xml(xml);   
        
        var marker_indexer = 0;
  
        GMapLocations.ResetCanvas();

        // if we've got about 25 results, let's use a lettering system
        if ($(xml).find(GMapLocations.ResultLocationNode).length < 26)
            GMapLocations.Icons.Type.Set('letter');
        else
            GMapLocations.Icons.Type.Set('dot');

        if ($(xml).find(GMapLocations.ResultLocationNode).length > 0)
        {
            $(xml).find(GMapLocations.ResultLocationNode).each(function() {
                    var lat = $(this).find('latitude').text();
                    var lng = $(this).find('longitude').text();
                    
                    if (lat.length > 0 && lng.length > 0)
                    {
                        var location = {
                            link:       $(this).find('url').text(),
                            company:    $(this).find('company').text(),
                            address1:   $(this).find('address1').text(),
                            address2:   $(this).find('address2').text(),
                            city:       $(this).find('city').text(),
                            state:      $(this).find('state').text(),
                            postalcode: $(this).find('postalcode').text(),
                            phone:      $(this).find('phone').text(),
                            distance:   $(this).find('distance').text(),
                            coords:     { latitude: lat, longitude: lng }
                        }

                        // Embelish the link with Zip and Radius if specified. These will be used for Return To Results
                        // link created on the BranchLocation page
                        if (! GMapLocations.Origination.data.postalcode == false)
                        {
                            location.link = location.link + 
                              "?zip=" + GMapLocations.Origination.data.postalcode + 
                              "&radius=" + GMapLocations.Origination.data.radius;
                        }
                        
                        var latlng = new GLatLng(location.coords.latitude, location.coords.longitude);                        
                        GMap.addOverlay(GMapLocations.CreateMarker(latlng, location, marker_indexer));
                        GMapLocations.Bounds.Points.push(latlng);
                        
                        marker_indexer = marker_indexer + 1;
		            }
	            });

            GMapLocations.Bounds.Set(new GBounds(GMapLocations.Bounds.Points));
            var bounds = new GLatLngBounds(
                            new GLatLng(GMapLocations.Bounds.SouthWest.Lat, GMapLocations.Bounds.SouthWest.Lng),
                            new GLatLng(GMapLocations.Bounds.NorthEast.Lat, GMapLocations.Bounds.NorthEast.Lng)
                         );

            if (! bounds.isEmpty())
            {
                var zoomLevel = GMap.getBoundsZoomLevel(bounds, new GSize());
                var centerCoords = this._parse_lat_lng_from_string(bounds.getCenter());
                GMap.setCenter(new GLatLng(centerCoords.lat, centerCoords.lng), zoomLevel);
            }
        }
        else
        {
            if (GMapLocations.Origination.point)
                GMap.setCenter(new GLatLng(GMapLocations.Origination.point.y, GMapLocations.Origination.point.x), 4);
            GMapLocations.RenderNoResultHtml();
        }
    },
    
    CreateMarker: function(point, location, index) {
        
        var letter = String.fromCharCode("A".charCodeAt(0) + index);
        var iconMarker = new GIcon(GMapLocations.Icons.Base());
        iconMarker.image = GMapLocations.Icons.Type.Get({'letter':letter, 'color':'blue'});

        var markerOptions = { icon:iconMarker, 'letter':letter, 'index':index };
        var marker = new GMarker(point, markerOptions);
                
        GEvent.addListener(marker, "click", function() {
            marker.openInfoWindowHtml(GMapLocations.RenderResultPopWindow(location));
        });
        
        GMapLocations.Markers[GMapLocations.Markers.length] = {'Marker':marker, 'MarkerOptions': markerOptions };
        GMapLocations.RenderResultHtml(location, markerOptions);
        
        return marker;
    },
    ResetCanvas: function() {
        // clear any prior results
        $('#locations').empty();
        for (var i = 0; i < GMapLocations.Markers.length; i++)
            GMap.removeOverlay(GMapLocations.Markers[i].Marker);
        GMapLocations.Markers = []; GMapLocations.Bounds.Points = [];
    },
    RenderResultHtml: function(o,opts) {
        var html_marker = $('<img>')
                            .attr('id','gmap-location-marker-'+opts.index)
                            .addClass(GMapLocations.Icons._type)
                            .attr('src',opts.icon.image)
                            .click(function() {
                                var indexer = this.id.replace('gmap-location-marker-','');
                                for (var i = 0; i < GMapLocations.Markers.length; i++) {
                                    if (GMapLocations.Markers[i].MarkerOptions.index == indexer) { 
                                        GEvent.trigger(GMapLocations.Markers[i].Marker,'click'); break;
                                    }
                                }
                            });
        
        var html_milage = '<span />';
        if (o.distance)
            html_milage = '<span class="mileage">'+o.distance+' mile(s)</span>';
        var html_detail = '<strong><a href="javascript:void(0);" onclick="$(\'img#gmap-location-marker-'+opts.index+'\').click();">' + o.company + '</a></strong><br />';
        html_detail += o.address1 + '<br />' + o.city + ', ' + o.state + ' ' + o.postalcode + '<br />' + o.phone;
        html_detail += '<br /><a href="'+o.link+'">View more information for this location</a>';
        html_detail = $('<div>').attr('id','gmap-location-detail-'+opts.index).html(html_detail);

        $('#locations').append(
        $('<div>').attr('id','gmap-location-'+opts.index)
                  .addClass('location-item').addClass((opts.index%2==0?'alt':''))
                  .append($('<span>').addClass('gmap-detail-clear').html('&nbsp;'))
                  .append($(html_milage))
                  .append($(html_marker))
                  .append($(html_detail))
                  .append($('<span>').addClass('gmap-detail-clear').html('&nbsp;'))
        );
    },
    
    RenderResultPopWindow: function(o) {
        var html = '<strong>' + o.company + '</strong><br />';
        html += o.address1 + '<br />' + o.city + ', ' + o.state + ' ' + o.postalcode + '<br />' + o.phone;
        html += '<br /><br /><a href="'+o.link+'">View more information for this location</a>';
        if (GMapLocations.Origination.data.postalcode)
        {
            var q = o.address1.replace('\u2022', '') + ', ' + o.city + ', ' + o.state + ' ' + o.postalcode;
            var dirlnk = 'http://maps.google.com/maps?saddr='+GMapLocations.Origination.data.postalcode+'&daddr='+q;       
            html += '<br /><br /><a href="'+dirlnk+'">Get driving directions</a>';
        }
        html += '<br /><br />';
        return html;
    },
    
    RenderNoResultHtml: function() {
        $('#locations').append($('<div>').html('<strong><em>No results were found.</em></strong>'));
    }
    
}

function BranchLocation_MSAjax_OnError(arg)
{
    alert("Error occurred: " + arg.get_message());
}
function BranchLocation_MSAjax_OnTimeOut(arg)
{
   alert("Google MAP service timed out");
}