<commit_before>define(function(require) {
  'use strict';

  var modules = require('modules');
  var states = require('states');
  var _ = require('lodash');
  var angular = require('angular');

  require('scripts/common/filters/inputs');

  require('scripts/applications/services/application_services');
  require('scripts/applications/services/application_environment_services');
  require('scripts/applications/services/application_version_services');
  require('scripts/applications/services/deployment_topology_processor.js');
  require('scripts/applications/services/tasks_processor.js');

  require('scripts/applications/controllers/application_deployment_locations');
  require('scripts/applications/controllers/application_deployment_match');
  require('scripts/applications/controllers/application_deployment_input');
  require('scripts/applications/controllers/application_deployment_deploy');

  require('scripts/deployment/directives/display_outputs');
  require('scripts/applications/directives/topology_errors_display');

  var globalConfTaskCodes = ['SCALABLE_CAPABILITY_INVALID', 'PROPERTIES'];

  function refreshDeploymentContext(deploymentContext, application, deploymentTopologyServices, deploymentTopologyProcessor, tasksProcessor, menus) {
    return deploymentTopologyServices.get({
      appId: application.id,
      envId: deploymentContext.selectedEnvironment.id
    }).$promise.then(function(response) {
        deploymentTopologyProcessor.process(response.data);
        deploymentContext.deploymentTopologyDTO = response.data;
        tasksProcessor.processAll(deploymentContext.deploymentTopologyDTO.validation);
        updateStepsStatuses(menus, deploymentContext.deploymentTopologyDTO.validation);
        return deploymentContext;
      });
  }

  var setNextStepMenuEnabled = function(currentStepMenu, nextStepMenu){
    nextStepMenu.disabled = currentStepMenu.disabled || (_.get(currentStepMenu, 'step.status', 'SUCCESS')!=='SUCCESS');
  };

  function buildMenuTree(menus) {
    _.each(menus, function(menu){
      if (_.definedPath(menu, 'step.nextStepId')){
        menu.nextStep = _.find(menus, function(item){
          return item.id===menu.step.nextStepId;
        });
      }
    });
  }

  function enabledOrDisableMenus(menus){
    _.each(menus, function(menu){
      if (_.defined(menu.nextStep)){
        setNextStepMenuEnabled(menu, menu.nextStep);
      }
    });
  }

  function updateStepsStatuses(menus, validationDTO){
    _.each(menus, function(menu){
      if(_.definedPath(menu, 'step.taskCodes')){
        delete menu.step.status;
        _.each(menu.step.taskCodes, function(taskCode){
          if(_.definedPath(validationDTO, 'taskList['+taskCode+']')){
            menu.step.status = 'ERROR';
            return;
          }
        });
      }
    });

    enabledOrDisableMenus(menus);
  }

  states.state('applications.detail.deployment', {
    url: '/deployment',
    resolve: {
      deploymentContext: ['application', 'appEnvironments', 'deploymentTopologyServices', 'deploymentTopologyProcessor', 'tasksProcessor', 'menu',
        function(application, appEnvironments, deploymentTopologyServices, deploymentTopologyProcessor, tasksProcessor, menu) {
          //build the menu tree
          buildMenuTree(menu);
          var deploymentContextResult = {
            selectedEnvironment: appEnvironments.selected
          };
          return refreshDeploymentContext(deploymentContextResult, application.data, deploymentTopologyServices, deploymentTopologyProcessor, tasksProcessor, menu);
        }
      ]
    },
    templateUrl: 'views/applications/application_deployment.html',
    controller: 'ApplicationDeploymentCtrl',
    menu: {
      id: 'am.applications.detail.deployment',
      state: 'applications.detail.deployment',
      key: 'NAVAPPLICATIONS.MENU_DEPLOYMENT',
      icon: 'fa fa-cloud-upload',
      roles: ['APPLICATION_MANAGER', 'APPLICATION_DEPLOYER'], // is deployer
      priority: 300
    },
    params: {
      // optional id of the environment to automatically select when triggering this state
      openOnEnvironment:null
    }
  });

  modules.get('a4c-applications').controller('ApplicationDeploymentCtrl',
    ['$scope', 'authService', 'application', '$state', 'appEnvironments', 'menu', 'deploymentContext', 'deploymentTopologyServices', 'deploymentTopologyProcessor', 'applicationServices', 'tasksProcessor',
      function($scope, authService, applicationResult, $state, appEnvironments, menu, deploymentContext, deploymentTopologyServices, deploymentTopologyProcessor, applicationServices, tasksProcessor) {
        $scope.deploymentContext = deploymentContext;
        var pageStateId = $state.current.name;
        $scope.menu = menu;

        // Initialization
        $scope.application = applicationResult.data;
        $scope.envs = appEnvironments.deployEnvironments;

        // Retrieval and validation of the topology associated with the deployment.
        var checkTopology = function() {

          $scope.isTopologyValid($scope.topologyId, $scope.deploymentContext.selectedEnvironment.id).$promise.then(function(validTopologyResult) {
            $scope.validTopologyDTO = validTopologyResult.data;
            tasksProcessor.processAll($scope.validTopologyDTO);
          });

          var processTopologyInfoResult = $scope.processTopologyInformations($scope.topologyId);

          // when the selected environment is deployed => refresh output properties
          processTopologyInfoResult.$promise.then(function() {
            if ($scope.deploymentContext.selectedEnvironment.status === 'DEPLOYED') {
              $scope.refreshInstancesStatuses($scope.application.id, $scope.deploymentContext.selectedEnvironment.id, pageStateId);
            }
          });

        };

        //register the checking topo function for others states to use it
        $scope.checkTopology = checkTopology;

        function doGoToNextInvalidStep(){
          //first step is locations
          var stepToGo = _.find($scope.menu, function(menu){
            return menu.id==='am.applications.detail.deployment.locations';
          });

          //look for the first invalid step, or the last one if all are valid
          while(stepToGo.nextStep){
            if(_.get(stepToGo, 'step.status', 'SUCCESS') !== 'SUCCESS'){
              break;
            }
            stepToGo = stepToGo.nextStep;
          }

          //go to the found step
          $state.go(stepToGo.state);
        }

        function goToNextInvalidStep() {
          //refresh initial topo validation first
          $scope.setTopologyId($scope.application.id, $scope.deploymentContext.selectedEnvironment.id, checkTopology).$promise.then(function() {
            //then refresh deployment context
            refreshDeploymentContext($scope.deploymentContext, $scope.application, deploymentTopologyServices, deploymentTopologyProcessor, tasksProcessor, menu).then(function() {
              //finally, go to the next invalid step
              doGoToNextInvalidStep();
            });
          });
        }

        $scope.onEnvironmentChange = function() {
          // update the global environment
          appEnvironments.select($scope.deploymentContext.selectedEnvironment.id, goToNextInvalidStep);
        };

        if(_.defined($state.params.openOnEnvironment) && appEnvironments.selected.id !== $state.params.openOnEnvironment){
          appEnvironments.select($state.params.openOnEnvironment, function(){
            $scope.deploymentContext.selectedEnvironment = appEnvironments.selected;
            goToNextInvalidStep();
          });
        }else{
          goToNextInvalidStep(); // immediately go to the next invalid tab
        }

        $scope.showTodoList = function() {
          return !$scope.validTopologyDTO.valid && $scope.isManager;
        };

        $scope.showWarningList = function() {
          return angular.isObject($scope.validTopologyDTO.warningList) && Object.keys($scope.validTopologyDTO.warningList).length > 0;
        };

        $scope.showConfgurationsErrors = function() {
          var show = false;
          if( _.definedPath($scope.deploymentContext, 'deploymentTopologyDTO.validation.taskList')){
            _.each(globalConfTaskCodes, function(taskCode){
              if (_.defined($scope.deploymentContext.deploymentTopologyDTO.validation.taskList[taskCode])){
                show= true;
                return;
              }
            });
          }
          return show;
        };

        // Map functions that should be available from scope.

        // Application rights
        $scope.isManager = authService.hasResourceRole($scope.application, 'APPLICATION_MANAGER');
        $scope.isDevops = authService.hasResourceRole($scope.application, 'APPLICATION_DEVOPS');
        // Application environment rights
        $scope.isDeployer = authService.hasResourceRole($scope.deploymentContext.selectedEnvironment, 'DEPLOYMENT_MANAGER');
        $scope.isUser = authService.hasResourceRole($scope.deploymentContext.selectedEnvironment, 'APPLICATION_USER');

        $scope.finalOutputAttributesValue = $scope.outputAttributesValue;
        $scope.validTopologyDTO = false;

        $scope.isAllowedDeployment = function() {
          return $scope.isDeployer || $scope.isManager;
        };

        // if the status or the environment changes we must update the event registration.
        $scope.$watch(function() {
          if (_.defined($scope.deploymentContext.selectedEnvironment)) {
            return $scope.deploymentContext.selectedEnvironment.id + '__' + $scope.deploymentContext.selectedEnvironment.status;
          }
          return 'UNDEPLOYED';
        }, function(newValue) {
          var undeployedValue = $scope.deploymentContext.selectedEnvironment.id + '__UNDEPLOYED';
          // no registration for this environement -> register if not undeployed!
          if (newValue === undeployedValue) {
            // if status the application is not undeployed we should register for events.
            $scope.stopEvent();
          } else {
            $scope.stopEvent();
            $scope.setTopologyId($scope.application.id, $scope.deploymentContext.selectedEnvironment.id, checkTopology).$promise.then(function(result) {
              $scope.processTopologyInformations(result.data).$promise.then(function() {
                $scope.refreshInstancesStatuses($scope.application.id, $scope.deploymentContext.selectedEnvironment.id, pageStateId);
              });
            });
          }
        });

        //proceed the deploymentTopologyDTO
        $scope.updateScopeDeploymentTopologyDTO = function(deploymentTopologyDTO){
          if(_.undefined(deploymentTopologyDTO)){
            return;
          }
          deploymentTopologyProcessor.process(deploymentTopologyDTO);
          tasksProcessor.processAll(deploymentTopologyDTO.validation);
          $scope.deploymentContext.deploymentTopologyDTO = deploymentTopologyDTO;
          updateStepsStatuses($scope.menu, $scope.deploymentContext.deploymentTopologyDTO.validation);
        };

        //show or not the status icon
        $scope.showStatusIcon = function(menuItem){
          if(menuItem.disabled || _.get(menuItem, 'step.status','SUCCESS')==='SUCCESS'){
            return false;
          }
          return true;
        };

        // when scope change, stop current event listener
        $scope.$on('$destroy', function() {
          $scope.stopEvent();
        });

      }
    ]); //controller
}); //Define
<commit_msg>[ALIEN-1520] small fix for error display<commit_after>define(function(require) {
  'use strict';

  var modules = require('modules');
  var states = require('states');
  var _ = require('lodash');
  var angular = require('angular');

  require('scripts/common/filters/inputs');

  require('scripts/applications/services/application_services');
  require('scripts/applications/services/application_environment_services');
  require('scripts/applications/services/application_version_services');
  require('scripts/applications/services/deployment_topology_processor.js');
  require('scripts/applications/services/tasks_processor.js');

  require('scripts/applications/controllers/application_deployment_locations');
  require('scripts/applications/controllers/application_deployment_match');
  require('scripts/applications/controllers/application_deployment_input');
  require('scripts/applications/controllers/application_deployment_deploy');

  require('scripts/deployment/directives/display_outputs');
  require('scripts/applications/directives/topology_errors_display');

  var globalConfTaskCodes = ['SCALABLE_CAPABILITY_INVALID', 'PROPERTIES', 'NODE_FILTER_INVALID'];

  function refreshDeploymentContext(deploymentContext, application, deploymentTopologyServices, deploymentTopologyProcessor, tasksProcessor, menus) {
    return deploymentTopologyServices.get({
      appId: application.id,
      envId: deploymentContext.selectedEnvironment.id
    }).$promise.then(function(response) {
        deploymentTopologyProcessor.process(response.data);
        deploymentContext.deploymentTopologyDTO = response.data;
        tasksProcessor.processAll(deploymentContext.deploymentTopologyDTO.validation);
        updateStepsStatuses(menus, deploymentContext.deploymentTopologyDTO.validation);
        return deploymentContext;
      });
  }

  var setNextStepMenuEnabled = function(currentStepMenu, nextStepMenu){
    nextStepMenu.disabled = currentStepMenu.disabled || (_.get(currentStepMenu, 'step.status', 'SUCCESS')!=='SUCCESS');
  };

  function buildMenuTree(menus) {
    _.each(menus, function(menu){
      if (_.definedPath(menu, 'step.nextStepId')){
        menu.nextStep = _.find(menus, function(item){
          return item.id===menu.step.nextStepId;
        });
      }
    });
  }

  function enabledOrDisableMenus(menus){
    _.each(menus, function(menu){
      if (_.defined(menu.nextStep)){
        setNextStepMenuEnabled(menu, menu.nextStep);
      }
    });
  }

  function updateStepsStatuses(menus, validationDTO){
    _.each(menus, function(menu){
      if(_.definedPath(menu, 'step.taskCodes')){
        delete menu.step.status;
        _.each(menu.step.taskCodes, function(taskCode){
          if(_.definedPath(validationDTO, 'taskList['+taskCode+']')){
            menu.step.status = 'ERROR';
            return;
          }
        });
      }
    });

    enabledOrDisableMenus(menus);
  }

  states.state('applications.detail.deployment', {
    url: '/deployment',
    resolve: {
      deploymentContext: ['application', 'appEnvironments', 'deploymentTopologyServices', 'deploymentTopologyProcessor', 'tasksProcessor', 'menu',
        function(application, appEnvironments, deploymentTopologyServices, deploymentTopologyProcessor, tasksProcessor, menu) {
          //build the menu tree
          buildMenuTree(menu);
          var deploymentContextResult = {
            selectedEnvironment: appEnvironments.selected
          };
          return refreshDeploymentContext(deploymentContextResult, application.data, deploymentTopologyServices, deploymentTopologyProcessor, tasksProcessor, menu);
        }
      ]
    },
    templateUrl: 'views/applications/application_deployment.html',
    controller: 'ApplicationDeploymentCtrl',
    menu: {
      id: 'am.applications.detail.deployment',
      state: 'applications.detail.deployment',
      key: 'NAVAPPLICATIONS.MENU_DEPLOYMENT',
      icon: 'fa fa-cloud-upload',
      roles: ['APPLICATION_MANAGER', 'APPLICATION_DEPLOYER'], // is deployer
      priority: 300
    },
    params: {
      // optional id of the environment to automatically select when triggering this state
      openOnEnvironment:null
    }
  });

  modules.get('a4c-applications').controller('ApplicationDeploymentCtrl',
    ['$scope', 'authService', 'application', '$state', 'appEnvironments', 'menu', 'deploymentContext', 'deploymentTopologyServices', 'deploymentTopologyProcessor', 'applicationServices', 'tasksProcessor',
      function($scope, authService, applicationResult, $state, appEnvironments, menu, deploymentContext, deploymentTopologyServices, deploymentTopologyProcessor, applicationServices, tasksProcessor) {
        $scope.deploymentContext = deploymentContext;
        var pageStateId = $state.current.name;
        $scope.menu = menu;

        // Initialization
        $scope.application = applicationResult.data;
        $scope.envs = appEnvironments.deployEnvironments;

        // Retrieval and validation of the topology associated with the deployment.
        var checkTopology = function() {

          $scope.isTopologyValid($scope.topologyId, $scope.deploymentContext.selectedEnvironment.id).$promise.then(function(validTopologyResult) {
            $scope.validTopologyDTO = validTopologyResult.data;
            tasksProcessor.processAll($scope.validTopologyDTO);
          });

          var processTopologyInfoResult = $scope.processTopologyInformations($scope.topologyId);

          // when the selected environment is deployed => refresh output properties
          processTopologyInfoResult.$promise.then(function() {
            if ($scope.deploymentContext.selectedEnvironment.status === 'DEPLOYED') {
              $scope.refreshInstancesStatuses($scope.application.id, $scope.deploymentContext.selectedEnvironment.id, pageStateId);
            }
          });

        };

        //register the checking topo function for others states to use it
        $scope.checkTopology = checkTopology;

        function doGoToNextInvalidStep(){
          //first step is locations
          var stepToGo = _.find($scope.menu, function(menu){
            return menu.id==='am.applications.detail.deployment.locations';
          });

          //look for the first invalid step, or the last one if all are valid
          while(stepToGo.nextStep){
            if(_.get(stepToGo, 'step.status', 'SUCCESS') !== 'SUCCESS'){
              break;
            }
            stepToGo = stepToGo.nextStep;
          }

          //go to the found step
          $state.go(stepToGo.state);
        }

        function goToNextInvalidStep() {
          //refresh initial topo validation first
          $scope.setTopologyId($scope.application.id, $scope.deploymentContext.selectedEnvironment.id, checkTopology).$promise.then(function() {
            //then refresh deployment context
            refreshDeploymentContext($scope.deploymentContext, $scope.application, deploymentTopologyServices, deploymentTopologyProcessor, tasksProcessor, menu).then(function() {
              //finally, go to the next invalid step
              doGoToNextInvalidStep();
            });
          });
        }

        $scope.onEnvironmentChange = function() {
          // update the global environment
          appEnvironments.select($scope.deploymentContext.selectedEnvironment.id, goToNextInvalidStep);
        };

        if(_.defined($state.params.openOnEnvironment) && appEnvironments.selected.id !== $state.params.openOnEnvironment){
          appEnvironments.select($state.params.openOnEnvironment, function(){
            $scope.deploymentContext.selectedEnvironment = appEnvironments.selected;
            goToNextInvalidStep();
          });
        }else{
          goToNextInvalidStep(); // immediately go to the next invalid tab
        }

        $scope.showTodoList = function() {
          return !$scope.validTopologyDTO.valid && $scope.isManager;
        };

        $scope.showWarningList = function() {
          return angular.isObject($scope.validTopologyDTO.warningList) && Object.keys($scope.validTopologyDTO.warningList).length > 0;
        };

        $scope.showConfgurationsErrors = function() {
          var show = false;
          if( _.definedPath($scope.deploymentContext, 'deploymentTopologyDTO.validation.taskList')){
            _.each(globalConfTaskCodes, function(taskCode){
              if (_.defined($scope.deploymentContext.deploymentTopologyDTO.validation.taskList[taskCode])){
                show= true;
                return;
              }
            });
          }
          return show;
        };

        // Map functions that should be available from scope.

        // Application rights
        $scope.isManager = authService.hasResourceRole($scope.application, 'APPLICATION_MANAGER');
        $scope.isDevops = authService.hasResourceRole($scope.application, 'APPLICATION_DEVOPS');
        // Application environment rights
        $scope.isDeployer = authService.hasResourceRole($scope.deploymentContext.selectedEnvironment, 'DEPLOYMENT_MANAGER');
        $scope.isUser = authService.hasResourceRole($scope.deploymentContext.selectedEnvironment, 'APPLICATION_USER');

        $scope.finalOutputAttributesValue = $scope.outputAttributesValue;
        $scope.validTopologyDTO = false;

        $scope.isAllowedDeployment = function() {
          return $scope.isDeployer || $scope.isManager;
        };

        // if the status or the environment changes we must update the event registration.
        $scope.$watch(function() {
          if (_.defined($scope.deploymentContext.selectedEnvironment)) {
            return $scope.deploymentContext.selectedEnvironment.id + '__' + $scope.deploymentContext.selectedEnvironment.status;
          }
          return 'UNDEPLOYED';
        }, function(newValue) {
          var undeployedValue = $scope.deploymentContext.selectedEnvironment.id + '__UNDEPLOYED';
          // no registration for this environement -> register if not undeployed!
          if (newValue === undeployedValue) {
            // if status the application is not undeployed we should register for events.
            $scope.stopEvent();
          } else {
            $scope.stopEvent();
            $scope.setTopologyId($scope.application.id, $scope.deploymentContext.selectedEnvironment.id, checkTopology).$promise.then(function(result) {
              $scope.processTopologyInformations(result.data).$promise.then(function() {
                $scope.refreshInstancesStatuses($scope.application.id, $scope.deploymentContext.selectedEnvironment.id, pageStateId);
              });
            });
          }
        });

        //proceed the deploymentTopologyDTO
        $scope.updateScopeDeploymentTopologyDTO = function(deploymentTopologyDTO){
          if(_.undefined(deploymentTopologyDTO)){
            return;
          }
          deploymentTopologyProcessor.process(deploymentTopologyDTO);
          tasksProcessor.processAll(deploymentTopologyDTO.validation);
          $scope.deploymentContext.deploymentTopologyDTO = deploymentTopologyDTO;
          updateStepsStatuses($scope.menu, $scope.deploymentContext.deploymentTopologyDTO.validation);
        };

        //show or not the status icon
        $scope.showStatusIcon = function(menuItem){
          if(menuItem.disabled || _.get(menuItem, 'step.status','SUCCESS')==='SUCCESS'){
            return false;
          }
          return true;
        };

        // when scope change, stop current event listener
        $scope.$on('$destroy', function() {
          $scope.stopEvent();
        });

      }
    ]); //controller
}); //Define
<|endoftext|>


