/**
* Google maps API routing
*/
// From: http://facstaff.unca.edu/mcmcclur/GoogleMaps/EncodePolyline/
// This function is from Google's polyline utility.
function decodeLine (encoded) {
  var len = encoded.length;
  var index = 0;
  var array = [];
  var lat = 0;
  var lng = 0;

  while (index < len) {
    var b;
    var shift = 0;
    var result = 0;
    do {
      b = encoded.charCodeAt(index++) - 63;
      result |= (b & 0x1f) << shift;
      shift += 5;
    } while (b >= 0x20);
    var dlat = ((result & 1) ? ~(result >> 1) : (result >> 1));
    lat += dlat;

    shift = 0;
    result = 0;
    do {
      b = encoded.charCodeAt(index++) - 63;
      result |= (b & 0x1f) << shift;
      shift += 5;
    } while (b >= 0x20);
    var dlng = ((result & 1) ? ~(result >> 1) : (result >> 1));
    lng += dlng;

    array.push([lat * 1e-5, lng * 1e-5]);
  }

  return array;
}


var gmapRouting = {
    service : null,
    locale: 'en_US',
    load_success_callback : null,
    load_error_callback : null,
    load : function(locale, route_type, fromAddress, toAddress, successCallBack, errorCallBack ) {
        var service = new GDirections();
        service.load_success_callback = successCallBack;
        service.load_error_callback = errorCallBack;
        // Listen to load event...
        GEvent.addListener(service, "load",  this.service_load);
        GEvent.addListener(service, "error", this.handle_errors);
        service.load( "from: " + fromAddress + " to: " + toAddress,
                { getPolyline: true, getSteps: true, "locale": locale, avoidHighways : ( route_type != 'roads' )});
    },
    service_load : function(){
        var dirbuf = [];

        // Assume we have only one route
        var r = this.getRoute(0);
        var polyline = this.getPolyline();

        for (i = 0; i < r.getNumSteps(); i++) {
            var step = r.getStep(i);
            var geom = [];
            if (i == r.getNumSteps() - 1) {
                var last_vertex = polyline.getVertexCount() - 1;
            } else {
                var last_vertex = r.getStep(i + 1).getPolylineIndex();
            }
            for ( j = step.getPolylineIndex(); j <= last_vertex ; j++){
                var vertex = polyline.getVertex(j);
                geom.push(vertex.x + ' ' + vertex.y);
            }
            dirbuf.push({
                geom : 'LINESTRING (' + geom.join(',') + ')',
                desc : step.getDescriptionHtml(),
                track_length : step.getDistance().meters,
                road_cost : step.getDuration().seconds
            });
        }

        this.load_success_callback(dirbuf);
    },
    handle_errors : function(){
        var errbuf =  [];
        if (this.getStatus().code == G_GEO_UNKNOWN_ADDRESS)
            errbuf.push(gettext("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: ") + this.getStatus().code);
        else if (this.getStatus().code == G_GEO_SERVER_ERROR)
            rrbuf.push(gettext("A geocoding or directions request could not be successfully processed, yet the exact reason for the failure is not known.\n Error code: ") + this.getStatus().code);

        else if (this.getStatus().code == G_GEO_MISSING_QUERY)
            errbuf.push(gettext("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: ") + this.getStatus().code);

        //   else if (this.service.getStatus().code == G_UNAVAILABLE_ADDRESS)  <--- Doc bug... this is either not defined, or Doc is wrong
        //     alert("The geocode for the given address or the route for the given directions query cannot be returned due to legal or contractual reasons.\n Error code: " + this.service.getStatus().code);

        else if (this.getStatus().code == G_GEO_BAD_KEY)
            errbuf.push(gettext("The given key is either invalid or does not match the domain for which it was given. \n Error code: ") + this.getStatus().code);

        else if (this.getStatus().code == G_GEO_BAD_REQUEST)
            errbuf.push(gettext("A directions request could not be successfully parsed.\n Error code: ") + this.getStatus().code);
        else errbuf.push(gettext("An unknown error occurred.\n Error code: ") + this.getStatus().code);
        this.load_error_callback(errbuf);
    }
};

