<commit_before>'use strict';

var app = angular.module('myApp.controllers', [
  'myApp.authentications.controller',
  'myApp.brands.controller',
  'myApp.boxes.controller',
  'myApp.heartbeats.controller',
  'myApp.jobs.controller',
  'myApp.invoices.controller',
  'myApp.locations.controller',
  'myApp.port_forwards.controller',
  'myApp.projects.controller',
  'myApp.reports.controller',
  'myApp.speedtests.controller',
  'myApp.splash_pages.controller',
  'myApp.registrations.controller',
  'myApp.zones.controller',
  'myApp.users.controller',
  'myApp.vouchers.controller'
]);

app.controller('MainCtrl', ['$rootScope', '$scope', '$localStorage', '$window', '$location', '$routeParams', 'AccessToken', 'RefreshToken', 'Auth', 'API_END_POINT', '$pusher', '$route', 'onlineStatus', '$cookies', 'Brand', 'locationHelper', 'BrandName', 'CTLogin', 'User', 'Me', 'AUTH_URL', 'menu', 'designer', '$mdSidenav', 'docs', '$mdMedia', '$q', 'INTERCOM', 'PUSHER', 'gettextCatalog', 'Translate', 'COMMITHASH', '$mdDialog',

  function ($rootScope, $scope, $localStorage, $window, $location, $routeParams, AccessToken, RefreshToken, Auth, API, $pusher, $route, onlineStatus, $cookies, Brand, locationHelper, BrandName, CTLogin, User, Me, AUTH_URL, menu, designer, $mdSidenav, docs, $mdMedia, $q, INTERCOM, PUSHER, gettextCatalog, Translate, COMMITHASH, $mdDialog) {

    var domain = 'ctapp.io';

    $scope.brandName  = BrandName;
    $scope.commit     = COMMITHASH;
    $scope.ct_login   = CTLogin;

    function isOpen(section) {
      return (menu.isSectionSelected(section) && menu.isOpen());
    }

    $scope.toggle = function(section){
      $mdSidenav(section || 'left').toggle();
    };

    var toggleOpen = function(){
      if ($mdMedia('gt-sm')) {
        vm.menu.isOpenLeft = false;
        menu.isOpen = !menu.isOpen;
        vm._ctm = !vm._ctm;
        $cookies.put('_ctm', !menu.isOpen);
      } else {
        vm.menu.isOpenLeft = !vm.menu.isOpenLeft;
      }
      $(window).trigger('resize');
    };

    function toggle(section) {
      menu.toggleSelectSection(section);
    }

    var vm = this;

    vm._ctm = $cookies.get('_ctm');
    vm.menu = menu;

    vm.designer = designer;
    vm.toggle = toggle;

    if ($cookies.get('_ctm') === 'true') {
      vm.menu.isOpenLeft = false;
      vm.menu.isOpen = false;
    }

    vm.menu.main = [];
    // vm.menu.reports = [];
    vm.settingsMenu = [];
    vm.menuRight = [];

    // vm.menu.reports.push({
    //   title: gettextCatalog.getString('Reports'),
    //   type: 'link',
    //   link: '/#/reports',
    //   icon: 'timeline'
    // });

    // vm.menu.reports.push({
    //   title: gettextCatalog.getString('Audit'),
    //   type: 'link',
    //   link: '/#/audit',
    //   icon: 'assignment'
    // });

    vm.status = {
      isFirstOpen: true,
      isFirstDisabled: false
    };

    vm.menuRight.push({
      name: gettextCatalog.getString('Home'),
      link: '/#/',
      type: 'link',
      icon: 'home'
    });

    vm.menuRight.push({
      name: gettextCatalog.getString('Locations'),
      link: '/#/locations',
      type: 'link',
      icon: 'business'
    });

    vm.menuRight.push({
      name: gettextCatalog.getString('Reports'),
      link: '/#/reports',
      type: 'link',
      icon: 'timeline'
    });

    // vm.menuRight.push({
    //   name: gettextCatalog.getString('Audit'),
    //   link: '/#/audit',
    //   type: 'link',
    //   icon: 'assignment'
    // });

    vm.menuRight.push({
      type: 'divider',
    });

    vm.menuRight.push({
      name: gettextCatalog.getString('Developer'),
      link: '/#/apps',
      type: 'link',
      icon: 'android'
    });

    // Permissions //
    if ($localStorage.user && !$localStorage.user.custom) {
      vm.menuRight.push({
        name: gettextCatalog.getString('Documentation'),
        link: 'http://docs.cucumberwifi.io',
        type: 'link',
        target: '_blank',
        icon: 'account_balance'
      });

      vm.menuRight.push({
        name: gettextCatalog.getString('Discussions'),
        link: 'https://discuss.cucumberwifi.io',
        target: '_blank',
        type: 'link',
        icon: 'forum'
      });

      vm.menuRight.push({
        name: gettextCatalog.getString('Support'),
        icon: 'get_app',
        id: 'intercom'
      });
    }

    vm.menuRight.push({
      name: gettextCatalog.getString('Support'),
      icon: 'get_app',
      id: 'intercom'
    });

    vm.menuRight.push({
      name: gettextCatalog.getString('Downloads'),
      link: '/#/downloads',
      type: 'link',
      icon: 'get_app'
    });

    vm.menuRight.push({
      type: 'divider',
    });

    vm.showPromo = function(offer) {
      $mdDialog.show({
        controller: TrialController,
        templateUrl: 'components/views/main/promos.tmpl.html',
        parent: angular.element(document.body),
        clickOutsideToClose:true,
        locals: {
          offer: offer
        },
        fullscreen: $scope.customFullscreen // Only for -xs, -sm breakpoints.
      });
    };

    function TrialController($scope, $mdDialog, $sce, offer) {
      $scope.offer = $sce.trustAsHtml(offer);
      $scope.hide = function() {
        $mdDialog.hide();
      };

      $scope.upgrade = function() {
        $mdDialog.hide();
        $location.path('/users/' + Auth.currentUser().slug + '/billing');
        $location.search({trial: 'y'});
      };
    }

    vm.showUpgrade = function() {
      $mdDialog.show({
        controller: DialogController,
        templateUrl: 'components/views/main/upgrade.tmpl.html',
        parent: angular.element(document.body),
        clickOutsideToClose:true,
        fullscreen: $scope.customFullscreen // Only for -xs, -sm breakpoints.
      });
    };

    function DialogController($scope, $mdDialog) {
      $scope.hide = function() {
        $mdDialog.hide();
      };

      $scope.upgrade = function() {
        $mdDialog.hide();
        $location.path('/users/' + Auth.currentUser().slug + '/billing');
      };
    }

    $scope.toggleOpen = toggleOpen;

    $scope.$on('logout', function(args) {
      logout().then(function(response) {
        $route.reload();
        console.log('Refreshing Token.');
      }, function() {
        Auth.fullLogin();
      });
    });

    var logout = function(args) {
      var deferred = $q.defer();
      var user = $localStorage.user;
      var path = $location.path();
      AccessToken.del();
      if ( user && user.refresh ) {
        var host  = locationHelper.domain();
        $cookies.put('_ctp', JSON.stringify(path) );
        RefreshToken.refresh(user.refresh, path).then(function(response) {
          Auth.refresh(response).then(function(a){
            deferred.resolve();
          });
        }, function(er) {
          deferred.reject();
        });
      } else {
        deferred.reject();
      }
      return deferred.promise;
    };

    $scope.$on('login', function(args,event) {
      console.log('Logging in...');
      doLogin(event);
    });

    function doLogin(event) {
      Auth.login(event.data).then(function(a) {
        var path;
        $scope.loggedIn = true;
        if (event.path) {
          path = event.path;
        } else {
          var raw = $cookies.get('_ctp');
          if (raw) {
            try{
              path = JSON.parse(raw);
            }catch(e){
              console.log('Couldn\'t parse JSON to redirect');
            }
          }
        }
        $location.path(path || '/').search(event.search || {});
        if (event !== undefined && event.rdir !== undefined) {
          $location.search({rdir: event.rdir});
        }
        $cookies.remove('_ctp');
        $scope.ct_login = undefined;
        // Translate.load();
      });
    }

    $scope.$on('intercom', function(args,event) {
      if (Auth.currentUser() && Auth.currentUser().user_hash !== undefined) {
        vm.menu.Intercom = true;
        window.intercomSettings = {
            app_id: INTERCOM,
            user_id: Auth.currentUser().accountId,
            reseller: Auth.currentUser().reseller,
            email: Auth.currentUser().email,
            name: Auth.currentUser().username,
            created_at: Auth.currentUser().created_at,
            user_hash: Auth.currentUser().user_hash,
            brand_name: Auth.currentUser().url,
            cname: Auth.currentUser().cname,
            sense_active: Auth.currentUser().sense_active,
            plan_name: Auth.currentUser().plan_name,
            paid_plan: Auth.currentUser().paid_plan,
            locs: Auth.currentUser().locs,
            version: '2',
            hide_default_launcher: !Auth.currentUser().chat_enabled || false
        };
      }

      // check for customers from reseller brands who aren't resellers
      if ($scope.brandName && $scope.brandName.reseller === true && Auth.currentUser().reseller !== true) {
        // check if there is a special brand intercom id, otherwise just hide it
        if ($scope.brandName.intercom_id) {
          window.intercomSettings.app_id = $scope.brandName.intercom_id;
        } else {
          window.intercomSettings.hide_default_launcher = true;
        }
      }
    });

    function promos() {
      User.promos({}, {
        action: 'promos',
        id: Auth.currentUser().slug
      }).$promise.then(function(results) {
        vm.promos = results;
      }, function() {
        if (Auth.currentUser().paid_plan !== true) {
          vm.upgrade = true;
        }
      });
    }

    function menuPush() {
      if (vm.menu.main.length === 0) {
        vm.menu.main.push({
          title: gettextCatalog.getString('Locations'),
          type: 'link',
          link: '/#/locations',
          icon: 'business'
        });

        if ($localStorage.user && ($localStorage.user.custom !== true || $localStorage.user.reseller === true)) {
          vm.menu.main.push({
            title: gettextCatalog.getString('Brands'),
            type: 'link',
            link: '/#/brands',
            icon: 'branding_watermark'
          });

          vm.menu.main.push({
            title: gettextCatalog.getString('Users'),
            type: 'link',
            link: '/#/users',
            icon: 'people'
          });

          vm.menuRight.push({
            name: gettextCatalog.getString('Brands'),
            type: 'link',
            link: '/#/brands',
            icon: 'branding_watermark'
          });

          vm.menuRight.push({
            name: gettextCatalog.getString('Users'),
            type: 'link',
            link: '/#/users',
            icon: 'people'
          });

          vm.menu.main.push({
            title: gettextCatalog.getString('Projects'),
            type: 'link',
            link: '/#/projects',
            icon: 'dns'
          });

          vm.menuRight.push({
            type: 'divider',
          });
        }

        vm.menuRight.push({
          name: gettextCatalog.getString('Profile'),
          link: '/#/me',
          type: 'link',
          icon: 'face'
        });

        vm.menuRight.push({
          type: 'divider',
        });
      }

      if (Auth.currentUser().promo !== '' && Auth.currentUser().promo !== null && Auth.currentUser().promo !== undefined) {
        promos();
      } else if (Auth.currentUser().paid_plan !== true) {
        vm.upgrade = true;
      }
    }

    var setDefaultImages = function(sub) {
      if ($localStorage.brandName) {
        $scope.brandName = $localStorage.brandName;
      } else {
        $scope.brandName.name = 'CT';
      }
    };

    function getBrand(sub, cname) {
      if (Auth.currentUser() && Auth.currentUser().url !== null) {
        sub = Auth.currentUser().url;
      }

      Brand.query({}, {
        id: sub,
        cname: cname,
        type: 'showcase'
      }).$promise.then(function(results) {
        // Decide to switch the brand here
        // Can we turn CT into a variable so we don't just set
        // Maybe use the config files - Simon TBD //

        var t = $cookies.get('_ctt');
        // if (t !== results.theme_primary) {
        $cookies.put('_ctt', results.theme_primary + '.' + results.theme_accent);
        // }
        $scope.brandName.name  = results.brand_name || 'CT';
        // Maybe use the config files - Simon TBD //
        $scope.brandName.admin = results.admin;
        $scope.brandName.url   = results.url;
        $scope.brandName.id    = results.id;
        $scope.brandName.intercom_id = results.intercom_id;
        $scope.brandName.logo_url = results.logo_url;
        $scope.brandName.reseller = results.reseller;
        $localStorage.brandName = $scope.brandName;
      }, function() {
        setDefaultImages(sub);
      });
    }

    var removeCtCookie = function() {
      $cookies.remove('_ct', { domain: domain });
    };

    function getSubdomain () {
      var sub   = locationHelper.subdomain();
      var host  = locationHelper.domain();
      var parts = $location.host().split('.');
      var cname;
      if (host !== 'ctapp.io' && host !== 'ctapp.dev') {
        getBrand(host, true);
      }
      else if (parts.length === 3) {
        sub = parts[0];
        if (sub !== 'dashboard' && sub !== 'alpha-preview' && sub !== 'dev-egg') {
          if (sub !== 'my') {
            getBrand(sub);
          }
          window.location.hostname = 'dashboard.' + host;
          return;
        }
        setDefaultImages();
      } else {
        window.location.hostname = 'dashboard.' + host;
        return;
      }
    }

    function getMe() {
      Me.get({}).$promise.then(function(res) {
        Auth.login(res).then(function(a) {
          $scope.user = Auth.currentUser();
          $scope.loggedIn = true;
          menuPush();
          if ($scope.user.promo !== '') {
            console.log('Getting promo...');
          }
        });
      });
    }

    function routeChangeStart() {
      var pusher;

      // If user logged in, load pusher
      if (Auth.currentUser() && Auth.currentUser().key !== null) {
        $scope.$broadcast('intercom', {hi: 'user'});
        window.client = new Pusher(PUSHER, {
          authEndpoint: API + '/pusherAuth?token=' + Auth.currentUser().key
        });
        pusher = $pusher(client);
      }

      var a = AccessToken.get();
      if ( (!Auth.currentUser() && a ) || Auth.currentUser() && (Auth.currentUser().url !== 'default' )) {
        getMe();
      }
      getSubdomain();

      // Translate.load();
    }

    var setLoggedIn = function(isLoggedIn) {
      $scope.loggedIn = isLoggedIn;
      return isLoggedIn;
    };

    setLoggedIn(AccessToken.get() !== undefined);

    $scope.logout = function() {
      Auth.logout();
    };

    // $scope.onlineStatus = onlineStatus;
    // if ( $scope.loggedIn ) {
      // $scope.$watch('onlineStatus.isOnline()', function(online) {
      //   $scope.online_status_string = online ? 'online' : 'offline';
      //   if ($scope.online_status_string === 'offline') {
      //     $scope.open('md');
      //   } else if ($scope.online_status_string === 'online' ){
      //     // if ($scope.modalInstance !== undefined) {
      //     //   $scope.modalInstance.close();
      //     // }
      //   }
      // });
    // }

    $rootScope.$on('$routeChangeStart', function (event, next, current) {
      routeChangeStart();
    });

}]);

