<commit_before>if (typeof phoxy === 'undefined')
  phoxy = {};
if (typeof phoxy.state !== 'undefined')
  if (phoxy.state.loaded === true)
    throw "Phoxy already loaded. Dont mess with this";

var phoxy =
{
  config : false,
  state :
  {
    runlevel: 0,
    /* Runlevels description:
      0 - phoxy ready for instancing but currently not active
      1 - phoxy early stage code ready
      2 - ready for compilation
      3 - compilation finished, configuration fetched
      4 - initial client code executed
      Other levels optional
    */
    loaded : false,
    hash : false,
    ajax :
    {
      nesting_level : 0,
      active_id : 0,
      active : []
    },
    verbose : typeof phoxy.verbose === 'undefined' ? 10 : phoxy.verbose,
    early:
    {
      require: 0,
      loaded: 0,
      optional:
      {
        initial: 0
      }
    },
    exception:
    {
      cases: {},
      handlers: {}
    },
    cascade_debug: true,
    birth:
    {
      active: {},
      finished: {}
    }
  },
  _:
  {
    plugin : {},
    prestart: phoxy
  } // for internal code
};

phoxy._.EarlyStage =
{
  subsystem_dir: '/phoxy/subsystem'
  ,
  systems:
    {
      'early.js': undefined,
      'legacy.js': 'legacy',
      'time.js': 'time',
      'render.js': 'render',
      'api.js': 'api',
      'internal.js': 'internal',
      'click.js': 'click',
      'enjs_overload.js': 'OverrideENJS'
    }
  ,
  sync_require:
    [
    ]
  ,
  async_require:
    [
      "enjs" // composer now IS required
    ]
  ,
  Prepare: function()
    {
      if (typeof requirejs === 'undefined')
        return setTimeout(arguments.callee, 10);
      phoxy.state.runlevel = 0.5;

      requirejs.config(
      {
        waitSeconds: 60
      });

      if (phoxy._.prestart.subsystem_dir)
        phoxy._.EarlyStage.subsystem_dir = phoxy._.prestart.subsystem_dir;

      if (!phoxy._.prestart.wait)
        phoxy._.EarlyStage.EntryPoint();
      else
        if (typeof phoxy._.prestart.OnWaiting === 'function')
          phoxy._.prestart.OnWaiting();
    }
  ,
  EntryPoint: function()
    {
      phoxy.state.runlevel = 1;
      var dir = phoxy._.EarlyStage.subsystem_dir;
      var require_systems = [];

      for (var k in phoxy._.EarlyStage.systems)
        require_systems.push(dir + "/" + k);

      phoxy._.EarlyStage.CriticalRequire(require_systems);
    }
  ,
  Ready: function()
    {
      if (typeof phoxy._.EarlyStage.DependenciesLoaded === 'undefined')
        return setTimeout(arguments.callee, 10);

      phoxy._.EarlyStage.DependenciesLoaded();
    }
  ,
  CriticalRequire : function(require_systems)
    {
      // Summary move us to runlevel 2, ready for compilation
      requirejs.onResourceLoad = function()
      {
        phoxy.state.early.loaded++;
      }

      require
      (
        [require_systems[0]],
        function on_require_early_stage()
        {
          phoxy._.EarlyStage.LoadConfig();
        }
      );

      require
      (
        require_systems,
        function on_require_systems()
        {
          phoxy.state.runlevel += 0.5;
        }
      );

      require
      (
        phoxy._.EarlyStage.sync_require,
        function on_require_sync()
        {
          phoxy.state.runlevel += 0.5;
          phoxy._.EarlyStage.Ready();
        }
      );

      require
      (
        phoxy._.EarlyStage.async_require,
        function on_require_async()
        {
          phoxy._.EarlyStage.EnterFinalExecution();
        }
      );
    }
  ,
  LoadingPercentage : function()
    {
      var phoxy_itself = 1;
      var config_load = 1;
      var system_count = Object.keys(phoxy._.EarlyStage.systems).length;
      var sync_count = phoxy._.EarlyStage.sync_require.length;
      var async_count = phoxy._.EarlyStage.async_require.length;

      var optional_count = 0;

      for (var k in phoxy.state.early.optional)
        optional_count += phoxy.state.early.optional[k];

      phoxy.state.early.require =
        phoxy_itself
          + config_load
          + system_count
          + sync_count
          + async_count
          + optional_count;

      var percent = 100 * phoxy.state.early.loaded / phoxy.state.early.require;
      if (percent > 100)
        percent = 100;

      return percent;
    }
  ,
  Deprecated : function()
    {
      var args = arguments;
      return function deprecated_method_report()
      {
        phoxy.Log.apply(phoxy, args);
      };
    }
}

phoxy._.EarlyStage.Prepare();

if (!Object.keys)
  Object.keys = function(obj)
  {
    var keys = [];

    for (var i in obj)
      if (obj.hasOwnProperty(i))
        keys.push(i);

    return keys;
  };<commit_msg>Fix #153<commit_after>if (typeof phoxy === 'undefined')
  phoxy = {};
if (typeof phoxy.state !== 'undefined')
  if (phoxy.state.loaded === true)
    throw "Phoxy already loaded. Dont mess with this";

var phoxy =
{
  config : false,
  state :
  {
    runlevel: 0,
    /* Runlevels description:
      0 - phoxy ready for instancing but currently not active
      1 - phoxy early stage code ready
      2 - ready for compilation
      3 - compilation finished, configuration fetched
      4 - initial client code executed
      Other levels optional
    */
    loaded : false,
    hash : false,
    ajax :
    {
      nesting_level : 0,
      active_id : 0,
      active : []
    },
    verbose : typeof phoxy.verbose === 'undefined' ? 10 : phoxy.verbose,
    early:
    {
      require: 0,
      loaded: 0,
      optional:
      {
        initial: 0
      }
    },
    exception:
    {
      cases: {},
      handlers: {}
    },
    cascade_debug: true,
    birth:
    {
      active: {},
      finished: {}
    }
  },
  _:
  {
    plugin : {},
    prestart: phoxy
  } // for internal code
};

phoxy._.EarlyStage =
{
  subsystem_dir: '/phoxy/subsystem'
  ,
  systems:
    {
      'early.js': undefined,
      'legacy.js': 'legacy',
      'time.js': 'time',
      'render.js': 'render',
      'api.js': 'api',
      'internal.js': 'internal',
      'click.js': 'click',
      'enjs_overload.js': 'OverrideENJS'
    }
  ,
  sync_require:
    [
    ]
  ,
  async_require:
    [
      "enjs" // composer now IS required
    ]
  ,
  Prepare: function()
    {
      if (typeof requirejs === 'undefined')
        return setTimeout(arguments.callee, 10);
      phoxy.state.runlevel = 0.5;

      requirejs.config(
      {
        waitSeconds: 60
      });

      if (phoxy._.prestart.subsystem_dir)
        phoxy._.EarlyStage.subsystem_dir = phoxy._.prestart.subsystem_dir;

      if (!phoxy._.prestart.wait)
        phoxy._.EarlyStage.EntryPoint();
      else
        if (typeof phoxy._.prestart.OnWaiting === 'function')
          phoxy._.prestart.OnWaiting();
    }
  ,
  EntryPoint: function()
    {
      phoxy.state.runlevel = 1;
      var dir = phoxy._.EarlyStage.subsystem_dir;
      var require_systems = [];

      for (var k in phoxy._.EarlyStage.systems)
        require_systems.push(dir + "/" + k);

      phoxy._.EarlyStage.CriticalRequire(require_systems);
    }
  ,
  Ready: function()
    {
      if (typeof phoxy._.EarlyStage.DependenciesLoaded === 'undefined')
        return setTimeout(arguments.callee, 10);

      phoxy._.EarlyStage.DependenciesLoaded();
    }
  ,
  CriticalRequire : function(require_systems)
    {
      // Summary move us to runlevel 2, ready for compilation
      requirejs.onResourceLoad = function()
      {
        phoxy.state.early.loaded++;
      }

      require
      (
        [require_systems[0]],
        function on_require_early_stage()
        {
          phoxy._.EarlyStage.LoadConfig();
        }
      );

      require
      (
        require_systems,
        function on_require_systems()
        {
          phoxy.state.runlevel += 0.5;
        }
      );

      require
      (
        phoxy._.EarlyStage.sync_require,
        function on_require_sync()
        {
          phoxy.state.runlevel += 0.5;
          phoxy._.EarlyStage.Ready();
        }
      );

      require
      (
        phoxy._.EarlyStage.async_require,
        function on_require_async()
        {
          // Wait for sync code to finish
          if (phoxy.state.runlevel < 2)
            return setTimeout(arguments.callee, 10);

          phoxy._.EarlyStage.EnterFinalExecution();
        }
      );
    }
  ,
  LoadingPercentage : function()
    {
      var phoxy_itself = 1;
      var config_load = 1;
      var system_count = Object.keys(phoxy._.EarlyStage.systems).length;
      var sync_count = phoxy._.EarlyStage.sync_require.length;
      var async_count = phoxy._.EarlyStage.async_require.length;

      var optional_count = 0;

      for (var k in phoxy.state.early.optional)
        optional_count += phoxy.state.early.optional[k];

      phoxy.state.early.require =
        phoxy_itself
          + config_load
          + system_count
          + sync_count
          + async_count
          + optional_count;

      var percent = 100 * phoxy.state.early.loaded / phoxy.state.early.require;
      if (percent > 100)
        percent = 100;

      return percent;
    }
  ,
  Deprecated : function()
    {
      var args = arguments;
      return function deprecated_method_report()
      {
        phoxy.Log.apply(phoxy, args);
      };
    }
}

phoxy._.EarlyStage.Prepare();

if (!Object.keys)
  Object.keys = function(obj)
  {
    var keys = [];

    for (var i in obj)
      if (obj.hasOwnProperty(i))
        keys.push(i);

    return keys;
  };<|endoftext|>


<commit_before>'use strict';