<commit_before>(function(root) {

  var SessionTimeoutWarning = function () {}

  SessionTimeoutWarning.prototype.count = function () {
    root.setTimeout(this.show, 780000);  // count up to 13 minutes
  };

  SessionTimeoutWarning.prototype.show = function () {
    $('#renew-session').slideDown();
  };

  root.SessionTimeoutWarning = SessionTimeoutWarning;

})(window)

$(function() {

  if ($('body').hasClass('educator-signed-in')) {
    (new SessionTimeoutWarning).count();
  }

  $("#renew-sesion-link").click(function () {
    $.ajax({
      url: '/educators/reset',
      success: function () {
        $('#renew-session').slideUp();
      }
    });
  });
});
<commit_msg>Reset timeout warning count each time user renews session<commit_after>(function(root) {

  var SessionTimeoutWarning = function () {}

  SessionTimeoutWarning.prototype.count = function () {
    root.setTimeout(this.show, 780000);  // count up to 13 minutes
  };

  SessionTimeoutWarning.prototype.show = function () {
    $('#renew-session').slideDown();
  };

  root.SessionTimeoutWarning = SessionTimeoutWarning;

})(window)

$(function() {

  if ($('body').hasClass('educator-signed-in')) {
    var warning = new SessionTimeoutWarning;
    warning.count();
  }

  $("#renew-sesion-link").click(function () {
    $.ajax({
      url: '/educators/reset',
      success: function () {
        $('#renew-session').slideUp();
        warning.count();   // Resent timeout count
      }
    });
  });
});
<|endoftext|>