app.controller( 'ParentCtrl', function ParentCtrl($scope, onlineStatus) {
});
<commit_msg>dont redirect custom url for resellers<commit_after>'use strict';

var app = angular.module('myApp.controllers', [
  'myApp.authentications.controller',
  'myApp.brands.controller',
  'myApp.boxes.controller',
  'myApp.heartbeats.controller',
  'myApp.jobs.controller',
  'myApp.invoices.controller',
  'myApp.locations.controller',
  'myApp.port_forwards.controller',
  'myApp.projects.controller',
  'myApp.reports.controller',
  'myApp.speedtests.controller',
  'myApp.splash_pages.controller',
  'myApp.registrations.controller',
  'myApp.zones.controller',
  'myApp.users.controller',
  'myApp.vouchers.controller'
]);

app.controller('MainCtrl', ['$rootScope', '$scope', '$localStorage', '$window', '$location', '$routeParams', 'AccessToken', 'RefreshToken', 'Auth', 'API_END_POINT', '$pusher', '$route', 'onlineStatus', '$cookies', 'Brand', 'locationHelper', 'BrandName', 'CTLogin', 'User', 'Me', 'AUTH_URL', 'menu', 'designer', '$mdSidenav', 'docs', '$mdMedia', '$q', 'INTERCOM', 'PUSHER', 'gettextCatalog', 'Translate', 'COMMITHASH', '$mdDialog',

  function ($rootScope, $scope, $localStorage, $window, $location, $routeParams, AccessToken, RefreshToken, Auth, API, $pusher, $route, onlineStatus, $cookies, Brand, locationHelper, BrandName, CTLogin, User, Me, AUTH_URL, menu, designer, $mdSidenav, docs, $mdMedia, $q, INTERCOM, PUSHER, gettextCatalog, Translate, COMMITHASH, $mdDialog) {

    var domain = 'ctapp.io';

    $scope.brandName  = BrandName;
    $scope.commit     = COMMITHASH;
    $scope.ct_login   = CTLogin;

    function isOpen(section) {
      return (menu.isSectionSelected(section) && menu.isOpen());
    }

    $scope.toggle = function(section){
      $mdSidenav(section || 'left').toggle();
    };

    var toggleOpen = function(){
      if ($mdMedia('gt-sm')) {
        vm.menu.isOpenLeft = false;
        menu.isOpen = !menu.isOpen;
        vm._ctm = !vm._ctm;
        $cookies.put('_ctm', !menu.isOpen);
      } else {
        vm.menu.isOpenLeft = !vm.menu.isOpenLeft;
      }
      $(window).trigger('resize');
    };

    function toggle(section) {
      menu.toggleSelectSection(section);
    }

    var vm = this;

    vm._ctm = $cookies.get('_ctm');
    vm.menu = menu;

    vm.designer = designer;
    vm.toggle = toggle;

    if ($cookies.get('_ctm') === 'true') {
      vm.menu.isOpenLeft = false;
      vm.menu.isOpen = false;
    }

    vm.menu.main = [];
    // vm.menu.reports = [];
    vm.settingsMenu = [];
    vm.menuRight = [];

    // vm.menu.reports.push({
    //   title: gettextCatalog.getString('Reports'),
    //   type: 'link',
    //   link: '/#/reports',
    //   icon: 'timeline'
    // });

    // vm.menu.reports.push({
    //   title: gettextCatalog.getString('Audit'),
    //   type: 'link',
    //   link: '/#/audit',
    //   icon: 'assignment'
    // });

    vm.status = {
      isFirstOpen: true,
      isFirstDisabled: false
    };

    vm.menuRight.push({
      name: gettextCatalog.getString('Home'),
      link: '/#/',
      type: 'link',
      icon: 'home'
    });

    vm.menuRight.push({
      name: gettextCatalog.getString('Locations'),
      link: '/#/locations',
      type: 'link',
      icon: 'business'
    });

    vm.menuRight.push({
      name: gettextCatalog.getString('Reports'),
      link: '/#/reports',
      type: 'link',
      icon: 'timeline'
    });

    // vm.menuRight.push({
    //   name: gettextCatalog.getString('Audit'),
    //   link: '/#/audit',
    //   type: 'link',
    //   icon: 'assignment'
    // });

    vm.menuRight.push({
      type: 'divider',
    });

    vm.menuRight.push({
      name: gettextCatalog.getString('Developer'),
      link: '/#/apps',
      type: 'link',
      icon: 'android'
    });

    // Permissions //
    if ($localStorage.user && !$localStorage.user.custom) {
      vm.menuRight.push({
        name: gettextCatalog.getString('Documentation'),
        link: 'http://docs.cucumberwifi.io',
        type: 'link',
        target: '_blank',
        icon: 'account_balance'
      });

      vm.menuRight.push({
        name: gettextCatalog.getString('Discussions'),
        link: 'https://discuss.cucumberwifi.io',
        target: '_blank',
        type: 'link',
        icon: 'forum'
      });

      vm.menuRight.push({
        name: gettextCatalog.getString('Support'),
        icon: 'get_app',
        id: 'intercom'
      });
    }

    vm.menuRight.push({
      name: gettextCatalog.getString('Support'),
      icon: 'get_app',
      id: 'intercom'
    });

    vm.menuRight.push({
      name: gettextCatalog.getString('Downloads'),
      link: '/#/downloads',
      type: 'link',
      icon: 'get_app'
    });

    vm.menuRight.push({
      type: 'divider',
    });

    vm.showPromo = function(offer) {
      $mdDialog.show({
        controller: TrialController,
        templateUrl: 'components/views/main/promos.tmpl.html',
        parent: angular.element(document.body),
        clickOutsideToClose:true,
        locals: {
          offer: offer
        },
        fullscreen: $scope.customFullscreen // Only for -xs, -sm breakpoints.
      });
    };

    function TrialController($scope, $mdDialog, $sce, offer) {
      $scope.offer = $sce.trustAsHtml(offer);
      $scope.hide = function() {
        $mdDialog.hide();
      };

      $scope.upgrade = function() {
        $mdDialog.hide();
        $location.path('/users/' + Auth.currentUser().slug + '/billing');
        $location.search({trial: 'y'});
      };
    }

    vm.showUpgrade = function() {
      $mdDialog.show({
        controller: DialogController,
        templateUrl: 'components/views/main/upgrade.tmpl.html',
        parent: angular.element(document.body),
        clickOutsideToClose:true,
        fullscreen: $scope.customFullscreen // Only for -xs, -sm breakpoints.
      });
    };

    function DialogController($scope, $mdDialog) {
      $scope.hide = function() {
        $mdDialog.hide();
      };

      $scope.upgrade = function() {
        $mdDialog.hide();
        $location.path('/users/' + Auth.currentUser().slug + '/billing');
      };
    }

    $scope.toggleOpen = toggleOpen;

    $scope.$on('logout', function(args) {
      logout().then(function(response) {
        $route.reload();
        console.log('Refreshing Token.');
      }, function() {
        Auth.fullLogin();
      });
    });

    var logout = function(args) {
      var deferred = $q.defer();
      var user = $localStorage.user;
      var path = $location.path();
      AccessToken.del();
      if ( user && user.refresh ) {
        var host  = locationHelper.domain();
        $cookies.put('_ctp', JSON.stringify(path) );
        RefreshToken.refresh(user.refresh, path).then(function(response) {
          Auth.refresh(response).then(function(a){
            deferred.resolve();
          });
        }, function(er) {
          deferred.reject();
        });
      } else {
        deferred.reject();
      }
      return deferred.promise;
    };

    $scope.$on('login', function(args,event) {
      console.log('Logging in...');
      doLogin(event);
    });

    function doLogin(event) {
      Auth.login(event.data).then(function(a) {
        var path;
        $scope.loggedIn = true;
        if (event.path) {
          path = event.path;
        } else {
          var raw = $cookies.get('_ctp');
          if (raw) {
            try{
              path = JSON.parse(raw);
            }catch(e){
              console.log('Couldn\'t parse JSON to redirect');
            }
          }
        }
        $location.path(path || '/').search(event.search || {});
        if (event !== undefined && event.rdir !== undefined) {
          $location.search({rdir: event.rdir});
        }
        $cookies.remove('_ctp');
        $scope.ct_login = undefined;
        // Translate.load();
      });
    }

    $scope.$on('intercom', function(args,event) {
      if (Auth.currentUser() && Auth.currentUser().user_hash !== undefined) {
        vm.menu.Intercom = true;
        window.intercomSettings = {
            app_id: INTERCOM,
            user_id: Auth.currentUser().accountId,
            reseller: Auth.currentUser().reseller,
            email: Auth.currentUser().email,
            name: Auth.currentUser().username,
            created_at: Auth.currentUser().created_at,
            user_hash: Auth.currentUser().user_hash,
            brand_name: Auth.currentUser().url,
            cname: Auth.currentUser().cname,
            sense_active: Auth.currentUser().sense_active,
            plan_name: Auth.currentUser().plan_name,
            paid_plan: Auth.currentUser().paid_plan,
            locs: Auth.currentUser().locs,
            version: '2',
            hide_default_launcher: !Auth.currentUser().chat_enabled || false
        };
      }

      // check for customers from reseller brands who aren't resellers
      if ($scope.brandName && $scope.brandName.reseller === true && Auth.currentUser().reseller !== true) {
        // check if there is a special brand intercom id, otherwise just hide it
        if ($scope.brandName.intercom_id) {
          window.intercomSettings.app_id = $scope.brandName.intercom_id;
        } else {
          window.intercomSettings.hide_default_launcher = true;
        }
      }
    });

    function promos() {
      User.promos({}, {
        action: 'promos',
        id: Auth.currentUser().slug
      }).$promise.then(function(results) {
        vm.promos = results;
      }, function() {
        if (Auth.currentUser().paid_plan !== true) {
          vm.upgrade = true;
        }
      });
    }

    function menuPush() {
      if (vm.menu.main.length === 0) {
        vm.menu.main.push({
          title: gettextCatalog.getString('Locations'),
          type: 'link',
          link: '/#/locations',
          icon: 'business'
        });

        if ($localStorage.user && ($localStorage.user.custom !== true || $localStorage.user.reseller === true)) {
          vm.menu.main.push({
            title: gettextCatalog.getString('Brands'),
            type: 'link',
            link: '/#/brands',
            icon: 'branding_watermark'
          });

          vm.menu.main.push({
            title: gettextCatalog.getString('Users'),
            type: 'link',
            link: '/#/users',
            icon: 'people'
          });

          vm.menuRight.push({
            name: gettextCatalog.getString('Brands'),
            type: 'link',
            link: '/#/brands',
            icon: 'branding_watermark'
          });

          vm.menuRight.push({
            name: gettextCatalog.getString('Users'),
            type: 'link',
            link: '/#/users',
            icon: 'people'
          });

          vm.menu.main.push({
            title: gettextCatalog.getString('Projects'),
            type: 'link',
            link: '/#/projects',
            icon: 'dns'
          });

          vm.menuRight.push({
            type: 'divider',
          });
        }

        vm.menuRight.push({
          name: gettextCatalog.getString('Profile'),
          link: '/#/me',
          type: 'link',
          icon: 'face'
        });

        vm.menuRight.push({
          type: 'divider',
        });
      }

      if (Auth.currentUser().promo !== '' && Auth.currentUser().promo !== null && Auth.currentUser().promo !== undefined) {
        promos();
      } else if (Auth.currentUser().paid_plan !== true) {
        vm.upgrade = true;
      }
    }

    var setDefaultImages = function(sub) {
      if ($localStorage.brandName) {
        $scope.brandName = $localStorage.brandName;
      } else {
        $scope.brandName.name = 'CT';
      }
    };

    function getBrand(sub, cname) {
      var deferred = $q.defer();
      if (Auth.currentUser() && Auth.currentUser().url !== null) {
        sub = Auth.currentUser().url;
      }

      Brand.query({}, {
        id: sub,
        cname: cname,
        type: 'showcase'
      }).$promise.then(function(results) {
        // Decide to switch the brand here
        // Can we turn CT into a variable so we don't just set
        // Maybe use the config files - Simon TBD //

        var t = $cookies.get('_ctt');
        // if (t !== results.theme_primary) {
        $cookies.put('_ctt', results.theme_primary + '.' + results.theme_accent);
        // }
        $scope.brandName.name  = results.brand_name || 'CT';
        // Maybe use the config files - Simon TBD //
        $scope.brandName.admin = results.admin;
        $scope.brandName.url   = results.url;
        $scope.brandName.id    = results.id;
        $scope.brandName.intercom_id = results.intercom_id;
        $scope.brandName.logo_url = results.logo_url;
        $scope.brandName.reseller = results.reseller;
        $localStorage.brandName = $scope.brandName;
        deferred.resolve();
      }, function() {
        deferred.reject();
        setDefaultImages(sub);
      });
      return deferred.promise;
    }

    var removeCtCookie = function() {
      $cookies.remove('_ct', { domain: domain });
    };

    function getSubdomain () {
      var sub   = locationHelper.subdomain();
      var host  = locationHelper.domain();
      var parts = $location.host().split('.');
      var cname;
      if (host !== 'ctapp.io' && host !== 'ctapp.dev') {
        getBrand(host, true);
      }
      else if (parts.length === 3) {
        sub = parts[0];
        if (sub !== 'dashboard' && sub !== 'alpha-preview' && sub !== 'dev-egg') {
          if (sub !== 'my') {
            getBrand(sub).then(function() {
              if ($scope.brandName.reseller !== true) {
                window.location.hostname = 'dashboard.' + host;
              }
            });
          }
          return;
        }
        setDefaultImages();
      } else {
        window.location.hostname = 'dashboard.' + host;
        return;
      }
    }

    function getMe() {
      Me.get({}).$promise.then(function(res) {
        Auth.login(res).then(function(a) {
          $scope.user = Auth.currentUser();
          $scope.loggedIn = true;
          menuPush();
          if ($scope.user.promo !== '') {
            console.log('Getting promo...');
          }
        });
      });
    }

    function routeChangeStart() {
      var pusher;

      // If user logged in, load pusher
      if (Auth.currentUser() && Auth.currentUser().key !== null) {
        $scope.$broadcast('intercom', {hi: 'user'});
        window.client = new Pusher(PUSHER, {
          authEndpoint: API + '/pusherAuth?token=' + Auth.currentUser().key
        });
        pusher = $pusher(client);
      }

      var a = AccessToken.get();
      if ( (!Auth.currentUser() && a ) || Auth.currentUser() && (Auth.currentUser().url !== 'default' )) {
        getMe();
      }
      getSubdomain();

      // Translate.load();
    }

    var setLoggedIn = function(isLoggedIn) {
      $scope.loggedIn = isLoggedIn;
      return isLoggedIn;
    };

    setLoggedIn(AccessToken.get() !== undefined);

    $scope.logout = function() {
      Auth.logout();
    };

    // $scope.onlineStatus = onlineStatus;
    // if ( $scope.loggedIn ) {
      // $scope.$watch('onlineStatus.isOnline()', function(online) {
      //   $scope.online_status_string = online ? 'online' : 'offline';
      //   if ($scope.online_status_string === 'offline') {
      //     $scope.open('md');
      //   } else if ($scope.online_status_string === 'online' ){
      //     // if ($scope.modalInstance !== undefined) {
      //     //   $scope.modalInstance.close();
      //     // }
      //   }
      // });
    // }

    $rootScope.$on('$routeChangeStart', function (event, next, current) {
      routeChangeStart();
    });

}]);