(function(){

    var moduleSgUtilsIso3166 = angular.module('sg-utils-iso3166', []);
    var moduleSgUtilsIso4217 = angular.module('sg-utils-iso4217', []);
    var moduleSgUtilsUbigeo = angular.module('sg-utils-ubigeo', []);
    var moduleSgUtilsPersona = angular.module('sg-utils-persona', []);
    var moduleSgUtilsOrganizacion = angular.module('sg-utils-organizacion', []);
    var moduleSgUtilsCooperativa = angular.module('sg-utils-cooperativa', []);
    var moduleSgUtilsProducto = angular.module('sg-utils-producto', []);

    var moduleSgUtils = angular.module('sg-utils',
        [
            'sg-utils-iso3166',
            'sg-utils-iso4217',
            'sg-utils-ubigeo',
            'sg-utils-persona',
            'sg-utils-organizacion',
            'sg-utils-cooperativa',
            'sg-utils-producto'
        ]);

    /**
     * Module sg-utils.
     *
     * Utils generales para sg.
     * Estas clases no necesitan dependencias.
     */

    moduleSgUtils.filter('si_no', function() {
        return function(input, mode) {
            var defaultResult = ['Si', 'No'];
            var modeOneResult = ['Activo', 'Inactivo'];
            var modeTwoResult = ['Abierto', 'Cerrado'];
            var modeTreeResult = ['Descongelado', 'Congelado'];

            var result = defaultResult;
            if(mode){
                if(mode.toLowerCase() == 'si'){
                    result = defaultResult;
                } else if(mode.toLowerCase() == 'activo'){
                    result = modeOneResult;
                } else if(mode.toLowerCase() == 'abierto'){
                    result = modeTwoResult;
                } else if(mode.toLowerCase() == 'congelado'){
                    result = modeTreeResult;
                } else {
                    result = defaultResult;
                }
            }

            if (input) {
                return result[0];
            }
            return result[1];
        }
    });

    moduleSgUtils.directive('sgMaxDate', function() {
        return {
            require: 'ngModel',
            link: function($scope, elem, attrs, ngModel) {
                ngModel.$validators.sgmaxdate = function(modelValue,viewValue){
                    var value = modelValue || viewValue;
                    return $scope.maxDate >= value;
                }
            }
        };
    });

    /**
     * Module sg-utils-iso3166.
     *
     * Utils generales para sg-utils-iso3166.
     * Estas clases dependen de sg-3166.
     */

    /**
     * Module sg-utils-iso4217.
     *
     * Utils generales para sg-utils-iso4217.
     * Estas clases dependen de sg-4217.
     */

    /**
     * Module sg-utils-ubigeo.
     *
     * Utils generales para sg-utils-ubigeo.
     * Estas clases dependen de sg-ubigeo.
     */

    moduleSgUtilsUbigeo.directive('sgUbigeo',function(SGDepartamento, SGProvincia, SGDistrito){
        return {
            restrict:'E',
            replace: false,
            require: ['^form','ngModel'],
            link: function($scope, elem, attrs, ngModel){

                ngModel[1].$validators.sgubigeo = function(modelValue,viewValue){
                    var value = modelValue || viewValue;
                    value = value ? value : '';
                    //false representa error y true represeta exito
                    if($scope.requerido)
                        return (value.length == 6);
                    else
                        return (value.length == 6  || value.length == 0);
                };

                SGDepartamento.$search().then(function(data){
                    $scope.departamentos = data;
                    $scope.activeListener();
                });
                $scope.provincias = undefined;
                $scope.distritos = undefined;

                $scope.ubigeo = {
                    departamento: undefined,
                    provincia: undefined,
                    distrito: undefined
                };

                $scope.$watch('ubigeo.departamento', function(){
                    if(!angular.isUndefined($scope.ubigeo.departamento) && $scope.ubigeo.departamento){
                        $scope.provincias = $scope.ubigeo.departamento.$getProvincias().$object;
                        ngModel[1].$setDirty();
                    } else {
                        $scope.ubigeo.provincia = undefined;
                        $scope.ubigeo.distrito = undefined;

                        $scope.provincias = undefined;
                        $scope.distritos = undefined;
                    }
                });
                $scope.$watch('ubigeo.provincia', function(){
                    if(!angular.isUndefined($scope.ubigeo.provincia) && $scope.ubigeo.provincia){
                        $scope.distritos = SGProvincia.$getDistritos($scope.ubigeo.departamento.codigo, $scope.ubigeo.provincia.codigo).$object;
                    } else {
                        $scope.ubigeo.distrito = undefined;

                        $scope.distritos = undefined;
                    }
                });
                $scope.$watch('ubigeo.distrito', function(){
                    if(!angular.isUndefined($scope.ubigeo.distrito) && $scope.ubigeo.distrito){
                        var ubigeo = $scope.ubigeo.departamento.codigo + $scope.ubigeo.provincia.codigo + $scope.ubigeo.distrito.codigo;
                        ngModel[1].$setViewValue(ubigeo);
                    }
                });

                $scope.activeListener = function(){
                    var listener = $scope.$watch(function(){return ngModel[1].$modelValue}, function(){
                        if( ngModel[1].$modelValue
                            && ngModel[1].$modelValue.length == 6
                                //&& angular.isUndefined($scope.departamentos)
                            && angular.isUndefined($scope.provincias)
                            && angular.isUndefined($scope.distritos)){

                            for(var i=0;i<$scope.departamentos.length;i++){
                                if($scope.departamentos[i].codigo == ngModel[1].$modelValue.substring(0, 2)){
                                    $scope.ubigeo.departamento = $scope.departamentos[i];
                                    break;
                                }
                            }

                            $scope.ubigeo.departamento.$getProvincias().then(function(data){
                                $scope.provincias = data;
                                for(var i=0;i<$scope.provincias.length;i++){
                                    if($scope.provincias[i].codigo == ngModel[1].$modelValue.substring(2, 4)){
                                        $scope.ubigeo.provincia = $scope.provincias[i];
                                        break;
                                    }
                                }

                                SGProvincia.distritos($scope.ubigeo.departamento.codigo, $scope.ubigeo.provincia.codigo).then(function(data){
                                    $scope.distritos = data;

                                    for(var i=0;i<$scope.distritos.length;i++){
                                        if($scope.distritos[i].codigo == ngModel[1].$modelValue.substring(4, 6)){
                                            $scope.ubigeo.distrito = $scope.distritos[i];
                                            break;
                                        }
                                    }
                                });

                            });
                            listener();
                        } else {
                            listener();
                        }
                    });
                };
            },
            scope: {
                requerido: '@'
            },
            template: ''
            +'
'
            +'
'
            +'
'
            +'Departamento'
            +'<ui-select name="departamento" ng-model="ubigeo.departamento">'
            +'<ui-select-match placeholder="Seleccione">{{$select.selected.denominacion}}</ui-select-match>'
            +'<ui-select-choices repeat="item in departamentos | filter: $select.search">'
            +'

'
            +''
            +'</ui-select-choices>'
            +'</ui-select>'
            +'
'
            +'
Ingrese departamento.
'
            +'
'
            +'
'
            +'
'
            +'
'
            +'
'
            +'Provincia'
            +'<ui-select name="provincia" ng-model="ubigeo.provincia">'
            +'<ui-select-match placeholder="Seleccione">{{$select.selected.denominacion}}</ui-select-match>'
            +'<ui-select-choices repeat="item in provincias | filter: $select.search">'
            +'

'
            +''
            +'</ui-select-choices>'
            +'</ui-select>'
            +'
'
            +'
Ingrese provincia.
'
            +'
'
            +'
'
            +'
'
            +'
'
            +'
'
            +'Distrito'
            +'<ui-select name="distrito" ng-model="ubigeo.distrito">'
            +'<ui-select-match placeholder="Seleccione">{{$select.selected.denominacion}}</ui-select-match>'
            +'<ui-select-choices repeat="item in distritos | filter: $select.search">'
            +'

'
            +''
            +'</ui-select-choices>'
            +'</ui-select>'
            +'
'
            +'
Ingrese provincia.
'
            +'
'
            +'
'
            +'
'
            +'
'
        }
    });

    /**
     * Module sg-utils-persona.
     *
     * Utils generales para sg-utils-persona.
     * Estas clases dependen de sg-persona.
     */

})();<commit_msg>sgMaxDate<commit_after>'use strict';