<commit_before>import React from 'react'

import { hideModalCalc } from '../actions'
import ReactCSSTransitionGroup from 'react-addons-css-transition-group'

const Calculator = React.createClass({
  propTypes: {
    dispatch: React.PropTypes.func,
    visible: React.PropTypes.bool
  },

  onOutClick: function (e) {
    if (e.target === e.currentTarget) {
      this.props.dispatch(hideModalCalc())
    }
  },

  renderModal: function () {
    if (!this.props.visible) return null

    return (

About this Tool

              <button className='modal__button-dismiss' title='Close' onClick={() => this.props.dispatch(hideModalCalculator())}>Dismiss</button>

Section Header

Lorem ipsum dolor sit amet, consectetur adipiscing elit, sed do eiusmod tempor incididunt ut labore et dolore magna aliqua. Ut enim ad minim veniam, quis nostrud exercitation ullamco laboris nisi ut aliquip ex ea commodo consequat. Duis aute irure dolor in reprehenderit in voluptate velit esse cillum dolore eu fugiat nulla pariatur. Excepteur sint occaecat cupidatat non proident, sunt in culpa qui officia deserunt mollit anim id est laborum.

Section Header

Sed ut perspiciatis unde omnis iste natus error sit voluptatem accusantium doloremque laudantium, totam rem aperiam, eaque ipsa quae ab illo inventore veritatis et quasi architecto beatae vitae dicta sunt explicabo. Nemo enim ipsam voluptatem quia voluptas sit aspernatur aut odit aut fugit, sed quia consequuntur magni dolores eos qui ratione voluptatem sequi nesciunt. Neque porro quisquam est, qui dolorem ipsum quia dolor sit amet, consectetur, adipisci velit, sed quia non numquam eius modi tempora incidunt ut labore et dolore magnam aliquam quaerat voluptatem. Ut enim ad minima veniam, quis nostrum exercitationem ullam corporis suscipit laboriosam, nisi ut aliquid ex ea commodi consequatur? Quis autem vel eum iure reprehenderit qui in ea voluptate velit esse quam nihil molestiae consequatur, vel illum qui dolorem eum fugiat quo voluptas nulla pariatur?

Sed ut perspiciatis unde omnis iste natus error sit voluptatem accusantium doloremque laudantium, totam rem aperiam, eaque ipsa quae ab illo inventore veritatis et quasi architecto beatae vitae dicta sunt explicabo. Nemo enim ipsam voluptatem quia voluptas sit aspernatur aut odit aut fugit, sed quia consequuntur magni dolores eos qui ratione voluptatem sequi nesciunt. Neque porro quisquam est, qui dolorem ipsum quia dolor sit amet, consectetur, adipisci velit, sed quia non numquam eius modi tempora incidunt ut labore et dolore magnam aliquam quaerat voluptatem. Ut enim ad minima veniam, quis nostrum exercitationem ullam corporis suscipit laboriosam, nisi ut aliquid ex ea commodi consequatur? Quis autem vel eum iure reprehenderit qui in ea voluptate velit esse quam nihil molestiae consequatur, vel illum qui dolorem eum fugiat quo voluptas nulla pariatur?

    )
  },

  render: function () {
    return (
      <ReactCSSTransitionGroup
        component='div'
        transitionName='modal'
        transitionEnterTimeout={300}
        transitionLeaveTimeout={300} >
          {this.renderModal()}
      </ReactCSSTransitionGroup>
    )
  }
})