app.controller( 'ParentCtrl', function ParentCtrl($scope, onlineStatus) {
});
<|endoftext|>


<commit_before>'use strict';

import alt from '../alt';
import UserSource from '../sources/UserSource';
import WeightSource from '../sources/WeightSource';
import HeightSource from '../sources/HeightSource';
import GoalSource from '../sources/GoalSource';

class AppActions {
    constructor() {

    }

    getWeight() {
        this.getWeightInit();

        return (dispatch) => {
            WeightSource.fetch().then((weight)=>{
                this.getWeightSuccess(weight);
            })
        }

    }

    postWeight(data) {
        let weightData = data;
        this.postWeightInit();

        return (dispatch) => {
            WeightSource.post(weightData).then((data)=>{
                this.postWeightSuccess(weightData);
            })
        }

    }

    postHeight(data) {
        let heightData = data;
        this.postWeightInit();

        return (dispatch) => {
            HeightSource.post(heightData).then((data)=>{
                this.postHeightSuccess(heightData);
            })
        }

    }

    postGoal(data) {
        let goal = data;
        this.postWeightInit();

        return (dispatch) => {
            GoalSource.post(goal).then((data)=>{
                this.postGoalSuccess(goal);
            })
        }

    }

    getWeightInit() {
        this.isLoading = true;
    }

    postWeightInit() {
        this.isLoading = true;
    }

    getUser() {
        return (dispatch) => {
            dispatch();
            UserSource.fetch().then((user)=>{
                this.getUserSuccess(user);
            }).fail((e)=>{
                this.getUserError(e);
            })
        }

    }

    getUserSuccess(user) {
        return user;
    }

    getUserError(e) {
        window.location.hash = '';
        localStorage.removeItem('userToken');
        return {e};
    }

    getWeightSuccess(weight) {
        this.isLoading = false;
        return weight;
    }

    postWeightSuccess(data) {
        this.isLoading = false;
        return data;
    }

    postHeightSuccess(data) {
        this.isLoading = false;
        return data;
    }

    postGoalSuccess(data) {
        this.isLoading = false;
        return data;
    }

}

export default alt.createActions(AppActions);
<commit_msg>[client] handled calling the 2 endpoints to get the user data and the user meta data<commit_after>'use strict';

import alt from '../alt';
import UserSource from '../sources/UserSource';
import WeightSource from '../sources/WeightSource';
import HeightSource from '../sources/HeightSource';
import GoalSource from '../sources/GoalSource';

class AppActions {
    constructor() {

    }

    getWeight() {
        this.getWeightInit();

        return (dispatch) => {
            WeightSource.fetch().then((weight)=>{
                this.getWeightSuccess(weight);
            })
        }

    }

    postWeight(data) {
        let weightData = data;
        this.postWeightInit();

        return (dispatch) => {
            WeightSource.post(weightData).then((data)=>{
                this.postWeightSuccess(weightData);
            })
        }

    }

    postHeight(data) {
        let heightData = data;
        this.postWeightInit();

        return (dispatch) => {
            HeightSource.post(heightData).then((data)=>{
                this.postHeightSuccess(heightData);
            })
        }

    }

    postGoal(data) {
        let goal = data;
        this.postWeightInit();
        return (dispatch) => {
            GoalSource.post(goal).then((data)=>{
                this.postGoalSuccess(goal);
            })
        }

    }

    getWeightInit() {
        this.isLoading = true;
    }

    postWeightInit() {
        this.isLoading = true;
    }