(function(){

    var moduleSgUtilsIso3166 = angular.module('sg-utils-iso3166', []);
    var moduleSgUtilsIso4217 = angular.module('sg-utils-iso4217', []);
    var moduleSgUtilsUbigeo = angular.module('sg-utils-ubigeo', []);
    var moduleSgUtilsPersona = angular.module('sg-utils-persona', []);
    var moduleSgUtilsOrganizacion = angular.module('sg-utils-organizacion', []);
    var moduleSgUtilsCooperativa = angular.module('sg-utils-cooperativa', []);
    var moduleSgUtilsProducto = angular.module('sg-utils-producto', []);

    var moduleSgUtils = angular.module('sg-utils',
        [
            'sg-utils-iso3166',
            'sg-utils-iso4217',
            'sg-utils-ubigeo',
            'sg-utils-persona',
            'sg-utils-organizacion',
            'sg-utils-cooperativa',
            'sg-utils-producto'
        ]);

    /**
     * Module sg-utils.
     *
     * Utils generales para sg.
     * Estas clases no necesitan dependencias.
     */

    moduleSgUtils.filter('si_no', function() {
        return function(input, mode) {
            var defaultResult = ['Si', 'No'];
            var modeOneResult = ['Activo', 'Inactivo'];
            var modeTwoResult = ['Abierto', 'Cerrado'];
            var modeTreeResult = ['Descongelado', 'Congelado'];

            var result = defaultResult;
            if(mode){
                if(mode.toLowerCase() == 'si'){
                    result = defaultResult;
                } else if(mode.toLowerCase() == 'activo'){
                    result = modeOneResult;
                } else if(mode.toLowerCase() == 'abierto'){
                    result = modeTwoResult;
                } else if(mode.toLowerCase() == 'congelado'){
                    result = modeTreeResult;
                } else {
                    result = defaultResult;
                }
            }

            if (input) {
                return result[0];
            }
            return result[1];
        }
    });

    moduleSgUtils.directive('sgMaxDate', function() {
        return {
            require: 'ngModel',
            link: function($scope, elem, attrs, ngModel) {
                ngModel.$validators.sgmaxdate = function(modelValue,viewValue){
                    var value = modelValue || viewValue;
                    return $scope.maxDate >= value;
                }
            }
        };
    });

    /**
     * Module sg-utils-iso3166.
     *
     * Utils generales para sg-utils-iso3166.
     * Estas clases dependen de sg-3166.
     */

    /**
     * Module sg-utils-iso4217.
     *
     * Utils generales para sg-utils-iso4217.
     * Estas clases dependen de sg-4217.
     */

    /**
     * Module sg-utils-ubigeo.
     *
     * Utils generales para sg-utils-ubigeo.
     * Estas clases dependen de sg-ubigeo.
     */

    moduleSgUtilsUbigeo.directive('sgUbigeo',function(SGDepartamento, SGProvincia, SGDistrito){
        return {
            restrict:'E',
            replace: false,
            require: ['^form','ngModel'],
            link: function($scope, elem, attrs, ngModel){

                ngModel[1].$validators.sgubigeo = function(modelValue,viewValue){
                    var value = modelValue || viewValue;
                    value = value ? value : '';
                    //false representa error y true represeta exito
                    if($scope.requerido)
                        return (value.length == 6);
                    else
                        return (value.length == 6  || value.length == 0);
                };

                SGDepartamento.$search().then(function(data){
                    $scope.departamentos = data;
                    $scope.activeListener();
                });
                $scope.provincias = undefined;
                $scope.distritos = undefined;

                $scope.ubigeo = {
                    departamento: undefined,
                    provincia: undefined,
                    distrito: undefined
                };

                $scope.$watch('ubigeo.departamento', function(){
                    if(!angular.isUndefined($scope.ubigeo.departamento) && $scope.ubigeo.departamento){
                        $scope.provincias = $scope.ubigeo.departamento.$getProvincias().$object;
                        ngModel[1].$setDirty();
                    } else {
                        $scope.ubigeo.provincia = undefined;
                        $scope.ubigeo.distrito = undefined;

                        $scope.provincias = undefined;
                        $scope.distritos = undefined;
                    }
                });
                $scope.$watch('ubigeo.provincia', function(){
                    if(!angular.isUndefined($scope.ubigeo.provincia) && $scope.ubigeo.provincia){
                        $scope.distritos = SGProvincia.$getDistritos($scope.ubigeo.departamento.codigo, $scope.ubigeo.provincia.codigo).$object;
                    } else {
                        $scope.ubigeo.distrito = undefined;

                        $scope.distritos = undefined;
                    }
                });
                $scope.$watch('ubigeo.distrito', function(){
                    if(!angular.isUndefined($scope.ubigeo.distrito) && $scope.ubigeo.distrito){
                        var ubigeo = $scope.ubigeo.departamento.codigo + $scope.ubigeo.provincia.codigo + $scope.ubigeo.distrito.codigo;
                        ngModel[1].$setViewValue(ubigeo);
                    }
                });

                $scope.activeListener = function(){
                    var listener = $scope.$watch(function(){return ngModel[1].$modelValue}, function(){
                        if( ngModel[1].$modelValue
                            && ngModel[1].$modelValue.length == 6
                                //&& angular.isUndefined($scope.departamentos)
                            && angular.isUndefined($scope.provincias)
                            && angular.isUndefined($scope.distritos)){

                            for(var i=0;i<$scope.departamentos.length;i++){
                                if($scope.departamentos[i].codigo == ngModel[1].$modelValue.substring(0, 2)){
                                    $scope.ubigeo.departamento = $scope.departamentos[i];
                                    break;
                                }
                            }

                            $scope.ubigeo.departamento.$getProvincias().then(function(data){
                                $scope.provincias = data;
                                for(var i=0;i<$scope.provincias.length;i++){
                                    if($scope.provincias[i].codigo == ngModel[1].$modelValue.substring(2, 4)){
                                        $scope.ubigeo.provincia = $scope.provincias[i];
                                        break;
                                    }
                                }

                                SGProvincia.distritos($scope.ubigeo.departamento.codigo, $scope.ubigeo.provincia.codigo).then(function(data){
                                    $scope.distritos = data;

                                    for(var i=0;i<$scope.distritos.length;i++){
                                        if($scope.distritos[i].codigo == ngModel[1].$modelValue.substring(4, 6)){
                                            $scope.ubigeo.distrito = $scope.distritos[i];
                                            break;
                                        }
                                    }
                                });

                            });
                            listener();
                        } else {
                            listener();
                        }
                    });
                };
            },
            scope: {
                requerido: '@'
            },
            template: ''
            +'
'
            +'
'
            +'
'
            +'Departamento'
            +'<ui-select name="departamento" ng-model="ubigeo.departamento">'
            +'<ui-select-match placeholder="Seleccione">{{$select.selected.denominacion}}</ui-select-match>'
            +'<ui-select-choices repeat="item in departamentos | filter: $select.search">'
            +'

'
            +''
            +'</ui-select-choices>'
            +'</ui-select>'
            +'
'
            +'
Ingrese departamento.
'
            +'
'
            +'
'
            +'
'
            +'
'
            +'
'
            +'Provincia'
            +'<ui-select name="provincia" ng-model="ubigeo.provincia">'
            +'<ui-select-match placeholder="Seleccione">{{$select.selected.denominacion}}</ui-select-match>'
            +'<ui-select-choices repeat="item in provincias | filter: $select.search">'
            +'

'
            +''
            +'</ui-select-choices>'
            +'</ui-select>'
            +'
'
            +'
Ingrese provincia.
'
            +'
'
            +'
'
            +'
'
            +'
'
            +'
'
            +'Distrito'
            +'<ui-select name="distrito" ng-model="ubigeo.distrito">'
            +'<ui-select-match placeholder="Seleccione">{{$select.selected.denominacion}}</ui-select-match>'
            +'<ui-select-choices repeat="item in distritos | filter: $select.search">'
            +'

'
            +''
            +'</ui-select-choices>'
            +'</ui-select>'
            +'
'
            +'
Ingrese provincia.
'
            +'
'
            +'
'
            +'
'
            +'
'
        }
    });

    /**
     * Module sg-utils-persona.
     *
     * Utils generales para sg-utils-persona.
     * Estas clases dependen de sg-persona.
     */

})();<|endoftext|>


<commit_before>/*
 jQuery UI Sortable plugin wrapper

 @param [ui-sortable] {object} Options to pass to $.fn.sortable() merged onto ui.config
 */
