var gmarkers = [];
var initMapCalled = false;
/**
* Note: This is used for other pages and is NOT used
* on the location.html page because the selection
* drop down is build in the map creation. This is because the "values"
* for the select are different (array indexes), where on other pages,
* the "values" are the index ids.
*
* @see initMap
*/
function createLocationSelection(element_id, xml_location) {
    if (initMapCalled == true) return;
    document.getElementById(element_id).options[0] = new Option("Choose One", "Choose One", true, false);
    var i = 0;
    $.get(xml_location, {},
    function (xml) {
        $(xml).find("marker").each(function (index) {
            var marker = $(this);
            var label = marker.attr("label");
            document.getElementById(element_id).options[i + 1] = new Option(label, label, true, false);
            i++;
        }
        )
    }
  );
}

function initMap() {
    initMapCalled = true;
    if (GBrowserIsCompatible()) {
        var map = new GMap2(document.getElementById("map_canvas"));
        map.setCenter(new GLatLng(34.03407918689516, -118.36989641189575), 8);
        map.setUIToDefault();
        map.removeMapType(G_HYBRID_MAP);
        map.removeMapType(G_SATELLITE_MAP);
        map.removeMapType(G_PHYSICAL_MAP);

        // Read the data from xml
        GDownloadUrl(xml_location, function (doc) {
            var xmlDoc = GXml.parse(doc);
            var markers = xmlDoc.documentElement.getElementsByTagName("marker");
            // If we have a get var for a location, we need to go there.
            var $_GET = {};
            var init_location = -1;
            document.location.search.replace(/\??(?:([^=]+)=([^&]*)&?)/g, function () {
                function decode(s) {
                    return decodeURIComponent(s).replace(/\+/g, " ");
                }
                $_GET[decode(arguments[1])] = decode(arguments[2]);
            });
            var init_label_name = $_GET['init_location'];
            document.getElementById("location_select").options[0] = new Option("Choose One", "Choose One", true, false);
            for (var i = 0; i < markers.length; i++) {
                // obtain the attribues of each marker
                var lat = parseFloat(markers[i].getAttribute("lat"));
                var lng = parseFloat(markers[i].getAttribute("lng"));
                var point = new GLatLng(lat, lng);
                var html = GXml.value(markers[i].getElementsByTagName("infowindow")[0]);
                var street = GXml.value(markers[i].getElementsByTagName("street")[0]);
                var directions = GXml.value(markers[i].getElementsByTagName("crossstreet")[0]);
                var city = GXml.value(markers[i].getElementsByTagName("city")[0]);
                var state = GXml.value(markers[i].getElementsByTagName("state")[0]);
                var zip = GXml.value(markers[i].getElementsByTagName("zip")[0]);
                var bhours = GXml.value(markers[i].getElementsByTagName("branchhours")[0]);
                var phours = GXml.value(markers[i].getElementsByTagName("phonehours")[0]);
                var ahours = GXml.value(markers[i].getElementsByTagName("automatedhours")[0]);
                var phone = GXml.value(markers[i].getElementsByTagName("phone")[0]);
                var label = markers[i].getAttribute("label");
                if (label == init_label_name) {
                    init_location = i;
                }
                var info = '';
                // Build the HTML
                html += "<h5>" + label + "</h5>";
                html += "<p>" + street + "<br />";
                html += city + ", " + state + " " + zip + "<br />";
                html += "<strong>Phone:</strong> " + phone + "<br />";
                html += "<strong>Cross Street:</strong> " + directions;
                html += "</p>";
                // Info HTML
                info += '<p>';
                info += '<strong>Branch Hours:</strong> ' + bhours + "<br />";
                info += '<strong>Phone Hours: </strong> ' + phours + "<br />";
                info += '<strong>Automated Account Information:</strong> ' + ahours + "<br />";
                info += '</p>';
                //Directions Link

                street = replaceAll(street, ' ', '+');
                street = replaceAll(street, '#', '%23+');
                city = replaceAll(city, ' ', '+');
                state = replaceAll(state, ' ', '+');
                zip = replaceAll(zip, ' ', '+');

                html += '<p><a target="_blank" href="';
                html += 'http://maps.google.ca/maps?q=to%3A+';
                html += street + ',' + city + ',' + state + '+' + zip + '&f=d&hl=en';
                html += '">Get Directions</a>';
                html += '</p>';

                // create the marker
                var marker = createTabbedMarker(point, html, info, "Location", "Info");
                map.addOverlay(marker);
                // Add to the drop down
                document.getElementById("location_select").options[i + 1] = new Option(label, i + 1, false, false);
            }

            if (init_location > -1) {
                animateToBank(init_location + 1);
                document.getElementById("location_select").options[init_location + 1].selected = true;
            }
        });

        // A function to create the marker and set up the event window
        function createMarker(point, name, html) {
            var marker = new GMarker(point);
            GEvent.addListener(marker, "click", function () {
                marker.openInfoWindowHtml(html);
            });
            // save the info we need to use later for the side_bar
            gmarkers.push(marker);
            return marker;
        }

        function createTabbedMarker(point, html1, html2, label1, label2) {
            // Create our "tiny" marker icon
            var blueIcon = new GIcon(G_DEFAULT_ICON);
            blueIcon.image = '/Content/Assets/images/csb_google_icon2.png';
            // Set up our GMarkerOptions object
            markerOptions = { icon: blueIcon };

            var marker = new GMarker(point, markerOptions);
            GEvent.addListener(marker, "click", function () {
                marker.openInfoWindowTabsHtml([new GInfoWindowTab(label1, html1), new GInfoWindowTab(label2, html2)]);
            });
            gmarkers.push(marker);
            return marker;
        }
    }
}

function animateToBank(e) {
    if (e == "Choose One") {
        return false;
    }
    if (document.getElementById("map_canvas") != null) {
        GEvent.trigger(gmarkers[e - 1], "click");
    }
    else {
        document.location = '/about_us/locations?init_location=' + e;
    }
}

// Needs to handle relative paths.
function showBankLocation(e) {
    if (document.getElementById("map_canvas") != null) {
        document.location = '/about_us/locations?init_location=' + e;
    }
}

function replaceAll(OldString, FindString, ReplaceString) {
    var SearchIndex = 0;
    var NewString = "";
    while (OldString.indexOf(FindString, SearchIndex) != -1) {
        NewString += OldString.substring(
        SearchIndex,
        OldString.indexOf(FindString, SearchIndex)
    );
        NewString += ReplaceString;
        SearchIndex = (OldString.indexOf(FindString, SearchIndex) + FindString.length);
    }
    NewString += OldString.substring(SearchIndex, OldString.length);
    return NewString;
}