export default Calculator
<commit_msg>Fix build error, rename action<commit_after>import React from 'react'

import { hideModalCalc } from '../actions'
import ReactCSSTransitionGroup from 'react-addons-css-transition-group'

const Calculator = React.createClass({
  propTypes: {
    dispatch: React.PropTypes.func,
    visible: React.PropTypes.bool
  },

  onOutClick: function (e) {
    if (e.target === e.currentTarget) {
      this.props.dispatch(hideModalCalc())
    }
  },

  renderModal: function () {
    if (!this.props.visible) return null

    return (

About this Tool

              <button className='modal__button-dismiss' title='Close' onClick={() => this.props.dispatch(hideModalCalc())}>Dismiss</button>

Section Header

Lorem ipsum dolor sit amet, consectetur adipiscing elit, sed do eiusmod tempor incididunt ut labore et dolore magna aliqua. Ut enim ad minim veniam, quis nostrud exercitation ullamco laboris nisi ut aliquip ex ea commodo consequat. Duis aute irure dolor in reprehenderit in voluptate velit esse cillum dolore eu fugiat nulla pariatur. Excepteur sint occaecat cupidatat non proident, sunt in culpa qui officia deserunt mollit anim id est laborum.

Section Header

Sed ut perspiciatis unde omnis iste natus error sit voluptatem accusantium doloremque laudantium, totam rem aperiam, eaque ipsa quae ab illo inventore veritatis et quasi architecto beatae vitae dicta sunt explicabo. Nemo enim ipsam voluptatem quia voluptas sit aspernatur aut odit aut fugit, sed quia consequuntur magni dolores eos qui ratione voluptatem sequi nesciunt. Neque porro quisquam est, qui dolorem ipsum quia dolor sit amet, consectetur, adipisci velit, sed quia non numquam eius modi tempora incidunt ut labore et dolore magnam aliquam quaerat voluptatem. Ut enim ad minima veniam, quis nostrum exercitationem ullam corporis suscipit laboriosam, nisi ut aliquid ex ea commodi consequatur? Quis autem vel eum iure reprehenderit qui in ea voluptate velit esse quam nihil molestiae consequatur, vel illum qui dolorem eum fugiat quo voluptas nulla pariatur?

Sed ut perspiciatis unde omnis iste natus error sit voluptatem accusantium doloremque laudantium, totam rem aperiam, eaque ipsa quae ab illo inventore veritatis et quasi architecto beatae vitae dicta sunt explicabo. Nemo enim ipsam voluptatem quia voluptas sit aspernatur aut odit aut fugit, sed quia consequuntur magni dolores eos qui ratione voluptatem sequi nesciunt. Neque porro quisquam est, qui dolorem ipsum quia dolor sit amet, consectetur, adipisci velit, sed quia non numquam eius modi tempora incidunt ut labore et dolore magnam aliquam quaerat voluptatem. Ut enim ad minima veniam, quis nostrum exercitationem ullam corporis suscipit laboriosam, nisi ut aliquid ex ea commodi consequatur? Quis autem vel eum iure reprehenderit qui in ea voluptate velit esse quam nihil molestiae consequatur, vel illum qui dolorem eum fugiat quo voluptas nulla pariatur?

    )
  },

  render: function () {
    return (
      <ReactCSSTransitionGroup
        component='div'
        transitionName='modal'
        transitionEnterTimeout={300}
        transitionLeaveTimeout={300} >
          {this.renderModal()}
      </ReactCSSTransitionGroup>
    )
  }
})