    getUser() {
        return (dispatch) => {
            dispatch();
            UserSource.fetch().then((user)=>{
                UserSource.fetchMeta().then((meta)=>{
                    user.meta = meta;
                    this.getUserSuccess(user);
                })
            }).fail((e)=>{
                this.getUserError(e);
            })
        }

    }

    getUserSuccess(user) {
        return user;
    }

    getUserError(e) {
        window.location.hash = '';
        localStorage.removeItem('userToken');
        return {e};
    }

    getWeightSuccess(weight) {
        this.isLoading = false;
        return weight;
    }

    postWeightSuccess(data) {
        this.isLoading = false;
        return data;
    }

    postHeightSuccess(data) {
        this.isLoading = false;
        return data;
    }

    postGoalSuccess(data) {
        this.isLoading = false;
        return data;
    }

}

export default alt.createActions(AppActions);
<|endoftext|>


<commit_before>minerva.views.MapPanel = minerva.View.extend({

    events: {
        'click .m-save-current-baselayer': function () {
            this.session.sessionJsonContents.center = this.map.center();
            this.session.sessionJsonContents.zoom = this.map.zoom();
            this.session.saveSession();
        }
    },

    addDataset: function (dataset) {
        // TODO HACK
        // deleting and re-adding ui layer to keep it on top
        //this.map.deleteLayer(this.uiLayer);
        // this causes a problem when there are at least two feature layers,
        // so for now it is commented out
        // this means we keep re-adding the ui layer each time a dataset is
        // added as a feature layer, which is even more of a HACK
        if( dataset.get('meta').minerva.original_type === 'wms' ) {
            var baseUrl = dataset.get('meta').minerva.base_url;
            var layer = JSON.parse(dataset.get('meta').minerva.wms_params).layerName.slice(8);
            var wms = this.map.createLayer('osm');
            // TODO: Adding projection as a param ??
            var projection = 'EPSG:3857';
            wms.gcs(projection);

            wms.tileUrl(
                function (zoom, x, y) {

                  var xLowerLeft = geo.mercator.tilex2long(x, zoom);
                  var yLowerLeft = geo.mercator.tiley2lat(y + 1, zoom);
                  var xUpperRight = geo.mercator.tilex2long(x + 1, zoom);
                  var yUpperRight = geo.mercator.tiley2lat(y, zoom);

                  var sw = geo.mercator.ll2m(xLowerLeft, yLowerLeft, true);
                  var ne = geo.mercator.ll2m(xUpperRight, yUpperRight, true);
                  var bbox_mercator = sw.x + ',' + sw.y + ',' + ne.x + ',' + ne.y;
                  var params = {
                    'SERVICE': 'WMS',
                    'VERSION': '1.3.0',
                    'REQUEST': 'GetMap',
                    'LAYERS': layer,
                    'STYLES': '',
                    'BBOX': bbox_mercator,
                    'WIDTH': 256,
                    'HEIGHT': 256,
                    'FORMAT': 'image/png',
                    'TRANSPARENT': true,
                    'SRS': projection,
                    'TILED': true
                  };
                  return baseUrl + '?' + $.param(params);
                }
            );
        } else {
            if (!_.contains(this.datasets, dataset.id)) {

                dataset.once('m:dataLoaded', function (datasetId) {
                    var dataset = this.collection.get(datasetId);
                    var layer = this.map.createLayer('feature');

                    var reader = geo.createFileReader(dataset.geoFileReader, {layer: layer});
                    this.datasets[datasetId] = layer;

                    layer.clear();

                    reader.read(dataset.fileData, _.bind(function () {
                        this.uiLayer = this.map.createLayer('ui');
                        this.uiLayer.createWidget('slider');
                        this.map.draw();
                    }, this));
                }, this);

                dataset.loadData();
            }
        }
    },

    removeDataset: function (dataset) {
        var datasetId = dataset.id;
        var layer = this.datasets[datasetId];
        if (layer) {
            layer.clear();
            layer.draw();
            delete this.datasets[datasetId];
        }
    },

    initialize: function (settings) {
        girder.events.on('m:layerDatasetLoaded', this.addDataset, this);
        girder.events.on('m:layerDatasetRemoved', this.removeDataset, this);
        this.session = settings.session;
        this.listenTo(this.session, 'm:mapUpdated', function () {
            // TODO for now only dealing with center
            if (this.map) {
                // TODO could better separate geojs needs from session storage
                this.map.center(this.session.sessionJsonContents.center);
            }
        });
        this.datasets = {};
    },

    renderMap: function () {
        if (!this.map) {
            this.map = geo.map({
                node: '.mapPanelMap',
                center: this.session.sessionJsonContents.center,
                zoom: this.session.sessionJsonContents.zoom
            });
            this.map.createLayer(this.session.sessionJsonContents.basemap);
            this.uiLayer = this.map.createLayer('ui');
            this.uiLayer.createWidget('slider');
        }
        this.map.draw();
    },

    render: function () {
        this.$el.html(minerva.templates.mapPanel());
        this.renderMap();
        var tooltipProperties = {
            placement: 'left',
            delay: 400,
            container: this.$el,
            trigger: 'hover'
        };
        this.$('.m-save-current-baselayer').tooltip(tooltipProperties);
        return this;
    }
});
<commit_msg>Add the ability to remove WMS layers<commit_after>minerva.views.MapPanel = minerva.View.extend({

    events: {
        'click .m-save-current-baselayer': function () {
            this.session.sessionJsonContents.center = this.map.center();
            this.session.sessionJsonContents.zoom = this.map.zoom();
            this.session.saveSession();
        }
    },

    addDataset: function (dataset) {
        // TODO HACK
        // deleting and re-adding ui layer to keep it on top
        //this.map.deleteLayer(this.uiLayer);
        // this causes a problem when there are at least two feature layers,
        // so for now it is commented out
        // this means we keep re-adding the ui layer each time a dataset is
        // added as a feature layer, which is even more of a HACK
        if( dataset.get('meta').minerva.original_type === 'wms' ) {
            var layerId = dataset.get('id');
            var baseUrl = dataset.get('meta').minerva.base_url;
            var layer = JSON.parse(dataset.get('meta').minerva.wms_params).layerName.slice(8);
            this.wmsLayers[layerId] = this.map.createLayer('osm');
            // TODO: Adding projection as a param ??
            var projection = 'EPSG:3857';
            this.wmsLayers[layerId].gcs(projection);

            this.wmsLayers[layerId].tileUrl(
                function (zoom, x, y) {

                  var xLowerLeft = geo.mercator.tilex2long(x, zoom);
                  var yLowerLeft = geo.mercator.tiley2lat(y + 1, zoom);
                  var xUpperRight = geo.mercator.tilex2long(x + 1, zoom);
                  var yUpperRight = geo.mercator.tiley2lat(y, zoom);

                  var sw = geo.mercator.ll2m(xLowerLeft, yLowerLeft, true);
                  var ne = geo.mercator.ll2m(xUpperRight, yUpperRight, true);
                  var bbox_mercator = sw.x + ',' + sw.y + ',' + ne.x + ',' + ne.y;
                  var params = {
                    'SERVICE': 'WMS',
                    'VERSION': '1.3.0',
                    'REQUEST': 'GetMap',
                    'LAYERS': layer,
                    'STYLES': '',
                    'BBOX': bbox_mercator,
                    'WIDTH': 256,
                    'HEIGHT': 256,
                    'FORMAT': 'image/png',
                    'TRANSPARENT': true,
                    'SRS': projection,
                    'TILED': true
                  };
                  return baseUrl + '?' + $.param(params);
                }
            );
        } else {
            if (!_.contains(this.datasets, dataset.id)) {

                dataset.once('m:dataLoaded', function (datasetId) {
                    var dataset = this.collection.get(datasetId);
                    var layer = this.map.createLayer('feature');

                    var reader = geo.createFileReader(dataset.geoFileReader, {layer: layer});
                    this.datasets[datasetId] = layer;

                    layer.clear();

                    reader.read(dataset.fileData, _.bind(function () {
                        this.uiLayer = this.map.createLayer('ui');
                        this.uiLayer.createWidget('slider');
                        this.map.draw();
                    }, this));
                }, this);

                dataset.loadData();
            }
        }
    },

    removeDataset: function (dataset) {
        var datasetId = dataset.id;
        var layerId = dataset.get('id');
        var layer = this.datasets[datasetId];
        if (layer) {
            layer.clear();
            layer.draw();
            delete this.datasets[datasetId];
        }
        // Remove WMS layer, if any
        this.map.deleteLayer(this.wmsLayers[layerId]);
    },

    initialize: function (settings) {
        girder.events.on('m:layerDatasetLoaded', this.addDataset, this);
        girder.events.on('m:layerDatasetRemoved', this.removeDataset, this);
        this.session = settings.session;
        this.listenTo(this.session, 'm:mapUpdated', function () {
            // TODO for now only dealing with center
            if (this.map) {
                // TODO could better separate geojs needs from session storage
                this.map.center(this.session.sessionJsonContents.center);
            }
        });
        this.datasets = {};
        this.wmsLayers = {};
    },

    renderMap: function () {
        if (!this.map) {
            this.map = geo.map({
                node: '.mapPanelMap',
                center: this.session.sessionJsonContents.center,
                zoom: this.session.sessionJsonContents.zoom
            });
            this.map.createLayer(this.session.sessionJsonContents.basemap);
            this.uiLayer = this.map.createLayer('ui');
            this.uiLayer.createWidget('slider');
        }
        this.map.draw();
    },

    render: function () {
        this.$el.html(minerva.templates.mapPanel());
        this.renderMap();
        var tooltipProperties = {
            placement: 'left',
            delay: 400,
            container: this.$el,
            trigger: 'hover'
        };
        this.$('.m-save-current-baselayer').tooltip(tooltipProperties);
        return this;
    }
});
<|endoftext|>


<commit_before>/**
 * os-leaflet ; A [Leafletjs](http://leafletjs.com/) TileLayer to display Ordnance Survey
 *       data in your Leaflet map via the OS OpenSpace web map service.
 *
 * https://github.com/rob-murray/os-leaflet
 */