angular.module('ui.sortable', [])
  .value('uiSortableConfig',{
    // the default for jquery-ui sortable is "> *", we need to restrict this to
    // ng-repeat items
    // if the user uses
    items: '> [ng-repeat],> [data-ng-repeat],> [x-ng-repeat]'
  })
  .directive('uiSortable', [
    'uiSortableConfig', '$timeout', '$log',
    function(uiSortableConfig, $timeout, $log) {
      return {
        require: '?ngModel',
        scope: {
          ngModel: '=',
          uiSortable: '='
        },
        link: function(scope, element, attrs, ngModel) {
          var savedNodes;

          function combineCallbacks(first, second){
            var firstIsFunc = first && (typeof first === 'function');
            var secondIsFunc = second && (typeof second === 'function');
            if(firstIsFunc && secondIsFunc) {
              return function() {
                first.apply(this, arguments);
                second.apply(this, arguments);
              };
            } else if (secondIsFunc) {
              return second;
            }
            return first;
          }

          function getSortableWidgetInstance(element) {
            // this is a fix to support jquery-ui prior to v1.11.x
            // otherwise we should be using `element.sortable('instance')`
            var data = element.data('ui-sortable');
            if (data && typeof data === 'object' && data.widgetFullName === 'ui-sortable') {
              return data;
            }
            return null;
          }

          function patchSortableOption(key, value) {
            if (callbacks[key]) {
              if( key === 'stop' ){
                // call apply after stop
                value = combineCallbacks(
                  value, function() { scope.$apply(); });

                value = combineCallbacks(value, afterStop);
              }
              // wrap the callback
              value = combineCallbacks(callbacks[key], value);
            } else if (wrappers[key]) {
              value = wrappers[key](value);
            }

            if (key === 'items' && !value) {
              value = uiSortableConfig.items;
            }

            return value;
          }

          function patchUISortableOptions(newVal, oldVal, sortableWidgetInstance) {
            function addDummyOptionKey(value, key) {
              if (!(key in opts)) {
                // add the key in the opts object so that
                // the patch function detects and handles it
                opts[key] = null;
              }
            }
            // for this directive to work we have to attach some callbacks
            angular.forEach(callbacks, addDummyOptionKey);

            // only initialize it in case we have to
            // update some options of the sortable
            var optsDiff = null;

            if (oldVal) {
              // reset deleted options to default
              var defaultOptions;
              angular.forEach(oldVal, function(oldValue, key) {
                if (!newVal || !(key in newVal)) {
                  if (key in directiveOpts) {
                    opts[key] = 'auto';
                    return;
                  }

                  if (!defaultOptions) {
                    defaultOptions = angular.element.ui.sortable().options;
                  }
                  var defaultValue = defaultOptions[key];
                  defaultValue = patchSortableOption(key, defaultValue);

                  if (!optsDiff) {
                    optsDiff = {};
                  }
                  optsDiff[key] = defaultValue;
                  opts[key] = defaultValue;
                }
              });
            }

            // update changed options
            angular.forEach(newVal, function(value, key) {
              // if it's a custom option of the directive,
              // handle it approprietly
              if (key in directiveOpts) {
                if (key === 'ui-floating' && (value === false || value === true) && sortableWidgetInstance) {
                  sortableWidgetInstance.floating = value;
                }

                opts[key] = value;
                return;
              }

              value = patchSortableOption(key, value);

              if (!optsDiff) {
                optsDiff = {};
              }
              optsDiff[key] = value;
              opts[key] = value;
            });

            return optsDiff;
          }

          function getPlaceholderElement (element) {
            var placeholder = element.sortable('option','placeholder');

            // placeholder.element will be a function if the placeholder, has
            // been created (placeholder will be an object).  If it hasn't
            // been created, either placeholder will be false if no
            // placeholder class was given or placeholder.element will be
            // undefined if a class was given (placeholder will be a string)
            if (placeholder && placeholder.element && typeof placeholder.element === 'function') {
              var result = placeholder.element();
              // workaround for jquery ui 1.9.x,
              // not returning jquery collection
              result = angular.element(result);
              return result;
            }
            return null;
          }

          function getPlaceholderExcludesludes (element, placeholder) {
            // exact match with the placeholder's class attribute to handle
            // the case that multiple connected sortables exist and
            // the placehoilder option equals the class of sortable items
            var notCssSelector = uiSortableConfig.items.replace(/>/g, '');
            var excludes = element.find('[class="' + placeholder.attr('class') + '"]:not(' + notCssSelector + ')');
            return excludes;
          }

          function hasSortingHelper (element, ui) {
            var helperOption = element.sortable('option','helper');
            return helperOption === 'clone' || (typeof helperOption === 'function' && ui.item.sortable.isCustomHelperUsed());
          }

          function getSortingHelper (element, ui, savedNodes) {
            var result = null;
            if (hasSortingHelper(element, ui) &&
                element.sortable( 'option', 'appendTo' ) === 'parent') {
              // The .ui-sortable-helper element (that's the default class name)
              // is placed last.
              result = savedNodes.last();
            }
            return result;
          }

          // thanks jquery-ui
          function isFloating (item) {
            return (/left|right/).test(item.css('float')) || (/inline|table-cell/).test(item.css('display'));
          }

          function getElementScope(elementScopes, element) {
            var result = null;
            for (var i = 0; i < elementScopes.length; i++) {
              var x = elementScopes[i];
              if (x.element[0] === element[0]) {
                result = x.scope;
                break;
              }
            }
            return result;
          }

          function afterStop(e, ui) {
            ui.item.sortable._destroy();
          }

          // return the index of ui.item among the items
          // we can't just do ui.item.index() because there it might have siblings
          // which are not items
          function getItemIndex(ui) {
            return ui.item.parent().find(uiSortableConfig.items)
              .index(ui.item);
          }

          var opts = {};

          // directive specific options
          var directiveOpts = {
            'ui-floating': undefined
          };

          var callbacks = {
            receive: null,
            remove:null,
            start:null,
            stop:null,
            update:null
          };

          var wrappers = {
            helper: null
          };

          angular.extend(opts, directiveOpts, uiSortableConfig, scope.uiSortable);

          if (!angular.element.fn || !angular.element.fn.jquery) {
            $log.error('ui.sortable: jQuery should be included before AngularJS!');
            return;
          }

          function wireUp () {
            // When we add or remove elements, we need the sortable to 'refresh'
            // so it can find the new/removed elements.
            scope.$watchCollection('ngModel', function() {
              // Timeout to let ng-repeat modify the DOM
              $timeout(function() {
                // ensure that the jquery-ui-sortable widget instance
                // is still bound to the directive's element
                if (!!getSortableWidgetInstance(element)) {
                  element.sortable('refresh');
                }
              }, 0, false);
            });

            callbacks.start = function(e, ui) {
              if (opts['ui-floating'] === 'auto') {
                // since the drag has started, the element will be
                // absolutely positioned, so we check its siblings
                var siblings = ui.item.siblings();
                var sortableWidgetInstance = getSortableWidgetInstance(angular.element(e.target));
                sortableWidgetInstance.floating = isFloating(siblings);
              }

              // Save the starting position of dragged item
              var index = getItemIndex(ui);
              ui.item.sortable = {
                model: ngModel.$modelValue[index],
                index: index,
                source: ui.item.parent(),
                sourceModel: ngModel.$modelValue,
                cancel: function () {
                  ui.item.sortable._isCanceled = true;
                },
                isCanceled: function () {
                  return ui.item.sortable._isCanceled;
                },
                isCustomHelperUsed: function () {
                  return !!ui.item.sortable._isCustomHelperUsed;
                },
                _isCanceled: false,
                _isCustomHelperUsed: ui.item.sortable._isCustomHelperUsed,
                _destroy: function () {
                  angular.forEach(ui.item.sortable, function(value, key) {
                    ui.item.sortable[key] = undefined;
                  });
                }
              };
            };

            callbacks.activate = function(e, ui) {
              // We need to make a copy of the current element's contents so
              // we can restore it after sortable has messed it up.
              // This is inside activate (instead of start) in order to save
              // both lists when dragging between connected lists.
              savedNodes = element.contents();

              // If this list has a placeholder (the connected lists won't),
              // don't inlcude it in saved nodes.
              var placeholder = getPlaceholderElement(element);
              if (placeholder && placeholder.length) {
                var excludes = getPlaceholderExcludesludes(element, placeholder);
                savedNodes = savedNodes.not(excludes);
              }

              // save the directive's scope so that it is accessible from ui.item.sortable
              var connectedSortables = ui.item.sortable._connectedSortables || [];

              connectedSortables.push({
                element: element,
                scope: scope
              });

              ui.item.sortable._connectedSortables = connectedSortables;
            };

            callbacks.update = function(e, ui) {
              // Save current drop position but only if this is not a second
              // update that happens when moving between lists because then
              // the value will be overwritten with the old value
              if(!ui.item.sortable.received) {
                ui.item.sortable.dropindex = getItemIndex(ui);
                var droptarget = ui.item.parent();
                ui.item.sortable.droptarget = droptarget;

                var droptargetScope = getElementScope(ui.item.sortable._connectedSortables, droptarget);
                ui.item.sortable.droptargetModel = droptargetScope.ngModel;

                // Cancel the sort (let ng-repeat do the sort for us)
                // Don't cancel if this is the received list because it has
                // already been canceled in the other list, and trying to cancel
                // here will mess up the DOM.
                element.sortable('cancel');
              }

              // Put the nodes back exactly the way they started (this is very
              // important because ng-repeat uses comment elements to delineate
              // the start and stop of repeat sections and sortable doesn't
              // respect their order (even if we cancel, the order of the
              // comments are still messed up).
              var sortingHelper = !ui.item.sortable.received && getSortingHelper(element, ui, savedNodes);
              if (sortingHelper && sortingHelper.length) {
                // Restore all the savedNodes except from the sorting helper element.
                // That way it will be garbage collected.
                savedNodes = savedNodes.not(sortingHelper);
              }
              savedNodes.appendTo(element);

              // If this is the target connected list then
              // it's safe to clear the restored nodes since:
              // update is currently running and
              // stop is not called for the target list.
              if(ui.item.sortable.received) {
                savedNodes = null;
              }

              // If received is true (an item was dropped in from another list)
              // then we add the new item to this list otherwise wait until the
              // stop event where we will know if it was a sort or item was
              // moved here from another list
              if(ui.item.sortable.received && !ui.item.sortable.isCanceled()) {
                scope.$apply(function () {
                  ngModel.$modelValue.splice(ui.item.sortable.dropindex, 0,
                                             ui.item.sortable.moved);
                });
              }
            };

            callbacks.stop = function(e, ui) {
              // If the received flag hasn't be set on the item, this is a
              // normal sort, if dropindex is set, the item was moved, so move
              // the items in the list.
              if(!ui.item.sortable.received &&
                 ('dropindex' in ui.item.sortable) &&
                 !ui.item.sortable.isCanceled()) {

                scope.$apply(function () {
                  ngModel.$modelValue.splice(
                    ui.item.sortable.dropindex, 0,
                    ngModel.$modelValue.splice(ui.item.sortable.index, 1)[0]);
                });
              } else {
                // if the item was not moved, then restore the elements
                // so that the ngRepeat's comment are correct.
                if ((!('dropindex' in ui.item.sortable) || ui.item.sortable.isCanceled()) &&
                    !angular.equals(element.contents(), savedNodes)) {

                  var sortingHelper = getSortingHelper(element, ui, savedNodes);
                  if (sortingHelper && sortingHelper.length) {
                    // Restore all the savedNodes except from the sorting helper element.
                    // That way it will be garbage collected.
                    savedNodes = savedNodes.not(sortingHelper);
                  }
                  savedNodes.appendTo(element);
                }
              }

              // It's now safe to clear the savedNodes
              // since stop is the last callback.
              savedNodes = null;
            };

            callbacks.receive = function(e, ui) {
              // An item was dropped here from another list, set a flag on the
              // item.
              ui.item.sortable.received = true;
            };

            callbacks.remove = function(e, ui) {
              // Workaround for a problem observed in nested connected lists.
              // There should be an 'update' event before 'remove' when moving
              // elements. If the event did not fire, cancel sorting.
              if (!('dropindex' in ui.item.sortable)) {
                element.sortable('cancel');
                ui.item.sortable.cancel();
              }

              // Remove the item from this list's model and copy data into item,
              // so the next list can retrive it
              if (!ui.item.sortable.isCanceled()) {
                scope.$apply(function () {
                  ui.item.sortable.moved = ngModel.$modelValue.splice(
                    ui.item.sortable.index, 1)[0];
                });
              }
            };

            wrappers.helper = function (inner) {
              if (inner && typeof inner === 'function') {
                return function (e, item) {
                  var innerResult = inner.apply(this, arguments);
                  item.sortable._isCustomHelperUsed = item !== innerResult;
                  return innerResult;
                };
              }
              return inner;
            };

            scope.$watchCollection('uiSortable', function(newVal, oldVal) {
              // ensure that the jquery-ui-sortable widget instance
              // is still bound to the directive's element
              var sortableWidgetInstance = getSortableWidgetInstance(element);
              if (!!sortableWidgetInstance) {
                var optsDiff = patchUISortableOptions(newVal, oldVal, sortableWidgetInstance);

                if (optsDiff) {
                  element.sortable('option', optsDiff);
                }
              }
            }, true);

            patchUISortableOptions(opts);
          }

          function init () {
            if (ngModel) {
              wireUp();
            } else {
              $log.info('ui.sortable: ngModel not provided!', element);
            }

            // Create sortable
            element.sortable(opts);
          }

          function initIfEnabled () {
            if (scope.uiSortable && scope.uiSortable.disabled) {
              return false;
            }

            init();

            // Stop Watcher
            initIfEnabled.cancelWatcher();
            initIfEnabled.cancelWatcher = angular.noop;

            return true;
          }

          initIfEnabled.cancelWatcher = angular.noop;

          if (!initIfEnabled()) {
            initIfEnabled.cancelWatcher = scope.$watch('uiSortable.disabled', initIfEnabled);
          }
        }
      };
    }
  ]);
<commit_msg>feat(sortable): add ui-model-item option, sets the model generated items<commit_after>/*
 jQuery UI Sortable plugin wrapper

 @param [ui-sortable] {object} Options to pass to $.fn.sortable() merged onto ui.config
 */