export default Calculator
<|endoftext|>


<commit_before>'use strict';

angular.module('bansho.table.actionbar')

	.directive('banshoAcknowledgeForm', function () {
		return {
			restrict: 'E',
			templateUrl: 'components/table/actionbar/actions/acknowledge_form.html',
			scope: {
				isShown: '='
			},
			controller: 'banshoAcknowledgeFormCtrl'
		};
	})

	.controller('banshoAcknowledgeFormCtrl',
		['$scope', '$filter', 'tablesConfig', 'actionbarFilters', 'backendClient',
		function ($scope, $filter, tablesConfig, actionbarFilters, backendClient) {

		$scope.acknowledgeProblems = function () {
			angular.forEach(tablesConfig, function (tableConfig) {
				var entries = $filter('filter')(tableConfig.entries,
					actionbarFilters.searchFilter);

				angular.forEach(entries, function (entry) {
					var service_description;

					if (entry.is_checked) {
						if ('description' in entry) {
							service_description = entry.description;
						}

						backendClient.acknowledge(entry.host_name, service_description, $scope.attrs).error(function (data) {
								throw new Error('Acknowledge request failed');
							});
					}
				});
			});
		};
	}])

	.directive('banshoDowntimeForm', function () {
		return {
			restrict: 'E',
			templateUrl: 'components/table/actionbar/actions/downtime_form.html',
			scope: {
				isShown: '='
			},
			controller: 'banshoDowntimeFormCtrl'
		};
	})

	.controller('banshoDowntimeFormCtrl',
		['$scope', '$filter', 'tablesConfig', 'actionbarFilters', 'backendClient',
		function ($scope, $filter, tablesConfig, actionbarFilters, backendClient) {

		$scope.messages = [];

		$scope.sendDowntime = function () {
			angular.forEach(tablesConfig, function (table) {
				var entries = $filter('filter')(table.entries, actionbarFilters.searchFilter);

				angular.forEach(entries, function (entry) {
					var service_description;

					if (entry.is_checked) {
						if ('description' in entry) {
							service_description = entry.description;
						}

						backendClient.downtime(entry.host_name, service_description, $scope.attrs).then(function (data) {
							$scope.messages.push({
								text: entry.host_name + " success ",
								type: "success"
							});
						},
						function (error) {
							$scope.messages.push({
								text: entry.host_name + " error",
								type: "error"
							});
						});
					}
				});
			});
		};
	}]);
<commit_msg>Hide downtime form after it is sent<commit_after>'use strict';

