﻿$(document).ready(function()
{  
    retrieveGoogleAPI($(".googleKey").html(), "loadMaps");                                                                                                          
    
    $(".additionalDetailsLnk").click(function(event)
    {
        $("#additionalDetails").slideToggle("medium", function()
        {
            $(".additionalDetailsLnk").text(toggleText($(".additionalDetailsLnk").html()));
        });
        event.preventDefault();
    });
    
    $(window).scroll(function()
    {
        $("#mapContainer").css("top", document.documentElement.scrollTop + "px");
    });    
    
    $(".buyerHelpGuide").click(function(event)
    {
        var winHeight = 500;
        var winWidth = 600;                
        var winLeftPostn = (screen.width - winWidth) / 2;
        var winTopPostn = (screen.height - winHeight) / 2;
        
        window.open("/HowToBuy.aspx", "PurchaseGuide", "scrollbars=1, resizable=0, location=0, height=" 
            + winHeight + ", width=" + winWidth + ", left=" + winLeftPostn + ", top=" + winTopPostn);
        event.preventDefault();
    });                    
});

function loadMaps() 
{
    google.load("maps", "2", {"callback" : mapProviders});
}

function mapProviders()
{                                                    
    var content;            
    var icon;
    var map = new GMap2($("#mapCanvas")[0]);                            
    var markedProviders = new Array();
    var marker;              
    var markers = new Array();
    var location = $(".location");                                                
    var providers = $(".geoCodeInfoLbl");
    var provider;   
    var providerID;     
    var providerNames = $(".providerNameLnk");                
    var providerImgs = $(".providerImgLnk");
    var providerName;
    var providerImg; 
    var latitude;
    var longitude;           
            
    icon = new GIcon();            
    icon.iconAnchor = new GPoint(15,30);
    icon.infoWindowAnchor = new GPoint(10, 5);                        
    
    if(!Boolean.parse(location.attr("isGeoCodeSuccessful")))
    {   
        $("#mapCanvas").css("background-image", "none").html("<span>No Map to Display</span>");          
    }
    else
    {                                                                        
        initializeMap(map, location.attr("latd"), location.attr("longd"));
        
        for(var i = 0; i < providers.length; i++)
        {                                                                        
            provider = $("#" + providers[i].id);                                    
            providerID = provider.attr("providerID");
            latitude = provider.attr("latitude");
            longitude = provider.attr("longitude");
            
            providerImg = $("#" + providerImgs[i].id);
            providerName = $("#" + providerNames[i].id);                                        
                                                     
            //Dont add a marker for a provider more than once
            if(jQuery.inArray(providerID, markedProviders) == -1)
            {                                            
                content = "<b>" + provider.attr("practiceName") + "</b><br />" + 
                    provider.attr("streetAddress") + "<br />" + provider.attr("cityStateZip");                                   
                                                                                                                
                icon.image = '/Resources/Images/Controls/GoogleMapMarkers/' + (i + 1) + '_pin.png';                                                                                                            
                 
                //Dont add hover events for providers that have not been GeoCoded.  
                //Doing so will cause the GMap object to be buggy.                       
                if(latitude && latitude != 0 && longitude && longitude != 0)
                {                                                                    
                    marker = addMarker(map, provider.attr("latitude"), provider.attr("longitude"), 
                        icon, content);
                                                                                                                                                
                    if(i == 0)
                    {                            
                        map.setCenter(marker.getLatLng(), 11);        
                    }
                    
                    markedProviders.push(providerID);
                    markers.push(marker);                                                   
                    
                    //Note the use of closures here.  
                    providerName.hover(function() { showMarker(this, markedProviders, markers); },
                        function() { hideMarker(this, markedProviders, markers); });
                    providerImg.hover(function() { showMarker(this, markedProviders, markers); },
                        function() { hideMarker(this, markedProviders, markers); });
                }                                                
            }                                                                       
            else
            {
                //Note the use of closures here.  
                providerName.hover(function() { showMarker(this, markedProviders, markers); },
                    function() { hideMarker(this, markedProviders, markers); });
                providerImg.hover(function() { showMarker(this, markedProviders, markers); },
                    function() { hideMarker(this, markedProviders, markers); });
            }         
        }                                                             
    }                                                                                 
}        
                        
function toggleText(promptMsg)
{        
    var readMorePrompt = "More Details";
        
    if(promptMsg == readMorePrompt)
    {
        return "Hide Details";
    }
        
    return readMorePrompt;
}

function showMarker(url, markedProviders, markers)
{                
    var ID = extractProviderID(url);

    if(ID)
    {                                        
        GEvent.trigger(markers[jQuery.inArray(ID, markedProviders)], "click");
    }            
}

function hideMarker(url, markedProviders, markers)
{
    var ID = extractProviderID(url);
    
    if(ID)
    {
        markers[jQuery.inArray(ID, markedProviders)].closeInfoWindow();
    }    
}

//Note:  The url is expected to be in the following format: http://localhost/ProviderProfile.aspx?providerID=131718
function extractProviderID(url)
{
    var providerIDRegEx = /(providerID=[\d]+)/
    var IDRegEx = /([\d]+)$/
    
    var providerIDResults = providerIDRegEx.exec(url.href);            
    var IDResults;
                    
    if(providerIDResults)
    {
        IDResults = IDRegEx.exec(providerIDResults[0]);
        
        if(IDResults)
        {
            return IDResults[0];
        }
    }
}

//To do:  This has been refactored to be generic enough to move to a utility namespace
function initializeMap(map, latitude, longitude)
{                    
    //Create and define the position of the 'mapType' buttons
    var mapTypesButtons = new GMapTypeControl();
    var mapTypesButtonsLocation = new GControlPosition(G_ANCHOR_TOP_RIGHT, new GSize(10,10));    
            
    //Add the Map Type Buttons (e.g. Map, Satellite, Hybrid)
    map.addControl(mapTypesButtons, mapTypesButtonsLocation);               
    
    //Add the Pan and Zoom Buttons
    map.addControl(new GSmallMapControl());    
    
    //Center the map
    map.setCenter(new GLatLng(latitude, longitude), 13);
}

//To do:  This has been refactored to be generic enough to move to a utility namespace
function addMarker(map, latitude, longitude, icon, content)
{                
    var marker = new GMarker(new GLatLng(latitude, longitude), 
    { 
        "icon": icon,
        "clickable": true
    });

    GEvent.addListener(marker, "click", function() 
    {
        marker.openInfoWindowHtml(content)
    });
    
    map.addOverlay(marker); 
    
    return marker;
} 

//To do:  This has been refactored to be generic enough to move to a utility namespace
function retrieveGoogleAPI(key, callbackName)
{
    $.getScript("http://www.google.com/jsapi?callback=" + callbackName + "&key=" + key);
}
