<commit_before>//fixed a bug with the comment up here ;)
define([
    'app', 'app/services/app-config-service.js',
    '/app/views/forms/edit/editFormUtility.js',
    '/app/views/forms/edit/field-embed-contact.directive.js',
    '/app/views/forms/edit/edit-contact-base.directive.js',
    '/app/views/forms/view/view-contact-reference.directive.js',
    '/app/views/forms/view/view-default-reference.directive.js',
    '/app/views/forms/view/view-organization-reference.directive.js',
    '/app/views/forms/view/record-loader.directive.html.js',
    '/app/views/forms/view/view-organization.directive.js',
    '/app/views/forms/view/view-organization-reference.directive.js',
    '/app/views/forms/view/view-history-directive.html.js',
    '/app/views/directives/workflow-std-buttons.html.js',
    '/app/views/forms/edit/document-selector.html.js',
    '/app/views/register/directives/register-top-menu.js'
  ], function (app) {

  app.controller("editController", ["$rootScope", "$scope", "$http", "$window", "guid", "$filter", "Thesaurus", "$q", "$location", "IStorage",
                                   "authentication", "Enumerable", "editFormUtility", "$routeParams", "$timeout","underscore", "$route", "breadcrumbs", "appConfigService",
                                    function ($rootScope, $scope, $http, $window, guid, $filter, thesaurus, $q, $location, storage,
                                              authentication, Enumerable, editFormUtility, $routeParams, $timeout, _, $route, breadcrumbs, appConfigService) {

    $scope.type = $route.current.$$route.documentType;

    if(_.contains(appConfigService.nationalSchemas, $filter('mapSchema')($scope.type)))
      $scope.schemaType = 'nationalRecords';
    else
      $scope.schemaType = 'referenceRecords';

    $scope.status   = "loading";
    $scope.error    = null;
    $scope.tab      = "edit";
    $scope.review   = { locale: "en" };

    console.log(breadcrumbs.breadcrumbs);
    var breadcrumb = {
        label : $filter('schemaName')($filter('mapSchema')($scope.type)),
        originalPath : "/register/:document_type",
        param:$scope.type,
        path:"/register/" + $scope.type
    }
    breadcrumbs.breadcrumbs.splice(2, 0 , breadcrumb);
    console.log(breadcrumbs.breadcrumbs);

    $scope.options  = {
      countries		: function() {
        return $http.get("/api/v2013/thesaurus/domains/countries/terms", { cache: true }).then(function(o){
          var countries = $filter("orderBy")(o.data, "name");
          _.each(countries, function(element) {
            element.__value = element.name;
          });
          return countries;
        });
      },
      libraries		: function() {
        return $http.get("/api/v2013/thesaurus/domains/cbdClearingHouses/terms", { cache: true }).then(function(o){
          return o.data;
        });
      },
      regions			: function() {
        return $q.all([
          $http.get("/api/v2013/thesaurus/domains/regions/terms", { cache: true }),
          $http.get("/api/v2013/thesaurus/domains/countries/terms",   { cache: true })
        ]).then(function(o) {
          return Enumerable.from($filter("orderBy")(o[0].data, "name")).union(
            Enumerable.from($filter("orderBy")(o[1].data, "name"))
          ).toArray();
        });
      },
    };

    $scope.ac_countries = function() {
      return $scope.options.countries();
    };

    $scope.genericFilter = function($query, items) {
      var matchedOptions = [];
      for(var i=0; i!=items.length; ++i)
        if(items[i].__value.toLowerCase().indexOf($query.toLowerCase()) !== -1)
          matchedOptions.push(items[i]);

      return matchedOptions;
    };

    $scope.genericMapping = function(item) {
      return {identifier: item.identifier};
    };

    //==================================
    //
    //==================================
    $scope.scrollToTop = function() {
          $("body, html").animate({scrollTop: 0}, "slow");
        };

    //==================================
    //
    //==================================
    $scope.isDefined = function(obj) {
      return angular.isDefined(obj);
    };

    //==================================
    //
    //==================================
    $scope.$on("documentInvalid", function(){
      $scope.tab = "review";
    });

    $scope.$on("clearDocumentErrors", function(){
      $scope.validationReport = {clearErrors:[]};
    });

    //==================================
    //
    //==================================
    $scope.$watch("tab", function(tab) {
      if(tab == "review")
        validate();
    });

    $scope.isOtherSelected = function(document){

       return document &&  Enumerable.from(document).any(function(type){
              return type.identifier == "5B6177DD-5E5E-434E-8CB7-D63D67D5EBED";
            });
    };

    //==================================
    //
    //==================================
    $scope.isInLibrary = function(name, document) {
      document = document || $scope.document;

      if (!document || !document.libraries)
        return false;

      var qLibraries = Enumerable.from(document.libraries);

      if(name=="chm"  ) return qLibraries.any(function(o){ return o.identifier == "cbdLibrary:chm";    });
      if(name=="absch") return qLibraries.any(function(o){ return o.identifier == "cbdLibrary:abs-ch"; });
      if(name=="bch"  ) return qLibraries.any(function(o){ return o.identifier == "cbdLibrary:bch";    });
      if(name=="ebsa" ) return qLibraries.any(function(o){ return o.identifier == "cbdLibrary:ebsa";   });

      return false;
  };

    //==================================
    //
    //==================================
    $scope.canAddRegionalMeasure = function(document) {
      document = document || $scope.document;

      if (!document)
        return false;

      if(document.jurisdiction.identifier == '528B1187-F1BD-4479-9FB3-ADBD9076D361' && (document.government.identifier == "eur" ||  document.government.identifier == "eu")){
         document.jurisdictionRegions = [{"identifier":"bd12d7fb-91f7-4b2d-996c-e70f18a51f0e"}];
         return true;
      }

      document.jurisdictionRegions = null;
        return false;

     };

    //==================================
    //
    //==================================
    $scope.isJurisdictionRegional = function(document) {
      document = document || $scope.document;

      if (!document || !document.jurisdiction)
        return false;

      var qJurisdiction = Enumerable.from([document.jurisdiction]);

      return qJurisdiction.any(function (o) { return o.identifier == "528B1187-F1BD-4479-9FB3-ADBD9076D361"; });
  };

    //==================================
    //
    //==================================
    $scope.isJurisdictionSubNationalOrCommunity = function (document) {
      document = document || $scope.document;

      if (!document || !document.jurisdiction)
        return false;

      var qJurisdiction = Enumerable.from([document.jurisdiction]);

      var response  = qJurisdiction.any(function (o) { return o.identifier == "DEBB019D-8647-40EC-8AE5-10CA88572F6E"; });
          response |= qJurisdiction.any(function (o) { return o.identifier == "9627DF2B-FFAC-4F85-B075-AF783FF2A0B5"; });
          response |= qJurisdiction.any(function (o) { return o.identifier == "5B6177DD-5E5E-434E-8CB7-D63D67D5EBED"; });

      return response;
    }

    //==================================
    //
    //==================================
    $scope.isNotLegallyBinded = function (document) {
      document = document || $scope.document;

      if (!document || !document.status)
        return false;

      var qStatus = Enumerable.from([document.status]);

      return qStatus.any(function (o) { return o.identifier == "C9E33B71-D92A-4AC1-96E3-A136A1FDF135" });
    }

    //==================================
    //
    //==================================
    $scope.isLegallyBinded = function (document) {
      document = document || $scope.document;

      if (!document || !document.status)
        return false;

      var qStatus = Enumerable.from([document.status]);

      return qStatus.any(function (o) { return o.identifier == "97D6C7E6-5EAD-48B2-BD8D-DAB77153FF9C" });
    }

    //==================================
    //
    //==================================
    $scope.isRetired = function (document) {
      document = document || $scope.document;

      if (!document || !document.status)
        return false;

      var qStatus = Enumerable.from([document.status]);

      return qStatus.any(function (o) { return o.identifier == "0F8F3A6D-1BF7-4468-8BFC-8DD52F7F6E50" });
    }

    //==================================
    //
    //==================================
    $scope.isLoading = function() {
      return $scope.status=="loading";
    }

    //==================================
    //
    //==================================
    $scope.hasError = function() {
      return $scope.error!=null;
    }

    //==================================
    //
    //==================================
    $scope.userGovernment = function() {
      return $scope.$root.user.government;
    };

    //==================================
    //
    //==================================
    function validate() {

      $scope.validationReport = null;

      var oDocument = $scope.reviewDocument = $scope.getCleanDocument();

      return storage.documents.validate(oDocument).then(function(success) {

        $scope.validationReport = success.data;
        return !!(success.data && success.data.errors && success.data.errors.length);

      }).catch(function(error) {

        $scope.onError(error.data);
        return true;

      });
    }

    //==================================
    //
    //==================================
    $scope.isFieldValid = function(field) {
      if (field && $scope.validationReport && $scope.validationReport.errors)
        return !Enumerable.from($scope.validationReport.errors).any(function(x){return x.property==field})

      return true;
    }

    //==================================
    //
    //==================================
    $scope.onError = function(error, status)
    {
      $scope.status = "error";

      if (status == "notAuthorized") {
        $scope.status = "hidden";
        $scope.error  = "You are not authorized to modify this record";
      }
      else if (status == 404) {
        $scope.status = "hidden";
        $scope.error  = "Record not found.";
      }
      else if (status == "badSchema") {
        $scope.status = "hidden";
        $scope.error  = "Record type is invalid.";
      }
      else if (error.Message)
        $scope.error = error.Message
      else
        $scope.error = error;
    }

    //==================================
    //
    //==================================
    $scope.loadRecords = function(identifier, schema, cache) {

      if(cache == undefined) cache = true;

      if (identifier) { //lookup single record
        var deferred = $q.defer();

        storage.documents.get(identifier, { info: "", cache: cache })
          .then(function(r) {
            deferred.resolve(r.data);
          }, function(e) {
            // if (e.status == 404) {
            //   storage.drafts.get(identifier, { info: "" })
            //     .then(function(r) { deferred.resolve(r.data)},
            //         function(e) { deferred.reject (e)});
            // }
            // else {
              deferred.reject (e)
            // }
          });
        return deferred.promise;
      }

      //Load all record of specified schema;

      var sQuery = "type eq '" + encodeURI(schema) + "'";
      //,storage.drafts   .query(sQuery, null, { cache: true })
      return $q.all([storage.documents.query(sQuery, null, { cache: cache })])
        .then(function(results) {
          var qResult = Enumerable.from (results[0].data.Items)
                     //.union(results[1].data.Items, "$.identifier");
          return qResult.toArray();
        });
    }

    $scope.setDocument = function(additionalParams, excludeGovernment) {

      $scope.status = "loading";

      var qDocument = {};
      $scope.document = {};
      if($routeParams.identifier)
        qDocument = editFormUtility.load($routeParams.identifier, $filter("mapSchema")($scope.type));
      else {
        qDocument = {
          header: {
            identifier: guid(),
            schema   : $filter("mapSchema")($scope.type),
            languages: ["en"]
          },
          government: $scope.userGovernment() ? { identifier: $scope.userGovernment() } : undefined,
        };
        for(var key in additionalParams)
          qDocument[key] = additionalParams[key];
        if(excludeGovernment)
          delete qDocument['government'];

        // canCreate(qDocument);
      }
      /*
      console.log('doc, ', qDocument);
      console.log('languages: ', qDocument.header.languages);
      console.log('id, ', qDocument.header.identifier);
      */

      $q.when(qDocument).then(function(doc) {

        $scope.tab    = "edit";
        $scope.document = doc;

        $scope.origanalDocument = angular.copy(doc);

        if($routeParams.tour)
        {
            $scope.startTour=true;
            $location.search("tour", null);
        }

        $scope.$emit("loadDocument", {identifier:doc.header.identifier,schema:doc.header.schema});

        $scope.status = "ready";

      }).catch(function(err) {

        $scope.onError(err.data, err.status)
        throw err;

      });
    };

    var consideringClosing = false;
    //TODO: burn angular... essentially the issue is that this function is called once the ng-include finished with the form html, but that form html still needs to be parsed and the directives still need to load THEIR templates, so those inputs aren't in the form yet... hence while change isn't triggering.
    var attachEvents = _.once(function() {
      $timeout(function() {
        $('.editForm input').change(function() {
          $(this).closest('form').addClass('dirty');
        });
        $('#dialogCancel').find('.closeWithoutSaving').click(function() {
          consideringClosing = true;
        });
        $('.cancelClose').click(function() {
          consideringClosing = false;
        });
        $('#dialogSave').on('shown.bs.modal', function() {
          consideringClosing = true;
        });
        $('#dialogDuplicate').on('shown.bs.modal', function() {
          consideringClosing = true;
        });
      }, 2000);
    });

    function canCreate(document){
        $q.when(storage.drafts.security.canCreate(document.header.identifier, document.header.schema)).then(function(doc) {
            if(!doc.isAllowed){
              $scope.status = "hidden";
              $scope.error  = "You are not authorized to modify this record";
            }
        }).catch(function(err) {
          $scope.onError(err.data, err.status)
          throw err;
      });
    }

    $rootScope.$on('$includeContentLoaded', function(event) {

      if($('#dialogCancel').length != 0){
        attachEvents();
      }
    });
    function confirmLeaving(evt, next, current) {
        var formChanged = !angular.equals($scope.getCleanDocument(), $scope.origanalDocument);

        if(formChanged)
            $('.editForm').closest('form').addClass('dirty');

      if(consideringClosing || $('form').filter('.dirty').length == 0)
        return;

      evt.preventDefault();

      $('#dialogCancel').modal('show');
      $rootScope.next_url = next;
      consideringClosing = true;
    }

    $scope.$on('$locationChangeStart', confirmLeaving);

    //raised when  a document is published or requested for publishing
    //update orignal document with the updated one to avoid validation on page leave event(confirmLeaving).
    $scope.$on('updateOrignalDocument', function(evt,newDocument){

        $scope.origanalDocument = newDocument;
    });

  }]);
});
<commit_msg>remove debug info<commit_after>//fixed a bug with the comment up here ;)
define([
    'app', 'app/services/app-config-service.js',
    '/app/views/forms/edit/editFormUtility.js',
    '/app/views/forms/edit/field-embed-contact.directive.js',
    '/app/views/forms/edit/edit-contact-base.directive.js',
    '/app/views/forms/view/view-contact-reference.directive.js',
    '/app/views/forms/view/view-default-reference.directive.js',
    '/app/views/forms/view/view-organization-reference.directive.js',
    '/app/views/forms/view/record-loader.directive.html.js',
    '/app/views/forms/view/view-organization.directive.js',
    '/app/views/forms/view/view-organization-reference.directive.js',
    '/app/views/forms/view/view-history-directive.html.js',
    '/app/views/directives/workflow-std-buttons.html.js',
    '/app/views/forms/edit/document-selector.html.js',
    '/app/views/register/directives/register-top-menu.js'
  ], function (app) {

  app.controller("editController", ["$rootScope", "$scope", "$http", "$window", "guid", "$filter", "Thesaurus", "$q", "$location", "IStorage",
                                   "authentication", "Enumerable", "editFormUtility", "$routeParams", "$timeout","underscore", "$route", "breadcrumbs", "appConfigService",
                                    function ($rootScope, $scope, $http, $window, guid, $filter, thesaurus, $q, $location, storage,
                                              authentication, Enumerable, editFormUtility, $routeParams, $timeout, _, $route, breadcrumbs, appConfigService) {

    $scope.type = $route.current.$$route.documentType;

    if(_.contains(appConfigService.nationalSchemas, $filter('mapSchema')($scope.type)))
      $scope.schemaType = 'nationalRecords';
    else
      $scope.schemaType = 'referenceRecords';

    $scope.status   = "loading";
    $scope.error    = null;
    $scope.tab      = "edit";
    $scope.review   = { locale: "en" };

    var breadcrumb = {
        label : $filter('schemaName')($filter('mapSchema')($scope.type)),
        originalPath : "/register/:document_type",
        param:$scope.type,
        path:"/register/" + $scope.type
    }
    breadcrumbs.breadcrumbs.splice(2, 0 , breadcrumb);

    $scope.options  = {
      countries		: function() {
        return $http.get("/api/v2013/thesaurus/domains/countries/terms", { cache: true }).then(function(o){
          var countries = $filter("orderBy")(o.data, "name");
          _.each(countries, function(element) {
            element.__value = element.name;
          });
          return countries;
        });
      },
      libraries		: function() {
        return $http.get("/api/v2013/thesaurus/domains/cbdClearingHouses/terms", { cache: true }).then(function(o){
          return o.data;
        });
      },
      regions			: function() {
        return $q.all([
          $http.get("/api/v2013/thesaurus/domains/regions/terms", { cache: true }),
          $http.get("/api/v2013/thesaurus/domains/countries/terms",   { cache: true })
        ]).then(function(o) {
          return Enumerable.from($filter("orderBy")(o[0].data, "name")).union(
            Enumerable.from($filter("orderBy")(o[1].data, "name"))
          ).toArray();
        });
      },
    };

    $scope.ac_countries = function() {
      return $scope.options.countries();
    };

    $scope.genericFilter = function($query, items) {
      var matchedOptions = [];
      for(var i=0; i!=items.length; ++i)
        if(items[i].__value.toLowerCase().indexOf($query.toLowerCase()) !== -1)
          matchedOptions.push(items[i]);

      return matchedOptions;
    };

    $scope.genericMapping = function(item) {
      return {identifier: item.identifier};
    };

    //==================================
    //
    //==================================
    $scope.scrollToTop = function() {
          $("body, html").animate({scrollTop: 0}, "slow");
        };

    //==================================
    //
    //==================================
    $scope.isDefined = function(obj) {
      return angular.isDefined(obj);
    };

    //==================================
    //
    //==================================
    $scope.$on("documentInvalid", function(){
      $scope.tab = "review";
    });

    $scope.$on("clearDocumentErrors", function(){
      $scope.validationReport = {clearErrors:[]};
    });

    //==================================
    //
    //==================================
    $scope.$watch("tab", function(tab) {
      if(tab == "review")
        validate();
    });

    $scope.isOtherSelected = function(document){

       return document &&  Enumerable.from(document).any(function(type){
              return type.identifier == "5B6177DD-5E5E-434E-8CB7-D63D67D5EBED";
            });
    };

    //==================================
    //
    //==================================
    $scope.isInLibrary = function(name, document) {
      document = document || $scope.document;

      if (!document || !document.libraries)
        return false;

      var qLibraries = Enumerable.from(document.libraries);

      if(name=="chm"  ) return qLibraries.any(function(o){ return o.identifier == "cbdLibrary:chm";    });
      if(name=="absch") return qLibraries.any(function(o){ return o.identifier == "cbdLibrary:abs-ch"; });
      if(name=="bch"  ) return qLibraries.any(function(o){ return o.identifier == "cbdLibrary:bch";    });
      if(name=="ebsa" ) return qLibraries.any(function(o){ return o.identifier == "cbdLibrary:ebsa";   });

      return false;
  };

    //==================================
    //
    //==================================
    $scope.canAddRegionalMeasure = function(document) {
      document = document || $scope.document;

      if (!document)
        return false;

      if(document.jurisdiction.identifier == '528B1187-F1BD-4479-9FB3-ADBD9076D361' && (document.government.identifier == "eur" ||  document.government.identifier == "eu")){
         document.jurisdictionRegions = [{"identifier":"bd12d7fb-91f7-4b2d-996c-e70f18a51f0e"}];
         return true;
      }

      document.jurisdictionRegions = null;
        return false;

     };

    //==================================
    //
    //==================================
    $scope.isJurisdictionRegional = function(document) {
      document = document || $scope.document;

      if (!document || !document.jurisdiction)
        return false;

      var qJurisdiction = Enumerable.from([document.jurisdiction]);

      return qJurisdiction.any(function (o) { return o.identifier == "528B1187-F1BD-4479-9FB3-ADBD9076D361"; });
  };

    //==================================
    //
    //==================================
    $scope.isJurisdictionSubNationalOrCommunity = function (document) {
      document = document || $scope.document;

      if (!document || !document.jurisdiction)
        return false;

      var qJurisdiction = Enumerable.from([document.jurisdiction]);

      var response  = qJurisdiction.any(function (o) { return o.identifier == "DEBB019D-8647-40EC-8AE5-10CA88572F6E"; });
          response |= qJurisdiction.any(function (o) { return o.identifier == "9627DF2B-FFAC-4F85-B075-AF783FF2A0B5"; });
          response |= qJurisdiction.any(function (o) { return o.identifier == "5B6177DD-5E5E-434E-8CB7-D63D67D5EBED"; });

      return response;
    }

    //==================================
    //
    //==================================
    $scope.isNotLegallyBinded = function (document) {
      document = document || $scope.document;

      if (!document || !document.status)
        return false;

      var qStatus = Enumerable.from([document.status]);

      return qStatus.any(function (o) { return o.identifier == "C9E33B71-D92A-4AC1-96E3-A136A1FDF135" });
    }

    //==================================
    //
    //==================================
    $scope.isLegallyBinded = function (document) {
      document = document || $scope.document;

      if (!document || !document.status)
        return false;

      var qStatus = Enumerable.from([document.status]);

      return qStatus.any(function (o) { return o.identifier == "97D6C7E6-5EAD-48B2-BD8D-DAB77153FF9C" });
    }

    //==================================
    //
    //==================================
    $scope.isRetired = function (document) {
      document = document || $scope.document;

      if (!document || !document.status)
        return false;

      var qStatus = Enumerable.from([document.status]);

      return qStatus.any(function (o) { return o.identifier == "0F8F3A6D-1BF7-4468-8BFC-8DD52F7F6E50" });
    }

    //==================================
    //
    //==================================
    $scope.isLoading = function() {
      return $scope.status=="loading";
    }

    //==================================
    //
    //==================================
    $scope.hasError = function() {
      return $scope.error!=null;
    }

    //==================================
    //
    //==================================
    $scope.userGovernment = function() {
      return $scope.$root.user.government;
    };

    //==================================
    //
    //==================================
    function validate() {

      $scope.validationReport = null;

      var oDocument = $scope.reviewDocument = $scope.getCleanDocument();

      return storage.documents.validate(oDocument).then(function(success) {

        $scope.validationReport = success.data;
        return !!(success.data && success.data.errors && success.data.errors.length);

      }).catch(function(error) {

        $scope.onError(error.data);
        return true;

      });
    }

    //==================================
    //
    //==================================
    $scope.isFieldValid = function(field) {
      if (field && $scope.validationReport && $scope.validationReport.errors)
        return !Enumerable.from($scope.validationReport.errors).any(function(x){return x.property==field})

      return true;
    }

    //==================================
    //
    //==================================
    $scope.onError = function(error, status)
    {
      $scope.status = "error";

      if (status == "notAuthorized") {
        $scope.status = "hidden";
        $scope.error  = "You are not authorized to modify this record";
      }
      else if (status == 404) {
        $scope.status = "hidden";
        $scope.error  = "Record not found.";
      }
      else if (status == "badSchema") {
        $scope.status = "hidden";
        $scope.error  = "Record type is invalid.";
      }
      else if (error.Message)
        $scope.error = error.Message
      else
        $scope.error = error;
    }

    //==================================
    //
    //==================================
    $scope.loadRecords = function(identifier, schema, cache) {

      if(cache == undefined) cache = true;

      if (identifier) { //lookup single record
        var deferred = $q.defer();

        storage.documents.get(identifier, { info: "", cache: cache })
          .then(function(r) {
            deferred.resolve(r.data);
          }, function(e) {
            // if (e.status == 404) {
            //   storage.drafts.get(identifier, { info: "" })
            //     .then(function(r) { deferred.resolve(r.data)},
            //         function(e) { deferred.reject (e)});
            // }
            // else {
              deferred.reject (e)
            // }
          });
        return deferred.promise;
      }

      //Load all record of specified schema;

      var sQuery = "type eq '" + encodeURI(schema) + "'";
      //,storage.drafts   .query(sQuery, null, { cache: true })
      return $q.all([storage.documents.query(sQuery, null, { cache: cache })])
        .then(function(results) {
          var qResult = Enumerable.from (results[0].data.Items)
                     //.union(results[1].data.Items, "$.identifier");
          return qResult.toArray();
        });
    }

    $scope.setDocument = function(additionalParams, excludeGovernment) {

      $scope.status = "loading";

      var qDocument = {};
      $scope.document = {};
      if($routeParams.identifier)
        qDocument = editFormUtility.load($routeParams.identifier, $filter("mapSchema")($scope.type));
      else {
        qDocument = {
          header: {
            identifier: guid(),
            schema   : $filter("mapSchema")($scope.type),
            languages: ["en"]
          },
          government: $scope.userGovernment() ? { identifier: $scope.userGovernment() } : undefined,
        };
        for(var key in additionalParams)
          qDocument[key] = additionalParams[key];
        if(excludeGovernment)
          delete qDocument['government'];

        // canCreate(qDocument);
      }
      /*
      console.log('doc, ', qDocument);
      console.log('languages: ', qDocument.header.languages);
      console.log('id, ', qDocument.header.identifier);
      */

      $q.when(qDocument).then(function(doc) {

        $scope.tab    = "edit";
        $scope.document = doc;

        $scope.origanalDocument = angular.copy(doc);

        if($routeParams.tour)
        {
            $scope.startTour=true;
            $location.search("tour", null);
        }

        $scope.$emit("loadDocument", {identifier:doc.header.identifier,schema:doc.header.schema});

        $scope.status = "ready";

      }).catch(function(err) {

        $scope.onError(err.data, err.status)
        throw err;

      });
    };

    var consideringClosing = false;
    //TODO: burn angular... essentially the issue is that this function is called once the ng-include finished with the form html, but that form html still needs to be parsed and the directives still need to load THEIR templates, so those inputs aren't in the form yet... hence while change isn't triggering.
    var attachEvents = _.once(function() {
      $timeout(function() {
        $('.editForm input').change(function() {
          $(this).closest('form').addClass('dirty');
        });
        $('#dialogCancel').find('.closeWithoutSaving').click(function() {
          consideringClosing = true;
        });
        $('.cancelClose').click(function() {
          consideringClosing = false;
        });
        $('#dialogSave').on('shown.bs.modal', function() {
          consideringClosing = true;
        });
        $('#dialogDuplicate').on('shown.bs.modal', function() {
          consideringClosing = true;
        });
      }, 2000);
    });

    function canCreate(document){
        $q.when(storage.drafts.security.canCreate(document.header.identifier, document.header.schema)).then(function(doc) {
            if(!doc.isAllowed){
              $scope.status = "hidden";
              $scope.error  = "You are not authorized to modify this record";
            }
        }).catch(function(err) {
          $scope.onError(err.data, err.status)
          throw err;
      });
    }

    $rootScope.$on('$includeContentLoaded', function(event) {

      if($('#dialogCancel').length != 0){
        attachEvents();
      }
    });
    function confirmLeaving(evt, next, current) {
        var formChanged = !angular.equals($scope.getCleanDocument(), $scope.origanalDocument);

        if(formChanged)
            $('.editForm').closest('form').addClass('dirty');

      if(consideringClosing || $('form').filter('.dirty').length == 0)
        return;

      evt.preventDefault();

      $('#dialogCancel').modal('show');
      $rootScope.next_url = next;
      consideringClosing = true;
    }

    $scope.$on('$locationChangeStart', confirmLeaving);

    //raised when  a document is published or requested for publishing
    //update orignal document with the updated one to avoid validation on page leave event(confirmLeaving).
    $scope.$on('updateOrignalDocument', function(evt,newDocument){

        $scope.origanalDocument = newDocument;
    });

  }]);
});
<|endoftext|>