angular.module('bansho.table.actionbar')

	.directive('banshoAcknowledgeForm', function () {
		return {
			restrict: 'E',
			templateUrl: 'components/table/actionbar/actions/acknowledge_form.html',
			scope: {
				isShown: '='
			},
			controller: 'banshoAcknowledgeFormCtrl'
		};
	})

	.controller('banshoAcknowledgeFormCtrl',
		['$scope', '$filter', 'tablesConfig', 'actionbarFilters', 'backendClient',
		function ($scope, $filter, tablesConfig, actionbarFilters, backendClient) {

		$scope.acknowledgeProblems = function () {
			angular.forEach(tablesConfig, function (tableConfig) {
				var entries = $filter('filter')(tableConfig.entries,
					actionbarFilters.searchFilter);

				angular.forEach(entries, function (entry) {
					var service_description;

					if (entry.is_checked) {
						if ('description' in entry) {
							service_description = entry.description;
						}

						backendClient.acknowledge(entry.host_name, service_description, $scope.attrs).error(function (data) {
								throw new Error('Acknowledge request failed');
							});
					}
				});
			});
		};
	}])

	.directive('banshoDowntimeForm', function () {
		return {
			restrict: 'E',
			templateUrl: 'components/table/actionbar/actions/downtime_form.html',
			scope: {
				isShown: '='
			},
			controller: 'banshoDowntimeFormCtrl'
		};
	})

	.controller('banshoDowntimeFormCtrl',
		['$scope', '$filter', 'tablesConfig', 'actionbarFilters', 'backendClient',
		function ($scope, $filter, tablesConfig, actionbarFilters, backendClient) {

		$scope.messages = [];

		$scope.sendDowntime = function () {
			angular.forEach(tablesConfig, function (table) {
				var entries = $filter('filter')(table.entries, actionbarFilters.searchFilter);

				angular.forEach(entries, function (entry) {
					var service_description;

					if (entry.is_checked) {
						if ('description' in entry) {
							service_description = entry.description;
						}

						backendClient.downtime(entry.host_name, service_description, $scope.attrs).then(function (data) {
							$scope.messages.push({
								text: entry.host_name + " success ",
								type: "success"
							});
							$scope.isShown = false;
						},
						function (error) {
							$scope.messages.push({
								text: entry.host_name + " error",
								type: "error"
							});
						});
					}
				});
			});
		};
	}]);
<|endoftext|>


<commit_before>'use strict';

/**
 * Module dependencies.
 */
var mongoose = require('mongoose'),
	errorHandler = require('./errors.server.controller'),
	BirthdayFund = mongoose.model('BirthdayFund'),
	Usuario = mongoose.model('User'),
	_ = require('lodash');

var listOfBirthdayFund;

function getListOfBirthdayFund(){

	//BithdayFund harcodeados
	listOfBirthdayFund = [{'id':0,'firstname':'Eduardo','lastname':'Malvino','username':'emalvino', 'birthday':new Date('01/11/1983'),'usersCollecting':[{'name':'Lolo'},{'name':'Juan'}, {'name': 'Pedro'}],'usersGivers':[{'name':'Juan', 'amount':10}, {'name': 'Pedro', 'amount':20}], 'collectingDateLimit':'2015-11-25','state':'Active'},
						  {'id':1,'firstname':'Oscar','lastname':'Pinto','username':'opinto', 'birthday':new Date('01/05/1983'),'usersCollecting':[{'name':'Juan'}, {'name': 'Pedro'}],'usersGivers':[{'name':'Juan', 'amount':15}, {'name': 'Pedro', 'amount':25}],'collectingDateLimit':'2015-11-25','state':'Active'},
						  {'id':2,'firstname':'Victor','lastname':'Di Lena','username':'vdilena', 'birthday':new Date('08/15/1984'),'usersCollecting':[{'name':'Juan'}, {'name': 'Pedro'}],'usersGivers':[{'name':'Juan', 'amount':13}, {'name': 'Pedro', 'amount':23}], 'collectingDateLimit':'2015-11-25','state':'Active'},
						  {'id':3,'firstname':'Jesica','lastname':'Taira','username':'jtaira', 'birthday':new Date('06/08/1984'),'usersCollecting':[{'name':'Juan'}, {'name': 'Pedro'}],'usersGivers':[{'name':'Juan', 'amount':12}, {'name': 'Pedro', 'amount':22}],'collectingDateLimit':'2015-11-25','state':'Active'},
						  {'id':4,'firstname':'Juan','lastname':'Jaime','username':'jjaime', 'birthday':new Date('11/12/1983'),'usersCollecting':[{'name':'Jesica'}, {'name': 'Victor'}],'usersGivers':[{'name':'Oscar', 'amount':14}],'collectingDateLimit':'2015-11-25','state':'Inactive'},
						  {'id':6,'firstname':'Marcelo','lastname':'Wieja','username':'mwieja', 'birthday':new Date('11/07/1983'),'usersCollecting':[{'name':'Jesica'}, {'name': 'Victor'}],'usersGivers':[{'name':'Oscar', 'amount':17}],'collectingDateLimit':'2015-11-25','state':'Inactive'},
						  {'id':7,'firstname':'Pablo','lastname':'Morixe','username':'pmorixe', 'birthday':new Date('11/08/1983'),'usersCollecting':[{'name':'Jesica'}, {'name': 'Victor'}],'usersGivers':[{'name':'Oscar', 'amount':18}],'collectingDateLimit':'2015-11-25','state':'Inactive'},
						  {'id':8,'firstname':'Tomas','lastname':'Franco','username':'tfranco', 'birthday':new Date('11/09/1983'),'usersCollecting':[{'name':'Jesica'}, {'name': 'Victor'}],'usersGivers':[{'name':'Oscar', 'amount':19}],'collectingDateLimit':'2015-11-25','state':'Inactive'}];

	return listOfBirthdayFund;
}

//Borrar cuando se trabaje con datos reales
function getBirthday(req, res, next ,id){
	console.log('***ID de birthdayFund a editar: ' + id);
	BirthdayFund.findOne().where('id').equals(id).exec(function(err, birthdayFund) {
		if (err) return next(err);
		if (!birthdayFund) return next(new Error('Failed to load BirthdayFund ' + id));
		req.birthdayFund = birthdayFund;
		next();
	});
	//return listOfBirthdayFund[id];
}

/**
 * Update a BirthdayFundFund
 */
exports.update = function(req, res) {

	console.log('update(): ' + JSON.stringify(req.body));

	var birthdayFund = req.birthdayFund;
	var message = null;

	birthdayFund = _.extend(birthdayFund, req.body);

	birthdayFund.save(function(err) {
		if (err) {
			console.log('********Error en el Update');
			return res.status(400).send({
				message: errorHandler.getErrorMessage(err)
			});
		} else {
			console.log('***********No Error Update');
			res.jsonp(birthdayFund);
		}
	});
};

/**
 * List of BirthdayFunds
 */
