if (typeof Redbaron == 'undefined') var Redbaron = {};

Redbaron.exception = function(errorCode) {
/*
    switch (errorCode){
        case 400 : console.log('Invalid Argument'); break; 
        case 401 : console.log('Class Cast Error Src'); break;
        case 402 : console.log('Class Cast Error Dst'); break;
        case 404 : console.log('Not Fount Routes'); break;
    }
*/
    var swf = swfobject.getObjectById('contents');
    if (typeof swf['setRouteResponse'] == 'function') {
        swf.setRouteResponse(errorCode);
    }
}

Redbaron.route = function(routes) {
    if (!$.isArray(routes)) {
        return Redbaron.exception(400);
    }

    if (routes.length !== 2) {
        return Redbaron.exception(400);
    }

    var from = routes[0];
    var to = routes[1];
    if (!from || !to) {
        return Redbaron.exception(400);
    }

    Redbaron.directions.clear();
    GEvent.addListener(Redbaron.directions, "load", function () {
        GEvent.clearListeners(Redbaron.directions, 'load');
        if (Redbaron.directions.getNumRoutes() < 1){
            return Redbaron.exception(404);
        }
        var route = Redbaron.directions.getRoute(0);
        var request = {};
        request.total_distance = route.getDistance().meters;
        request.total_duration = route.getDuration().seconds;

        request.start = {}
        request.start.name = from;
        request.start.lat = route.getStep(0).getLatLng().lat();
        request.start.lon = route.getStep(0).getLatLng().lng();
        request.goal = {}
        request.goal.name = to;
        request.goal.lat = route.getEndLatLng().lat();
        request.goal.lon = route.getEndLatLng().lng();

        request.routes = [];
        for (var i = 0; i < route.getNumSteps(); ++i) {
            var step = route.getStep(i);
            var stepMap = {};
            stepMap.lat = step.getLatLng().lat();
            stepMap.lon = step.getLatLng().lng();
            stepMap.distance = step.getDistance().meters;
            stepMap.duration = step.getDuration().seconds;
            request.routes.push(stepMap);
        }

        $.post('/api/route/receive/', { json : $.toJSON(request) }, function(data) {
                Redbaron.exception(data.code);
                }, 'json');

    }); 

    Redbaron.directions.load('from: ' + from + ' to: ' + to, {locale: 'ja_JP', getSteps: true, avoidHighways: true});
};

$(function() {
    if (GBrowserIsCompatible()) {
        Redbaron.map = new GMap2(document.getElementById("map"));
        Redbaron.directions = new GDirections(Redbaron.map);
    }
});