<commit_before>/*
 * Adapted from Tom Nightingale's https://github.com/tnightingale/Leaflet.widget/blob/master/src/Select.js
 */
L.Feature.Edit = L.Handler.extend({
	includes: L.Mixin.Events,

	options: {},

	initialize: function (map, options) {
		this._container = map._container;

		L.Util.setOptions(this, options);

		L.Handler.prototype.initialize.call(this, map);
	},

	enable: function () {
		this.fire('enabled');
		L.Handler.prototype.enable.call(this);
	},

	disable: function () {
		this.fire('disabled');
		L.Handler.prototype.disable.call(this);
	},

	addHooks: function () {
		if (this._map && this.options.selectableLayers) {
			this._selectableLayers = this.options.selectableLayers;

			if (!(this._selectableLayers instanceof L.LayerGroup) && !(this._selectableLayers instanceof L.FeatureGroup)) {
				throw new Error('options.selectableLayers must be a L.LayerGroup or L.FeatureGroup');
			}

			// Used to store the selected layers
			this._selected = L.layerGroup();

			this._selectableLayers.eachLayer(function (layer) {
				this._bind(layer);
			}, this);

			// Listen for new layers being added to the map
			this._map.on({
				layeradd: this._bind,
				layerremove: this._unbind
			}, this);
		}
	},

	removeHooks: function () {
		if (this._map && this._selectableLayers) {
			// Clean up selected layers.
			this._selectableLayers.eachLayer(function (layer) {
				this._unbind(layer);
			}, this);
			delete this._selected;

			this._map.off({
				layeradd: this._bind,
				layerremove: this._unbind
			}, this);
		}
	},

	select: function (e) {
		var layer = e.layer || e.target || e;

		// TODO: cache the old colour and change back to it
		if (!(layer instanceof L.Marker)) {
			layer.setStyle({color: '#f00'});
		}

		layer
			.off('click', this.select)
			.on('click', this._deselect, this);

		this._selected.addLayer(layer);

		this._map.fire('feature-selected', { layer: layer });
	},

	removeItems: function (callback) {
		if (!this.enabled()) {
			return;
		}

		this._selected.eachLayer(function (layer) {
			this._map.removeLayer(layer);
		}, this);
	},

	_deselect: function (e, permanent) {
		var layer = e.layer || e.target || e;

		if (!(layer instanceof L.Marker)) {
			layer.setStyle({color: '#0f0'});
		}

		layer.off('click', this._deselect, this);
		if (!permanent) {
			layer.on('click', this.select, this);
		}

		this._selected.removeLayer(layer);

		this._map.fire('feature-deselected', { layer: layer });
	},

	_bind: function (e) {
		var layer = e.layer ? e.layer : e;

		if (this._selectableLayers.hasLayer(layer)) {
			layer.on('click', this.select, this);
		}
	},

	_unbind: function (e) {
		var layer = e.layer ? e.layer : e;

		if (this._selectableLayers.hasLayer(layer) && this._selected.hasLayer(layer)) {
			this._deselect(layer, true);
		}
	}
});

