﻿function drawSportsMuseumMap() {

    var geocoder = new google.maps.Geocoder();


    geocoder.geocode({ 'address': "100 Legends Way, Boston, MA" }, function (results, status) {
        if (status == google.maps.GeocoderStatus.OK) {
            if (results[0]) {
                var sportsMusuemLocation = results[0].geometry.location;
                var mapDiv = document.getElementById('map-canvas');
                var map = new google.maps.Map(mapDiv, {
                    zoom: 17,
                    mapTypeId: google.maps.MapTypeId.ROADMAP
                });
                map.setCenter(sportsMusuemLocation);

                //alert(map.getCenter());
                var infowindow = new google.maps.InfoWindow({
                    position: map.getCenter(),
                    content: '<span id="map-info-box"><h1>The Sports Museum</h1><p>100 Legends Way</p><p>Boston, MA 02114-1309</p><p>(617) 624-1050</p></span>'
                });
                infowindow.open(map);

            }
        } else {
            //alert("Geocoder failed due to: " + status);
        }
    });


    //get the users location
    // Try W3C Geolocation (Preferred)
    if (navigator.geolocation) {
        browserSupportFlag = true;
        navigator.geolocation.getCurrentPosition(function (position) {
            initialLocation = new google.maps.LatLng(position.coords.latitude, position.coords.longitude);
            //map.setCenter(initialLocation);
            convertLatLng(initialLocation);
        }, function () {
            handleNoGeolocation(browserSupportFlag);
        });
        // Try Google Gears Geolocation
    } else if (google.gears) {
        browserSupportFlag = true;
        var geo = google.gears.factory.create('beta.geolocation');
        geo.getCurrentPosition(function (position) {
            initialLocation = new google.maps.LatLng(position.latitude, position.longitude);
            //map.setCenter(initialLocation);
            convertLatLng(position.latitude, position.longitude);
        }, function () {
            handleNoGeoLocation(browserSupportFlag);
        });
        // Browser doesn't support Geolocation
    } else {
        browserSupportFlag = false;
        handleNoGeolocation(browserSupportFlag);
    }
    function handleNoGeolocation(flag) { 
    
    }

    function convertLatLng(location) {
        var geocoder = new google.maps.Geocoder();

        geocoder.geocode({ 'latLng': location }, function (results, status) {
            if (status == google.maps.GeocoderStatus.OK) {
                if (results[0]) {
                    var userLocation = results[0].formatted_address;
                    $('#input-origin').attr('value',userLocation);
                    //alert(results[0].formatted_address);
                }
            } else {
                //alert("Geocoder failed due to: " + status);
            }
        });

    }

}

function convertLatLng(location) {
    var geocoder = new google.maps.Geocoder();

    geocoder.geocode({ 'latLng': location }, function (results, status) {
        if (status == google.maps.GeocoderStatus.OK) {
            if (results[0]) {
                var userLocation = results[0].formatted_address;
                alert(results[0].formatted_address);
            }
        } else {
            alert("Geocoder failed due to: " + status);
        }
    });
        
}


function getDirectionsMap() {
    var geocoder = new google.maps.Geocoder();
    var origin = $('#input-origin').attr('value');


    $('#map-canvas div').first().fadeOut(600);

    var mapDiv = document.getElementById('map-canvas');
    var map = new google.maps.Map(mapDiv, {
        zoom: 17,
        mapTypeId: google.maps.MapTypeId.ROADMAP
    });


    directionsDisplay = new google.maps.DirectionsRenderer();
    directionsDisplay.setMap(map);

    var directionsTextDiv = document.getElementById('directions-text');
    directionsDisplay.setPanel(directionsTextDiv);

    var directionsService = new google.maps.DirectionsService();
    var directionsOptions = {
        origin: origin,
        destination: "100 Legends Way, Boston, MA",
        travelMode: google.maps.TravelMode.DRIVING
    };
    directionsService.route(directionsOptions, function (result, status) {
        if (status == google.maps.DirectionsStatus.OK) {
            directionsDisplay.setDirections(result);
        }
    });

    var urlOrigin = (origin.replace(' ', "+"));
    var urlDestination = (("100 Legends Way, Boston, MA").replace(' ', "+"));
    var plink = '' + 'http://maps.google.com/maps?saddr=' + urlOrigin + '&daddr=' + urlDestination + '&hl=en&vpsrc=0&mra=ls&t=m&z=14';

    DisplayDirections(plink);


}

var timeoutID;

function DisplayDirections(permalink) {
    $("body").css("cursor", "progress");

    if ($('#directions table tr:first-child').length == 0) {
        timeoutID = setTimeout(function () { DisplayDirections(permalink); }, 500);
    } else {
        $('#map-form').fadeOut(400);
        $("body").css("cursor", "auto");

        setTimeout(function () {
            $('#map-canvas div').first().fadeIn(600);
        }, 600);

        setTimeout(function () {
            $('#directions').fadeIn(400);
            $('.scroll-pane').jScrollPane({
                verticalDragMaxHeight: 100
            });
        }, 400); 



        clearTimeout(timeoutID);


        $('#grab-the-link').attr('href', permalink);
//      $('#grab-the-link').click(function(){
//            copyToClipboard(permalink);
//        });
    }
}


function copyToClipboard(text)
{
        window.prompt("Copy to clipboard: Ctrl+C, Enter", text);
}

function parseUrl() {
    var urlParams = {};
    (function () {
        var e,
        a = /\+/g,  // Regex for replacing addition symbol with a space
        r = /([^&=]+)=?([^&]*)/g,
        d = function (s) { return decodeURIComponent(s.replace(a, " ")); },
        q = window.location.search.substring(1);

        while (e = r.exec(q))
            urlParams[d(e[1])] = d(e[2]);
    })();
    return urlParams["utm_campaign"];
}
function regAddress(address) {
    var pattern = "^[a-zA-Z0-9\s,'-]*$";
    var re = new RegExp(pattern);
    return re.test(address);
}


$(document).ready(function () {
    var utm_campaign = parseUrl();


    if (utm_campaign == "NESM_Display_Campaign") {
        $("#black-bar").slideDown();
        switch (utm_campaign) {
            case "vinateiri":
                $("#black-bar p").text("Some fun fact about Vinateri's shoes");
                break;
            default:
                $("#black-bar p").text("The Sports Museum is located in the TD Garden Building");
                break;

        }

        drawSportsMuseumMap();
        $("#map-inner-wrap").slideDown(1000);

        $('#get-directions').click(function () {

            var origin = $("#input-origin").val();
            var destination = $("#input-destination").val();
            if (!destination && !origin) {
                $('.validation-text').first().fadeIn(100);
                $('.validation-text').last().fadeIn(100);
            }
            else if (!origin) {
                $('.validation-text').first().fadeIn(100);
            } else if (!destination) {
                $('.validation-text').last().fadeIn(100);
            } else {
                getDirectionsMap();
            }
        });







        $('#close-maps').click(function () {
            $("#map-inner-wrap").slideUp(1000);
            $(this).hide();
            $('#open-maps').show();
            e.preventDefault()
        });
        $('#open-maps').click(function () {
            $("#map-inner-wrap").slideDown(1000);
            $(this).hide();
            $('#close-maps').show();
            e.preventDefault()
        });
    }


});