(function (root, factory) {
  // UMD for  Node, AMD or browser globals
  if (typeof define === 'function' && define.amd) {
    // AMD. Register as an anonymous module.
    define(['leaflet', 'proj4leaflet'], factory);
  } else if (typeof exports === 'object') {
    // Node & CommonJS-like environments.
    var L = require('leaflet'); // eslint-disable-line vars-on-top
    require('proj4leaflet');

    module.exports = factory(L);
  } else {
    // Browser globals
    if (typeof window.L === 'undefined') {
      throw new Error('Leaflet missing');
    }
    root.returnExports = factory(root.L);
  }
}(this, function (L) {
  /* This is our namespace for OSOpenSpace on Leaflet js */
  L.OSOpenSpace = L.OSOpenSpace || {};
  L.OSOpenSpace.CRS = L.extend(
    new L.Proj.CRS(
      'EPSG:27700',
      '+proj=tmerc +lat_0=49 +lon_0=-2 +k=0.9996012717 +x_0=400000 +y_0=-100000 +ellps=airy +datum=OSGB36 +units=m +no_defs', {
        resolutions: [2500, 1000, 500, 200, 100, 50, 25, 10, 5, 2.5]
      }
    ), {
      distance: function (a, b) {
        return L.CRS.Earth.distance(a, b);
      }
    }
  );

  L.OSOpenSpace.LogoControl = L.Control.extend({
    options: {
      position: 'bottomleft'
    },

    onAdd: function () {
      var container = L.DomUtil.create('div', 'os-logo-control');
      var logoImage = L.DomUtil.create('img', '', container);
      logoImage.title = 'Powered by OS OpenSpace';
      logoImage.src = 'data:image/png;base64,iVBORw0KGgoAAAANSUhEUgAAAEIAAAA7CAMAAAD4p6zTAAAAdVBMVEUAAABDPYxDPY1AQI9EPY5EPoxEPY3///9EPY3z8/iWkr+KhrhzbqrEB1FnYaJbVZtQSZR+erGinsb00d7Fwtv78PTwwdTQz+PTRX3IF1zc2+ro5/Gtqs25ttTig6jaZJLtssn44OnLJmfpor7lk7PPNnLWVYfBOrQkAAAAB3RSTlMAUJ8Qv8+vnqzJJAAAAmNJREFUeAHl14Vi2zAUheHyuVds5nD6/o84211YcsHj/aVA85lBd0P3T/S1nu7vxh5fiIyIP58wRA+PA/FApsHXagw9DEtBhvHV2FC/LM/U4Os19Hx3RwZzMtQTAnMSAxFjTvE5QaRkg4lUARRqkgDLaC6BVHWOhBToeo9qS4adU4JIsCJrB8I5Em0EmM5HxMIJV7ORFhGlXWRaRDHVtWN2MkJNI9GwjYlrBx9RFE2sgFjZwrUy6kgpJQit6/+6DjDfFySOZStFYEFQWEbUCisb59imYKbxtVrKw1wwVFtY14QISGcN15TCSHSkXEdAZI1t+h83EtYaholwSxxqahzj4uy1gk9P2BYe4jOxFZhJ9P0vRN1K1RenjIvWu2WJbblIME1wa+mYbM6Ape7DbqP1ZjtFpJYuEoc5WVV6aLB6pcyChKDrTP0m6LcwttBVEiAk3eYGY11dEMir0k9I8uUYWOpLAknuJVLypwB9aHqjsqNAHZYfI2IKZbH+GGEpWIrXA5HkSZCoKZzE7kCUWleLzE/EFM4hPyN6ZOslJE3EOCf6tj5C0UTFNaFX84kqm03oxS0R0USM/TWx+ewWQVZeETq7IQoKF6Fvu78k8hsCjoJ1GFvnizAxvSSOceiMSD5zpMbwEbgl0JI/Ax/x6iFC29XVWCW3RO4l2JCnAiir/JoInDvBkf/sm1R6cUlUWYAAWkcXqQZD673ebLMTsUmmblGkOwMKHNpV/cwvF9lILLPpayqnQlkiFbUNzlst91onZVXu1n/mzcH8kcD88cj8UdGPGJvNHyH2PT7MHKfOHy1/Axgmj2KBwwXnAAAAAElFTkSuQmCC';

      return container;
    }
  });

  /**
   * A custom Layer for Ordnance Survey OpenSpace service.
   * Note: An API key is needed, see OS website for details
   *
   */
  L.OSOpenSpace.TileLayer = L.TileLayer.WMS.extend({

    initialize: function (apiKey, apiUrl, options) { // (String, String, Object)
      if (!apiKey) {
        throw new Error('OSOpenSpace layer requires an API Key parameter to function.');
      }
      apiUrl = typeof apiUrl !== 'undefined' ? apiUrl : 'file:///';

      L.TileLayer.WMS.prototype.initialize.call(this,
        'https://openspace.ordnancesurvey.co.uk/osmapapi/ts', {
          crs: L.OSOpenSpace.CRS,
          maxZoom: 14,
          minZoom: 0,
          tileSize: 200
        },
        options
      );

      this.wmsParams = {
        KEY: apiKey,
        FORMAT: 'image/png',
        URL: apiUrl,
        REQUEST: 'GetMap',
        WIDTH: this.options.tileSize,
        HEIGHT: this.options.tileSize
      };
    },

    getAttribution: function () {
      return '© Crown copyright and database rights ' +
        new Date().getFullYear() +
        ' Ordnance Survey. ' +
        '' +
        'Terms of Use.';
    },

    onAdd: function (map) {
      if (map.options.attributionControl) {
        map.addControl(new L.OSOpenSpace.LogoControl());
      }
      L.TileLayer.prototype.onAdd.call(this, map);
    },

  /**
   * Return a url for this tile.
   * Calculate the bbox for the tilePoint and format the wms request
   */
    getTileUrl: function (tilePoint) { // (Point, Number) -> String
      var resolutionMpp = this.options.crs.options.resolutions[tilePoint.z],
        tileSizeMetres = this.options.tileSize * resolutionMpp,
        tileBboxX0 = tileSizeMetres * tilePoint.x,
        tileBboxY0 = tileSizeMetres * (-1 - tilePoint.y); // TODO: Is there a missing transformation ? tilePoint appears to be topLeft in this config

      // service is a tile based wms format and only requires x0, y0 - ignore other points
      this.wmsParams.BBOX = [tileBboxX0, tileBboxY0, 0, 0].join(',');
      this.wmsParams.LAYERS = resolutionMpp;

      return this._url + L.Util.getParamString(this.wmsParams); // eslint-disable-line no-underscore-dangle
    }
  });

  /*
   * Factory method to create a new OSOpenSpace tilelayer.
   *
   * @public
   * @param {string} apiKey Your API key for OSOpenSpace.
   * @param {string} apiUrl The URL of your site as provided to OSOpenSpace.
   * @param {object} options Any options to pass to the tilelayer.
   * @return {L.TileLayer} TileLayer for Ordnance Survey OpenSpace service.
   */
  L.OSOpenSpace.tilelayer = function (apiKey, apiUrl, options) {
    return new L.OSOpenSpace.TileLayer(apiKey, apiUrl, options);
  };

  return L.OSOpenSpace;
}));
<commit_msg>Assign default apiUrl if not set in function params<commit_after>/**
 * os-leaflet ; A [Leafletjs](http://leafletjs.com/) TileLayer to display Ordnance Survey
 *       data in your Leaflet map via the OS OpenSpace web map service.
 *
 * https://github.com/rob-murray/os-leaflet
 */
(function (root, factory) {
  // UMD for  Node, AMD or browser globals
  if (typeof define === 'function' && define.amd) {
    // AMD. Register as an anonymous module.
    define(['leaflet', 'proj4leaflet'], factory);
  } else if (typeof exports === 'object') {
    // Node & CommonJS-like environments.
    var L = require('leaflet'); // eslint-disable-line vars-on-top
    require('proj4leaflet');

    module.exports = factory(L);
  } else {
    // Browser globals
    if (typeof window.L === 'undefined') {
      throw new Error('Leaflet missing');
    }
    root.returnExports = factory(root.L);
  }
}(this, function (L) {
  /* This is our namespace for OSOpenSpace on Leaflet js */
  L.OSOpenSpace = L.OSOpenSpace || {};
  L.OSOpenSpace.CRS = L.extend(
    new L.Proj.CRS(
      'EPSG:27700',
      '+proj=tmerc +lat_0=49 +lon_0=-2 +k=0.9996012717 +x_0=400000 +y_0=-100000 +ellps=airy +datum=OSGB36 +units=m +no_defs', {
        resolutions: [2500, 1000, 500, 200, 100, 50, 25, 10, 5, 2.5]
      }
    ), {
      distance: function (a, b) {
        return L.CRS.Earth.distance(a, b);
      }
    }
  );

  L.OSOpenSpace.LogoControl = L.Control.extend({
    options: {
      position: 'bottomleft'
    },

    onAdd: function () {
      var container = L.DomUtil.create('div', 'os-logo-control');
      var logoImage = L.DomUtil.create('img', '', container);
      logoImage.title = 'Powered by OS OpenSpace';
      logoImage.src = 'data:image/png;base64,iVBORw0KGgoAAAANSUhEUgAAAEIAAAA7CAMAAAD4p6zTAAAAdVBMVEUAAABDPYxDPY1AQI9EPY5EPoxEPY3///9EPY3z8/iWkr+KhrhzbqrEB1FnYaJbVZtQSZR+erGinsb00d7Fwtv78PTwwdTQz+PTRX3IF1zc2+ro5/Gtqs25ttTig6jaZJLtssn44OnLJmfpor7lk7PPNnLWVYfBOrQkAAAAB3RSTlMAUJ8Qv8+vnqzJJAAAAmNJREFUeAHl14Vi2zAUheHyuVds5nD6/o84211YcsHj/aVA85lBd0P3T/S1nu7vxh5fiIyIP58wRA+PA/FApsHXagw9DEtBhvHV2FC/LM/U4Os19Hx3RwZzMtQTAnMSAxFjTvE5QaRkg4lUARRqkgDLaC6BVHWOhBToeo9qS4adU4JIsCJrB8I5Em0EmM5HxMIJV7ORFhGlXWRaRDHVtWN2MkJNI9GwjYlrBx9RFE2sgFjZwrUy6kgpJQit6/+6DjDfFySOZStFYEFQWEbUCisb59imYKbxtVrKw1wwVFtY14QISGcN15TCSHSkXEdAZI1t+h83EtYaholwSxxqahzj4uy1gk9P2BYe4jOxFZhJ9P0vRN1K1RenjIvWu2WJbblIME1wa+mYbM6Ape7DbqP1ZjtFpJYuEoc5WVV6aLB6pcyChKDrTP0m6LcwttBVEiAk3eYGY11dEMir0k9I8uUYWOpLAknuJVLypwB9aHqjsqNAHZYfI2IKZbH+GGEpWIrXA5HkSZCoKZzE7kCUWleLzE/EFM4hPyN6ZOslJE3EOCf6tj5C0UTFNaFX84kqm03oxS0R0USM/TWx+ewWQVZeETq7IQoKF6Fvu78k8hsCjoJ1GFvnizAxvSSOceiMSD5zpMbwEbgl0JI/Ax/x6iFC29XVWCW3RO4l2JCnAiir/JoInDvBkf/sm1R6cUlUWYAAWkcXqQZD673ebLMTsUmmblGkOwMKHNpV/cwvF9lILLPpayqnQlkiFbUNzlst91onZVXu1n/mzcH8kcD88cj8UdGPGJvNHyH2PT7MHKfOHy1/Axgmj2KBwwXnAAAAAElFTkSuQmCC';

      return container;
    }
  });

  /**
   * A custom Layer for Ordnance Survey OpenSpace service.
   * Note: An API key is needed, see OS website for details
   *
   */
  L.OSOpenSpace.TileLayer = L.TileLayer.WMS.extend({

    initialize: function (apiKey, apiUrl, options) { // (String, String, Object)
      if (!apiKey) {
        throw new Error('OSOpenSpace layer requires an API Key parameter to function.');
      }
      if (!apiUrl) {
        apiUrl = 'file:///';
      }

      L.TileLayer.WMS.prototype.initialize.call(this,
        'https://openspace.ordnancesurvey.co.uk/osmapapi/ts', {
          crs: L.OSOpenSpace.CRS,
          maxZoom: 14,
          minZoom: 0,
          tileSize: 200
        },
        options
      );

      this.wmsParams = {
        KEY: apiKey,
        FORMAT: 'image/png',
        URL: apiUrl,
        REQUEST: 'GetMap',
        WIDTH: this.options.tileSize,
        HEIGHT: this.options.tileSize
      };
    },

    getAttribution: function () {
      return '© Crown copyright and database rights ' +
        new Date().getFullYear() +
        ' Ordnance Survey. ' +
        '' +
        'Terms of Use.';
    },

    onAdd: function (map) {
      if (map.options.attributionControl) {
        map.addControl(new L.OSOpenSpace.LogoControl());
      }
      L.TileLayer.prototype.onAdd.call(this, map);
    },

  /**
   * Return a url for this tile.
   * Calculate the bbox for the tilePoint and format the wms request
   */
    getTileUrl: function (tilePoint) { // (Point, Number) -> String
      var resolutionMpp = this.options.crs.options.resolutions[tilePoint.z],
        tileSizeMetres = this.options.tileSize * resolutionMpp,
        tileBboxX0 = tileSizeMetres * tilePoint.x,
        tileBboxY0 = tileSizeMetres * (-1 - tilePoint.y); // TODO: Is there a missing transformation ? tilePoint appears to be topLeft in this config

      // service is a tile based wms format and only requires x0, y0 - ignore other points
      this.wmsParams.BBOX = [tileBboxX0, tileBboxY0, 0, 0].join(',');
      this.wmsParams.LAYERS = resolutionMpp;

      return this._url + L.Util.getParamString(this.wmsParams); // eslint-disable-line no-underscore-dangle
    }
  });

  /*
   * Factory method to create a new OSOpenSpace tilelayer.
   *
   * @public
   * @param {string} apiKey Your API key for OSOpenSpace.
   * @param {string} apiUrl The URL of your site as provided to OSOpenSpace.
   * @param {object} options Any options to pass to the tilelayer.
   * @return {L.TileLayer} TileLayer for Ordnance Survey OpenSpace service.
   */
  L.OSOpenSpace.tilelayer = function (apiKey, apiUrl, options) {
    return new L.OSOpenSpace.TileLayer(apiKey, apiUrl, options);
  };

  return L.OSOpenSpace;
}));
<|endoftext|>