angular.module('ui.sortable', [])
  .value('uiSortableConfig',{
    // the default for jquery-ui sortable is "> *", we need to restrict this to
    // ng-repeat items
    // if the user uses
    items: '> [ng-repeat],> [data-ng-repeat],> [x-ng-repeat]'
  })
  .directive('uiSortable', [
    'uiSortableConfig', '$timeout', '$log',
    function(uiSortableConfig, $timeout, $log) {
      return {
        require: '?ngModel',
        scope: {
          ngModel: '=',
          uiSortable: '='
        },
        link: function(scope, element, attrs, ngModel) {
          var savedNodes;

          function combineCallbacks(first, second){
            var firstIsFunc = first && (typeof first === 'function');
            var secondIsFunc = second && (typeof second === 'function');
            if(firstIsFunc && secondIsFunc) {
              return function() {
                first.apply(this, arguments);
                second.apply(this, arguments);
              };
            } else if (secondIsFunc) {
              return second;
            }
            return first;
          }

          function getSortableWidgetInstance(element) {
            // this is a fix to support jquery-ui prior to v1.11.x
            // otherwise we should be using `element.sortable('instance')`
            var data = element.data('ui-sortable');
            if (data && typeof data === 'object' && data.widgetFullName === 'ui-sortable') {
              return data;
            }
            return null;
          }

          function patchSortableOption(key, value) {
            if (callbacks[key]) {
              if( key === 'stop' ){
                // call apply after stop
                value = combineCallbacks(
                  value, function() { scope.$apply(); });

                value = combineCallbacks(value, afterStop);
              }
              // wrap the callback
              value = combineCallbacks(callbacks[key], value);
            } else if (wrappers[key]) {
              value = wrappers[key](value);
            }

            // patch the options that need to have values set
            if (!value) {
              if (key === 'items') {
                value = uiSortableConfig.items;
              } else if (key === 'ui-model-items') {
                value = uiSortableConfig.items;
              }
            }

            return value;
          }

          function patchUISortableOptions(newVal, oldVal, sortableWidgetInstance) {
            function addDummyOptionKey(value, key) {
              if (!(key in opts)) {
                // add the key in the opts object so that
                // the patch function detects and handles it
                opts[key] = null;
              }
            }
            // for this directive to work we have to attach some callbacks
            angular.forEach(callbacks, addDummyOptionKey);

            // only initialize it in case we have to
            // update some options of the sortable
            var optsDiff = null;

            if (oldVal) {
              // reset deleted options to default
              var defaultOptions;
              angular.forEach(oldVal, function(oldValue, key) {
                if (!newVal || !(key in newVal)) {
                  if (key in directiveOpts) {
                    if (key === 'ui-floating') {
                      opts[key] = 'auto';
                    } else {
                      opts[key] = patchSortableOption(key, undefined);
                    }
                    return;
                  }

                  if (!defaultOptions) {
                    defaultOptions = angular.element.ui.sortable().options;
                  }
                  var defaultValue = defaultOptions[key];
                  defaultValue = patchSortableOption(key, defaultValue);

                  if (!optsDiff) {
                    optsDiff = {};
                  }
                  optsDiff[key] = defaultValue;
                  opts[key] = defaultValue;
                }
              });
            }

            // update changed options
            angular.forEach(newVal, function(value, key) {
              // if it's a custom option of the directive,
              // handle it approprietly
              if (key in directiveOpts) {
                if (key === 'ui-floating' && (value === false || value === true) && sortableWidgetInstance) {
                  sortableWidgetInstance.floating = value;
                }

                opts[key] = patchSortableOption(key, value);
                return;
              }

              value = patchSortableOption(key, value);

              if (!optsDiff) {
                optsDiff = {};
              }
              optsDiff[key] = value;
              opts[key] = value;
            });

            return optsDiff;
          }

          function getPlaceholderElement (element) {
            var placeholder = element.sortable('option','placeholder');

            // placeholder.element will be a function if the placeholder, has
            // been created (placeholder will be an object).  If it hasn't
            // been created, either placeholder will be false if no
            // placeholder class was given or placeholder.element will be
            // undefined if a class was given (placeholder will be a string)
            if (placeholder && placeholder.element && typeof placeholder.element === 'function') {
              var result = placeholder.element();
              // workaround for jquery ui 1.9.x,
              // not returning jquery collection
              result = angular.element(result);
              return result;
            }
            return null;
          }

          function getPlaceholderExcludesludes (element, placeholder) {
            // exact match with the placeholder's class attribute to handle
            // the case that multiple connected sortables exist and
            // the placeholder option equals the class of sortable items
            var notCssSelector = opts['ui-model-items'].replace(/[^,]*>/g, '');
            var excludes = element.find('[class="' + placeholder.attr('class') + '"]:not(' + notCssSelector + ')');
            return excludes;
          }

          function hasSortingHelper (element, ui) {
            var helperOption = element.sortable('option','helper');
            return helperOption === 'clone' || (typeof helperOption === 'function' && ui.item.sortable.isCustomHelperUsed());
          }

          function getSortingHelper (element, ui, savedNodes) {
            var result = null;
            if (hasSortingHelper(element, ui) &&
                element.sortable( 'option', 'appendTo' ) === 'parent') {
              // The .ui-sortable-helper element (that's the default class name)
              // is placed last.
              result = savedNodes.last();
            }
            return result;
          }

          // thanks jquery-ui
          function isFloating (item) {
            return (/left|right/).test(item.css('float')) || (/inline|table-cell/).test(item.css('display'));
          }

          function getElementScope(elementScopes, element) {
            var result = null;
            for (var i = 0; i < elementScopes.length; i++) {
              var x = elementScopes[i];
              if (x.element[0] === element[0]) {
                result = x.scope;
                break;
              }
            }
            return result;
          }

          function afterStop(e, ui) {
            ui.item.sortable._destroy();
          }

          // return the index of ui.item among the items
          // we can't just do ui.item.index() because there it might have siblings
          // which are not items
          function getItemIndex(ui) {
            return ui.item.parent().find(opts['ui-model-items'])
              .index(ui.item);
          }

          var opts = {};

          // directive specific options
          var directiveOpts = {
            'ui-floating': undefined,
            'ui-model-items': uiSortableConfig.items
          };

          var callbacks = {
            receive: null,
            remove:null,
            start:null,
            stop:null,
            update:null
          };

          var wrappers = {
            helper: null
          };

          angular.extend(opts, directiveOpts, uiSortableConfig, scope.uiSortable);

          if (!angular.element.fn || !angular.element.fn.jquery) {
            $log.error('ui.sortable: jQuery should be included before AngularJS!');
            return;
          }

          function wireUp () {
            // When we add or remove elements, we need the sortable to 'refresh'
            // so it can find the new/removed elements.
            scope.$watchCollection('ngModel', function() {
              // Timeout to let ng-repeat modify the DOM
              $timeout(function() {
                // ensure that the jquery-ui-sortable widget instance
                // is still bound to the directive's element
                if (!!getSortableWidgetInstance(element)) {
                  element.sortable('refresh');
                }
              }, 0, false);
            });

            callbacks.start = function(e, ui) {
              if (opts['ui-floating'] === 'auto') {
                // since the drag has started, the element will be
                // absolutely positioned, so we check its siblings
                var siblings = ui.item.siblings();
                var sortableWidgetInstance = getSortableWidgetInstance(angular.element(e.target));
                sortableWidgetInstance.floating = isFloating(siblings);
              }

              // Save the starting position of dragged item
              var index = getItemIndex(ui);
              ui.item.sortable = {
                model: ngModel.$modelValue[index],
                index: index,
                source: ui.item.parent(),
                sourceModel: ngModel.$modelValue,
                cancel: function () {
                  ui.item.sortable._isCanceled = true;
                },
                isCanceled: function () {
                  return ui.item.sortable._isCanceled;
                },
                isCustomHelperUsed: function () {
                  return !!ui.item.sortable._isCustomHelperUsed;
                },
                _isCanceled: false,
                _isCustomHelperUsed: ui.item.sortable._isCustomHelperUsed,
                _destroy: function () {
                  angular.forEach(ui.item.sortable, function(value, key) {
                    ui.item.sortable[key] = undefined;
                  });
                }
              };
            };

            callbacks.activate = function(e, ui) {
              // We need to make a copy of the current element's contents so
              // we can restore it after sortable has messed it up.
              // This is inside activate (instead of start) in order to save
              // both lists when dragging between connected lists.
              savedNodes = element.contents();

              // If this list has a placeholder (the connected lists won't),
              // don't inlcude it in saved nodes.
              var placeholder = getPlaceholderElement(element);
              if (placeholder && placeholder.length) {
                var excludes = getPlaceholderExcludesludes(element, placeholder);
                savedNodes = savedNodes.not(excludes);
              }

              // save the directive's scope so that it is accessible from ui.item.sortable
              var connectedSortables = ui.item.sortable._connectedSortables || [];

              connectedSortables.push({
                element: element,
                scope: scope
              });

              ui.item.sortable._connectedSortables = connectedSortables;
            };

            callbacks.update = function(e, ui) {
              // Save current drop position but only if this is not a second
              // update that happens when moving between lists because then
              // the value will be overwritten with the old value
              if(!ui.item.sortable.received) {
                ui.item.sortable.dropindex = getItemIndex(ui);
                var droptarget = ui.item.parent();
                ui.item.sortable.droptarget = droptarget;

                var droptargetScope = getElementScope(ui.item.sortable._connectedSortables, droptarget);
                ui.item.sortable.droptargetModel = droptargetScope.ngModel;

                // Cancel the sort (let ng-repeat do the sort for us)
                // Don't cancel if this is the received list because it has
                // already been canceled in the other list, and trying to cancel
                // here will mess up the DOM.
                element.sortable('cancel');
              }

              // Put the nodes back exactly the way they started (this is very
              // important because ng-repeat uses comment elements to delineate
              // the start and stop of repeat sections and sortable doesn't
              // respect their order (even if we cancel, the order of the
              // comments are still messed up).
              var sortingHelper = !ui.item.sortable.received && getSortingHelper(element, ui, savedNodes);
              if (sortingHelper && sortingHelper.length) {
                // Restore all the savedNodes except from the sorting helper element.
                // That way it will be garbage collected.
                savedNodes = savedNodes.not(sortingHelper);
              }
              savedNodes.appendTo(element);

              // If this is the target connected list then
              // it's safe to clear the restored nodes since:
              // update is currently running and
              // stop is not called for the target list.
              if(ui.item.sortable.received) {
                savedNodes = null;
              }

              // If received is true (an item was dropped in from another list)
              // then we add the new item to this list otherwise wait until the
              // stop event where we will know if it was a sort or item was
              // moved here from another list
              if(ui.item.sortable.received && !ui.item.sortable.isCanceled()) {
                scope.$apply(function () {
                  ngModel.$modelValue.splice(ui.item.sortable.dropindex, 0,
                                             ui.item.sortable.moved);
                });
              }
            };

            callbacks.stop = function(e, ui) {
              // If the received flag hasn't be set on the item, this is a
              // normal sort, if dropindex is set, the item was moved, so move
              // the items in the list.
              if(!ui.item.sortable.received &&
                 ('dropindex' in ui.item.sortable) &&
                 !ui.item.sortable.isCanceled()) {

                scope.$apply(function () {
                  ngModel.$modelValue.splice(
                    ui.item.sortable.dropindex, 0,
                    ngModel.$modelValue.splice(ui.item.sortable.index, 1)[0]);
                });
              } else {
                // if the item was not moved, then restore the elements
                // so that the ngRepeat's comment are correct.
                if ((!('dropindex' in ui.item.sortable) || ui.item.sortable.isCanceled()) &&
                    !angular.equals(element.contents(), savedNodes)) {

                  var sortingHelper = getSortingHelper(element, ui, savedNodes);
                  if (sortingHelper && sortingHelper.length) {
                    // Restore all the savedNodes except from the sorting helper element.
                    // That way it will be garbage collected.
                    savedNodes = savedNodes.not(sortingHelper);
                  }
                  savedNodes.appendTo(element);
                }
              }

              // It's now safe to clear the savedNodes
              // since stop is the last callback.
              savedNodes = null;
            };

            callbacks.receive = function(e, ui) {
              // An item was dropped here from another list, set a flag on the
              // item.
              ui.item.sortable.received = true;
            };

            callbacks.remove = function(e, ui) {
              // Workaround for a problem observed in nested connected lists.
              // There should be an 'update' event before 'remove' when moving
              // elements. If the event did not fire, cancel sorting.
              if (!('dropindex' in ui.item.sortable)) {
                element.sortable('cancel');
                ui.item.sortable.cancel();
              }

              // Remove the item from this list's model and copy data into item,
              // so the next list can retrive it
              if (!ui.item.sortable.isCanceled()) {
                scope.$apply(function () {
                  ui.item.sortable.moved = ngModel.$modelValue.splice(
                    ui.item.sortable.index, 1)[0];
                });
              }
            };

            wrappers.helper = function (inner) {
              if (inner && typeof inner === 'function') {
                return function (e, item) {
                  var innerResult = inner.apply(this, arguments);
                  item.sortable._isCustomHelperUsed = item !== innerResult;
                  return innerResult;
                };
              }
              return inner;
            };

            scope.$watchCollection('uiSortable', function(newVal, oldVal) {
              // ensure that the jquery-ui-sortable widget instance
              // is still bound to the directive's element
              var sortableWidgetInstance = getSortableWidgetInstance(element);
              if (!!sortableWidgetInstance) {
                var optsDiff = patchUISortableOptions(newVal, oldVal, sortableWidgetInstance);

                if (optsDiff) {
                  element.sortable('option', optsDiff);
                }
              }
            }, true);

            patchUISortableOptions(opts);
          }

          function init () {
            if (ngModel) {
              wireUp();
            } else {
              $log.info('ui.sortable: ngModel not provided!', element);
            }

            // Create sortable
            element.sortable(opts);
          }

          function initIfEnabled () {
            if (scope.uiSortable && scope.uiSortable.disabled) {
              return false;
            }

            init();

            // Stop Watcher
            initIfEnabled.cancelWatcher();
            initIfEnabled.cancelWatcher = angular.noop;

            return true;
          }

          initIfEnabled.cancelWatcher = angular.noop;

          if (!initIfEnabled()) {
            initIfEnabled.cancelWatcher = scope.$watch('uiSortable.disabled', initIfEnabled);
          }
        }
      };
    }
  ]);