L.LayerGroup.include({
	hasLayer: function (layer) {
		return !!this._layers[L.Util.stamp(layer)];
	}
});<commit_msg>Reset vectors to their original colour once deselected.<commit_after>/*
 * Adapted from Tom Nightingale's https://github.com/tnightingale/Leaflet.widget/blob/master/src/Select.js
 */
L.Feature.Edit = L.Handler.extend({
	includes: L.Mixin.Events,

	options: {},

	initialize: function (map, options) {
		this._container = map._container;

		L.Util.setOptions(this, options);

		L.Handler.prototype.initialize.call(this, map);
	},

	enable: function () {
		this.fire('enabled');
		L.Handler.prototype.enable.call(this);
	},

	disable: function () {
		this.fire('disabled');
		L.Handler.prototype.disable.call(this);
	},

	addHooks: function () {
		if (this._map && this.options.selectableLayers) {
			this._selectableLayers = this.options.selectableLayers;

			if (!(this._selectableLayers instanceof L.LayerGroup) && !(this._selectableLayers instanceof L.FeatureGroup)) {
				throw new Error('options.selectableLayers must be a L.LayerGroup or L.FeatureGroup');
			}

			// Used to store the selected layers
			this._selected = L.layerGroup();

			this._selectableLayers.eachLayer(function (layer) {
				this._bind(layer);
			}, this);

			// Listen for new layers being added to the map
			this._map.on({
				layeradd: this._bind,
				layerremove: this._unbind
			}, this);
		}
	},

	removeHooks: function () {
		if (this._map && this._selectableLayers) {
			// Clean up selected layers.
			this._selectableLayers.eachLayer(function (layer) {
				this._unbind(layer);
			}, this);
			delete this._selected;

			this._map.off({
				layeradd: this._bind,
				layerremove: this._unbind
			}, this);
		}
	},

	select: function (e) {
		var layer = e.layer || e.target || e;

		// TODO: cache the old colour and change back to it
		if (!(layer instanceof L.Marker)) {
			layer.options.previousColor = layer.options.color;
			layer.setStyle({color: '#f00'});
		}

		layer
			.off('click', this.select)
			.on('click', this._deselect, this);

		this._selected.addLayer(layer);

		this._map.fire('feature-selected', { layer: layer });
	},

	removeItems: function (callback) {
		if (!this.enabled()) {
			return;
		}

		this._selected.eachLayer(function (layer) {
			this._map.removeLayer(layer);
		}, this);
	},

	_deselect: function (e, permanent) {
		var layer = e.layer || e.target || e;

		if (!(layer instanceof L.Marker)) {
			layer.setStyle({color: layer.options.previousColor});
		}

		layer.off('click', this._deselect, this);
		if (!permanent) {
			layer.on('click', this.select, this);
		}

		this._selected.removeLayer(layer);

		this._map.fire('feature-deselected', { layer: layer });
	},

	_bind: function (e) {
		var layer = e.layer ? e.layer : e;

		if (this._selectableLayers.hasLayer(layer)) {
			layer.on('click', this.select, this);
		}
	},

	_unbind: function (e) {
		var layer = e.layer ? e.layer : e;

		if (this._selectableLayers.hasLayer(layer) && this._selected.hasLayer(layer)) {
			this._deselect(layer, true);
		}
	}
});

