﻿//geocode the address, then get the closest hospital
//using the hospital service, then render the map
function geocodeAddess(str_address, rightsToSetHome, homeHospitalID, clientCoordinates)
{
    geocoder = new google.maps.Geocoder();
    success = false;
    $('.pNoResults').hide();

    geocoder.geocode({ 'address': str_address }, function (results, status)
    {
        if (status == google.maps.GeocoderStatus.OK)
        {

            var location = results[0].geometry.location.toString();
            location = location.replace(")", "");
            location = location.replace("(", "");
            location = location.replace(" ", "");
            getHospitalLocations(location, rightsToSetHome, homeHospitalID, true);
        }
        else
        {
            renderZoomedUSMap(); 
        }
    });

}

//geocode the address then redirect to a page with the 
//ll=lat,lng parameter
function geocodeAddessRedirect(str_address, url, clientCoordinates)
{

    geocoder = new google.maps.Geocoder();
    geocoder.geocode({ 'address': str_address }, function (results, status)
    {
        if (status == google.maps.GeocoderStatus.OK)
        {

            var location = results[0].geometry.location.toString();
            location = location.replace(")", "");
            location = location.replace("(", "");
            location = location.replace(" ", "");

            //getHospitalLocations(location);

            url = url + "?ll=" + location;
            //window.location.replace(url);
            //$(location).attr('href', url);
            window.location = url;
        }
        else
        {
            //window.location.replace(url + "?ll=0,0");
            //$(location).attr('href', url + "?ll=0,0");
            window.location = url + "?ll=" + clientCoordinates + "&noresult=1";
        }
    });
}


//run the coordinates through our hospital service online
function getHospitalLocations(latLng, rightsToSetHome, homeHospitalID, resultsFound)
{
    resultsFound = false;
    //check for https so we use the correct protocol in url
    //var ajaxUrl = window.parent.document.location.protocol + "//dev.banfield.com";
    var ajaxUrl = "";
    $.get(ajaxUrl + "/locatorservice?ll=" + latLng + "&m=1",
        function (data)
        {
            //$('.result').html(data);
            //alert('Load was performed.' + data);
            renderZoomedUSMap();
            $(data).find('locations').each(function ()
            {
                $('.pNoResults').hide();
                $(this).find('location').each(function ()
                {
                    var id = $(this).attr('id');
                    var name = $(this).attr('name');
                    var address = $(this).attr('address');
                    var city = $(this).attr('city');
                    var state = $(this).attr('state');
                    var zip = $(this).attr('zip');
                    var phone = $(this).attr('phone');
                    var lat = $(this).attr('lat');
                    var lng = $(this).attr('lng');
                    var distance = $(this).attr('distance');
                    var code = $(this).attr('code');

                    initMmap('google-map', lat, lng, 9, { title: name, position: new google.maps.LatLng(lat, lng), icon: "/CMSWebParts/Banfield/MiniLocator/MiniLocator_files/img/MapMarker.png" }, "<h2>" + name + "</h2><ul class='store_details'><li>" + address + "</li><li>" + city + ", " + state + "</li><li>" + phone + "</li><li><a href='/Pet-Owners/Our-Hospitals/Locations/Location-Pages/" + code + "'>View hospital</a></li>" + buildSetHomeHospitalUrl(rightsToSetHome, homeHospitalID, id) + "</ul>", '{ title: "' + name + '", position: new google.maps.LatLng(' + lat + ',' + lng + '), icon: "/CMSWebParts/Banfield/MiniLocator/MiniLocator_files/img/MapMarker.png" }');
                });
            });
        });

    $(document).ready(function () { $('#close').click(function () { $('#map_content_window').css('display', 'none'); }); });
}


function buildSetHomeHospitalUrl(hasRights, homeHospitalID, currentHospitalIDResult)
{
    if (hasRights == 'True' && parseInt(homeHospitalID) != parseInt(currentHospitalIDResult))
        return "<li><a href='?id=" + currentHospitalIDResult + "&sethospital=1'>Make this My Hospital</a></li>";
    else
        return "";
}

//initialize the google map via apps api
function initMmap(map_canvas_id, lat, lng, zoomLevel, marker, window_content, marker_content)
{
    if (lat == '0' && lng == '0')
    {
        renderZoomedUSMap();
        return;
    }

    //save cookie    
    setCookie("googleMapInfo", "marker=" + marker_content + "&window_html=" + window_content + "&latitude=" + lat + "&longitude=" + lng, 7);

    var myLatLng = new google.maps.LatLng(lat, lng);

    var options = {

        zoom: zoomLevel,
        center: myLatLng,
        mapTypeId: google.maps.MapTypeId.ROADMAP,
        disableDefaultUI: true
    };

    var map_canvas = document.getElementById(map_canvas_id);

    var map = new google.maps.Map(map_canvas, options);

    var infowindow = new google.maps.InfoWindow({
        content: window_content,
        disableAutoPan: true,
        pane: "floatPane"

    });

    var marker = new google.maps.Marker(marker);
    marker.setMap(map);

    google.maps.event.addListener(marker, 'click', function ()
    {
        var content_container = document.getElementById("map_content_window");
        var content = document.getElementById("window_content");
        content_container.style.display = "block";
        content.innerHTML = window_content;
    });
}

function setCookie(c_name, value, exdays)
{
    var exdate = new Date();
    exdate.setDate(exdate.getDate() + exdays);
    var c_value = value + ((exdays == null) ? "" : "; expires=" + exdate.toUTCString());
    document.cookie = c_name + "=" + c_value;
}

function renderZoomedUSMap()
{
    //show no results message
    $('.pNoResults').show();

    //load default us map
    init_map('google-map', 39.8097343, -98.5556199000000, 2, '', '');
}

function IsEnter(el,ev)
{
    if (ev.keyCode == 13)
    {
        geocodeAddessRedirect(el.value, '');
        return false;
    }
}



