<repo_name>alaponin/TindomondoClient<file_sep>/src/app/main/main.html
<div ng-controller="MainController as controller">
  <div>
      <div class = "text">Tindomondo helps you find<p>new companions for your<p>sport activities.</div>
        <div class = "citation">"If Tindomondo had been there in<p>my childhood, me and the whole<p>Estonian basketball community
                                <p>would definitely have<p>benefited from it!"</div>
          <div class = "name"><b><NAME> (BC TU/Rock)</b></div>

            <div class = "but"><button type="button" class="btn btn-default loginButton" data-ng-show="!controller.logged"
            data-ng-disabled="!controller.facebookReady && controller.buttonDisabled"
            data-ng-click="controller.IntentLogin()">Login with Facebook</button></div>
  </div>
</div>
<file_sep>/src/app/main/main.controller.js
(function() {
  'use strict';

  angular
    .module('client')
    .controller('MainController', MainController);

  /** @ngInject */
  function MainController($scope, $rootScope, $route, $timeout, Facebook, $http, $location, userService, $cookieStore) {
    var vm = this;

    // Define user empty data :/
    vm.user = {};

    // Defining user logged status
    vm.logged = false;
    vm.buttonDisabled = false;


    /**
     * Watch for Facebook to be ready.
     * There's also the event that could be used
     */
    $scope.$watch(
      function() {
        return Facebook.isReady();
      },
      function(newVal) {
        if (newVal)
          vm.facebookReady = true;
      }
    );

    var userIsConnected = false;

    Facebook.getLoginStatus(function(response) {
      if (response.status == 'connected') {
        userIsConnected = true;
        vm.logged = true;
        vm.me();
        $location.path('/eventList');
      }
    });

    /**
     * IntentLogin
     */
    vm.IntentLogin = function() {
      console.log("Before: ", vm.buttonDisabled);
      vm.buttonDisabled = true;
      console.log("After: ", vm.buttonDisabled);
      console.log("Login started!");
      if(!userIsConnected) {
        vm.login();
      }
    };

    /**
     * Login
     */
    vm.login = function() {
      Facebook.login(function(response) {

        if (response.status == 'connected') {
          vm.logged = true;
          vm.me();
        } else {
          vm.buttonDisabled = false;
        }

      }, {scope: 'email,public_profile'});
    };

    /**
     * me
     */
    vm.me = function() {
      Facebook.api('/me', function(response) {
        /**
         * Using $scope.$apply since this happens outside angular framework.
         */
        userService.createUser({name: response.name, fb_id: response.id});
        userService.getUserByFbId(response.id).then(function(response){
          $cookieStore.put('user_id',response.data.id);
        });
        $scope.$apply(function() {
          vm.user = response;
          $rootScope.$broadcast('fbLoginHappened', vm.user);
          $location.path('/eventList');
        });

      });
    };

    /**
     * Logout
     */
    vm.logout = function() {
      Facebook.logout(function() {
        $scope.$apply(function() {
          vm.user   = {};
          vm.logged = false;
          userIsConnected = false;
          $route.reload();
        });
      });
    };

    $rootScope.$on('logOutHappened', function() {
      vm.user   = {};
      vm.logged = false;
      userIsConnected = false;
      vm.buttonDisabled = false;
      $route.reload();
    });

  }
})();
<file_sep>/src/app/serverApi/registrationService.service.js
(function() {
  'use strict';

  angular
    .module('client')
    .service('registrationService', registrationService);

  /** @ngInject */
  function registrationService($http, $q, backendlink) {
    return {
      getRegistrations: function(data) {
        var registration = $q.defer();
        $http({
          method: 'GET',
          url: backendlink+'registrations.json',
          data: data
        }).then(function(data) {
          registration.resolve(data);
        });
        return registration.promise;
      },
      getRegistrationByEvent: function(data) {
        var registration = $q.defer();
        $http({
          method: 'GET',
          url: backendlink+'registrations/'+data+'.json',
        }).then(function(data) {
          registration.resolve(data);
        });
        return registration.promise;
      },
      createRegistration: function(data) {
        console.log(data);
        var registration = $q.defer();
        $http({
          method: 'POST',
          url: backendlink+'registrations.json',
          data: data
        }).then(function(data) {
          registration.resolve(data);
        });
        return registration.promise;
      },
      unjoinEvent: function(data) {
        console.log(data);
        var registration = $q.defer();
        $http({
          method: 'POST',
          url: backendlink+'registrations/unjoin',
          data: data
        }).then(function(data) {
          registration.resolve(data);
        });
        return registration.promise;
      },
      getUserRegistrations: function(data) {
        console.log(data);
        var registration = $q.defer();
        $http({
          method: 'GET',
          url: backendlink+'registrations/userevents?user_id='+data,
        }).then(function(data) {
          registration.resolve(data);
        });
        return registration.promise;
      },
      getUserEvents: function(data) {
        console.log(data);
        var registration = $q.defer();
        $http({
          method: 'GET',
          url: backendlink+'registrations/usereventid?user_id='+data.user_id+'&event_id='+data.event_id,
          data: data
        }).then(function(data) {
          registration.resolve(data);
        });
        return registration.promise;
      },
      getEventParticipants: function(data) {
        console.log(data);
        var registration = $q.defer();
        $http({
          method: 'GET',
          url: backendlink+'registrations/eventparticipants?event_id='+data,
          data: data
        }).then(function(data) {
          registration.resolve(data);
        });
        return registration.promise;
      },
      getParticipantsList: function(data) {
        console.log(data);
        var registration = $q.defer();
        $http({
          method: 'GET',
          url: backendlink+'registrations/eventparticipantslist?event_id='+data,
          data: data
        }).then(function(data) {
          registration.resolve(data);
        });
        return registration.promise;
      }
    }
  }
})();<file_sep>/src/app/components/navbar/navbar.controller.js
(function() {
  'use strict';

  angular
    .module('client')
    .controller('NavbarController', NavbarController);

  /** @ngInject */
  function NavbarController($scope, $rootScope, $timeout, Facebook, $route) {
    var vm = this;
    vm.loggedIn = false;
    vm.user = {};
    vm.profilePicImage = "";
    vm.facebookReady = true;

    vm.me = function() {
      Facebook.api('/me', function(response) {
        Facebook.api("/me/picture?type=large",
          function (response2) {
            if (response2 && !response2.error) {
              vm.profilePicImage = response2.data.url;
            }
          }
        );
        /**
         * Using $scope.$apply since this happens outside angular framework.
         */
        $scope.$apply(function() {
          vm.user = response;
        });

      });
    };

    vm.logout = function() {
      Facebook.logout(function() {
        $scope.$apply(function() {
          vm.user   = {};
          vm.loggedIn = false;
          vm.profilePicImage = "";
          $rootScope.$broadcast('logOutHappened');
          $route.reload();
        });
      });
    };

    $rootScope.$on('fbLoginHappened', function(ev, user) {
        vm.user   = user;
        vm.loggedIn = true;
        vm.me();
    });


  }

  angular
    .module('client')
    .controller('AppCtrl', function ($scope, $timeout, $mdSidenav, $log) {
      $scope.toggleLeft = buildDelayedToggler('left');
      $scope.toggleRight = buildToggler('right');
      $scope.isOpenRight = function(){
        return $mdSidenav('right').isOpen();
      };

      /**
       * Supplies a function that will continue to operate until the
       * time is up.
       */
      function debounce(func, wait, context) {
        var timer;

        return function debounced() {
          var context = $scope,
            args = Array.prototype.slice.call(arguments);
          $timeout.cancel(timer);
          timer = $timeout(function() {
            timer = undefined;
            func.apply(context, args);
          }, wait || 10);
        };
      }

      /**
       * Build handler to open/close a SideNav; when animation finishes
       * report completion in console
       */
      function buildDelayedToggler(navID) {
        return debounce(function() {
          $mdSidenav(navID)
            .toggle()
            .then(function () {
              $log.debug("toggle " + navID + " is done");
            });
        }, 200);
      }

      function buildToggler(navID) {
        return function() {
          $mdSidenav(navID)
            .toggle()
            .then(function () {
              $log.debug("toggle " + navID + " is done");
            });
        }
      }
    })
    .controller('LeftCtrl', function ($scope, $timeout, $mdSidenav, $log) {
      $scope.close = function () {
        $mdSidenav('left').close()
          .then(function () {
            $log.debug("close LEFT is done");
          });

      };
    })
    .controller('RightCtrl', function ($scope, $timeout, $mdSidenav, $log) {
      $scope.close = function () {
        $mdSidenav('right').close()
          .then(function () {
            $log.debug("close RIGHT is done");
          });
      };
    });



})();
<file_sep>/src/app/components/googleMaps/googleMaps.mock.js
window.google = {
  maps: {
    LatLng: function(lat, lng) {
      return {
        latitude: parseFloat(lat),
        longitude: parseFloat(lng)
      };
    },
    LatLngBounds: function(ne, sw) {
      return {};
    },
    DirectionsService: function() {
      return {
        route: function (request, callback) {
          return callback();
        }
      };
    },
    TravelMode: {
      DRIVING: 'DRIVING'
    }
  }
};<file_sep>/gulpfile.js
/**
 *  Welcome to your gulpfile!
 *  The gulp tasks are splitted in several files in the gulp directory
 *  because putting all here was really too long
 */