<|endoftext|>


<commit_before>angular.module('genome.self', [])

.controller('SelfController', [ '$scope', '$cookies', '$location', 'SelfFactory', 'd3Service', '$rootScope', function ($scope, $cookies, $location, SelfFactory, d3Service, $rootScope) {

  $scope.outcomes = $scope.outcomes || [];
  $scope.current = {};

  $scope.whichView = whichView;

  var whichView = function() {
    $rootScope.view = $location.$$path;
  };

  whichView();

  $rootScope.removeHelix = function () {
    d3.select("svg#helix").remove();
  };

  $scope.fills = fills;

    /* The 'FILLS' block will determine the availability of colors, balls and lines
     * and what quantity and other attributes the d3 plot should contain */
  var fills = ['#E74C3C', '#3498DB', '#2ECC71'],
    h = 800,
    w = 150,
    numX = 0,
    numY = 0,
    speed = 0.01,
    torsion = 0.3,
    x = d3.scale.linear().range([20, w - 20]),
    y = d3.scale.linear().range([h - 100, 20]),
    z = d3.scale.linear().range([18, 5]);
      /**
        * This block will append the built svg elements to the "body" of the HTML
      **/
  var svg = d3.select(".BodyContainer")
      .append("svg")
      .attr("id", "helix")
      .attr("width", w)
      .attr("height", h);

  /** Appends the inner SVG to a larger SVG container **/
  svg.append("DNAHelix")
      .attr("width", w)
      .attr("height", h)
      .attr("fill", "white");
  var container = svg.append("g");
  var counter = 0;

  $scope.generateData = generateData;

  function generateData() {
    counter++;
    // Creating a range of numX (set to outcomes length) and then map
    var data = d3.range(numX).map(function (d, i) {
        var t = d * torsion - speed * counter;
          return [{ x: Math.cos(t),
                    y: d,
                    z: Math.sin(t),
                    title: $scope.outcomes[d].title,
                    rsid: $scope.outcomes[d].rsid,
                    pair: $scope.outcomes[d].pair,
                    outcome: $scope.outcomes[d].outcome,
                    video: $scope.outcomes[d].video
                  },
                  { x: Math.cos(t - Math.PI),
                    y: d,
                    z: Math.sin(t - Math.PI),
                    title: $scope.outcomes[d].title,
                    rsid: $scope.outcomes[d].rsid,
                    pair: $scope.outcomes[d].pair,
                    outcome: $scope.outcomes[d].outcome,
                    video: $scope.outcomes[d].video
                  }];
        });
      var flat = _.flatten(data);
      x.domain(d3.extent(flat, function(d){ return d.x; }));
      y.domain(d3.extent(flat, function(d){ return d.y; }));
      z.domain(d3.extent(flat, function(d){ return d.z; }));
      return data;
  }
  var exit = false;

  $scope.draw = draw;

  function draw () {
    if(exit) {
      return;
    }
    var cont = container.selectAll("g").data(generateData());
    cont.exit().remove();
    var enter = cont.enter()
      .append("g")
      .each(function (d, index) {
          d3.select(this)
            .selectAll("circle")
            .data(d)
            .enter()
            .append("circle")
            .attr("fill", "black")
          d3.select(this).append('line')
              .attr("stroke", function (d, i) {
                return fills[index%3];
              })
              .attr("stroke-width", 2);
      });

      cont.each(function (d, index) {
        var inverted = (d[0].y < d[1].x) ? 1 : -1;
        d3.select(this)
          .selectAll("circle")
          .data(d)
          .attr("cx", function (d) { return x(d.x); })
          .attr("cy", function (d) { return y(d.y); })
          .attr("r",  function (d) { return z(d.z); })
          .attr("fill-opacity", function (d) { return z(d.z) / 10;})
          .attr("fill", function (d, i) { return fills[index%3]; })
          .attr("title", function (d){ return d.title; })
          .attr("rsid", function(d){ return d.rsid; })
          .attr("pair", function(d){ return d.pair; })
          .attr("outcome", function(d){ return d.outcome; })
          .attr("video", function(d) { return d.video; })
          .on("mouseover", function (d, i) {
            $('iframe').remove();
            $('div.youtubevidbox').append(d.video);
            // Using $scope.$apply to force angular to rerender once the scope has been updated with the current snp
            $scope.$apply($scope.current = { title: d.title, rsid: d.rsid, pair: d.pair, outcome: d.outcome, video: d.video });
          });
        d3.select(this)
            .select('line')
            .attr("x2", x(d[0].x) + inverted * z(d[0].z))
            .attr("x1", x(d[1].x) - inverted * z(d[1].z))
            .attr("y2", y(d[0].y))
            .attr("y1", y(d[0].y));
      });
  }

  SelfFactory.getSnps($cookies.user_profile_id).then(function (outcomes) {
    $scope.allOutcomes = outcomes; //for testing purposes only
    console.log($scope.outcomes)
    for (var key in outcomes) {
      $scope.outcomes.push(outcomes[key]);
    }

    $scope.current = {
      title: 'Example Box',
      rsid: 'rs12345',
      pair: 'AA',
      outcome: 'A very interesting fact'
    };

    $('div.youtubevidbox').append('');

    numX = $scope.outcomes.length;

    setInterval(draw, 25);
  });

  $rootScope.IntroOptions = {
      steps:[{
          intro: "Welcome to your personal DNA helix. You can hover your mouse over the spinning DNA helix bubbles for information about your DNA."
        },
        {
          element: document.querySelector('#helix-path-2'),
          intro: "This box will display information about your DNA.",
          position: 'left'
        },
        {
          element: document.querySelector('#helix-path-3'),
          intro: "This ID represents the specific location on your genome. You can click on the link to find scientific articles about this information.",
          position: 'left'
        },
        {
          element: document.querySelector('#helix-path-4'),
          intro: "These letters represent the specific nucleotide base pair you have at this location.",
          position: 'left'
        },
        {
          element: document.querySelector('#helix-path-5'),
          intro: "Here is a commonly reported outcome of having the specific base pair at this specific location.",
          position: 'left'
        },
        {
          element: document.querySelector('#helix-path-7'),
          intro: "Use these buttons if you want to use this walkthrough or sign out.",
          position: 'bottom'
        }
      ],
      showStepNumbers: false,
      exitOnOverlayClick: true,
      exitOnEsc:true,
      nextLabel: 'Next',
      prevLabel: 'Previous',
      skipLabel: 'Exit',
      doneLabel: 'Thanks'
  };
  //This function collapses the helix for a visual transition into the Pool Page.
  //This function gets called by the transitionToPool function
  var remove = function() {
    $('div.dna-info').remove();
    d3.select("svg#helix")
      .attr("width", 3000);

    d3.selectAll("line")
      .transition()
      .duration(500)
      .attr('y1', 200)
      .attr('y2', 200);

    d3.selectAll("circle")
      .transition()
      .duration(2000)
      .attr("r", 5)
      .attr("cx", function(d){return 120000 * d.x;})
      .attr("cy", 100);

    d3.selectAll("line")
      .transition()
      .delay(400)
      .attr("x1", 3000)
      .attr("x2", 5000);

   };
   //Calls the remove function, and sets a timeout to transition the user to the pool
   //page after the helix has collapsed and been removed from the page.
  $rootScope.transitionToPool = function(){
    exit = true;
    remove();
    setTimeout(function(){$scope.$apply($location.path('/tree'));  $rootScope.removeHelix();}, 500);
  };

}])
.factory('SelfFactory', function ($http) {
/**
  * Used to retrieve information about SNPs pertaining to currently logged in user
**/
  var getSnps = function (userId) {
    return $http({
      method: 'POST',
      url: '/api/getsnps',
      data: userId
    }).then(function (snps) {
      return snps.data.outcomes;
    }).catch(function (err) {
      console.error('An error occured retreiving your SNPs ', err);
    });
  };

  return {
    getSnps: getSnps
  };
});
<commit_msg>Took out console logs<commit_after>angular.module('genome.self', [])