L.LayerGroup.include({
	hasLayer: function (layer) {
		return !!this._layers[L.Util.stamp(layer)];
	}
});<|endoftext|>


<commit_before>(function (factory) {
  if (typeof define === 'function' && define.amd) {
    define(['jquery'], factory);
  } else if (typeof module === 'object' && typeof module.exports === 'object') {
    factory(require('jquery'));
  } else {
    factory(jQuery);
  }
}(function (jQuery) {
  // Turkish shortened
  jQuery.timeago.settings.strings = {
    prefixAgo: null,
    prefixFromNow: null,
    suffixAgo: "",
    suffixFromNow: "",
    seconds: "1dk",
    minute: "1d",
    minutes: "%dd",
    hour: "1s",
    hours: "%ds",
    day: "1g",
    days: "%dg",
    month: "1ay",
    months: "%day",
    year: "1y",
    years: "%dy",
    wordSeparator: " ",
    numbers: []
  };
}));
<commit_msg>Fix Turkish abbreviation for "minutes"<commit_after>(function (factory) {
  if (typeof define === 'function' && define.amd) {
    define(['jquery'], factory);
  } else if (typeof module === 'object' && typeof module.exports === 'object') {
    factory(require('jquery'));
  } else {
    factory(jQuery);
  }
}(function (jQuery) {
  // Turkish shortened
  jQuery.timeago.settings.strings = {
    prefixAgo: null,
    prefixFromNow: null,
    suffixAgo: "",
    suffixFromNow: "",
    seconds: "1dk",
    minute: "1dk",
    minutes: "%ddk",
    hour: "1s",
    hours: "%ds",
    day: "1g",
    days: "%dg",
    month: "1ay",
    months: "%day",
    year: "1y",
    years: "%dy",
    wordSeparator: " ",
    numbers: []
  };
}));
<|endoftext|>


<commit_before>(function(){
    var app = angular.module("roster", []);

    app.controller("RosterMenuController", function(){
        this.checkoutAddJid = function(event){
            if(event.key == "Enter")
                Roster_ajaxSearchContact(event.target.value);
        };
    });

    app.controller("RosterController", function($scope){
        $scope.contacts = /*localStorage.getObject('rosterContacts') ||*/ [];
        $scope.groups = /*localStorage.getObject('rosterGroups') ||*/ [];

        /* Dictionaries */
        $scope.lookupgroups = {};
        $scope.lookupjid = {};
        $scope.lookupressource = {};

        $scope.initContacts = function(list){
            //$scope.contacts = [];
            for(i=0; i<list.length; i++){
                /* New group */
                if(!(list[i].groupname in $scope.lookupgroups)){
                    l = $scope.contacts.length;
                    $scope.contacts.push({
                        'agroup': list[i].groupname,
                        'agroupitems': []
                    });
                    $scope.lookupgroups[list[i].groupname] = $scope.contacts[l];
                }
                /* New jid */
                if(!(list[i].jid in $scope.lookupjid)){
                    l = $scope.lookupgroups[list[i].groupname].agroupitems.length;
                    $scope.lookupgroups[list[i].groupname].agroupitems.push({
                        'ajid':     list[i].jid,
                        'aval':     list[i].value,
                        'ajiditems': []
                    });
                    $scope.lookupjid[list[i].jid] = $scope.lookupgroups[list[i].groupname].agroupitems[l];
                }
                /* New ressource */
                if(!(list[i].jid+"/"+list[i].ressource in $scope.lookupressource)){
                    l = $scope.lookupjid[list[i].jid].ajiditems.length;
                    $scope.lookupjid[list[i].jid].ajiditems.push(list[i]);
                    $scope.lookupressource[list[i].jid + "/" + list[i].ressource] = $scope.lookupjid[list[i].jid].ajiditems[l];
                }
            }
            /* Sort jid by presence in each group and update jid dictionary */
            for(i=0; i<$scope.contacts.length; i++){
                $scope.contacts[i].agroupitems.sort(function(a, b){return a.aval - b.aval;});
                for(j=0; j<$scope.contacts[i].agroupitems.length; j++){
                    jid = $scope.contacts[i].agroupitems[j].jid;
                    $scope.lookupjid[jid] = $scope.contacts[i].agroupitems[j];
                }
            }
            /* Sort groups alphabetically */
            $scope.contacts.sort(function(a, b){return a.agroup.localeCompare(b.agroup);});

            //localStorage.setObject('rosterContacts', $scope.contacts);
            $scope.$apply();
        };

        $scope.initGroups = function(list){
            //$scope.groups = [];
            for (i in list){
                if(localStorage.getItem("rosterGroup_"+i) == null){
                    list[i] = true;
                    localStorage.setItem("rosterGroup_"+i, true);
                }
                else list[i] = localStorage.getItem("rosterGroup_"+i);
            }
            $scope.groups = list;
            //localStorage.setObject('rosterGroups', $scope.groups);
            $scope.$apply();
        };

        $scope.updatePresence = function(list){
            /* New group */
            if(!(list[0].groupname in $scope.lookupgroups)){
                l = $scope.contacts.length;
                $scope.contacts.push({
                    'agroup': list[0].groupname,
                    'agroupitems': []
                });
                $scope.lookupgroups[list[0].groupname] = $scope.contacts[l];
            }
            /* New jid */
            if(!(list[0].jid in $scope.lookupjid)){
                l = $scope.lookupgroups[list[0].groupname].agroupitems.length;
                $scope.lookupgroups[list[0].groupname].agroupitems.push({
                    'ajid':     list[0].jid,
                    'aval':     list[0].value,
                    'ajiditems': []
                });
                $scope.lookupjid[list[0].jid] = $scope.lookupgroups[list[0].groupname].agroupitems[l];
            }

            /* Replace the ajiditems by the new list of ressource */
            $scope.lookupjid[list[0].jid].ajiditems = list;
            /* Update the value of the global presence */
            $scope.lookupjid[list[0].jid].aval = list[0].value;
            /* Update the ressources dictionary */
            for(i=0; i<list.length; i++){
                resid = list[i].jid + "/" + list[i].ressource;
                $scope.lookupressource[resid] = $scope.lookupjid[list[0].jid].ajiditems[i];
            }

             /*
             * Sort jid array of the concerned group by global presence of each jid
             * and update jids dictionary
             **/
            $scope.lookupgroups[list[0].groupname].agroupitems.sort(function(a, b){return a.aval - b.aval;});
            for(j=0; j<$scope.lookupgroups[list[0].groupname].agroupitems.length; j++){
                jid = $scope.lookupgroups[list[0].groupname].agroupitems[j].jid;
                $scope.lookupjid[jid] = $scope.lookupgroups[list[0].groupname].agroupitems[j];
            }

            $scope.$apply();
        };

        this.showHideGroup = function(g){
            ls = localStorage.getItem("rosterGroup_"+g);
            if(ls == null){
                ls = localStorage.getItem("rosterGroup_ungrouped");
                g = "ungrouped";
            }

            ls = ls == 'true' ? 'false' : 'true';

            localStorage.setItem("rosterGroup_"+g, ls);
            $scope.groups[g] = ls;
        };

        this.postChatAction = function(c){
            eval(c.rosterview.openchat);
        };

        this.postJingleAction = function(c){
            Popup.close();
            Popup.open(c.jid+"/"+c.ressource);
        };

        this.groupIsShown = function(grp){
            if(typeof $scope.groups[grp] != "undefined"){
                return $scope.groups[grp];
            }
            else return $scope.groups["ungrouped"];
        };

        this.offlineIsShown = function(){
            if(localStorage.getItem("rosterShow_offline") == "true")
                return "offlineshown";
            else
                return "";
        };

        this.getContactTitle = function(c){
            status = c.status || "";
            ressource = c.ressource || "";
            title = c.jid;
            if(status != "") title += " - " + status;
            if(ressource != "") title += " - " + ressource;
            return title;
        };

        this.getContactClient = function(c){
            liclass = "";
            if(c.rosterview.client)
                liclass = "client "+c.rosterview.client;
            return liclass;
        };

        this.getContactClient = function(c){
            liclass = "";
            if(c.rosterview.client)
                liclass = "client "+c.rosterview.client;
            return liclass;
        };

        this.getJidStatusRessource = function(c){
            lititle = c.jid;
            if(c.status != '') lititle+= " - "+c.status;
            lititle += " - "+c.ressource;
            return lititle;
        };

        this.getPresenceInactiveClient = function(c){
            liclass = c.rosterview.presencetxt+" "+contact.rosterview.inactive;
            if(c.client) liclass += " client "+c.client;
            return liclass;
        };
    });
})();

function initContacts(tab){
    angular.element(roster).scope().initContacts(JSON.parse(tab));
}

function initGroups(tab){
    angular.element(roster).scope().initGroups(JSON.parse(tab));
}

function updatePresence(tab){
    angular.element(roster).scope().updatePresence(JSON.parse(tab));
}

function locationOf(element, array, comparer, start, end) {
    if (array.length === 0)
        return -1;

    start = start || 0;
    end = end || array.length;
    var pivot = (start + end) >> 1;  // should be faster than the above calculation

    var c = comparer(element, array[pivot]);
    if (end - start <= 1) return c == -1 ? pivot - 1 : pivot;

    switch (c) {
        case -1: return locationOf(element, array, comparer, start, pivot);
        case 0: return pivot;
        case 1: return locationOf(element, array, comparer, pivot, end);
    };
};

// sample for objects like {lastName: 'Miller', ...}
var groupnameCompare = function (a, b) {
    return a.agroup.localeCompare(b.agroup);
};