'use strict';

var gulp = require('gulp');
var wrench = require('wrench');
var rsync = require('gulp-rsync');
var gutil = require('gulp-util');
var push = require('git-push');
var argv = require('minimist')(process.argv.slice(2));


/**
 *  This will load all js or coffee files in the gulp directory
 *  in order to load all gulp tasks
 */
wrench.readdirSyncRecursive('./gulp').filter(function(file) {
  return (/\.(js|coffee)$/i).test(file);
}).map(function(file) {
  require('./gulp/' + file);
});


/**
 *  Default task clean temporaries directories and launch the
 *  main optimization build task
 */
gulp.task('default', ['clean'], function () {
  gulp.start('build');
});



gulp.task('deploy', function() {
  gulp.src('dist/**')
    .pipe(rsync({
      root: 'dist',
      hostname: 'tindomondo.com',
      username: 'TindoAdmin',
      destination: '~/production',
      incremental: true
    }));
});

gulp.task('rsync', function() {
  return gulp.src('./dist/**')
    .pipe(rsync({
      destination: '~/production',
      root: '~',
      hostname: 'tindomondo.com',
      username: 'TindoAdmin',
      incremental: true,
      progress: true,
      relative: true,
      emptyDirectories: true,
      recursive: true,
      clean: true,
      exclude: ['.DS_Store'],
      include: []
    }));
});