exports.list = function(req, res) {
	BirthdayFund.find().where('username').ne(req.user.username).sort('-birthday').exec(function(err, birthdayFunds) {
		if(err) {
			return res.status(400).send({
				message: errorHandler.getErrorMessage(err)
			});
		} else {
			res.jsonp(birthdayFunds);
		}
	});
};

/**
 * BirthdayFund middleware
 */
exports.BirthdayFundByID = function(req, res, next, id) {
	BirthdayFund.findById(id).populate('user', 'displayName').exec(function(err, BirthdayFund) {
		if (err) {
			return next(err);
		}
		if (! BirthdayFund) {
			return next(new Error('Failed to load BirthdayFund ' + id));
		}
		req.BirthdayFund = BirthdayFund ;
		next();
	});
};

/**
 * BirthdayFund authorization middleware
 */
exports.hasAuthorization = function(req, res, next) {
	if (req.BirthdayFund.user.id !== req.user.id) {
		return res.status(403).send('User is not authorized');
	}
	next();
};

exports.beginFund = function(req, res, next, id) {

	// Usar cuando se trabaje con datos reales
	BirthdayFund.findOne().where('id').equals(id).exec(function(err, birthdayFund) {
		if (err) return next(err);
		if (! birthdayFund){

			 next(new Error('Failed to load BirthdayFund ' + id));
		}
		req.birthdayFund = birthdayFund ;
		next();
	});
	/*req.birthdayFund = getBirthday(req, res, next, id);
	next();*/
};

exports.editFund = function(req, res, next, id) {

	// Usar cuando se trabaje con datos reales
	BirthdayFund.findOne().where('id').equals(id).exec(function(err, birthdayFund) {
		if (err) return next(err);
		if (! birthdayFund){

			 next(new Error('Failed to load BirthdayFund ' + id));
		}
		req.birthdayFund = birthdayFund ;
		next();
	});
	/*req.birthdayFund = getBirthday(req, res, next, id);
	next();*/
};

exports.changeFund = function(req, res, next, id) {
	req.birthdayFund = getBirthday(req, res, next, id);
	next();
};

exports.read = function(req, res) {
	res.jsonp(req.birthdayFund);
};

exports.users = function (req,res,next,birthdayUser){
	Usuario.find().where('username').nin([req.user.username,birthdayUser]).sort('firstName').exec(function(err, users) {
		if (err) {
			return res.status(400).send({
				message: errorHandler.getErrorMessage(err)
			});
		} else {
			res.jsonp(users);
		}
	});
};<commit_msg>Se cambia el parametro id por _id en las busquedas de Colectas ya que se elimino el campo id porque se podia usar _id que ya existia y se incrementa automaticamente con cada nuevo registro<commit_after>'use strict';

/**
 * Module dependencies.
 */
var mongoose = require('mongoose'),
	errorHandler = require('./errors.server.controller'),
	BirthdayFund = mongoose.model('BirthdayFund'),
	Usuario = mongoose.model('User'),
	_ = require('lodash');

var listOfBirthdayFund;

function getListOfBirthdayFund(){

	//BithdayFund harcodeados
	listOfBirthdayFund = [{'id':0,'firstname':'Eduardo','lastname':'Malvino','username':'emalvino', 'birthday':new Date('01/11/1983'),'usersCollecting':[{'name':'Lolo'},{'name':'Juan'}, {'name': 'Pedro'}],'usersGivers':[{'name':'Juan', 'amount':10}, {'name': 'Pedro', 'amount':20}], 'collectingDateLimit':'2015-11-25','state':'Active'},
						  {'id':1,'firstname':'Oscar','lastname':'Pinto','username':'opinto', 'birthday':new Date('01/05/1983'),'usersCollecting':[{'name':'Juan'}, {'name': 'Pedro'}],'usersGivers':[{'name':'Juan', 'amount':15}, {'name': 'Pedro', 'amount':25}],'collectingDateLimit':'2015-11-25','state':'Active'},
						  {'id':2,'firstname':'Victor','lastname':'Di Lena','username':'vdilena', 'birthday':new Date('08/15/1984'),'usersCollecting':[{'name':'Juan'}, {'name': 'Pedro'}],'usersGivers':[{'name':'Juan', 'amount':13}, {'name': 'Pedro', 'amount':23}], 'collectingDateLimit':'2015-11-25','state':'Active'},
						  {'id':3,'firstname':'Jesica','lastname':'Taira','username':'jtaira', 'birthday':new Date('06/08/1984'),'usersCollecting':[{'name':'Juan'}, {'name': 'Pedro'}],'usersGivers':[{'name':'Juan', 'amount':12}, {'name': 'Pedro', 'amount':22}],'collectingDateLimit':'2015-11-25','state':'Active'},
						  {'id':4,'firstname':'Juan','lastname':'Jaime','username':'jjaime', 'birthday':new Date('11/12/1983'),'usersCollecting':[{'name':'Jesica'}, {'name': 'Victor'}],'usersGivers':[{'name':'Oscar', 'amount':14}],'collectingDateLimit':'2015-11-25','state':'Inactive'},
						  {'id':6,'firstname':'Marcelo','lastname':'Wieja','username':'mwieja', 'birthday':new Date('11/07/1983'),'usersCollecting':[{'name':'Jesica'}, {'name': 'Victor'}],'usersGivers':[{'name':'Oscar', 'amount':17}],'collectingDateLimit':'2015-11-25','state':'Inactive'},
						  {'id':7,'firstname':'Pablo','lastname':'Morixe','username':'pmorixe', 'birthday':new Date('11/08/1983'),'usersCollecting':[{'name':'Jesica'}, {'name': 'Victor'}],'usersGivers':[{'name':'Oscar', 'amount':18}],'collectingDateLimit':'2015-11-25','state':'Inactive'},
						  {'id':8,'firstname':'Tomas','lastname':'Franco','username':'tfranco', 'birthday':new Date('11/09/1983'),'usersCollecting':[{'name':'Jesica'}, {'name': 'Victor'}],'usersGivers':[{'name':'Oscar', 'amount':19}],'collectingDateLimit':'2015-11-25','state':'Inactive'}];

	return listOfBirthdayFund;
}

//Borrar cuando se trabaje con datos reales
function getBirthday(req, res, next ,id){
	console.log('***ID de birthdayFund a editar: ' + id);
	BirthdayFund.findOne().where('_id').equals(id).exec(function(err, birthdayFund) {
		if (err) return next(err);
		if (!birthdayFund) return next(new Error('Failed to load BirthdayFund ' + id));
		req.birthdayFund = birthdayFund;
		next();
	});
	//return listOfBirthdayFund[id];
}

/**
 * Update a BirthdayFundFund
 */