function showHideOffline() {
    if(localStorage.getItem("rosterShow_offline") != "true" ){
        document.querySelector('ul#rosterlist').className = 'offlineshown';
        localStorage.setItem("rosterShow_offline", "true");
    }
    else{
        document.querySelector('ul#rosterlist').className = '';
        localStorage.setItem("rosterShow_offline", "false");
    }
}

MovimWebsocket.attach(function()
{
    Roster_ajaxGetRoster();
});

movim_add_onload(function()
{
    var search      = document.querySelector('#rostersearch');
    var roster      = document.querySelector('#roster');
    var rosterlist  = document.querySelector('#rosterlist');

    var roster_classback      = document.querySelector('#roster').className;
    var rosterlist_classback  = document.querySelector('#rosterlist').className;

    roster.onblur  = function() {
        roster.className = roster_classback;
        rosterlist.className = rosterlist_classback;
    };
    search.onkeyup = function(event) {
        if(search.value.length > 0) {
            roster.className = 'search';
            rosterlist.className = 'offlineshown';
        } else {
            roster.className = roster_classback;
            rosterlist.className = rosterlist_classback;
        }

        // We clear the old search
        var selector_clear = '#rosterlist div > li';
        var li = document.querySelectorAll(selector_clear);

        for(i = 0; i < li.length; i++) {
            li.item(i).className = '';
        }

        // We select the interesting li
        var selector = '#rosterlist div > li[title*=\'' + search.value + '\']';
        var li = document.querySelectorAll(selector);

        for(i = 0; i < li.length; i++) {
            li.item(i).className = 'found';
        }
    };
});
<commit_msg>- mouarf...nothing interesting...<commit_after>(function(){
    var app = angular.module("roster", []);

    /* Controller for Rostermenu */
    app.controller("RosterMenuController", function(){
        this.checkoutAddJid = function(event){
            if(event.key == "Enter")
                Roster_ajaxSearchContact(event.target.value);
        };
    });

    /* Controller for Rosterlist */
    app.controller("RosterController", function($scope){
        $scope.contacts = /*localStorage.getObject('rosterContacts') ||*/ [];
        $scope.groups = /*localStorage.getObject('rosterGroups') ||*/ [];
//$scope.list = [];

        /* Dictionaries */
        $scope.lookupgroups = {};
        $scope.lookupjid = {};
        $scope.lookupressource = {};

        $scope.initContacts = function(list){
            //$scope.contacts = [];
//$scope.list = list;
            for(i=0; i<list.length; i++){
                /* New group */
                if(!(list[i].groupname in $scope.lookupgroups)){
                    l = $scope.contacts.length;
                    $scope.contacts.push({
                        'agroup': list[i].groupname,
                        'agroupitems': []
                    });
                    $scope.lookupgroups[list[i].groupname] = $scope.contacts[l];
                }
                /* New jid */
                if(!(list[i].jid in $scope.lookupjid)){
                    l = $scope.lookupgroups[list[i].groupname].agroupitems.length;
                    $scope.lookupgroups[list[i].groupname].agroupitems.push({
                        'ajid':     list[i].jid,
                        'aval':     list[i].value,
                        'ajiditems': []
                    });
                    $scope.lookupjid[list[i].jid] = $scope.lookupgroups[list[i].groupname].agroupitems[l];
                }
                /* New ressource */
                if(!(list[i].jid+"/"+list[i].ressource in $scope.lookupressource)){
                    l = $scope.lookupjid[list[i].jid].ajiditems.length;
                    $scope.lookupjid[list[i].jid].ajiditems.push(list[i]);
                    $scope.lookupressource[list[i].jid + "/" + list[i].ressource] = $scope.lookupjid[list[i].jid].ajiditems[l];
                }
            }
            /* Sort jid by presence in each group and update jid dictionary */
            for(i=0; i<$scope.contacts.length; i++){
                $scope.contacts[i].agroupitems.sort(function(a, b){return a.aval - b.aval;});
                for(j=0; j<$scope.contacts[i].agroupitems.length; j++){
                    jid = $scope.contacts[i].agroupitems[j].jid;
                    $scope.lookupjid[jid] = $scope.contacts[i].agroupitems[j];
                }
            }
            /* Sort groups alphabetically */
            $scope.contacts.sort(function(a, b){return a.agroup.localeCompare(b.agroup);});

            //localStorage.setObject('rosterContacts', $scope.contacts);
            $scope.$apply();
        };

        $scope.initGroups = function(list){
            //$scope.groups = [];
            for (i in list){
                if(localStorage.getItem("rosterGroup_"+i) == null){
                    list[i] = true;
                    localStorage.setItem("rosterGroup_"+i, true);
                }
                else list[i] = localStorage.getItem("rosterGroup_"+i);
            }
            $scope.groups = list;
            //localStorage.setObject('rosterGroups', $scope.groups);
            $scope.$apply();
        };

        $scope.updateContact = function(list){
            /* New group */
            if(!(list[0].groupname in $scope.lookupgroups)) {
                l = $scope.contacts.length;
                /* A jid has been moved to a new group */
                if (list[0].jid in $scope.lookupjid){
                    /* Create the group and put the jid in it */
                    $scope.contacts.push({
                        'agroup': list[0].groupname,
                        'agroupitems': [{
                            'ajid':     list[0].jid,
                            'aval':     list[0].value,
                            'ajiditems': list
                        }]
                    });
                    /* Remove jid of old location */
                    $scope.lookupgroups[$scope.lookupjid[list[0].jid].ajiditems[0].groupname]
                    /* Update dictionaries */
                    $scope.lookupgroups[list[0].groupname] = $scope.contacts[l];
                    $scope.lookupjid[list[0].jid] = $scope.lookupgroups[list[0].groupname].agroupitems[0];
                }
                else {
                    $scope.contacts.push({
                        'agroup': list[0].groupname,
                        'agroupitems': []
                    });
                    $scope.lookupgroups[list[0].groupname] = $scope.contacts[l];
                }
            }
            /* New jid */
            if(!(list[0].jid in $scope.lookupjid)){
                l = $scope.lookupgroups[list[0].groupname].agroupitems.length;
                $scope.lookupgroups[list[0].groupname].agroupitems.push({
                    'ajid':     list[0].jid,
                    'aval':     list[0].value,
                    'ajiditems': []
                });
                $scope.lookupjid[list[0].jid] = $scope.lookupgroups[list[0].groupname].agroupitems[l];
            }

            /* Replace the ajiditems by the new list of ressource */
            $scope.lookupjid[list[0].jid].ajiditems = list;
            /* Update the value of the global presence */
            $scope.lookupjid[list[0].jid].aval = list[0].value;
            /* Update the ressources dictionary */
            for(i=0; i<list.length; i++){
                resid = list[i].jid + "/" + list[i].ressource;
                $scope.lookupressource[resid] = $scope.lookupjid[list[0].jid].ajiditems[i];
            }

             /*
             * Sort jid array of the concerned group by global presence of each jid
             * and update jids dictionary
             **/
            $scope.lookupgroups[list[0].groupname].agroupitems.sort(function(a, b){return a.aval - b.aval;});
            for(j=0; j<$scope.lookupgroups[list[0].groupname].agroupitems.length; j++){
                jid = $scope.lookupgroups[list[0].groupname].agroupitems[j].jid;
                $scope.lookupjid[jid] = $scope.lookupgroups[list[0].groupname].agroupitems[j];
            }

            $scope.$apply();
        };

        this.showHideGroup = function(g){
            ls = localStorage.getItem("rosterGroup_"+g);
            if(ls == null){
                ls = localStorage.getItem("rosterGroup_ungrouped");
                g = "ungrouped";
            }

            ls = ls == 'true' ? 'false' : 'true';

            localStorage.setItem("rosterGroup_"+g, ls);
            $scope.groups[g] = ls;
        };

        this.postChatAction = function(c){
            eval(c.rosterview.openchat);
        };

        this.postJingleAction = function(c){
            Popup.close();
            Popup.open(c.jid+"/"+c.ressource);
        };

        this.groupIsShown = function(grp){
            if(typeof $scope.groups[grp] != "undefined"){
                return $scope.groups[grp];
            }
            else return $scope.groups["ungrouped"];
        };

        this.offlineIsShown = function(){
            if(localStorage.getItem("rosterShow_offline") == "true")
                return "offlineshown";
            else
                return "";
        };

        this.getContactTitle = function(c){
            status = c.status || "";
            ressource = c.ressource || "";
            title = c.jid;
            if(status != "") title += " - " + status;
            if(ressource != "") title += " - " + ressource;
            return title;
        };

        this.getContactClient = function(c){
            liclass = "";
            if(c.rosterview.client)
                liclass = "client "+c.rosterview.client;
            return liclass;
        };

        this.getContactClient = function(c){
            liclass = "";
            if(c.rosterview.client)
                liclass = "client "+c.rosterview.client;
            return liclass;
        };

        this.getJidStatusRessource = function(c){
            lititle = c.jid;
            if(c.status != '') lititle+= " - "+c.status;
            lititle += " - "+c.ressource;
            return lititle;
        };

        this.getPresenceInactiveClient = function(c){
            liclass = c.rosterview.presencetxt+" "+contact.rosterview.inactive;
            if(c.client) liclass += " client "+c.client;
            return liclass;
        };
    });
})();

function initContacts(tab){
    angular.element(roster).scope().initContacts(JSON.parse(tab));
}

function initGroups(tab){
    angular.element(roster).scope().initGroups(JSON.parse(tab));
}

function updatePresence(tab){
    angular.element(roster).scope().updateContact(JSON.parse(tab));
}

function locationOf(element, array, comparer, start, end) {
    if (array.length === 0)
        return -1;

    start = start || 0;
    end = end || array.length;
    var pivot = (start + end) >> 1;  // should be faster than the above calculation

    var c = comparer(element, array[pivot]);
    if (end - start <= 1) return c == -1 ? pivot - 1 : pivot;

    switch (c) {
        case -1: return locationOf(element, array, comparer, start, pivot);
        case 0: return pivot;
        case 1: return locationOf(element, array, comparer, pivot, end);
    };
};

// sample for objects like {lastName: 'Miller', ...}
var groupnameCompare = function (a, b) {
    return a.agroup.localeCompare(b.agroup);
};

function showHideOffline() {
    if(localStorage.getItem("rosterShow_offline") != "true" ){
        document.querySelector('ul#rosterlist').className = 'offlineshown';
        localStorage.setItem("rosterShow_offline", "true");
    }
    else{
        document.querySelector('ul#rosterlist').className = '';
        localStorage.setItem("rosterShow_offline", "false");
    }
}

MovimWebsocket.attach(function()
{
    Roster_ajaxGetRoster();
});