<commit_before><commit_msg>swallow 404 exceptions when getting ad groups, not 400 exceptions<commit_after><|endoftext|>


<commit_before>/* @flow */
/* globals MutationObserver */

import { noop } from 'shared/util'

// can we use __proto__?
export const hasProto = '__proto__' in {}

// Browser environment sniffing
export const inBrowser =
  typeof window !== 'undefined' &&
  Object.prototype.toString.call(window) !== '[object Object]'

export const UA = inBrowser && window.navigator.userAgent.toLowerCase()
export const isIE = UA && /msie|trident/.test(UA)
export const isIE9 = UA && UA.indexOf('msie 9.0') > 0
export const isEdge = UA && UA.indexOf('edge/') > 0
export const isAndroid = UA && UA.indexOf('android') > 0
export const isIOS = UA && /iphone|ipad|ipod|ios/.test(UA)

// detect devtools
export const devtools = inBrowser && window.__VUE_DEVTOOLS_GLOBAL_HOOK__

/* istanbul ignore next */
function isNative (Ctor: Function): boolean {
  return /native code/.test(Ctor.toString())
}

/**
 * Defer a task to execute it asynchronously.
 */
export const nextTick = (function () {
  const callbacks = []
  let pending = false
  let timerFunc

  function nextTickHandler () {
    pending = false
    const copies = callbacks.slice(0)
    callbacks.length = 0
    for (let i = 0; i < copies.length; i++) {
      copies[i]()
    }
  }

  // the nextTick behavior leverages the microtask queue, which can be accessed
  // via either native Promise.then or MutationObserver.
  // MutationObserver has wider support, however it is seriously bugged in
  // UIWebView in iOS >= 9.3.3 when triggered in touch event handlers. It
  // completely stops working after triggering a few times... so, if native
  // Promise is available, we will use it:
  /* istanbul ignore if */
  if (typeof Promise !== 'undefined' && isNative(Promise)) {
    var p = Promise.resolve()
    timerFunc = () => {
      p.then(nextTickHandler)
      // in problematic UIWebViews, Promise.then doesn't completely break, but
      // it can get stuck in a weird state where callbacks are pushed into the
      // microtask queue but the queue isn't being flushed, until the browser
      // needs to do some other work, e.g. handle a timer. Therefore we can
      // "force" the microtask queue to be flushed by adding an empty timer.
      if (isIOS) setTimeout(noop)
    }
  } else if (typeof MutationObserver !== 'undefined' && isNative(MutationObserver)) {
    // use MutationObserver where native Promise is not available,
    // e.g. IE11, iOS7, Android 4.4
    var counter = 1
    var observer = new MutationObserver(nextTickHandler)
    var textNode = document.createTextNode(String(counter))
    observer.observe(textNode, {
      characterData: true
    })
    timerFunc = () => {
      counter = (counter + 1) % 2
      textNode.data = String(counter)
    }
  } else {
    // fallback to setTimeout
    /* istanbul ignore next */
    timerFunc = setTimeout
  }

  return function queueNextTick (cb: Function, ctx?: Object) {
    const func = ctx
      ? function () { cb.call(ctx) }
      : cb
    callbacks.push(func)
    if (!pending) {
      pending = true
      timerFunc(nextTickHandler, 0)
    }
  }
})()

let _Set
/* istanbul ignore if */
if (typeof Set !== 'undefined' && isNative(Set)) {
  // use native Set when available.
  _Set = Set
} else {
  // a non-standard Set polyfill that only works with primitive keys.
  _Set = class Set {
    set: Object;
    constructor () {
      this.set = Object.create(null)
    }
    has (key: string | number) {
      return this.set[key] !== undefined
    }
    add (key: string | number) {
      this.set[key] = 1
    }
    clear () {
      this.set = Object.create(null)
    }
  }
}

export { _Set }
<commit_msg>fix coverage<commit_after>/* @flow */
/* globals MutationObserver */

import { noop } from 'shared/util'

// can we use __proto__?
export const hasProto = '__proto__' in {}

// Browser environment sniffing
export const inBrowser =
  typeof window !== 'undefined' &&
  Object.prototype.toString.call(window) !== '[object Object]'

export const UA = inBrowser && window.navigator.userAgent.toLowerCase()
export const isIE = UA && /msie|trident/.test(UA)
export const isIE9 = UA && UA.indexOf('msie 9.0') > 0
export const isEdge = UA && UA.indexOf('edge/') > 0
export const isAndroid = UA && UA.indexOf('android') > 0
export const isIOS = UA && /iphone|ipad|ipod|ios/.test(UA)

// detect devtools
export const devtools = inBrowser && window.__VUE_DEVTOOLS_GLOBAL_HOOK__

/* istanbul ignore next */
function isNative (Ctor: Function): boolean {
  return /native code/.test(Ctor.toString())
}

/**
 * Defer a task to execute it asynchronously.
 */
export const nextTick = (function () {
  const callbacks = []
  let pending = false
  let timerFunc

  function nextTickHandler () {
    pending = false
    const copies = callbacks.slice(0)
    callbacks.length = 0
    for (let i = 0; i < copies.length; i++) {
      copies[i]()
    }
  }

  // the nextTick behavior leverages the microtask queue, which can be accessed
  // via either native Promise.then or MutationObserver.
  // MutationObserver has wider support, however it is seriously bugged in
  // UIWebView in iOS >= 9.3.3 when triggered in touch event handlers. It
  // completely stops working after triggering a few times... so, if native
  // Promise is available, we will use it:
  /* istanbul ignore if */
  if (typeof Promise !== 'undefined' && isNative(Promise)) {
    var p = Promise.resolve()
    timerFunc = () => {
      p.then(nextTickHandler)
      // in problematic UIWebViews, Promise.then doesn't completely break, but
      // it can get stuck in a weird state where callbacks are pushed into the
      // microtask queue but the queue isn't being flushed, until the browser
      // needs to do some other work, e.g. handle a timer. Therefore we can
      // "force" the microtask queue to be flushed by adding an empty timer.
      if (isIOS) setTimeout(noop)
    }
  } else if (typeof MutationObserver !== 'undefined' && (
    isNative(MutationObserver) ||
    // PhantomJS and iOS 7.x
    MutationObserver.toString() === '[object MutationObserverConstructor]'
  )) {
    // use MutationObserver where native Promise is not available,
    // e.g. PhantomJS IE11, iOS7, Android 4.4
    var counter = 1
    var observer = new MutationObserver(nextTickHandler)
    var textNode = document.createTextNode(String(counter))
    observer.observe(textNode, {
      characterData: true
    })
    timerFunc = () => {
      counter = (counter + 1) % 2
      textNode.data = String(counter)
    }
  } else {
    // fallback to setTimeout
    /* istanbul ignore next */
    timerFunc = setTimeout
  }

  return function queueNextTick (cb: Function, ctx?: Object) {
    const func = ctx
      ? function () { cb.call(ctx) }
      : cb
    callbacks.push(func)
    if (!pending) {
      pending = true
      timerFunc(nextTickHandler, 0)
    }
  }
})()

let _Set
/* istanbul ignore if */
if (typeof Set !== 'undefined' && isNative(Set)) {
  // use native Set when available.
  _Set = Set
} else {
  // a non-standard Set polyfill that only works with primitive keys.
  _Set = class Set {
    set: Object;
    constructor () {
      this.set = Object.create(null)
    }
    has (key: string | number) {
      return this.set[key] !== undefined
    }
    add (key: string | number) {
      this.set[key] = 1
    }
    clear () {
      this.set = Object.create(null)
    }
  }
}

export { _Set }
<|endoftext|>


<commit_before>/* global MessageChannel, performance, Promise */
var re = require('../vr-register-element');
var registerElement = re.registerElement;
var isNode = re.isNode;

var THREE = require('../../lib/three');
var RStats = require('../../lib/vendor/rStats');
var TWEEN = require('tween.js');
var VRNode = require('./vr-node');
var utils = require('../vr-utils');

var DEFAULT_LIGHT_ATTR = 'data-aframe-default-light';

