'use strict';

angular.module('<%=angularAppName%>')
    .factory('Tracker', function ($rootScope, $cookies, $http, $q) {
        var stompClient = null;
        var subscriber = null;
        var listener = $q.defer();
        var connected = $q.defer();
        function sendActivity() {
            if (stompClient != null && stompClient.connected) {
                stompClient
                    .send('/topic/activity',
                    {},
                    JSON.stringify({'page': $rootScope.toState.name}));
            }
        }
        return {
            connect: function () {
                var socket = new SockJS('/websocket/tracker');
                stompClient = Stomp.over(socket);
                var headers = {};
                headers['X-CSRF-TOKEN'] = $cookies[$http.defaults.xsrfCookieName];
                stompClient.connect(headers, function(frame) {
                    connected.resolve("success");
                    sendActivity();
                    $rootScope.$on('$stateChangeStart', function (event) {
                        sendActivity();
                    });
                });
            },
            subscribe: function() {
                connected.promise.then(function() {
                    subscriber = stompClient.subscribe("/topic/tracker", function(data) {
                        listener.notify(JSON.parse(data.body));
                    });
                }, null, null);
            },
            unsubscribe: function() {
                if (subscriber != null) {
                    subscriber.unsubscribe();
                }
            },
            receive: function() {
                return listener.promise;
            },
            sendActivity: function () {
                if (stompClient != null) {
                    sendActivity();
                }
            },
            disconnect: function() {
                if (stompClient != null) {
                    stompClient.disconnect();
                    stompClient = null;
                }
            }
        };
    });

@@ -241,32 +241,74 @@
 d = $q.defer();%0A
+        var alreadyConnectedOnce = false;%0A
         function
@@ -1005,32 +1005,85 @@
 sendActivity();%0A
+                    if (!alreadyConnectedOnce) %7B%0A    
                 
@@ -1157,32 +1157,36 @@
                 
+    
 sendActivity();%0A
@@ -1197,35 +1197,114 @@
                 
-%7D);
+    %7D);%0A                        alreadyConnectedOnce = true;%0A                    %7D
 %0A               

Check if the Tracker already looks for stateChangeStart