movim_add_onload(function()
{
    var search      = document.querySelector('#rostersearch');
    var roster      = document.querySelector('#roster');
    var rosterlist  = document.querySelector('#rosterlist');

    var roster_classback      = document.querySelector('#roster').className;
    var rosterlist_classback  = document.querySelector('#rosterlist').className;

    roster.onblur  = function() {
        roster.className = roster_classback;
        rosterlist.className = rosterlist_classback;
    };
    search.onkeyup = function(event) {
        if(search.value.length > 0) {
            roster.className = 'search';
            rosterlist.className = 'offlineshown';
        } else {
            roster.className = roster_classback;
            rosterlist.className = rosterlist_classback;
        }

        // We clear the old search
        var selector_clear = '#rosterlist div > li';
        var li = document.querySelectorAll(selector_clear);

        for(i = 0; i < li.length; i++) {
            li.item(i).className = '';
        }

        // We select the interesting li
        var selector = '#rosterlist div > li[title*=\'' + search.value + '\']';
        var li = document.querySelectorAll(selector);

        for(i = 0; i < li.length; i++) {
            li.item(i).className = 'found';
        }
    };
});
<|endoftext|>


<commit_before>(function(){
    var app = angular.module("roster", []);

    /* Controller for Rostermenu */
    app.controller("RosterMenuController", function(){
        this.checkoutAddJid = function(event){
            if(event.key == "Enter")
                Roster_ajaxSearchContact(event.target.value);
        };
    });

    /* Controller for Rosterlist */
    app.controller("RosterController", function($scope){
        $scope.contacts = localStorage.getObject('rosterContacts') || [];
        $scope.groups = [];

        $scope.lsJid = localStorage.getItem("username").replace("@", "at");
        $scope.lsRoster = localStorage.getObject($scope.lsJid + "_Roster") || {};
        $scope.lsGroupState = "groupState" in $scope.lsRoster ? $scope.lsRoster.groupState : {};
        $scope.lsCache = localStorage.getObject($scope.lsJid + "_cache") && ("Roster" in localStorage.getObject($scope.lsJid + "_cache")) ?
                        localStorage.getObject($scope.lsJid + "_cache")["Roster"] : {};

        /* Dictionaries */
        $scope.lookupgroups = {};
        $scope.lookupjid = {};

        $scope.initContacts = function(list){
            if($scope.contacts.length == 0){
                for(var i = 0; i < list.length; i++){
                    /* New group */
                    if(!(list[i].groupname in $scope.lookupgroups)){
                        el = {
                            'agroup': list[i].groupname,
                            'agroupitems': [],
                            'tombstone': false,
                        };
                        $scope.pushInPlace(el, $scope.contacts, groupnameCompare);

                        /* Create a reference in the localstorage for toggling */
                        $scope.lsGroupState["rosterGroup_"+list[0].groupname] = true;
                    }
                    /* New jid */
                    if(!(list[i].jid in $scope.lookupjid)){
                        el = {
                            'ajid': list[i].jid,
                            'aval': list[i].value,
                            'ajiditems': [],
                            'tombstone': false,
                        };
                        $scope.pushInPlace(el, $scope.lookupgroups[list[i].groupname].agroupitems, jidAvalCompare);
                    }
                    /* New ressource (can't just push the whole set of same jid because there is no set) */
                    if(!$scope.isInJidItems(list[i].jid, list[i].ressource)){
                        $scope.pushInPlace(list[i], $scope.lookupjid[list[i].jid].ajiditems, ressourceCompare);
                    }
                }
            }
            /* Rebound from cache */
            else{
                for(var i = 0; i < $scope.contacts.length; i++){
                    if(!$scope.contacts[i].tombstone){
                        $scope.lookupgroups[$scope.contacts[i].agroup] = $scope.contacts[i];
                        for(var j = 0; j < $scope.contacts[i].agroupitems.length; j++){
                            if(!$scope.contacts[i].agroupitems[j].tombstone)
                                $scope.lookupjid[$scope.contacts[i].agroupitems[j].ajid] = $scope.contacts[i].agroupitems[j];
                            else /* Cleanup tombstoned jid */
                                $scope.contacts[i].agroupitems.splice(j, 1);                        }
                    }
                    else /* Cleanup tombstoned groups */
                        $scope.contacts.splice(i, 1);
                }
            }

            $scope.$apply();
        };

        $scope.initGroups = function(list){
            for(var i in list){
                if(!("rosterGroup_"+i in $scope.lsGroupState)){
                    list[i] = true;
                    $scope.lsGroupState["rosterGroup_"+i] = true;
                }
                else list[i] = $scope.lsGroupState["rosterGroup_"+i];
            }

            $scope.groups = list;
            $scope.$apply();
        };

        $scope.deleteContact = function(jid){
            $scope.lookupjid[jid].tombstone = true;

            $scope.$apply();
        };

        $scope.isInJidItems = function(jid, ressource){
            l = $scope.lookupjid[jid].ajiditems.length;
            for(var i = 0; i < l; i++){
                if($scope.lookupjid[jid].ajiditems[i].ressource == ressource)
                    return true;
            }
            return false;
        };

        $scope.pushInPlace = function(element, array, comparer){
            if(array === $scope.contacts){
                dico = $scope.lookupgroups;
                key = "agroup";
            } else {
                dico = $scope.lookupjid;
                key = "ajid";
            }

            /* Put element in the right place inside array */
            index = locationOf(element, array, comparer);
            array.splice(index, 0, element);

            /* Update dictionnary from the appropriate index */
            for(var i=index; i<array.length; i++){
                dico[array[i][key]] = array[i];
            }
        };

        $scope.updateContact = function(list){
            if($scope.contacts === null) $scope.contacts = [];
            /* Group change */
            if((list[0].jid in $scope.lookupjid)
                && !($scope.lookupjid[list[0].jid].ajiditems[0].groupname == list[0].groupname)){
                /* Kill jid from old location or whole group if it's the only jid */
                oldgroupname = $scope.lookupjid[list[0].jid].ajiditems[0].groupname;
                if($scope.lookupgroups[oldgroupname].agroupitems.length == 1)
                    $scope.lookupgroups[oldgroupname].tombstone = true;
                else
                    $scope.lookupjid[list[0].jid].tombstone = true;
            }
            /* New group is not in the list */
            if(!(list[0].groupname in $scope.lookupgroups)) {
                /* Create group */
                el = {
                    'agroup': list[0].groupname,
                    'agroupitems': [],
                    'tombstone': false,
                };
                $scope.pushInPlace(el, $scope.contacts, groupnameCompare);
                /* Reference in the localstorage for toggling */
                $scope.lsGroupState["rosterGroup_"+list[0].groupname] = true;
            }

            /* Jid is in the list and no group change */
            if(list[0].jid in $scope.lookupjid
                && ($scope.lookupjid[list[0].jid].ajiditems[0].groupname == list[0].groupname))
            {
                $scope.lookupjid[list[0].jid].aval = list[0].value;
                $scope.lookupjid[list[0].jid].ajiditems = list;
                $scope.lookupgroups[list[0].groupname].agroupitems.sort(jidAvalCompare);
            }
            else{
                el = {
                    'ajid':     list[0].jid,
                    'aval':     list[0].value,
                    'ajiditems': list,
                    'tombstone': false,
                };
                $scope.pushInPlace(el, $scope.lookupgroups[list[0].groupname].agroupitems, jidAvalCompare);
            }
            $scope.$apply();
        };

        this.showHideGroup = function(g){
            ls = $scope.lsGroupState["rosterGroup_"+g];
            if(ls === null){
                ls = $scope.lsGroupState.rosterGroup_Ungrouped;
                g = "Ungrouped";
            }

            ls = !ls;

            $scope.lsGroupState["rosterGroup_"+g] = ls;
            $scope.groups[g] = ls;
        };

        this.postChatAction = function(c){
            eval(c.rosterview.openchat);
        };

        this.postJingleAction = function(c){
            Popup.close();
            Popup.open(c.jid + "/" + c.ressource);
        };

        this.groupIsShown = function(grp){
            if(typeof $scope.groups[grp] != "undefined"){
                return $scope.groups[grp];
            }
            else return $scope.groups["Ungrouped"];
        };

        this.offlineIsShown = function(){
            if($scope.lsGroupState.rosterShow_offline)
                return "offlineshown";
            else
                return "";
        };

        this.getContactTitle = function(c){
            status = c.status || "";
            ressource = c.ressource || "";
            title = c.jid;
            if(status != "") title += " - " + status;
            if(ressource != "") title += " - " + ressource;
            return title;
        };

        this.getContactClient = function(c){
            liclass = "";
            if(c.rosterview.client)
                liclass = "client " + c.rosterview.client;
            return liclass;
        };

        this.getJidStatusRessource = function(c){
            lititle = c.jid;
            if(c.status != '') lititle += " - " + c.status;
            lititle += " - " + c.ressource;
            return lititle;
        };

        this.getPresenceInactiveClient = function(c){
            liclass = c.rosterview.presencetxt + " " + contact.rosterview.inactive;
            if(c.client) liclass += " client " + c.client;
            return liclass;
        };
    });
})();

window.onunload = window.onbeforeunload = function(e){
    var lsjid = angular.element(roster).scope().lsJid;

    /* Cache Roster list in jid_cache.Roster */
    if(localStorage.getObject(lsjid + "_cache") === null)
        localStorage.setObject(lsjid + "_cache", {"Roster": angular.element(roster).scope().contacts});
    else{
        var nv = localStorage.getObject(lsjid + "_cache").Roster = angular.element(roster).scope().contacts;
        localStorage.setObject(lsjid + "_cache", nv);
    }

    /* Move this to disconnection moment ?? */
    /* Keep group states in jid_Roster.groupStates */
    angular.element(roster).scope().lsRoster.groupState = angular.element(roster).scope().lsGroupState;
    localStorage.setObject(lsjid + "_Roster", angular.element(roster).scope().lsRoster);
};

/* Functions to call angular inner functions */
function initContacts(tab){
    if(tab.length == 0)
        angular.element(roster).scope().contacts = null;
    else
        angular.element(roster).scope().initContacts(JSON.parse(tab));
}

function initGroups(tab){
    angular.element(roster).scope().initGroups(JSON.parse(tab));
}

function updateContact(tab){
    angular.element(roster).scope().updateContact(JSON.parse(tab));
}

function deleteContact(jid){
    angular.element(roster).scope().deleteContact(jid);
}

/* === PushInPlace subfunctions === */
function locationOf(element, array, comparer, start, end) {
    if (array.length === 0)
        return 0;
    start = start || 0;
    end = end || array.length;
    var pivot = (start + end) >> 1;  // >>1 = /2
    var c = comparer(element, array[pivot]);
    if ((end - start) <= 1){
        return (c == -1) ? pivot : pivot+1;
    }

    switch (c) {
        case -1: return locationOf(element, array, comparer, start, pivot);
        case 0: return pivot;
        case 1: return locationOf(element, array, comparer, pivot, end);
    };
};

/* Object comparison functions */
var groupnameCompare = function(a, b) {
    return a.agroup.localeCompare(b.agroup);
};