.controller('SelfController', [ '$scope', '$cookies', '$location', 'SelfFactory', 'd3Service', '$rootScope', function ($scope, $cookies, $location, SelfFactory, d3Service, $rootScope) {

  $scope.outcomes = $scope.outcomes || [];
  $scope.current = {};

  $scope.whichView = whichView;

  var whichView = function() {
    $rootScope.view = $location.$$path;
  };

  whichView();

  $rootScope.removeHelix = function () {
    d3.select("svg#helix").remove();
  };

  $scope.fills = fills;

    /* The 'FILLS' block will determine the availability of colors, balls and lines
     * and what quantity and other attributes the d3 plot should contain */
  var fills = ['#E74C3C', '#3498DB', '#2ECC71'],
    h = 800,
    w = 150,
    numX = 0,
    numY = 0,
    speed = 0.01,
    torsion = 0.3,
    x = d3.scale.linear().range([20, w - 20]),
    y = d3.scale.linear().range([h - 100, 20]),
    z = d3.scale.linear().range([18, 5]);
      /**
        * This block will append the built svg elements to the "body" of the HTML
      **/
  var svg = d3.select(".BodyContainer")
      .append("svg")
      .attr("id", "helix")
      .attr("width", w)
      .attr("height", h);

  /** Appends the inner SVG to a larger SVG container **/
  svg.append("DNAHelix")
      .attr("width", w)
      .attr("height", h)
      .attr("fill", "white");
  var container = svg.append("g");
  var counter = 0;

  $scope.generateData = generateData;

  function generateData() {
    counter++;
    // Creating a range of numX (set to outcomes length) and then map
    var data = d3.range(numX).map(function (d, i) {
        var t = d * torsion - speed * counter;
          return [{ x: Math.cos(t),
                    y: d,
                    z: Math.sin(t),
                    title: $scope.outcomes[d].title,
                    rsid: $scope.outcomes[d].rsid,
                    pair: $scope.outcomes[d].pair,
                    outcome: $scope.outcomes[d].outcome,
                    video: $scope.outcomes[d].video
                  },
                  { x: Math.cos(t - Math.PI),
                    y: d,
                    z: Math.sin(t - Math.PI),
                    title: $scope.outcomes[d].title,
                    rsid: $scope.outcomes[d].rsid,
                    pair: $scope.outcomes[d].pair,
                    outcome: $scope.outcomes[d].outcome,
                    video: $scope.outcomes[d].video
                  }];
        });
      var flat = _.flatten(data);
      x.domain(d3.extent(flat, function(d){ return d.x; }));
      y.domain(d3.extent(flat, function(d){ return d.y; }));
      z.domain(d3.extent(flat, function(d){ return d.z; }));
      return data;
  }
  var exit = false;

  $scope.draw = draw;

  function draw () {
    if(exit) {
      return;
    }
    var cont = container.selectAll("g").data(generateData());
    cont.exit().remove();
    var enter = cont.enter()
      .append("g")
      .each(function (d, index) {
          d3.select(this)
            .selectAll("circle")
            .data(d)
            .enter()
            .append("circle")
            .attr("fill", "black")
          d3.select(this).append('line')
              .attr("stroke", function (d, i) {
                return fills[index%3];
              })
              .attr("stroke-width", 2);
      });

      cont.each(function (d, index) {
        var inverted = (d[0].y < d[1].x) ? 1 : -1;
        d3.select(this)
          .selectAll("circle")
          .data(d)
          .attr("cx", function (d) { return x(d.x); })
          .attr("cy", function (d) { return y(d.y); })
          .attr("r",  function (d) { return z(d.z); })
          .attr("fill-opacity", function (d) { return z(d.z) / 10;})
          .attr("fill", function (d, i) { return fills[index%3]; })
          .attr("title", function (d){ return d.title; })
          .attr("rsid", function(d){ return d.rsid; })
          .attr("pair", function(d){ return d.pair; })
          .attr("outcome", function(d){ return d.outcome; })
          .attr("video", function(d) { return d.video; })
          .on("mouseover", function (d, i) {
            $('iframe').remove();
            $('div.youtubevidbox').append(d.video);
            // Using $scope.$apply to force angular to rerender once the scope has been updated with the current snp
            $scope.$apply($scope.current = { title: d.title, rsid: d.rsid, pair: d.pair, outcome: d.outcome, video: d.video });
          });
        d3.select(this)
            .select('line')
            .attr("x2", x(d[0].x) + inverted * z(d[0].z))
            .attr("x1", x(d[1].x) - inverted * z(d[1].z))
            .attr("y2", y(d[0].y))
            .attr("y1", y(d[0].y));
      });
  }

  SelfFactory.getSnps($cookies.user_profile_id).then(function (outcomes) {
    $scope.allOutcomes = outcomes; //for testing purposes only

    for (var key in outcomes) {
      $scope.outcomes.push(outcomes[key]);
    }

    $scope.current = {
      title: 'Example Box',
      rsid: 'rs12345',
      pair: 'AA',
      outcome: 'A very interesting fact'
    };

    $('div.youtubevidbox').append('');

    numX = $scope.outcomes.length;

    setInterval(draw, 25);
  });

  $rootScope.IntroOptions = {
      steps:[{
          intro: "Welcome to your personal DNA helix. You can hover your mouse over the spinning DNA helix bubbles for information about your DNA."
        },
        {
          element: document.querySelector('#helix-path-2'),
          intro: "This box will display information about your DNA.",
          position: 'left'
        },
        {
          element: document.querySelector('#helix-path-3'),
          intro: "This ID represents the specific location on your genome. You can click on the link to find scientific articles about this information.",
          position: 'left'
        },
        {
          element: document.querySelector('#helix-path-4'),
          intro: "These letters represent the specific nucleotide base pair you have at this location.",
          position: 'left'
        },
        {
          element: document.querySelector('#helix-path-5'),
          intro: "Here is a commonly reported outcome of having the specific base pair at this specific location.",
          position: 'left'
        },
        {
          element: document.querySelector('#helix-path-7'),
          intro: "Use these buttons if you want to use this walkthrough or sign out.",
          position: 'bottom'
        }
      ],
      showStepNumbers: false,
      exitOnOverlayClick: true,
      exitOnEsc:true,
      nextLabel: 'Next',
      prevLabel: 'Previous',
      skipLabel: 'Exit',
      doneLabel: 'Thanks'
  };
  //This function collapses the helix for a visual transition into the Pool Page.
  //This function gets called by the transitionToPool function
  var remove = function() {
    $('div.dna-info').remove();
    d3.select("svg#helix")
      .attr("width", 3000);

    d3.selectAll("line")
      .transition()
      .duration(500)
      .attr('y1', 200)
      .attr('y2', 200);

    d3.selectAll("circle")
      .transition()
      .duration(2000)
      .attr("r", 5)
      .attr("cx", function(d){return 120000 * d.x;})
      .attr("cy", 100);

    d3.selectAll("line")
      .transition()
      .delay(400)
      .attr("x1", 3000)
      .attr("x2", 5000);

   };
   //Calls the remove function, and sets a timeout to transition the user to the pool
   //page after the helix has collapsed and been removed from the page.
  $rootScope.transitionToPool = function(){
    exit = true;
    remove();
    setTimeout(function(){$scope.$apply($location.path('/tree'));  $rootScope.removeHelix();}, 500);
  };

}])
.factory('SelfFactory', function ($http) {
/**
  * Used to retrieve information about SNPs pertaining to currently logged in user
**/
  var getSnps = function (userId) {
    return $http({
      method: 'POST',
      url: '/api/getsnps',
      data: userId
    }).then(function (snps) {
      return snps.data.outcomes;
    }).catch(function (err) {
      console.error('An error occured retreiving your SNPs ', err);
    });
  };

  return {
    getSnps: getSnps
  };
});
<|endoftext|>


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

  angular.module('nin')
    .controller('MainCtrl', function ($scope, $http, $window, ScriptReloader, socket, demo, commands) {

      $scope.menu = [
        {
          name: 'File',
          items: [
            {name: 'Exit', shortcut: 'ESC', click: function() {}}
          ]
        },
        {
          name: 'Render',
          items: [
            {name: 'Start rendering', shortcut: 'Shift + R', click: function() {}}
          ]
        },
        {
          name: 'Help',
          items: [
            {name: 'Shortcuts', shortcut: '?', click: function() {}}
          ]
        },
      ];

      $scope.demo = demo;
      $scope.fullscreen = false;
      $scope.inspectedLayer = null;
      $scope.mute = localStorage.getItem('nin-mute') ? true : false;
      if (localStorage.hasOwnProperty('nin-volume')) {
        $scope.volume = +localStorage.getItem('nin-volume');
      } else {
        $scope.volume = 1;
      }

      commands.on('toggleFullscreen', function() {
        $scope.fullscreen = !$scope.fullscreen;
      });

      commands.on('toggleMusic', function() {
        $scope.mute = !$scope.mute;
        if ($scope.mute) {
          localStorage.setItem("nin-mute", 1);
        } else {
          localStorage.removeItem("nin-mute");
        }
      });

      commands.on('volumeDelta', function(delta) {
        $scope.mute = false;
        $scope.volume = clamp(0, $scope.volume + delta, 1);
        localStorage.setItem('nin-volume', $scope.volume);
      });

      socket.onopen = function() {
        console.log('nin socket connection established', arguments);
      };

      function updateLayers() {
        $http({
          method: 'GET',
          url: '//localhost:9000/res/layers.json'
        }).success(function(layers) {
          $scope.layers = layers;
          demo.lm.hardReset();
          for(var i = 0; i < layers.length; i++) {
            var layer = layers[i];
            layer.position = i;
            demo.lm.loadLayer(layer);
          }
          Loader.start(function() {}, function() {});
          demo.lm.jumpToFrame(demo.getCurrentFrame());
        });
      }

      function updateCamerapaths() {
        $http.get('//localhost:9000/res/camerapaths.json')
          .success(function(camerapaths) {
            CameraController.paths = camerapaths;
            for (var index in CameraController.layers) {
              CameraController.layers[index].parseCameraPath(camerapaths);
            }
          });
      }

      function updateShaders(path) {
        var splitted = path.split('/');
        var shaderName = splitted[splitted.length - 2];
        ScriptReloader.reload('//localhost:9000/gen/shaders.js', function() {
          for (var i=0; i < $scope.layers.length; i++) {
            var layer = $scope.layers[i];
            if (layer.shaders && layer.shaders.indexOf(shaderName) !== -1) {
              demo.lm.refresh(layer.type);
              demo.lm.update(demo.looper.currentFrame);
            }
          }
          Loader.start(function() {}, function() {});
        });
      }

      function updateSingleLayer(path) {
        var splitted = path.split('/');
        ScriptReloader.reload('//localhost:9000/' + path, function() {
          var className = splitted[splitted.length - 1].split('.')[0];
          demo.lm.refresh(className);
          demo.lm.update(demo.looper.currentFrame);
          Loader.start(function() {}, function() {});
        });
      }

      socket.on('add', function(e) {
        e.path = e.path.replace(/\\/g, '/');
        console.log('add!', e);
        if(e.path == 'res/layers.json') {
          updateLayers();
        } else if (e.path == 'res/camerapaths.json') {
          updateCamerapaths();
        } else if (e.path.indexOf('/shaders/') !== -1) {
          updateShaders(e.path);
        } else {
          updateSingleLayer(e.path);
        }
      });

      socket.on('change', function(e) {
        e.path = e.path.replace(/\\/g, '/');
        console.log('change!', e);
        if(e.path == 'res/layers.json') {
          updateLayers();
        } else if (e.path == 'res/camerapaths.json') {
          updateCamerapaths();
        } else if (e.path.indexOf('/shaders/') !== -1) {
          updateShaders(e.path);
        } else {
          updateSingleLayer(e.path);
        }
      });

      socket.onclose = function(e) {
        console.log('nin socket connection closed', e);
      };
    });
})();
<commit_msg>Add start and stop rendering to menu<commit_after>(function() {
  'use strict';

  angular.module('nin')
    .controller('MainCtrl', function ($scope, $http, $window, ScriptReloader, socket, demo, commands) {

      $scope.menu = [
        {
          name: 'File',
          items: [
            {name: 'Exit', shortcut: 'ESC', click: function() {}}
          ]
        },
        {
          name: 'Render',
          items: [
            {name: 'Start rendering', shortcut: 'Shift + R', click: function() {
              commands.startRendering();
            }},
            {name: 'Stop rendering', shortcut: 'Shift + R', click: function() {
              commands.stopRendering();
            }}
          ]
        },
        {
          name: 'Help',
          items: [
            {name: 'Shortcuts', shortcut: '?', click: function() {}}
          ]
        },
      ];

      $scope.demo = demo;
      $scope.fullscreen = false;
      $scope.inspectedLayer = null;
      $scope.mute = localStorage.getItem('nin-mute') ? true : false;
      if (localStorage.hasOwnProperty('nin-volume')) {
        $scope.volume = +localStorage.getItem('nin-volume');
      } else {
        $scope.volume = 1;
      }

      commands.on('toggleFullscreen', function() {
        $scope.fullscreen = !$scope.fullscreen;
      });

      commands.on('toggleMusic', function() {
        $scope.mute = !$scope.mute;
        if ($scope.mute) {
          localStorage.setItem("nin-mute", 1);
        } else {
          localStorage.removeItem("nin-mute");
        }
      });

      commands.on('volumeDelta', function(delta) {
        $scope.mute = false;
        $scope.volume = clamp(0, $scope.volume + delta, 1);
        localStorage.setItem('nin-volume', $scope.volume);
      });

      socket.onopen = function() {
        console.log('nin socket connection established', arguments);
      };

      function updateLayers() {
        $http({
          method: 'GET',
          url: '//localhost:9000/res/layers.json'
        }).success(function(layers) {
          $scope.layers = layers;
          demo.lm.hardReset();
          for(var i = 0; i < layers.length; i++) {
            var layer = layers[i];
            layer.position = i;
            demo.lm.loadLayer(layer);
          }
          Loader.start(function() {}, function() {});
          demo.lm.jumpToFrame(demo.getCurrentFrame());
        });
      }

      function updateCamerapaths() {
        $http.get('//localhost:9000/res/camerapaths.json')
          .success(function(camerapaths) {
            CameraController.paths = camerapaths;
            for (var index in CameraController.layers) {
              CameraController.layers[index].parseCameraPath(camerapaths);
            }
          });
      }

      function updateShaders(path) {
        var splitted = path.split('/');
        var shaderName = splitted[splitted.length - 2];
        ScriptReloader.reload('//localhost:9000/gen/shaders.js', function() {
          for (var i=0; i < $scope.layers.length; i++) {
            var layer = $scope.layers[i];
            if (layer.shaders && layer.shaders.indexOf(shaderName) !== -1) {
              demo.lm.refresh(layer.type);
              demo.lm.update(demo.looper.currentFrame);
            }
          }
          Loader.start(function() {}, function() {});
        });
      }

      function updateSingleLayer(path) {
        var splitted = path.split('/');
        ScriptReloader.reload('//localhost:9000/' + path, function() {
          var className = splitted[splitted.length - 1].split('.')[0];
          demo.lm.refresh(className);
          demo.lm.update(demo.looper.currentFrame);
          Loader.start(function() {}, function() {});
        });
      }

      socket.on('add', function(e) {
        e.path = e.path.replace(/\\/g, '/');
        console.log('add!', e);
        if(e.path == 'res/layers.json') {
          updateLayers();
        } else if (e.path == 'res/camerapaths.json') {
          updateCamerapaths();
        } else if (e.path.indexOf('/shaders/') !== -1) {
          updateShaders(e.path);
        } else {
          updateSingleLayer(e.path);
        }
      });

      socket.on('change', function(e) {
        e.path = e.path.replace(/\\/g, '/');
        console.log('change!', e);
        if(e.path == 'res/layers.json') {
          updateLayers();
        } else if (e.path == 'res/camerapaths.json') {
          updateCamerapaths();
        } else if (e.path.indexOf('/shaders/') !== -1) {
          updateShaders(e.path);
        } else {
          updateSingleLayer(e.path);
        }
      });

      socket.onclose = function(e) {
        console.log('nin socket connection closed', e);
      };
    });
})();
<|endoftext|>


