/* This Javascript is based on code provided by the Blackpool Community Church Javascript Team
 http://www.commchurch.freeserve.co.uk/
 http://www.econym.demon.co.uk/googlemaps/
 */

var map;
var geocoder;
var directionsDisplay;
var directionsService;

var bounds;
var arrMarkers = [];

/* Arrays to hold copies of the markers and html used by the side_bar */
var gmarkers = [];
var htmls = [];

var zoom;
var infoSeparator = "|";
var fullInfoCount = 5; //count of info parts that include lat/lng (pattern of line - lat|lng|address|html)
var partInfoCount = 2; //count of info parts that don't include lat/lng (pattern of line - address|html)

var icons = [];
var loaded_zoom_level;

function loadMap(mapId, startPointLat, startPointLng, address, zm) {
    if (!map) {
        // create the map
        var centerPoint = new google.maps.LatLng(startPointLat, startPointLng);
        var mapOptions = {
            zoom: zm,
            center: centerPoint,
            mapTypeId: google.maps.MapTypeId.ROADMAP
        };

        map = new google.maps.Map(document.getElementById(mapId), mapOptions);
    }

    if (!bounds) {
        bounds = new google.maps.LatLngBounds();
    }//if

    loadMarker(0);

    map.fitBounds(bounds);
    map.setCenter(bounds.getCenter());

    /*
     // 7389 zoom out, if marker behind icons
     var bv = false;
     for (i=0; i<arrMarkers.length; i++) {
     var p = map.fromLatLngToDivPixel(arrMarkers[i].getPoint());
     if ((p.x > (map.getSize().width - 210) && p.y < 35) || (p.x < 60 && p.y < 60) ) {
     bv = true;
     }
     }
     if(bv && map.getBoundsZoomLevel(bounds) != 1) {
     map.setZoom(map.getBoundsZoomLevel(bounds) - 1);
     }
     // end of 7389
     */

    // 7242 if one hotel
    if (arrMarkers.length == 1) {
        map.setZoom(15);
    }
    // end 7242

    loaded_zoom_level = map.getZoom();
    /*
     geocoder = new google.maps.Geocoder();
     if ((startPointLat != 0) && (startPointLng != 0)) {
     var point = new google.maps.LatLng(startPointLat, startPointLng);
     map.setCenter(point);
     map.setZoom(zoom);
     //loadMarker(0, useDirections);
     } else if (geocoder) {
     geocoder.getLatLng(address, function(point) {
     if (!point) {
     //alert(airport + " not found.");
     document.getElementById('mapId').style.display='none';
     }
     else {
     map.setCenter(point, zoom);
     setTimeout(function() { loadMarker(0, useDirections) }, 1725);
     }
     });
     }
     */
}

function loadMarker(markerIndex) {
    if (markerIndex < markersData.length) {
        parts = markersData[markerIndex].split(infoSeparator);
        markerIndex++;
        /* Lat/lng were given in a data string */
        if (parts.length == fullInfoCount) {
            var lat = parseFloat(parts[0]);
            var lng = parseFloat(parts[1]);
            var html = parts[3];

            if (!isNaN(lat) && lat != 0 && !isNaN(lng) && lng != 0) {
                var point = new google.maps.LatLng(lat, lng);
                var iconImage = parts[4];
                addMarker(point, html, markerIndex - 1, iconImage);
                loadMarker(markerIndex);
            } else {
                if (!geocoder) {
                    geocoder = new google.maps.Geocoder();
                }//if

                var request = {address : parts[2]};
                geocoder.geocode(request, function(results, status) {
                    if (!results) {
                        alert(request.address + " not found.");
                    } else {
                        if (status == google.maps.GeocoderStatus.OK) {
                            var geocoderResult = results[0];
                            var point = geocoderResult.geometry.location;

                            markersData[markerIndex - 1] = point.lat() + '|' + point.lng() + '|' + request.address + '|' + html + '|' + link;

                            var iconImage = parts[4];
                            addMarker(point, html, markerIndex - 1, iconImage);
                        }
                    }
                    setTimeout(function() { loadMarker(markerIndex) }, 1725);
                });
            }
        }
    }
}