var VRScene = module.exports = registerElement(
  'vr-scene',
  {
    prototype: Object.create(
      VRNode.prototype, {
        attributeChangedCallback: {
          value: function (attr, oldVal, newVal) {
            if (oldVal === newVal) { return; }
            if (attr === 'stats') { this.setupStats(); }
          }
        },

        attachedCallback: {
          value: function () {
            this.insideIframe = window.top !== window.self;
            this.insideLoader = false;
            this.defaultLightsEnabled = true;
            this.vrButton = null;
            this.setupStats();
            this.setupScene();
            this.attachEventListeners();
            this.attachFullscreenListeners();
            // For Chrome: https://github.com/MozVR/aframe-core/issues/321
            window.addEventListener('load', this.resizeCanvas.bind(this));
          }
        },

        detachedCallback: {
          value: function () {
            this.shutdown();
          }
        },

        shutdown: {
          value: function () {
            window.cancelAnimationFrame(this.animationFrameID);
          }
        },

        attachEventListeners: {
          value: function () {
            var self = this;
            var elementLoaded = this.elementLoaded.bind(this);
            this.pendingElements = 0;
            var assets = document.querySelector('vr-assets');
            if (assets && !assets.hasLoaded) {
              this.pendingElements++;
              attachEventListener(assets);
            }

            var children = this.querySelectorAll('*');
            Array.prototype.slice.call(children).forEach(countElement);

            function countElement (node) {
              if (!isNode(node)) { return; }
              self.pendingElements++;
              if (!node.hasLoaded) {
                attachEventListener(node);
              } else {
                elementLoaded(node);
              }
            }

            function attachEventListener (node) {
              node.addEventListener('loaded', function () {
                elementLoaded(node);
              });
            }
          }
        },

        attachMessageListeners: {
          value: function () {
            var self = this;
            window.addEventListener('message', function (e) {
              if (e.data) {
                switch (e.data.type) {
                  case 'loaderReady':
                    self.insideLoader = true;
                    self.removeEnterVrButton();
                    break;
                  case 'fullscreen':
                    switch (e.data.data) {
                      // Set renderer with fullscreen VR enter and exit.
                      case 'enter':
                        self.setStereoRenderer();
                        break;
                      case 'exit':
                        self.setMonoRenderer();
                        break;
                    }
                }
              }
            });
          }
        },

        attachFullscreenListeners: {
          value: function () {
            // handle fullscreen changes
            document.addEventListener('mozfullscreenchange',
                                      this.fullscreenChange.bind(this));
            document.addEventListener('webkitfullscreenchange',
                                      this.fullscreenChange.bind(this));
          }
        },

        fullscreenChange: {
          value: function (e) {
            // Switch back to the mono renderer if we have dropped out of
            // fullscreen VR mode.
            var fsElement = document.fullscreenElement ||
                            document.mozFullScreenElement ||
                            document.webkitFullscreenElement;

            // lock to landsape orientation on mobile.
            if (fsElement && utils.isMobile()) {
              window.screen.orientation.lock('landscape');
            }

            if (!fsElement) {
              this.renderer = this.monoRenderer;
            }
          }
        },

        elementLoaded: {
          value: function () {
            this.pendingElements--;
            // If we still need to wait for more elements.
            if (this.pendingElements > 0) { return; }
            // If the render loop is already running.
            if (this.renderLoopStarted) { return; }
            this.setupLoader();
            if (!this.cameraEl) {
              // If there's no user defined camera we
              // introduce a default one
              this.setupCamera();
              return;
            }
            this.resizeCanvas();
            // Kick off the render loop.
            this.render(performance.now());
            this.renderLoopStarted = true;
            this.load();
          }
        },

        createEnterVrButton: {
          value: function () {
            var vrButton = this.vrButton = document.createElement('button');
            vrButton.textContent = 'Enter VR';
            vrButton.className = 'vr-button';
            document.body.appendChild(vrButton);
            vrButton.addEventListener('click', this.enterVR.bind(this));
          }
        },

        removeEnterVrButton: {
          value: function () {
            if (this.vrButton) {
              this.vrButton.parentNode.removeChild(this.vrButton);
            }
          }
        },

        // returns a promise that resolves to true if loader is in VR mode.
        vrLoaderMode: {
          value: function () {
            return new Promise(function (resolve) {
              var channel = new MessageChannel();
              window.top.postMessage({type: 'checkVr'}, '*', [channel.port2]);
              channel.port1.onmessage = function (message) {
                resolve(!!message.data.data.isVr);
              };
            });
          }
        },

        setupLoader: {
          value: function () {
            var self = this;

            // Inside loader, check for VR mode before kicking off render loop.
            if (self.insideIframe) {
              self.attachMessageListeners();
              self.vrLoaderMode().then(function (isVr) {
                if (isVr) {
                  self.setStereoRenderer();
                } else {
                  self.setMonoRenderer();
                }
                window.top.postMessage({type: 'ready'}, '*');
              });
            }

            if (!self.insideLoader) {
              self.createEnterVrButton();
            }
          }
        },

        setStereoRenderer: {
          value: function () {
            this.renderer = this.stereoRenderer;
            this.resizeCanvas();
          }
        },

        setMonoRenderer: {
          value: function () {
            this.renderer = this.monoRenderer;
            this.resizeCanvas();
          }
        },

        setupStats: {
          value: function () {
            var statsEnabled = this.getAttribute('stats') === 'true';
            var statsEl = document.querySelector('.rs-base');
            if (!statsEnabled) {
              if (statsEl) { statsEl.classList.add('hidden'); }
              return;
            }
            if (statsEl) { statsEl.classList.remove('hidden'); }
            if (this.stats) { return; }
            this.stats = new RStats({
              CSSPath: '../../style/',
              values: {
                fps: { caption: 'Framerate (FPS)', below: 30 }
              },
              groups: [
                { caption: 'Framerate', values: [ 'fps' ] }
              ]
            });
          }
        },

        setupScene: {
          value: function () {
            // Three.js setup
            // We reuse the scene if there's already one
            var scene = this.object3D = (VRScene && VRScene.scene) || new THREE.Scene();
            VRScene.scene = scene;
            this.behaviors = [];
            // The canvas where the WebGL context will be painted
            this.setupCanvas();
            // The three.js renderer setup
            this.setupRenderer();
            // cursor camera setup
            this.setupCursor();
            this.setupDefaultLights();
          }
        },

        setupCanvas: {
          value: function () {
            var canvas = this.canvas = document.createElement('canvas');
            canvas.classList.add('vr-canvas');
            document.body.appendChild(canvas);
            window.addEventListener('resize', this.resizeCanvas.bind(this), false);
          }
        },

        setupCamera: {
          value: function () {
            var defaultCamera;
            // If there's a user defined camera
            if (this.cameraEl) { return; }
            // We create a default camera
            defaultCamera = document.createElement('vr-object');
            defaultCamera.setAttribute('camera', {fov: 45});
            defaultCamera.setAttribute('position', {x: 0, y: 0, z: 20});
            this.pendingElements++;
            defaultCamera.addEventListener('loaded',
                                           this.elementLoaded.bind(this));
            this.appendChild(defaultCamera);
          }
        },

        setupCursor: {
          value: function () {
            var cursor = this.querySelector('vr-cursor');
            if (cursor) {
              this.cursor = cursor;
            }
          }
        },

        /**
         * Prescibe default lights to the scene.
         * Does so by injecting markup such that this state is not invisible.
         * These lights are removed if the user adds any lights.
         */
        setupDefaultLights: {
          value: function () {
            var ambientLight = document.createElement('vr-object');
            ambientLight.setAttribute('light',
                                      {color: '#bebebe', type: 'ambient'});
            ambientLight.setAttribute(DEFAULT_LIGHT_ATTR, '');
            this.appendChild(ambientLight);

            var directionalLight = document.createElement('vr-object');
            directionalLight.setAttribute('light', {intensity: 2.5});
            directionalLight.setAttribute('position', {x: -10, y: 20, z: 10});
            directionalLight.setAttribute(DEFAULT_LIGHT_ATTR, '');
            this.appendChild(directionalLight);
          }
        },

        /**
         * Notify scene that light has been added and to remove the default
         *
         * @param {object} el - element holding the light component.
         */
        registerLight: {
          value: function (el) {
            if (this.defaultLightsEnabled &&
                !el.hasAttribute(DEFAULT_LIGHT_ATTR)) {
              // User added a light, remove default lights through DOM.
              var defaultLights = document.querySelectorAll(
                '[' + DEFAULT_LIGHT_ATTR + ']');
              for (var i = 0; i < defaultLights.length; i++) {
                this.removeChild(defaultLights[i]);
              }
              this.defaultLightsEnabled = false;
            }
          }
        },

        enterVR: {
          value: function () {
            this.renderer = this.stereoRenderer;
            this.setFullscreen();
          }
        },

        setFullscreen: {
          value: function () {
            var canvas = this.canvas;

            // Use the fullscreen method on effect when on desktop.
            if (!utils.isMobile()) {
              this.stereoRenderer.setFullScreen(true);
              return;
            }

            // For non-VR enabled mobile devices, the controls are polyfilled, but not the
            // vrDisplay, so the fullscreen method on the effect renderer does not work and
            // we request it here manually instead.
            if (canvas.requestFullscreen) {
              canvas.requestFullscreen();
            } else if (canvas.mozRequestFullScreen) {
              canvas.mozRequestFullScreen();
            } else if (canvas.webkitRequestFullscreen) {
              canvas.webkitRequestFullscreen();
            }
          }
        },

        setupRenderer: {
          value: function () {
            var canvas = this.canvas;
            var renderer = this.renderer = this.monoRenderer =
              (VRScene && VRScene.renderer) ||
              // To prevent creating multiple rendering contexts.
              new THREE.WebGLRenderer({canvas: canvas, antialias: true,
                                       alpha: true});
            renderer.setPixelRatio(window.devicePixelRatio);
            renderer.sortObjects = false;
            VRScene.renderer = renderer;
            this.stereoRenderer = new THREE.VREffect(renderer);
          }
        },

        resizeCanvas: {
          value: function () {
            var canvas = this.canvas;
            var camera = this.cameraEl.components.camera.camera;
            // Make it visually fill the positioned parent
            canvas.style.width = '100%';
            canvas.style.height = '100%';
            // Set the internal size to match
            canvas.width = canvas.offsetWidth;
            canvas.height = canvas.offsetHeight;
            // Updates camera
            camera.aspect = canvas.offsetWidth / canvas.offsetHeight;
            camera.updateProjectionMatrix();
            // Notify the renderer of the size change
            this.renderer.setSize(canvas.width, canvas.height);
          }
        },

        add: {
          value: function (el) {
            if (!el.object3D) { return; }
            this.object3D.add(el.object3D);
          }
        },

        addBehavior: {
          value: function (behavior) {
            this.behaviors.push(behavior);
          }
        },

        remove: {
          value: function (el) {
            if (!el.object3D) { return; }
            this.object3D.remove(el.object3D);
          }
        },

        render: {
          value: function (t) {
            var stats = this.stats;
            if (stats) {
              stats('rAF').tick();
              stats('FPS').frame();
            }
            var camera = this.cameraEl.components.camera.camera;
            TWEEN.update(t);
            // Updates behaviors
            this.behaviors.forEach(function (behavior) {
              behavior.update(t);
            });
            this.renderer.render(this.object3D, camera);
            if (stats) { stats().update(); }
            this.animationFrameID = window.requestAnimationFrame(
              this.render.bind(this));
          }
        }
      }
    )
  }
);
<commit_msg>update default cam pos to human height<commit_after>/* global MessageChannel, performance, Promise */
var re = require('../vr-register-element');
var registerElement = re.registerElement;
var isNode = re.isNode;

var THREE = require('../../lib/three');
var RStats = require('../../lib/vendor/rStats');
var TWEEN = require('tween.js');
var VRNode = require('./vr-node');
var utils = require('../vr-utils');

var DEFAULT_LIGHT_ATTR = 'data-aframe-default-light';