gulp.task('moveToDist', function() {
  push('./dist', 'https://github.com/alaponin/TindomondoClientDist', function() {
    console.log('Done!');
  });
});



<file_sep>/src/app/serverApi/sportService.service.js
(function() {
  'use strict';

  angular
    .module('client')
    .service('sportService', sportService);

  /** @ngInject */
  function sportService($http, $q, backendlink) {
    return {
      getSports: function(data) {
        var sport = $q.defer();
        $http({
          method: 'GET',
          url: backendlink+'/sports.json',
          data: data
        }).then(function(data) {
          sport.resolve(data);
        });
        return sport.promise;
      },
      getSport: function(data) {
        var sport = $q.defer();
        $http({
          method: 'GET',
          url: backendlink+'/sports/'+data+'.json',
        }).then(function(data) {
          sport.resolve(data);
        });
        return sport.promise;
      }
    }
  }

})();<file_sep>/src/app/components/eventList/eventList.controller.js
(function() {
  'use strict';

  angular
    .module('client')
    .controller('EventListController', EventListController);

  /** @ngInject */
  function EventListController($scope, $rootScope, eventService, sportService, Facebook) {
    var vm = this;
    vm.events = [];

    Facebook.api('/me', function(user) {
      $scope.$apply(function() {
        $rootScope.$broadcast('fbLoginHappened', user);
      });
    });

    eventService.getEvents().then(function(response) {
      var sports = [];
      sportService.getSports().then(function(sports_response){
        sports_response.data.forEach(function(sport) {
          sports[sport.id] = sport.name;
        });
        response.data.forEach(function(event) {
          var datetime = new Date(event.start_time);
          datetime = (datetime.getDate() + "-" + (datetime.getMonth() + 1) + "-" + datetime.getFullYear() + " " + datetime.toLocaleTimeString());

          vm.events.push(
              {event_id: event.id, sport_name: sports[event.sport_id], user_name: event.user_id, location: event.location, time: datetime}
          );
        });
      });
      $scope.events = vm.events;
  	});
  }
})();<file_sep>/src/app/serverApi/eventService.service.js
(function() {
  'use strict';

  angular
    .module('client')
    .service('eventService', eventService);

  /** @ngInject */
  function eventService($http, $q, backendlink) {
    return {
      getEvents: function(data) {
        var event = $q.defer();
        $http({
          method: 'GET',
          url: backendlink+'events.json',
          data: data
        }).then(function(data) {
          event.resolve(data);
        });
        return event.promise;
      },
      getEvent: function(data) {
        var event = $q.defer();
        $http({
          method: 'GET',
          url: backendlink+'events/'+data+'.json',
        }).then(function(data) {
          event.resolve(data);
        });
        return event.promise;
      },
      createEvent: function(data) {
        console.log(data);
        var event = $q.defer();
        $http({
          method: 'POST',
          url: backendlink+'events.json',
          data: data
        }).then(function(data) {
          event.resolve(data);
        });
        return event.promise;
        
      }
    }
  }

})();<file_sep>/src/app/index.route.js
(function() {
  'use strict';

  angular
    .module('client')
    .config(routerConfig);

  /** @ngInject */
  function routerConfig($stateProvider, $urlRouterProvider) {
    $stateProvider
      .state('home', {
        url: '/',
        templateUrl: 'app/main/main.html',
        controller: 'MainController',
        controllerAs: 'main'
      }).state('eventDetail', {
        url: '/eventDetail/:id',
        templateUrl: 'app/components/eventDetail/eventDetail.html',
        controller: 'EventController',
        onEnter: ['$state', 'Facebook', function($state, Facebook) {
          Facebook.getLoginStatus(function(response) {
            if (response.status != 'connected') {
              $state.go('home');
            }
          });
        }]
      }).state('addEvent', {
        url: '/addEvent',
        templateUrl: 'app/components/addEvent/addEvent.html',
        controller: 'addEventController',
        controllerAs: 'controller',
        onEnter: ['$state', 'Facebook', function($state, Facebook) {
          Facebook.getLoginStatus(function(response) {
            if (response.status != 'connected') {
              $state.go('home');
            }
          });
        }]
      }).state('eventList', {
        url: '/eventList',
        templateUrl: 'app/components/eventList/eventList.html',
        controller: 'EventListController',
        onEnter: ['$state', 'Facebook', function($state, Facebook) {
          Facebook.getLoginStatus(function(response) {
            if (response.status != 'connected') {
              $state.go('home');
            }
          });
        }]
      }).state('myEvents', {
        url: '/myEvents',
        templateUrl: 'app/components/myEvents/myEvents.html',
        controller: 'myEventsController',
        onEnter: ['$state', 'Facebook', function($state, Facebook) {
          Facebook.getLoginStatus(function(response) {
            if (response.status != 'connected') {
              $state.go('home');
            }
          });
        }]
      }).state('eventParticipants', {
        url: '/eventParticipants/:id',
        templateUrl: 'app/components/eventParticipants/eventParticipants.html',
        controller: 'EventParticipantsController',
        onEnter: ['$state', 'Facebook', function($state, Facebook) {
          Facebook.getLoginStatus(function(response) {
            if (response.status != 'connected') {
              $state.go('home');
            }
          });
        }]
      }).state('giveFeedback', {
        url: '/feedback',
        templateUrl: 'app/components/feedback/feedback.html',
        controller: 'giveFeedbackController',
        onEnter: ['$state', 'Facebook', function($state, Facebook) {
          Facebook.getLoginStatus(function(response) {
            if (response.status != 'connected') {
              $state.go('home');
            }
          });
        }]
      })

    $urlRouterProvider.otherwise('/');
  }

})();
<file_sep>/src/app/serverApi/feedbackService.service.js
(function() {
  'use strict';

  angular
    .module('client')
    .service('feedbackService', feedbackService);

  function feedbackService($http, $q, backendlink) {
    return {
      sendFeedback: function(data) {
        var event = $q.defer();
        $http({
          method: 'POST',
          url: backendlink+'feedbacks.json',
          data: data
        }).then(function(data) {
          event.resolve(data);
        });
        return event.promise;
      }
    }
  }
})();<file_sep>/src/app/components/addEvent/addEvent.controller.js
(function() {
  'use strict';

  angular
    .module('client')
    .controller('addEventController', addEventController);

  /** @ngInject */
  function addEventController($scope, $timeout, $state, $rootScope, Facebook, sportService, eventService, googleAddress, $cookieStore, $location, Notification) {
    var vm = this;
    vm.time = null;
    vm.minute = null;
    vm.sport = {};
    vm.participants;
    vm.place;
    $scope.eventData = {};
    vm.eventAddress = "Choose location on map";


    Facebook.api('/me', function(user) {
      $scope.$apply(function() {
        $rootScope.$broadcast('fbLoginHappened', user);
      });
    });

    vm.directionsService = new google.maps.DirectionsService();
    
    if (navigator.geolocation) {
      navigator.geolocation.getCurrentPosition(success);
    } else {
      error('Geo Location is not supported');
    }
    
    function success(position) {
        vm.map = {
        center: {
          latitude : position.coords.latitude,
          longitude : position.coords.longitude
        },
        bounds: new google.maps.LatLngBounds(),
        zoom: 15,
        options: {
          mapTypeControl: true,
          panControl: true,
          zoomControl: true,
          clickable: true
        },
        events: {
          click: function (mapModel, eventName, originalEventArgs) {
                  vm.markers = [];
                  var lat = originalEventArgs[0].latLng.lat();
                  var lng = originalEventArgs[0].latLng.lng();
                  var marker = {
                      id: 1,
                      coords: {
                          latitude: lat,
                          longitude: lng
                      }
                  };
                  vm.markers.push(marker);
                 ;
                  googleAddress.getAddress(lat, lng).then(function successCallback(response) {
                    vm.eventAddress = response.data.results[0].formatted_address;
                  });
                  $scope.$digest();
                  
                  
                  
              }
        }
      };
      
    }
    
    function error(err) {
        vm.map = {
        center: {
          latitude : 0,
          longitude : 0
        },
        bounds: new google.maps.LatLngBounds(),
        zoom: 1,
        options: {
          mapTypeControl: true,
          panControl: true,
          zoomControl: true,
          clickable: true
        },
        events: {
          click: function (mapModel, eventName, originalEventArgs) {
                  vm.markers = [];
                  var lat = originalEventArgs[0].latLng.lat();
                  var lng = originalEventArgs[0].latLng.lng();
                  var marker = {
                      id: 1,
                      coords: {
                          latitude: lat,
                          longitude: lng
                      }
                  };
                  vm.markers.push(marker);
                 ;
                  googleAddress.getAddress(lat, lng).then(function successCallback(response) {
                    vm.eventAddress = response.data.results[0].formatted_address;
                  });
                  $scope.$digest();
                  
                  
                  
              }
        }
      };
    };
    vm.markers = [];
    vm.markers.push(vm.marker);

  

    sportService.getSports().then(function(sports_response){
      vm.sports = [];
      sports_response.data.forEach(function(sport) {
        vm.sports.push(
            {id: sport.id, name: sport.name}
        );
      });
    });

    function convertTime() {

    }

    vm.createEvent = createEvent;

    function createEvent() {
      var start_date = new Date(vm.date);
      var start_time = new Date(vm.time);
      start_time = start_time.toTimeString();
      start_time = (start_time.split(" "))[0];
      var start = start_date.getFullYear() + "-" + (start_date.getMonth() + 1) + "-" + start_date.getDate() + " " + start_time;

      var eventData = {user_id: $cookieStore.get('user_id'), sport_id: vm.sport, start_time: start, duration: 2,
        registration_min: vm.registration_min, registration_limit: vm.registration_limit, location: vm.eventAddress, description: vm.description};
      eventService.createEvent(eventData).then(function() {
        Notification.success('Event was created.');
        $timeout(function() {
          $state.go('myEvents');
        }, 2000);
      });
    }



    vm.marker = {
          id: 0,
          coords: {
            latitude: 58.3661916,
            longitude: 26.69020660000001
          },
          options: { draggable: false, visible: true},
    };
    }
})();

angular
    .module('client').filter('range', function() {
  return function(input, min, max) {
    min = parseInt(min); //Make string input int
    max = parseInt(max);
    for (var i=min; i<max; i++)
      input.push(i);
    return input;
  };});