function addMarker(point, html, markerIndex, iconImage) {
    var htmlToMarker = '';
    htmlToMarker += html;
    var marker = createMarker(point, htmlToMarker, markerIndex, iconImage);

    bounds.extend(marker.getPosition());
    arrMarkers.push(marker); // 7389
}

/* A function to create the marker and set up the event window */
function createMarker(point, html, markerIndex, iconImage) {
    var marker = new google.maps.Marker({
        position: point,
        map: map,
        icon: iconImage,
        shadow: "/lq/images/mapquest/shadow50.png",
        flat: false,
        zIndex: markerIndex + 1
    });
    // The info window version with the "to here" form open

    var infowindow = new google.maps.InfoWindow({
        content: '<div style="font-size:11px;width:200px;">' + html + '</div>'
    });

    google.maps.event.addListener(marker, 'click', function() {
        infowindow.open(map, marker);
    });

    gmarkers[markerIndex] = marker;
    htmls[markerIndex] = html;
    return marker;
}

function resetCenter(lat, lng) {
    var point = new google.maps.LatLng(lat, lng);
    map.setCenter(point);
    map.setZoom(loaded_zoom_level);
}

function routeMap(oLat, oLng, dLat, dLng, context) {
    loadMap('mapWindow', oLat, oLng, '', 10);

    if (!map) return;

    if (!directionsDisplay) {
        var markerIcon = context ? context + '/images/mapquest/poi-marker.png' : '/lq/images/mapquest/poi-marker.png';
        var rendererOptions = {
            markerOptions: {
                zIndex: -100,
                icon: markerIcon
            }
        };
        directionsDisplay = new google.maps.DirectionsRenderer(rendererOptions);
    }
    directionsDisplay.setMap(map);

    if (!directionsService) {
        directionsService = new google.maps.DirectionsService();
    }

    var start = new google.maps.LatLng(oLat, oLng);
    var end = new google.maps.LatLng(dLat, dLng);
    var request = {
        origin:start,
        destination:end,
        travelMode: google.maps.DirectionsTravelMode.DRIVING
    };

    directionsService.route(request, function(response, status) {
        if (status == google.maps.DirectionsStatus.OK) {
            directionsDisplay.setDirections(response);
        }
    });
}

function routeMapWithDirections(oLat, oLng, dLat, dLng, mapId, directionId) {
    var map = new google.maps.Map(document.getElementById(mapId), {
        mapTypeId: google.maps.MapTypeId.ROADMAP
    });

    if (!map) {
        return;
    }

    if (!directionsService) {
        directionsService = new google.maps.DirectionsService();
    }
    if (!directionsDisplay) {
        directionsDisplay = new google.maps.DirectionsRenderer();
    }

    directionsDisplay.setMap(map);
    directionsDisplay.setPanel(document.getElementById(directionId));

    var request = {
        origin: new google.maps.LatLng(oLat, oLng),
        destination: new google.maps.LatLng(dLat, dLng),
        travelMode: google.maps.DirectionsTravelMode.DRIVING
    };

    directionsService.route(request, function(response, status) {
        if (status == google.maps.DirectionsStatus.OK) {
            directionsDisplay.setDirections(response);
        }
    });
}

function routeMapWithDirectionsAndHotels(oLat, oLng, dLat, dLng, mapId, directionId) {
    loadMap(mapId, oLat, oLng, '', 10);

    if (!map) return;

    if (!directionsDisplay) {
        directionsDisplay = new google.maps.DirectionsRenderer();
    }
    if (!directionsService) {
        directionsService = new google.maps.DirectionsService();
    }

    directionsDisplay.setMap(map);
    directionsDisplay.setPanel(document.getElementById(directionId));

    var request = {
        origin: new google.maps.LatLng(oLat, oLng),
        destination: new google.maps.LatLng(dLat, dLng),
        travelMode: google.maps.DirectionsTravelMode.DRIVING
    };

    directionsService.route(request, function(response, status) {
        if (status == google.maps.DirectionsStatus.OK) {
            directionsDisplay.setDirections(response);
        }
    });
}