var VRScene = module.exports = registerElement(
  'vr-scene',
  {
    prototype: Object.create(
      VRNode.prototype, {
        attributeChangedCallback: {
          value: function (attr, oldVal, newVal) {
            if (oldVal === newVal) { return; }
            if (attr === 'stats') { this.setupStats(); }
          }
        },

        attachedCallback: {
          value: function () {
            this.insideIframe = window.top !== window.self;
            this.insideLoader = false;
            this.defaultLightsEnabled = true;
            this.vrButton = null;
            this.setupStats();
            this.setupScene();
            this.attachEventListeners();
            this.attachFullscreenListeners();
            // For Chrome: https://github.com/MozVR/aframe-core/issues/321
            window.addEventListener('load', this.resizeCanvas.bind(this));
          }
        },

        detachedCallback: {
          value: function () {
            this.shutdown();
          }
        },

        shutdown: {
          value: function () {
            window.cancelAnimationFrame(this.animationFrameID);
          }
        },

        attachEventListeners: {
          value: function () {
            var self = this;
            var elementLoaded = this.elementLoaded.bind(this);
            this.pendingElements = 0;
            var assets = document.querySelector('vr-assets');
            if (assets && !assets.hasLoaded) {
              this.pendingElements++;
              attachEventListener(assets);
            }

            var children = this.querySelectorAll('*');
            Array.prototype.slice.call(children).forEach(countElement);

            function countElement (node) {
              if (!isNode(node)) { return; }
              self.pendingElements++;
              if (!node.hasLoaded) {
                attachEventListener(node);
              } else {
                elementLoaded(node);
              }
            }

            function attachEventListener (node) {
              node.addEventListener('loaded', function () {
                elementLoaded(node);
              });
            }
          }
        },

        attachMessageListeners: {
          value: function () {
            var self = this;
            window.addEventListener('message', function (e) {
              if (e.data) {
                switch (e.data.type) {
                  case 'loaderReady':
                    self.insideLoader = true;
                    self.removeEnterVrButton();
                    break;
                  case 'fullscreen':
                    switch (e.data.data) {
                      // Set renderer with fullscreen VR enter and exit.
                      case 'enter':
                        self.setStereoRenderer();
                        break;
                      case 'exit':
                        self.setMonoRenderer();
                        break;
                    }
                }
              }
            });
          }
        },

        attachFullscreenListeners: {
          value: function () {
            // handle fullscreen changes
            document.addEventListener('mozfullscreenchange',
                                      this.fullscreenChange.bind(this));
            document.addEventListener('webkitfullscreenchange',
                                      this.fullscreenChange.bind(this));
          }
        },

        fullscreenChange: {
          value: function (e) {
            // Switch back to the mono renderer if we have dropped out of
            // fullscreen VR mode.
            var fsElement = document.fullscreenElement ||
                            document.mozFullScreenElement ||
                            document.webkitFullscreenElement;

            // lock to landsape orientation on mobile.
            if (fsElement && utils.isMobile()) {
              window.screen.orientation.lock('landscape');
            }

            if (!fsElement) {
              this.renderer = this.monoRenderer;
            }
          }
        },

        elementLoaded: {
          value: function () {
            this.pendingElements--;
            // If we still need to wait for more elements.
            if (this.pendingElements > 0) { return; }
            // If the render loop is already running.
            if (this.renderLoopStarted) { return; }
            this.setupLoader();
            if (!this.cameraEl) {
              // If there's no user defined camera we
              // introduce a default one
              this.setupCamera();
              return;
            }
            this.resizeCanvas();
            // Kick off the render loop.
            this.render(performance.now());
            this.renderLoopStarted = true;
            this.load();
          }
        },

        createEnterVrButton: {
          value: function () {
            var vrButton = this.vrButton = document.createElement('button');
            vrButton.textContent = 'Enter VR';
            vrButton.className = 'vr-button';
            document.body.appendChild(vrButton);
            vrButton.addEventListener('click', this.enterVR.bind(this));
          }
        },

        removeEnterVrButton: {
          value: function () {
            if (this.vrButton) {
              this.vrButton.parentNode.removeChild(this.vrButton);
            }
          }
        },

        // returns a promise that resolves to true if loader is in VR mode.
        vrLoaderMode: {
          value: function () {
            return new Promise(function (resolve) {
              var channel = new MessageChannel();
              window.top.postMessage({type: 'checkVr'}, '*', [channel.port2]);
              channel.port1.onmessage = function (message) {
                resolve(!!message.data.data.isVr);
              };
            });
          }
        },

        setupLoader: {
          value: function () {
            var self = this;

            // Inside loader, check for VR mode before kicking off render loop.
            if (self.insideIframe) {
              self.attachMessageListeners();
              self.vrLoaderMode().then(function (isVr) {
                if (isVr) {
                  self.setStereoRenderer();
                } else {
                  self.setMonoRenderer();
                }
                window.top.postMessage({type: 'ready'}, '*');
              });
            }

            if (!self.insideLoader) {
              self.createEnterVrButton();
            }
          }
        },

        setStereoRenderer: {
          value: function () {
            this.renderer = this.stereoRenderer;
            this.resizeCanvas();
          }
        },

        setMonoRenderer: {
          value: function () {
            this.renderer = this.monoRenderer;
            this.resizeCanvas();
          }
        },

        setupStats: {
          value: function () {
            var statsEnabled = this.getAttribute('stats') === 'true';
            var statsEl = document.querySelector('.rs-base');
            if (!statsEnabled) {
              if (statsEl) { statsEl.classList.add('hidden'); }
              return;
            }
            if (statsEl) { statsEl.classList.remove('hidden'); }
            if (this.stats) { return; }
            this.stats = new RStats({
              CSSPath: '../../style/',
              values: {
                fps: { caption: 'Framerate (FPS)', below: 30 }
              },
              groups: [
                { caption: 'Framerate', values: [ 'fps' ] }
              ]
            });
          }
        },

        setupScene: {
          value: function () {
            // Three.js setup
            // We reuse the scene if there's already one
            var scene = this.object3D = (VRScene && VRScene.scene) || new THREE.Scene();
            VRScene.scene = scene;
            this.behaviors = [];
            // The canvas where the WebGL context will be painted
            this.setupCanvas();
            // The three.js renderer setup
            this.setupRenderer();
            // cursor camera setup
            this.setupCursor();
            this.setupDefaultLights();
          }
        },

        setupCanvas: {
          value: function () {
            var canvas = this.canvas = document.createElement('canvas');
            canvas.classList.add('vr-canvas');
            document.body.appendChild(canvas);
            window.addEventListener('resize', this.resizeCanvas.bind(this), false);
          }
        },

        setupCamera: {
          value: function () {
            var defaultCamera;
            // If there's a user defined camera
            if (this.cameraEl) { return; }
            // We create a default camera
            defaultCamera = document.createElement('vr-object');
            defaultCamera.setAttribute('camera', {fov: 45});
            // Default camera height at human level, and back such that
            // objects at (0, 0, 0) are perfectly framed.
            defaultCamera.setAttribute('position', {x: 0, y: 1.8, z: 10});
            this.pendingElements++;
            defaultCamera.addEventListener('loaded',
                                           this.elementLoaded.bind(this));
            this.appendChild(defaultCamera);
          }
        },

        setupCursor: {
          value: function () {
            var cursor = this.querySelector('vr-cursor');
            if (cursor) {
              this.cursor = cursor;
            }
          }
        },

        /**
         * Prescibe default lights to the scene.
         * Does so by injecting markup such that this state is not invisible.
         * These lights are removed if the user adds any lights.
         */
        setupDefaultLights: {
          value: function () {
            var ambientLight = document.createElement('vr-object');
            ambientLight.setAttribute('light',
                                      {color: '#bebebe', type: 'ambient'});
            ambientLight.setAttribute(DEFAULT_LIGHT_ATTR, '');
            this.appendChild(ambientLight);

            var directionalLight = document.createElement('vr-object');
            directionalLight.setAttribute('light', {intensity: 2.5});
            directionalLight.setAttribute('position', {x: -10, y: 20, z: 10});
            directionalLight.setAttribute(DEFAULT_LIGHT_ATTR, '');
            this.appendChild(directionalLight);
          }
        },

        /**
         * Notify scene that light has been added and to remove the default
         *
         * @param {object} el - element holding the light component.
         */
        registerLight: {
          value: function (el) {
            if (this.defaultLightsEnabled &&
                !el.hasAttribute(DEFAULT_LIGHT_ATTR)) {
              // User added a light, remove default lights through DOM.
              var defaultLights = document.querySelectorAll(
                '[' + DEFAULT_LIGHT_ATTR + ']');
              for (var i = 0; i < defaultLights.length; i++) {
                this.removeChild(defaultLights[i]);
              }
              this.defaultLightsEnabled = false;
            }
          }
        },

        enterVR: {
          value: function () {
            this.renderer = this.stereoRenderer;
            this.setFullscreen();
          }
        },

        setFullscreen: {
          value: function () {
            var canvas = this.canvas;

            // Use the fullscreen method on effect when on desktop.
            if (!utils.isMobile()) {
              this.stereoRenderer.setFullScreen(true);
              return;
            }

            // For non-VR enabled mobile devices, the controls are polyfilled, but not the
            // vrDisplay, so the fullscreen method on the effect renderer does not work and
            // we request it here manually instead.
            if (canvas.requestFullscreen) {
              canvas.requestFullscreen();
            } else if (canvas.mozRequestFullScreen) {
              canvas.mozRequestFullScreen();
            } else if (canvas.webkitRequestFullscreen) {
              canvas.webkitRequestFullscreen();
            }
          }
        },

        setupRenderer: {
          value: function () {
            var canvas = this.canvas;
            var renderer = this.renderer = this.monoRenderer =
              (VRScene && VRScene.renderer) ||
              // To prevent creating multiple rendering contexts.
              new THREE.WebGLRenderer({canvas: canvas, antialias: true,
                                       alpha: true});
            renderer.setPixelRatio(window.devicePixelRatio);
            renderer.sortObjects = false;
            VRScene.renderer = renderer;
            this.stereoRenderer = new THREE.VREffect(renderer);
          }
        },

        resizeCanvas: {
          value: function () {
            var canvas = this.canvas;
            var camera = this.cameraEl.components.camera.camera;
            // Make it visually fill the positioned parent
            canvas.style.width = '100%';
            canvas.style.height = '100%';
            // Set the internal size to match
            canvas.width = canvas.offsetWidth;
            canvas.height = canvas.offsetHeight;
            // Updates camera
            camera.aspect = canvas.offsetWidth / canvas.offsetHeight;
            camera.updateProjectionMatrix();
            // Notify the renderer of the size change
            this.renderer.setSize(canvas.width, canvas.height);
          }
        },

        add: {
          value: function (el) {
            if (!el.object3D) { return; }
            this.object3D.add(el.object3D);
          }
        },

        addBehavior: {
          value: function (behavior) {
            this.behaviors.push(behavior);
          }
        },

        remove: {
          value: function (el) {
            if (!el.object3D) { return; }
            this.object3D.remove(el.object3D);
          }
        },

        render: {
          value: function (t) {
            var stats = this.stats;
            if (stats) {
              stats('rAF').tick();
              stats('FPS').frame();
            }
            var camera = this.cameraEl.components.camera.camera;
            TWEEN.update(t);
            // Updates behaviors
            this.behaviors.forEach(function (behavior) {
              behavior.update(t);
            });
            this.renderer.render(this.object3D, camera);
            if (stats) { stats().update(); }
            this.animationFrameID = window.requestAnimationFrame(
              this.render.bind(this));
          }
        }
      }
    )
  }
);
<|endoftext|>


<commit_before>var CommandFactory = require('./CommandFactory'),
    Server = require('./Server');
    Storage = require('./Storage');

var storage = new Storage('127.0.0.1', 28015, 'dowser');
var commandFactory = new CommandFactory(storage);
var server = new Server(commandFactory);

server.start(8081);
<commit_msg>Change endpoint do BD<commit_after>var CommandFactory = require('./CommandFactory'),
    Server = require('./Server');
    Storage = require('./Storage');

var storage = new Storage('158.85.206.13', 28015, 'dowser');
var commandFactory = new CommandFactory(storage);
var server = new Server(commandFactory);

server.start(8081);
<|endoftext|>