exports.update = function(req, res) {

	console.log('update(): ' + JSON.stringify(req.body));

	var birthdayFund = req.birthdayFund;
	var message = null;

	birthdayFund = _.extend(birthdayFund, req.body);

	birthdayFund.save(function(err) {
		if (err) {
			console.log('********Error en el Update');
			return res.status(400).send({
				message: errorHandler.getErrorMessage(err)
			});
		} else {
			console.log('***********No Error Update');
			res.jsonp(birthdayFund);
		}
	});
};

/**
 * List of BirthdayFunds
 */
exports.list = function(req, res) {
	BirthdayFund.find().where('username').ne(req.user.username).sort('-birthday').exec(function(err, birthdayFunds) {
		if(err) {
			return res.status(400).send({
				message: errorHandler.getErrorMessage(err)
			});
		} else {
			res.jsonp(birthdayFunds);
		}
	});
};

/**
 * BirthdayFund middleware
 */
exports.BirthdayFundByID = function(req, res, next, id) {
	BirthdayFund.findById(id).populate('user', 'displayName').exec(function(err, BirthdayFund) {
		if (err) {
			return next(err);
		}
		if (! BirthdayFund) {
			return next(new Error('Failed to load BirthdayFund ' + id));
		}
		req.BirthdayFund = BirthdayFund ;
		next();
	});
};

/**
 * BirthdayFund authorization middleware
 */
exports.hasAuthorization = function(req, res, next) {
	if (req.BirthdayFund.user.id !== req.user.id) {
		return res.status(403).send('User is not authorized');
	}
	next();
};

exports.beginFund = function(req, res, next, id) {

	// Usar cuando se trabaje con datos reales
	BirthdayFund.findOne().where('_id').equals(id).exec(function(err, birthdayFund) {
		if (err) return next(err);
		if (! birthdayFund){

			 next(new Error('Failed to load BirthdayFund ' + id));
		}
		req.birthdayFund = birthdayFund ;
		next();
	});
	/*req.birthdayFund = getBirthday(req, res, next, id);
	next();*/
};

exports.editFund = function(req, res, next, id) {

	// Usar cuando se trabaje con datos reales
	BirthdayFund.findOne().where('_id').equals(id).exec(function(err, birthdayFund) {
		if (err) return next(err);
		if (! birthdayFund){

			 next(new Error('Failed to load BirthdayFund ' + id));
		}
		req.birthdayFund = birthdayFund ;
		next();
	});
	/*req.birthdayFund = getBirthday(req, res, next, id);
	next();*/
};

exports.changeFund = function(req, res, next, id) {
	req.birthdayFund = getBirthday(req, res, next, id);
	next();
};

exports.read = function(req, res) {
	res.jsonp(req.birthdayFund);
};

exports.users = function (req,res,next,birthdayUser){
	Usuario.find().where('username').nin([req.user.username,birthdayUser]).sort('firstName').exec(function(err, users) {
		if (err) {
			return res.status(400).send({
				message: errorHandler.getErrorMessage(err)
			});
		} else {
			res.jsonp(users);
		}
	});
};<|endoftext|>


<commit_before>'use strict';

var app = angular.module('myApp.controllers', [
  'myApp.authentications.controller',
  'myApp.brands.controller',
  'myApp.boxes.controller',
  'myApp.events.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('Events'),
      link: '/#/events',
      type: 'link',
      icon: 'warning'
    });

    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...');
      var cname = event.data.cname;
      if ((cname === null || cname === '') && event.data.url !== 'default') {
        var sub   = locationHelper.subdomain();
        var host  = locationHelper.domain();
        if (event.data.url && (sub !== event.data.url)) {
          var newUrl = locationHelper.reconstructed(event.data.url);
          var reconstructed = newUrl + '/#/';
          $cookies.put('event', JSON.stringify(event), {'domain': host});
          window.location = reconstructed;
        } else {
          doLogin(event);
        }
      } else {
        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().chat_enabled !== false && Auth.currentUser().user_hash !== undefined)) {
        vm.menu.Intercom = true;
        var app_id;
        if (Auth.currentUser().custom && !Auth.currentUser().reseller) {
          app_id = $scope.brandName.intercom_id;
        } else {
          app_id = INTERCOM;
        }
        if (app_id) {
          var settings = {
              app_id: app_id,
              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'
          };
          settings.widget = {
            activator: '#intercom'
          };
          window.Intercom('boot', settings);
        }
      }
    });

    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'
        });

        vm.menu.main.push({
          title: gettextCatalog.getString('Events'),
          type: 'link',
          link: '/#/events',
          icon: 'warning'
        });

        if ($localStorage.user && $localStorage.user.custom) {
          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) {
      $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;
      }, 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 !== 'my' && sub !== 'dashboard' ) {
          getBrand(sub);
          return;
        }
        setDefaultImages();
      } else {
        console.log('Domain error occured');
      }
    }

    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>check for reseller customer<commit_after>'use strict';

var app = angular.module('myApp.controllers', [
  'myApp.authentications.controller',
  'myApp.brands.controller',
  'myApp.boxes.controller',
  'myApp.events.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('Events'),
      link: '/#/events',
      type: 'link',
      icon: 'warning'
    });

    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...');
      var cname = event.data.cname;
      if ((cname === null || cname === '') && event.data.url !== 'default') {
        var sub   = locationHelper.subdomain();
        var host  = locationHelper.domain();
        if (event.data.url && (sub !== event.data.url)) {
          var newUrl = locationHelper.reconstructed(event.data.url);
          var reconstructed = newUrl + '/#/';
          $cookies.put('event', JSON.stringify(event), {'domain': host});
          window.location = reconstructed;
        } else {
          doLogin(event);
        }
      } else {
        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().chat_enabled !== false && Auth.currentUser().user_hash !== undefined)) {
        vm.menu.Intercom = true;
        var intercom_id;
        if ($scope.brandName.reseller === true && Auth.currentUser().reseller !== true) {
          intercom_id = $scope.brandName.intercom_id;
        }
        var settings = {
            app_id: intercom_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'
        };
        settings.widget = {
          activator: '#intercom'
        };
        window.Intercom('boot', settings);
      }
    });

    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'
        });

        vm.menu.main.push({
          title: gettextCatalog.getString('Events'),
          type: 'link',
          link: '/#/events',
          icon: 'warning'
        });

        if ($localStorage.user && $localStorage.user.custom) {
          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) {
      $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
      }, 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 !== 'my' && sub !== 'dashboard' ) {
          getBrand(sub);
          return;
        }
        setDefaultImages();
      } else {
        console.log('Domain error occured');
      }
    }

    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|>