var map;
var gdir;
var geocoder = null;
var addressMarker;
var xmlHttp;
var defaultLat = '45.324405';
var defaultLng = '-73.263329';

/*
getGoogleMapsCompany();
getGoogleMapsCity();
getGoogleMapsAddress();
getGoogleMapsProvince();
getGoogleMapsCountry();
getGoogleMapsZipcode();
*/

function initialize() {
    if (GBrowserIsCompatible()) {
        geocoder = new GClientGeocoder();
        map = new GMap2(document.getElementById('map'));
        gdir = new GDirections(map, document.getElementById('directions'));
        GEvent.addListener(gdir, 'load', onGDirectionsLoad);
        GEvent.addListener(gdir, 'error', handleErrors);

        map.addControl(new GSmallMapControl());
        map.addControl(new GMapTypeControl());
        
        xmlHttp.open('GET', '/ajax_commands/get_google_maps_addresses.php');
        xmlHttp.onreadystatechange = function myFunction() {

            if (ready_to_process()) {
                json = eval("(" + xmlHttp.responseText + ")")

                for (a = 0; a < json.length; a++) {
                    sCompanyName = json[a].name;
                    sCity = json[a].city;
                    sAddress = json[a].address;
                    sProvince = json[a].province;
                    sCountry = json[a].country;
                    sZipcode = json[a].zipcode;

                    if (geocoder) {
                        geocoder.getLatLng(sAddress + ' ' + sCity + ' ' + sProvince + ' ' + sCountry,
                            function(point) {
                                if (point) {
                                    iLatitude = point.lat().toFixed(5);
                                    iLongitude = point.lng().toFixed(5);

                                    map.setCenter(point, 12);

                                    marker = new GMarker(point);

                                    marker.bindInfoWindow('<b>' + sCompanyName + '</b><br>' + sAddress + '<br />' + sCity + '( ' + sProvince + ')<br />' + sCountry + ' ' + sZipcode);

                                    map.addOverlay(marker);
                                }
                            });
                    }
                }

            }
        }
        xmlHttp.send(null);
    }
}

function setPrintDirections(fromAddress, toAddress, locale) {
    var fast_track;
    if (document.google_maps_form.fast_track[0].checked) {
        fast_track = false;
    }
    else if (document.google_maps_form.fast_track[1].checked) {
        fast_track = true;
    }
    // $("#directions").slideUp("slow");
    gdir.load("from: " + fromAddress + " to: " + toAddress, { "locale": locale, "avoidHighways": fast_track });
    // gdir.loadFromWaypoints("from: " + fromAddress + " to: " + toAddress, { "locale": locale })
}

function setDirections(fromAddress, toAddress, locale) {
    var fast_track;
    if (document.google_maps_form.fast_track[0].checked) {
        fast_track = false;
    }
    else if (document.google_maps_form.fast_track[1].checked) {
        fast_track = true;
    }
    // $("#directions").slideUp("slow");
    gdir.load("from: " + fromAddress + " to: " + toAddress, { "locale": locale, "avoidHighways": fast_track });
    // gdir.loadFromWaypoints("from: " + fromAddress + " to: " + toAddress, { "locale": locale })
}

function handleErrors() {
    if (defaultLat && defaultLng) {
        map.setCenter(new GLatLng(defaultLat, defaultLng), 15);

        // ajout marker
        var marker = new GMarker(new GLatLng(defaultLat, defaultLng));
        marker.bindInfoWindow("<b>Barnab&eacute; Mazda</b><br />606, rue Champlain<br /> Saint-Jean-sur-Richelieu (Qu&eacute;bec)<br />J3B 6X1");
        map.addOverlay(marker);
    }
    else {
        map.setCenter(new GLatLng(46.863216, -71.271692), 7);
    }

    if (gdir.getStatus().code == G_GEO_UNKNOWN_ADDRESS) {
        alert("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: " + gdir.getStatus().code);
    }
    else if (gdir.getStatus().code == G_GEO_SERVER_ERROR) {
        alert("A geocoding or directions request could not be successfully processed, yet the exact reason for the failure is not known.\n Error code: " + gdir.getStatus().code);
    }
    else if (gdir.getStatus().code == G_GEO_MISSING_QUERY) {
        alert("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: " + gdir.getStatus().code);
    }
    else if (gdir.getStatus().code == G_GEO_BAD_KEY) {
        alert("The given key is either invalid or does not match the domain for which it was given. \n Error code: " + gdir.getStatus().code);
    }
    else if (gdir.getStatus().code == G_GEO_BAD_REQUEST) {
        alert("A directions request could not be successfully parsed.\n Error code: " + gdir.getStatus().code);
    }
    else {
        alert("Vous devez spécifier une adresse valide.");
    }
}

function onGDirectionsLoad() {
    var hauteurDirection = jQuery("#directions").height();

    if (hauteurDirection < 15) {
        //alert("ouvre les directions");
        jQuery("#directions").slideDown("slow");
        jQuery("#toggleDirec").html("Cacher les directions");

        if (document.getElementById('print_directions_form')) {
            document.getElementById('print_directions_form').style.display = '';
        }
    }
    else {
        jQuery("#toggleDirec").html("Afficher les directions");

        if (document.getElementById('print_directions_form')) {
            document.getElementById('print_directions_form').style.display = 'none';
        }
    }
}

function getDistance(monDiv, start, end) {
    var Gdist = new GDirections();

    GEvent.addListener(Gdist, "error", function() {
        //GLog.write("Failed: "+Gdist.getStatus().code);
        //alert("Failed: "+Gdist.getStatus().code);
        jQuery("#" + monDiv).html("Distance non trouv&eacute;");
    });

    GEvent.addListener(Gdist, "load", function() {
        //GLog.write("The distance is "+Gdist.getDistance().meters+" metres");
        //GLog.writeHtml("The distance is "+Gdist.getDistance().html);
        //alert("The distance is "+Gdist.getDistance().html);
        jQuery("#" + monDiv).html(Gdist.getDistance().html);
    });

    //var start = "H1W 3N5";
    //var end = "H2T 1S9";
    Gdist.loadFromWaypoints([start, end], { getSteps: true });
}

function toggleDirection() {
    jQuery("#directions").slideToggle("slow");

    var hauteurDirection = jQuery("#directions").height();

    if (hauteurDirection > 5) {
        jQuery("#toggleDirec").html("Afficher les directions");

        document.getElementById('print_directions_form').style.display = 'none';
    }
    else {
        jQuery("#toggleDirec").html("Cacher les directions");
        document.getElementById('print_directions_form').style.display = '';
    }
}
