(function () {

    var trackSearch = angular.module('trackSearch', [
        'backend'
    ]);

    trackSearch.directive('trackSearch', function () {
        return {
            restrict: 'E',
            replace: true,
            scope: {
                selected: '=',
                mapcenter: '='
            },
            templateUrl: 'track-search/track-search.html',
            controller: 'TrackSearchCtrl'
        };
    });

    trackSearch.controller('TrackSearchCtrl', ['$scope', '$backend',  function ($scope, $backend) {
        $scope.searchTrackId = '';

        var trimLine = function (line) {
            if (line === undefined)
                return '';
            return line.replace(/(?:(?:^|\n)\s+|\s+(?:$|\n))/g, '');
        };

        $scope.searchAndCenter = function () {
            var idToSearch = trimLine($scope.searchTrackId);
            if (idToSearch === '')
                return;
            var track = $backend.getTrackById(idToSearch);
            if(track) {
                $scope.mapcenter = track.dynInfo;
                $scope.selected = track;
            }
            else {
                $scope.selected = undefined;
            }
        };
    }]);

}());

