﻿function CarAnimation() {
///<summary>Object holding functionality for the animated drive</summary

}

CarAnimation.prototype.init = function(map) {
///<summary>Method used when initializing the object.</summary>
///<param name="map">Google Maps object</param>
    this.RoutePlanner = RoutePlanner;
    this.driveCar = true;
    this.animatedDistance = 0;
    this.map = map;
    
    this.animThread = null;
    this.carMarker = null;
    this.step = 5;      // metres
    this.ticktick = 60; // milliseconds
    this.k = 0;
    this.poly = null;
    this.eol = null;

    this.car = new GIcon();
    this.car.image = '/images/icons/routeplanner/cabriolet-32x32.png';
    this.car.iconSize = new GSize(32, 32);
    this.car.iconAnchor = new GPoint(16, 16);

    this.map = map;

    return this;
};

CarAnimation.prototype.start = function() {
    ///<summary>Method used when starting the animated drive</summary>
    if (this.RoutePlanner.finalDirs.getRoute(0).getNumSteps() > 1) {
        this.driveCar = true;
        this.RoutePlanner.expandAllRoutePoints();

        if (this.animatedDistance > 0) {
            this._animate(this.animatedDistance, this);
        } else {
            $('btnSearch').disabled = true;
            $('search').disabled = true;
            
            this.map.savePosition();
            this._animate(0, this);
        }
    }
};

CarAnimation.prototype.stop = function() {
///<summary>Method used when stopping the animated drive</summary>
    this.driveCar = false;
    this.animatedDistance = 0;
    this.map.returnToSavedPosition();
    this.map.removeOverlay(this.carMarker);
    this.carMarker = null;
    this.RoutePlanner.minimizeAllRoutePoints();
    
    $('btnSearch').disabled = false;
    $('search').disabled = false;

    clearTimeout(this.animThread);
};

CarAnimation.prototype.pause = function() {
///<summary>Method used when pausing the animated drive</summary>
    this.driveCar = false;
};

CarAnimation.prototype._animate = function(d, obj) {
    var _self = obj;
    var poly = _self.RoutePlanner.finalDirs.getPolyline();

    _self.animatedDistance = d;

    if (d == 0) {
        this.eol = poly.Distance();
        _self.map.setCenter(poly.getVertex(0), 15);
        _self.carMarker = new GMarker(poly.getVertex(0), { icon: _self.car });
        _self.map.addOverlay(_self.carMarker);
    }
    if (_self.driveCar) {
        if (d > _self.eol) {
            alert('Du er fremme, på tide å strekke litt på bena?');
            return;
        }
        var p = poly.GetPointAtDistance(d);
        if (_self.k++ >= 180 / _self.step) {
            _self.map.panTo(p);
            _self.k = 0;
        }
        _self.carMarker.setLatLng(p);
        _self.animThread = setTimeout(function() { _self._animate((d + _self.step), _self) }, _self.tick);
    }
};