var ressourceCompare = function(a, b) {
    n = a.value - b.value;
    return n ? n < 0 ? -1 : 1 : 0;
};
/* Presence + alphabetical comparison */
var jidAvalCompare = function(a, b) {
    n = a.aval - b.aval;
    if(n == 0 && a.ajiditems.length > 0){ /* if the array is empty keep the 0 value */
        n = a.ajiditems[0].rosterview.name.localeCompare(b.ajiditems[0].rosterview.name);
    }
    return n ? n < 0 ? -1 : 1 : 0;
};

/* === Old functions still in use === */
function showHideOffline() {
    if(!localStorage.getObject("rosterShow_offline")){
        document.querySelector('ul#rosterlist').className = 'offlineshown';
        localStorage.setObject("rosterShow_offline", true);
    }
    else{
        document.querySelector('ul#rosterlist').className = '';
        localStorage.setObject("rosterShow_offline", false);
    }
}

MovimWebsocket.attach(function(){
    Roster_ajaxGetRoster();
});

movim_add_onload(function(){
    var search      = document.querySelector('#rostersearch');
    var roster      = document.querySelector('#roster');
    var rosterlist  = document.querySelector('#rosterlist');

    var roster_classback      = document.querySelector('#roster').className;
    var rosterlist_classback  = document.querySelector('#rosterlist').className;

    roster.onblur  = function() {
        roster.className = roster_classback;
        rosterlist.className = rosterlist_classback;
    };
    search.onkeyup = function(event) {
        if(search.value.length > 0) {
            roster.className = 'search';
            rosterlist.className = 'offlineshown';
        } else {
            roster.className = roster_classback;
            rosterlist.className = rosterlist_classback;
        }

        // We clear the old search
        var selector_clear = '#rosterlist div > li';
        var li = document.querySelectorAll(selector_clear);

        for(i = 0; i < li.length; i++) {
            li.item(i).className = '';
        }

        // We select the interesting li
        var selector = '#rosterlist div > li[title*=\'' + search.value + '\']';
        var li = document.querySelectorAll(selector);

        for(i = 0; i < li.length; i++) {
            li.item(i).className = 'found';
        }
    };
});
<commit_msg>- fix use of cache with new structure<commit_after>(function(){
    var app = angular.module("roster", []);

    /* Controller for Rostermenu */
    app.controller("RosterMenuController", function(){
        this.checkoutAddJid = function(event){
            if(event.key == "Enter")
                Roster_ajaxSearchContact(event.target.value);
        };
    });

    /* Controller for Rosterlist */
    app.controller("RosterController", function($scope){
        /* Cache variables */
        $scope.lsJid = localStorage.getItem("username").replace("@", "at");
        $scope.lsRoster = localStorage.getObject($scope.lsJid + "_Roster") || {};
        $scope.lsGroupState = "groupState" in $scope.lsRoster ? $scope.lsRoster.groupState : {};

        this.cache = localStorage.getObject($scope.lsJid + '_cache');
        $scope.contacts = this.cache && ("Roster" in this.cache) && ("contactsList" in this.cache.Roster) ? localStorage.getObject($scope.lsJid + '_cache').Roster.contactsList : [];
        $scope.groups = [];

        /* Dictionaries */
        $scope.lookupgroups = {};
        $scope.lookupjid = {};

        $scope.initContacts = function(list){
            if($scope.contacts.length == 0){
                console.log("NO cache");
                for(var i = 0; i < list.length; i++){
                    /* New group */
                    if(!(list[i].groupname in $scope.lookupgroups)){
                        el = {
                            'agroup': list[i].groupname,
                            'agroupitems': [],
                            'tombstone': false,
                        };
                        $scope.pushInPlace(el, $scope.contacts, groupnameCompare);

                        /* Create a reference in the localstorage for toggling */
                        $scope.lsGroupState["rosterGroup_"+list[0].groupname] = true;
                    }
                    /* New jid */
                    if(!(list[i].jid in $scope.lookupjid)){
                        el = {
                            'ajid': list[i].jid,
                            'aval': list[i].value,
                            'ajiditems': [],
                            'tombstone': false,
                        };
                        $scope.pushInPlace(el, $scope.lookupgroups[list[i].groupname].agroupitems, jidAvalCompare);
                    }
                    /* New ressource (can't just push the whole set of same jid because there is no set) */
                    if(!$scope.isInJidItems(list[i].jid, list[i].ressource)){
                        $scope.pushInPlace(list[i], $scope.lookupjid[list[i].jid].ajiditems, ressourceCompare);
                    }
                }
            }
            /* Rebound from cache */
            else{
                console.log("cache");
                for(var i = 0; i < $scope.contacts.length; i++){
                    if(!$scope.contacts[i].tombstone){
                        $scope.lookupgroups[$scope.contacts[i].agroup] = $scope.contacts[i];
                        for(var j = 0; j < $scope.contacts[i].agroupitems.length; j++){
                            if(!$scope.contacts[i].agroupitems[j].tombstone)
                                $scope.lookupjid[$scope.contacts[i].agroupitems[j].ajid] = $scope.contacts[i].agroupitems[j];
                            else /* Cleanup tombstoned jid */
                                $scope.contacts[i].agroupitems.splice(j, 1);                        }
                    }
                    else /* Cleanup tombstoned groups */
                        $scope.contacts.splice(i, 1);
                }
            }

            $scope.$apply();
        };

        $scope.initGroups = function(list){
            for(var i in list){
                if(!("rosterGroup_"+i in $scope.lsGroupState)){
                    list[i] = true;
                    $scope.lsGroupState["rosterGroup_"+i] = true;
                }
                else list[i] = $scope.lsGroupState["rosterGroup_"+i];
            }

            $scope.groups = list;
            $scope.$apply();
        };

        $scope.deleteContact = function(jid){
            $scope.lookupjid[jid].tombstone = true;

            $scope.$apply();
        };

        $scope.isInJidItems = function(jid, ressource){
            l = $scope.lookupjid[jid].ajiditems.length;
            for(var i = 0; i < l; i++){
                if($scope.lookupjid[jid].ajiditems[i].ressource == ressource)
                    return true;
            }
            return false;
        };

        $scope.pushInPlace = function(element, array, comparer){
            if(array === $scope.contacts){
                dico = $scope.lookupgroups;
                key = "agroup";
            } else {
                dico = $scope.lookupjid;
                key = "ajid";
            }

            /* Put element in the right place inside array */
            index = locationOf(element, array, comparer);
            array.splice(index, 0, element);

            /* Update dictionnary from the appropriate index */
            for(var i=index; i<array.length; i++){
                dico[array[i][key]] = array[i];
            }
        };

        $scope.updateContact = function(list){
            if($scope.contacts === null) $scope.contacts = [];
            /* Group change */
            if((list[0].jid in $scope.lookupjid)
                && !($scope.lookupjid[list[0].jid].ajiditems[0].groupname == list[0].groupname)){
                /* Kill jid from old location or whole group if it's the only jid */
                oldgroupname = $scope.lookupjid[list[0].jid].ajiditems[0].groupname;
                if($scope.lookupgroups[oldgroupname].agroupitems.length == 1)
                    $scope.lookupgroups[oldgroupname].tombstone = true;
                else
                    $scope.lookupjid[list[0].jid].tombstone = true;
            }
            /* New group is not in the list */
            if(!(list[0].groupname in $scope.lookupgroups)) {
                /* Create group */
                el = {
                    'agroup': list[0].groupname,
                    'agroupitems': [],
                    'tombstone': false,
                };
                $scope.pushInPlace(el, $scope.contacts, groupnameCompare);
                /* Reference in the localstorage for toggling */
                $scope.lsGroupState["rosterGroup_"+list[0].groupname] = true;
            }

            /* Jid is in the list and no group change */
            if(list[0].jid in $scope.lookupjid
                && ($scope.lookupjid[list[0].jid].ajiditems[0].groupname == list[0].groupname))
            {
                $scope.lookupjid[list[0].jid].aval = list[0].value;
                $scope.lookupjid[list[0].jid].ajiditems = list;
                $scope.lookupgroups[list[0].groupname].agroupitems.sort(jidAvalCompare);
            }
            else{
                el = {
                    'ajid':     list[0].jid,
                    'aval':     list[0].value,
                    'ajiditems': list,
                    'tombstone': false,
                };
                $scope.pushInPlace(el, $scope.lookupgroups[list[0].groupname].agroupitems, jidAvalCompare);
            }
            $scope.$apply();
        };

        this.showHideGroup = function(g){
            ls = $scope.lsGroupState["rosterGroup_"+g];
            if(ls === null){
                ls = $scope.lsGroupState.rosterGroup_Ungrouped;
                g = "Ungrouped";
            }

            ls = !ls;

            $scope.lsGroupState["rosterGroup_"+g] = ls;
            $scope.groups[g] = ls;
        };

        this.postChatAction = function(c){
            eval(c.rosterview.openchat);
        };

        this.postJingleAction = function(c){
            Popup.close();
            Popup.open(c.jid + "/" + c.ressource);
        };

        this.groupIsShown = function(grp){
            if(typeof $scope.groups[grp] != "undefined"){
                return $scope.groups[grp];
            }
            else return $scope.groups["Ungrouped"];
        };

        this.offlineIsShown = function(){
            if($scope.lsGroupState.rosterShow_offline)
                return "offlineshown";
            else
                return "";
        };

        this.getContactTitle = function(c){
            status = c.status || "";
            ressource = c.ressource || "";
            title = c.jid;
            if(status != "") title += " - " + status;
            if(ressource != "") title += " - " + ressource;
            return title;
        };

        this.getContactClient = function(c){
            liclass = "";
            if(c.rosterview.client)
                liclass = "client " + c.rosterview.client;
            return liclass;
        };

        this.getJidStatusRessource = function(c){
            lititle = c.jid;
            if(c.status != '') lititle += " - " + c.status;
            lititle += " - " + c.ressource;
            return lititle;
        };

        this.getPresenceInactiveClient = function(c){
            liclass = c.rosterview.presencetxt + " " + contact.rosterview.inactive;
            if(c.client) liclass += " client " + c.client;
            return liclass;
        };
    });
})();

window.onunload = window.onbeforeunload = function(e){
    var lsjid = angular.element(roster).scope().lsJid;

    /* Cache Roster list in jid_cache.Roster */
    if(localStorage.getObject(lsjid + "_cache") === null)
        localStorage.setObject(lsjid + "_cache", {"Roster": {"contactsList": angular.element(roster).scope().contacts}});
    else{
        var nv = localStorage.getObject(lsjid + "_cache");
        nv.Roster = {"contactsList": angular.element(roster).scope().contacts};
        localStorage.setObject(lsjid + "_cache", nv);
    }

    /* Move this to disconnection moment ?? */
    /* Keep group states in jid_Roster.groupStates */
    angular.element(roster).scope().lsRoster.groupState = angular.element(roster).scope().lsGroupState;
    localStorage.setObject(lsjid + "_Roster", angular.element(roster).scope().lsRoster);
};

