//Our holding value
var passedMarkers, map, gInfoWindow = null;

// This code will load the map markers after a delay.
function LoadDelayedMap(markers) {

    passedMarkers = markers;
    jQuery(document).ready(function () {
        setTimeout("getMarkers()", 400);
    });
}

// Get the holding value for the markers and call the function to place them.
function getMarkers() {
    placeMarkers(passedMarkers);
    mapAvailable = 1;
}

// Function to loop through marker collection and place each on map
function placeMarkers(markers) {

    // If there are no markers change nothing
    if (markers !== null) {

        if (typeof google === 'undefined' || typeof google.maps === 'undefined') {
            passedMarkers = markers;
            return false;
        }

        var latlng = new google.maps.LatLng(54.23, -4.4),

            mapOptions = {
                mapTypeId: google.maps.MapTypeId.ROADMAP,
                streetViewControl: false,
                scrollwheel: false,
                center: latlng,
                zoom: 5
            };

        map = new google.maps.Map(document.getElementById("whereToBuyMap"), mapOptions);

        jQuery.each(markers, function (i, marker) {
            //place individual marker
            placeMarker(marker);
        });

        // new
        gInfoWindow = new google.maps.InfoWindow();
    }
}

// Function to place an individual marker on the map
function placeMarker(marker) {

    //get marker coordinates
    var latLng = new google.maps.LatLng(marker.latLong.split(",")[0], marker.latLong.split(",")[1]),

    //set the pointer type.
        strPointerURL = "http://www.google.com/mapfiles/marker.png",

    //create marker
        gMarker = new google.maps.Marker({
            clickable: true,
            position: latLng,
            map: map,
            icon: strPointerURL,
            title: marker.markerText
        });

    //add the click event to the marker which will trigger the InfoWindow's open method
    google.maps.event.addListener(gMarker, 'click', function () {

        var clickContent;


        for (var i = 0, len = passedMarkers.length; i < len; i++) {

            var formattedLL = "(" + passedMarkers[i].latLong.split(",")[0] + ", " + passedMarkers[i].latLong.split(",")[1] + ")";

            //if (new RegExp(gMarker.position).test(formattedLL)) {
            if (gMarker.position.toString().indexOf(formattedLL) != -1) {
                clickContent = passedMarkers[i].infoText;
                break;
            }
        }

        gInfoWindow.setContent("<span class='googleMapMarkerContent'>" + clickContent + "</span>");
        //open the InfoWindow
        gInfoWindow.open(map, gMarker);
    });
}