<commit_before>'use strict';

module.exports = {
  colors: {
    black: '#383A42',
    red: '#DC322F',
    green: '#50A14F',
    yellow: '#986801',
    blue: '#986801',
    magenta: '#A626A4',
    cyan: '#0184BC',
    white: '#FAFAFA',
    lightBlack: '#A0A1A7',
    lightRed: '#DC322F',
    lightGreen: '#50A14F',
    lightYellow: '#986801',
    lightBlue: '#986801',
    lightMagenta: '#A626A4',
    lightCyan: '#0184BC',
    lightWhite: '#FAFAFA',
  },

  // Default
  backgroundColor: '#FAFAFA',
  foregroundColor: '#383A42',
  cursorColor: '#526FFF',
  borderColor: 'transparent',

  // Accent color
  accentColor: '#526FFF',

  // Other
  inactiveTabTitleColor: 'rgba(56, 58, 66, 0.3)',
  activeTabTitleColor: '#383A42',
};
<commit_msg>:bug: Fix wrong color for one-light<commit_after>'use strict';

module.exports = {
  colors: {
    black: '#383A42',
    red: '#DC322F',
    green: '#50A14F',
    yellow: '#C18401',
    blue: '#4078F2',
    magenta: '#A626A4',
    cyan: '#0184BC',
    white: '#FAFAFA',
    lightBlack: '#A0A1A7',
    lightRed: '#DC322F',
    lightGreen: '#50A14F',
    lightYellow: '#C18401',
    lightBlue: '#4078F2',
    lightMagenta: '#A626A4',
    lightCyan: '#0184BC',
    lightWhite: '#FAFAFA',
  },

  // Default
  backgroundColor: '#FAFAFA',
  foregroundColor: '#383A42',
  cursorColor: '#526FFF',
  borderColor: 'transparent',

  // Accent color
  accentColor: '#526FFF',

  // Other
  inactiveTabTitleColor: 'rgba(56, 58, 66, 0.3)',
  activeTabTitleColor: '#383A42',
};
<|endoftext|>


<commit_before>'use strict'

// components
var Input = require('.')

const regex = /^([\w-]+){1,}@([\w-?]+){1,}((\.[a-z]+)+)?(\.([a-z]+){2,})+$/g

/**
 * Input element
 * @memberOf UIKit
 */
module.exports = new Input({
  placeholder: 'E-mail',
  attributes: {
    type: 'email'
  },
  on: {
    input: {
      verify (e) {
        var node = this.getNode()
        if (node.value.match(regex)) {
          this.css.setKey('valid', true)
        } else {
          this.css.setKey('valid', false)
        }
      }
    }
  }
}).Constructor
<commit_msg>email validation<commit_after>'use strict'

// components
var Input = require('.')

const regex = /^((\b([\w\.])+\b){1,})@([\w-?]+){1,}((\.\w+)+)?(\.([a-z]+){2,})+$/g

/**
 * Input element
 * @memberOf UIKit
 */
module.exports = new Input({
  placeholder: 'E-mail',
  attributes: {
    type: 'email'
  },
  on: {
    input: {
      verify (e) {
        var node = this.getNode()
        if (node.value.match(regex)) {
          this.css.setKey('valid', true)
        } else {
          this.css.setKey('valid', false)
        }
      }
    }
  }
}).Constructor
<|endoftext|>