/* Functions to call angular inner functions */
function initContacts(tab){
    if(tab.length == 0)
        angular.element(roster).scope().contacts = null;
    else
        angular.element(roster).scope().initContacts(JSON.parse(tab));
}

function initGroups(tab){
    angular.element(roster).scope().initGroups(JSON.parse(tab));
}

function updateContact(tab){
    angular.element(roster).scope().updateContact(JSON.parse(tab));
}

function deleteContact(jid){
    angular.element(roster).scope().deleteContact(jid);
}

/* === PushInPlace subfunctions === */
function locationOf(element, array, comparer, start, end) {
    if (array.length === 0)
        return 0;
    start = start || 0;
    end = end || array.length;
    var pivot = (start + end) >> 1;  // >>1 = /2
    var c = comparer(element, array[pivot]);
    if ((end - start) <= 1){
        return (c == -1) ? pivot : pivot+1;
    }

    switch (c) {
        case -1: return locationOf(element, array, comparer, start, pivot);
        case 0: return pivot;
        case 1: return locationOf(element, array, comparer, pivot, end);
    };
};

/* Object comparison functions */
var groupnameCompare = function(a, b) {
    return a.agroup.localeCompare(b.agroup);
};

var ressourceCompare = function(a, b) {
    n = a.value - b.value;
    return n ? n < 0 ? -1 : 1 : 0;
};
/* Presence + alphabetical comparison */
var jidAvalCompare = function(a, b) {
    n = a.aval - b.aval;
    if(n == 0 && a.ajiditems.length > 0){ /* if the array is empty keep the 0 value */
        n = a.ajiditems[0].rosterview.name.localeCompare(b.ajiditems[0].rosterview.name);
    }
    return n ? n < 0 ? -1 : 1 : 0;
};

/* === Old functions still in use === */
function showHideOffline() {
    if(!localStorage.getObject("rosterShow_offline")){
        document.querySelector('ul#rosterlist').className = 'offlineshown';
        localStorage.setObject("rosterShow_offline", true);
    }
    else{
        document.querySelector('ul#rosterlist').className = '';
        localStorage.setObject("rosterShow_offline", false);
    }
}

MovimWebsocket.attach(function(){
    Roster_ajaxGetRoster();
});

movim_add_onload(function(){
    var search      = document.querySelector('#rostersearch');
    var roster      = document.querySelector('#roster');
    var rosterlist  = document.querySelector('#rosterlist');

    var roster_classback      = document.querySelector('#roster').className;
    var rosterlist_classback  = document.querySelector('#rosterlist').className;

    roster.onblur  = function() {
        roster.className = roster_classback;
        rosterlist.className = rosterlist_classback;
    };
    search.onkeyup = function(event) {
        if(search.value.length > 0) {
            roster.className = 'search';
            rosterlist.className = 'offlineshown';
        } else {
            roster.className = roster_classback;
            rosterlist.className = rosterlist_classback;
        }

        // We clear the old search
        var selector_clear = '#rosterlist div > li';
        var li = document.querySelectorAll(selector_clear);

        for(i = 0; i < li.length; i++) {
            li.item(i).className = '';
        }

        // We select the interesting li
        var selector = '#rosterlist div > li[title*=\'' + search.value + '\']';
        var li = document.querySelectorAll(selector);

        for(i = 0; i < li.length; i++) {
            li.item(i).className = 'found';
        }
    };
});
<|endoftext|>


<commit_before>"use strict";
require('zone.js/dist/zone');
require('reflect-metadata');
require('@angular/core');
require('@angular/common');
require('@angular/compiler');
require('@angular/forms');
require('@angular/platform-browser');
require('@angular/platform-browser-dynamic');
require('@angular/http');
require('@angular/router');
require('rxjs');
require('h5webstorage');
require('@ng-bootstrap/ng-bootstrap');
require('angular2-component-outlet-modified/index.js');
require('jquery');
require('tether/dist/js/tether.min.js');
require('bootstrap/dist/js/bootstrap.min.js');
<commit_msg>removed useless file<commit_after><|endoftext|>


<commit_before>var Cell = require('./Cell');

function PlayerCell() {
    Cell.apply(this, Array.prototype.slice.call(arguments));

    this.cellType = 0;
    this._speed = null;
    this._canRemerge = false;
}

module.exports = PlayerCell;
PlayerCell.prototype = new Cell();

// Main Functions

PlayerCell.prototype.canEat = function (cell) {
    return true; // player cell can eat anyone
};

PlayerCell.prototype.getSpeed = function () {
    var speed = 2.1106 / Math.pow(this._size, 0.449);
    // tickStep = 40ms
    this._speed = speed * 40 * this.gameServer.config.playerSpeed;
    return this._speed * 32 / 32;
};

PlayerCell.prototype.onAdd = function (gameServer) {
    // Gamemode actions
    gameServer.gameMode.onCellAdd(this);
};

PlayerCell.prototype.onRemove = function (gameServer) {
    // Remove from player cell list
    var index = this.owner.cells.indexOf(this);
    if (index != -1) {
        this.owner.cells.splice(index, 1);
    }
    // Gamemode actions
    gameServer.gameMode.onCellRemove(this);
};
<commit_msg>Update PlayerCell.js<commit_after>var Cell = require('./Cell');

function PlayerCell() {
    Cell.apply(this, Array.prototype.slice.call(arguments));

    this.cellType = 0;
    this._speed = null;
    this._canRemerge = false;
}

module.exports = PlayerCell;
PlayerCell.prototype = new Cell();

// Main Functions

PlayerCell.prototype.canEat = function (cell) {
    return true; // player cell can eat anyone
};

PlayerCell.prototype.getSpeed = function () {
    var speed = 2.1106 / Math.pow(this._size, 0.449);
    // tickStep = 40ms
    this._speed = speed * 40 * this.gameServer.config.playerSpeed;
    return this._speed;
};

PlayerCell.prototype.onAdd = function (gameServer) {
    // Gamemode actions
    gameServer.gameMode.onCellAdd(this);
};

PlayerCell.prototype.onRemove = function (gameServer) {
    // Remove from player cell list
    var index = this.owner.cells.indexOf(this);
    if (index != -1) {
        this.owner.cells.splice(index, 1);
    }
    // Gamemode actions
    gameServer.gameMode.onCellRemove(this);
};
<|endoftext|>


<commit_before>
// pg - "Pot Game"
goog.provide('test.anim3');

goog.require('lime');
goog.require('lime.CoverNode');
goog.require('lime.Director');
goog.require('lime.Layer');
goog.require('lime.Scene');
goog.require('lime.Sprite');
goog.require('lime.Circle');
goog.require('lime.animation.MoveTo');
goog.require('lime.animation.Sequence');
goog.require('lime.animation.Loop');
goog.require('lime.animation.Delay');

test.WIDTH = 800;
test.HEIGHT = 400;

test.start = function() {

	//director
	test.director = new lime.Director(document.body,1024, 768);
	test.director.makeMobileWebAppCapable();

    var scene = new lime.Scene();

    var circle = new lime.Circle()
        .setSize(50, 50)
        .setFill(255, 150, 0)
        .setPosition(100, 100);

    scene.appendChild(circle);

    var moveRight = new lime.animation.MoveTo(874, 100)
        .setSpeed(1)
        .setEasing(lime.animation.Easing.LINEAR);

    var moveLeft = new lime.animation.MoveTo(100, 100)
        .setSpeed(1)
        .setEasing(lime.animation.Easing.LINEAR);

    goog.events.listen(moveRight,lime.animation.Event.STOP, function () {
        setTimeout(function () {
            circle.runAction(moveLeft);
        }, 500);
    });

    goog.events.listen(moveLeft,lime.animation.Event.STOP, function () {
        setTimeout(function () {
            circle.runAction(moveRight);
        }, 500);
    });

    circle.runAction(moveRight);

    // better solution

    var circle2 = new lime.Circle()
        .setSize(50, 50)
        .setFill(255, 150, 0)
        .setPosition(100, 200);

    scene.appendChild(circle2);

    var moveRight2 = new lime.animation.MoveTo(874, 200)
        .setDuration(774/100);

    var moveLeft2 = new lime.animation.MoveTo(100, 200)
        .setDuration(774/100);

    circle2.runAction(new lime.animation.Loop(
       new lime.animation.Sequence(
            moveRight2, new lime.animation.Delay().setDuration(.5),
            moveLeft2, new lime.animation.Delay().setDuration(.5)
       ).setEasing(lime.animation.Easing.LINEAR)
    ));

    // set current scene active
    test.director.replaceScene(scene);

};

goog.exportSymbol('test.start', test.start);
<commit_msg>Transition comparison to the anim4 demo<commit_after>
// pg - "Pot Game"
goog.provide('test.anim3');

goog.require('lime');
goog.require('lime.CoverNode');
goog.require('lime.Director');
goog.require('lime.Layer');
goog.require('lime.Scene');
goog.require('lime.Sprite');
goog.require('lime.Circle');
goog.require('lime.animation.MoveTo');
goog.require('lime.animation.Sequence');
goog.require('lime.animation.Loop');
goog.require('lime.animation.Delay');

test.WIDTH = 800;
test.HEIGHT = 400;

test.start = function() {

	//director
	test.director = new lime.Director(document.body,1024, 768);
	test.director.makeMobileWebAppCapable();

    var scene = new lime.Scene();

    var circle = new lime.Circle()
        .setSize(50, 50)
        .setFill(255, 150, 0)
        .setPosition(100, 100);

    scene.appendChild(circle);

    var moveRight = new lime.animation.MoveTo(874, 100)
        .setSpeed(1)
        .setEasing(lime.animation.Easing.LINEAR);

    var moveLeft = new lime.animation.MoveTo(100, 100)
        .setSpeed(1)
        .setEasing(lime.animation.Easing.LINEAR);

    goog.events.listen(moveRight,lime.animation.Event.STOP, function () {
        setTimeout(function () {
            circle.runAction(moveLeft);
        }, 500);
    });

    goog.events.listen(moveLeft,lime.animation.Event.STOP, function () {
        setTimeout(function () {
            circle.runAction(moveRight);
        }, 500);
    });

    circle.runAction(moveRight);

    // better solution

    var circle2 = new lime.Circle()
        .setSize(50, 50)
        .setFill(255, 150, 0)
        .setPosition(100, 200);

    scene.appendChild(circle2);

    var moveRight2 = new lime.animation.MoveTo(874, 200)
        .setDuration(774/100).enableOptimizations();

    var moveLeft2 = new lime.animation.MoveTo(100, 200)
        .setDuration(774/100).enableOptimizations();

    circle2.runAction(new lime.animation.Loop(
       new lime.animation.Sequence(
            moveRight2, new lime.animation.Delay().setDuration(.5),
            moveLeft2, new lime.animation.Delay().setDuration(.5)
       ).setEasing(lime.animation.Easing.LINEAR)
    ));

    // set current scene active
    test.director.replaceScene(scene);

};

goog.exportSymbol('test.start', test.start);
<|endoftext|>