
var sequenceCount = 1;
var sequence = new Array();
var map;
var homeMarker;

function load() {
    if (GBrowserIsCompatible()) {

        map = new GMap2(document.getElementById("map"));
        
        map.enableScrollWheelZoom();
        map.addControl(new GLargeMapControl());
        map.addControl(new GMapTypeControl());
        map.addControl(new GScaleControl());
        
        map.setCenter(new GLatLng(lat,lng), zoom);
        
        var url = "./getmarkers.php5?lat=" + lat + "&lng=" + lng + "&distance=" + distance + "&isUSA=" + isUSA;
        
        GDownloadUrl(url, function(data, responseCode) {
            var xml = GXml.parse(data);
            var markers = xml.documentElement.getElementsByTagName("marker");
            for (var i = 0; i < markers.length; i++) {
                var point = new GLatLng(parseFloat(markers[i].getAttribute("lat")), parseFloat(markers[i].getAttribute("lng")));                
                var markerUrl = "<strong>" + unescape(markers[i].getAttribute("title")) + "</strong><br><a target=_blank href=\"" + markers[i].getAttribute("url") + "\">website</a>";
                var markerTitle = unescape(markers[i].getAttribute("address"));

                map.addOverlay(createMarker(point, markerUrl, markerTitle));
            }
        });
        
        if (1 != isUSA) {
        
            // Create a base icon for all of our markers that specifies the
            // shadow, icon dimensions, etc.
            var baseIcon = new GIcon();
            baseIcon.shadow = "http://www.google.com/mapfiles/shadow50.png";
            baseIcon.iconSize = new GSize(20, 34);
            baseIcon.shadowSize = new GSize(37, 34);
            baseIcon.iconAnchor = new GPoint(9, 34);
            baseIcon.infoWindowAnchor = new GPoint(9, 2);
            baseIcon.infoShadowAnchor = new GPoint(18, 25);
        
            var homeIcon = new GIcon(baseIcon);
            homeIcon.image = "http://www.google.com/mapfiles/markerH.png";
            
            homeMarker = new GMarker(new GLatLng(lat,lng), {icon: homeIcon, title: homeAddress});
            
            GEvent.addListener(homeMarker, "click", function() {
                homeMarker.openInfoWindowHtml("<strong>Your House</strong>");
            }); 
            map.addOverlay(homeMarker);
        }
        
    }
}

var hoverMarker;
var hoverURL;
var hoverTimer;

function OpenDetails() {
    if (hoverMarker) {
        hoverMarker.openInfoWindowHtml(hoverURL);
    }
}
    
function createMarker(point, url, title) {
    
    var marker = new GMarker(point, { title: title});

    GEvent.addListener(marker, "dblclick", function() {
        clearTimeout(hoverTimer);
        hoverURL="";
        hoverMarker = "";
        AddToSequence(marker);
    });

    GEvent.addListener(marker, "click", function() {
        hoverURL = url;
        hoverMarker = marker;
        hoverTimer = setTimeout('OpenDetails()', 550);
    });

    return marker;
}

function AddToSequence(marker) {
    
    if (marker.getPoint().equals(homeMarker.getPoint())) {
        return;
    }
    
    var found = 0;
    var current;
    
    for (current in sequence)
    {
        if (sequence[current].getPoint().equals(marker.getPoint())) {
            found = 1;
            break;
        }
    }
    
    if (found) {
        sequence[current].setImage("http://www.google.com/mapfiles/marker.png");
        sequence.splice(current, 1);
        ResetMarkers();
        return;
    }
        
    if (9 < sequence.length ) {
        alert("Maximum number of Garage Sales selected. Double click selected garage sales to remove them from your travel list.");
        return;
    }
    
    var seqCount = sequence.push (marker);
    marker.setImage("/images/iconb" + seqCount + ".png");
}

function ResetMarkers() {
    for (current = 0; current < sequence.length; current++) {
        var iconImage = current + 1;
        sequence[current].setImage("/images/iconb" + iconImage + ".png");
    }
}

var directions;
var isDirections = 0;

function DirectionsButton() {
    if ( isDirections) {
        ClearDirections();
    } else {
        PrintDirections();
    }
}

function ClearDirections() {
    document.getElementById("dirbutton").innerHTML = "Get Directions";
    isDirections = 0;
    directions.clear();
}

function PrintDirections() {
    
    if ( 0 == sequence.length) {
        alert('Doulble click a garage sale or two, then click \"Get Directions\" to get directions from one to another, in order');
        return;
    }
    
    var wayPoints = new Array();
    
    wayPoints.push (homeMarker.getTitle());
    
    var current;
    for (current in sequence) {
        wayPoints.push (sequence[current].getTitle());
    }
    
    if ( ! directions) {
        directions = new GDirections(map, document.getElementById("adbottom"));
        GEvent.addListener(directions, "error", handleErrors);
    } else {
        directions.clear();
    }
    
    directions.loadFromWaypoints(wayPoints, {preserveViewport: true});        

    document.getElementById("dirbutton").innerHTML = "Clear Directions";
    isDirections = 1;
}

function handleErrors() {

//    if (directions.getStatus().code == G_GEO_UNKNOWN_ADDRESS)
//        message = "No corresponding geographic location could be found for one of the specified addresses. This may be due to the fact that the address is relatively new, or it may be incorrect.\nError code: " + directions.getStatus().code;
//    else if (directions.getStatus().code == G_GEO_SERVER_ERROR)
//        message = "A geocoding or directions request could not be successfully processed, yet the exact reason for the failure is not known.\n Error code: " + directions.getStatus().code;
//    else if (directions.getStatus().code == G_GEO_MISSING_QUERY)
//        message = "The HTTP q parameter was either missing or had no value. For geocoder requests, this means that an empty address was specified as input. For directions requests, this means that no query was specified in the input.\n Error code: " + directions.getStatus().code;
//    else if (directions.getStatus().code == G_GEO_BAD_KEY)
//        message = "The given key is either invalid or does not match the domain for which it was given. \n Error code: " + directions.getStatus().code;
//    else if (directions.getStatus().code == G_GEO_BAD_REQUEST)
//        message = "A directions request could not be successfully parsed.\n Error code: " + directions.getStatus().code;

    alert("An error occurred. Try removing a garage sale from your list and try again.");
    document.getElementById("dirbutton").innerHTML = "Get Directions";
    isDirections = 0;
    directions.clear();
}