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

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

  require('scripts/services/directives/managed_service');
  require('scripts/applications/services/application_services');

  states.state('applications.detail.environment.deploynext.deploy', {
    url: '/deploy',
    templateUrl: 'views/_ref/applications/applications_detail_environment_deploynext_deploy.html',
    controller: 'AppEnvDeployNextDeployCtrl',
    menu: {
      id: 'applications.detail.environment.deploynext.deploy',
      state: 'applications.detail.environment.deploynext.deploy',
      key: 'NAVAPPLICATIONS.MENU_DEPLOY_NEXT.DEPLOY',
      icon: '',
      priority: 600,
      step: {
        taskCodes: ['NODE_FILTER_INVALID', 'ORCHESTRATOR_PROPERTY', 'PROPERTIES', 'SCALABLE_CAPABILITY_INVALID']
      }
    }
  });

  modules.get('a4c-applications').controller('AppEnvDeployNextDeployCtrl',
    ['$scope', '$alresource', '$translate', 'toaster', '$uibModal', 'deploymentTopologyServices', 'applicationServices', 'breadcrumbsService', '$state', 'locationsMatchingServices',
    function ($scope, $alresource, $translate, toaster, $uibModal, deploymentTopologyServices, applicationServices, breadcrumbsService, $state, locationsMatchingServices) {
      breadcrumbsService.putConfig({
        state : 'applications.detail.environment.deploynext.deploy',
        text: function(){
          return $translate.instant('NAVAPPLICATIONS.MENU_DEPLOY_NEXT.DEPLOY');
        },
        onClick: function(){
          $state.go('applications.detail.environment.deploynext.deploy');
        }
      });

      $scope.doDeploy = function() {
        var deployApplicationRequest = {
          applicationId: $scope.application.id,
          applicationEnvironmentId: $scope.environment.id
        };
        $scope.setState('INIT_DEPLOYMENT');
        applicationServices.deployApplication.deploy([], angular.toJson(deployApplicationRequest), function() {
          $scope.environment.status = 'INIT_DEPLOYMENT';
          // the deployed version is the current one
          $scope.environment.deployedVersion = $scope.environment.currentVersionName;
          $scope.setEnvironment($scope.environment);
        }, function() {
          $scope.reloadEnvironment();
        });
      };

      $scope.doUpdate = function() {
        $scope.setState('INIT_DEPLOYMENT');

        applicationServices.deploymentUpdate({
          applicationId: $scope.application.id,
          applicationEnvironmentId: $scope.environment.id
        }, undefined, function(data) {
          if (data.error === null) {
            $scope.environment.status = 'UPDATE_IN_PROGRESS';
            $scope.setEnvironment($scope.environment);
          } else {
            $scope.environment.status = 'UPDATE_FAILURE';
            $scope.setEnvironment($scope.environment);
            toaster.pop(
              'error',
              $translate.instant('DEPLOYMENT.STATUS.UPDATE_FAILURE'),
              $translate.instant('DEPLOYMENT.TOASTER_STATUS.UPDATE_FAILURE', {
                envName : $scope.environment.name,
                appName : $scope.application.name
              }),
              0, 'trustedHtml', null
            );
          }
        }, function() {
          $scope.reloadEnvironment();
        });
      };

      /**
      * DEPLOYMENT PROPERTIES
      **/
      function refreshOrchestratorDeploymentPropertyDefinitions() {
        return $alresource('rest/latest/orchestrators/:orchestratorId/deployment-property-definitions')
        .get({orchestratorId: $scope.deploymentTopologyDTO.topology.orchestratorId}, function (result) {
          if (result.data) {
            $scope.orchestratorDeploymentPropertyDefinitions = result.data;
          }
        });
      }

      $scope.updateDeploymentProperty = function (propertyDefinition, propertyName, propertyValue) {
        if ((_.defined($scope.deploymentTopologyDTO.topology.providerDeploymentProperties) && propertyValue === $scope.deploymentTopologyDTO.topology.providerDeploymentProperties[propertyName]) || (_.undefined($scope.deploymentTopologyDTO.topology.providerDeploymentProperties) && _.undefined(propertyValue))) {
          return; // no change
        }
        var deploymentPropertyObject = {
          'definitionId': propertyName,
          'value': propertyValue
        };

        return applicationServices.checkProperty({
          orchestratorId: $scope.deploymentTopologyDTO.topology.orchestratorId
        }, angular.toJson(deploymentPropertyObject), function (data) {
          if (data.error === null) {
            if(_.undefined($scope.deploymentTopologyDTO.topology.providerDeploymentProperties)) {
              $scope.deploymentTopologyDTO.topology.providerDeploymentProperties = {};
            }
            $scope.deploymentTopologyDTO.topology.providerDeploymentProperties[propertyName] = propertyValue;
            // Update deployment setup when properties change
            deploymentTopologyServices.updateInputProperties({
                appId: $scope.application.id,
                envId: $scope.environment.id
              }, angular.toJson({
                providerDeploymentProperties: $scope.deploymentTopologyDTO.topology.providerDeploymentProperties
              }), function (result) {
                if (!result.error) {
                  $scope.updateScopeDeploymentTopologyDTO(result.data);
                }
              }
            );
          }
        }).$promise;
      };

      // the topology deployment is updatable if:
      // - the status is one of DEPLOYED , UPDATED,
      // - the current selectedlocation is the same as the one of the deployed topology
      $scope.isUpdatable = function() {
        return _.includes(['DEPLOYED', 'UPDATED'], $scope.environment.status) &&
               _.definedPath($scope.deploymentTopologyDTO, 'locationPolicies._A4C_ALL') &&
               _.get($scope.deploymentTopologyDTO, 'locationPolicies._A4C_ALL') === _.get($scope.deployedTopology, 'topology.locationGroups._A4C_ALL.policies[0].locationId');
      };

      $scope.$watch('deploymentTopologyDTO.topology.orchestratorId', function(newValue){
        if(_.undefined(newValue)){
          return;
        }
        refreshOrchestratorDeploymentPropertyDefinitions();
      });
    }
  ]);
});
<commit_msg>remove useless dependencies<commit_after>define(function (require) {
  'use strict';

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

  require('scripts/services/directives/managed_service');
  require('scripts/applications/services/application_services');

  states.state('applications.detail.environment.deploynext.deploy', {
    url: '/deploy',
    templateUrl: 'views/_ref/applications/applications_detail_environment_deploynext_deploy.html',
    controller: 'AppEnvDeployNextDeployCtrl',
    menu: {
      id: 'applications.detail.environment.deploynext.deploy',
      state: 'applications.detail.environment.deploynext.deploy',
      key: 'NAVAPPLICATIONS.MENU_DEPLOY_NEXT.DEPLOY',
      icon: '',
      priority: 600,
      step: {
        taskCodes: ['NODE_FILTER_INVALID', 'ORCHESTRATOR_PROPERTY', 'PROPERTIES', 'SCALABLE_CAPABILITY_INVALID']
      }
    }
  });

  modules.get('a4c-applications').controller('AppEnvDeployNextDeployCtrl',
    ['$scope', '$alresource', '$translate', 'toaster', 'deploymentTopologyServices', 'applicationServices', 'breadcrumbsService', '$state',
    function ($scope, $alresource, $translate, toaster, deploymentTopologyServices, applicationServices, breadcrumbsService, $state) {
      breadcrumbsService.putConfig({
        state : 'applications.detail.environment.deploynext.deploy',
        text: function(){
          return $translate.instant('NAVAPPLICATIONS.MENU_DEPLOY_NEXT.DEPLOY');
        },
        onClick: function(){
          $state.go('applications.detail.environment.deploynext.deploy');
        }
      });

      $scope.doDeploy = function() {
        var deployApplicationRequest = {
          applicationId: $scope.application.id,
          applicationEnvironmentId: $scope.environment.id
        };
        $scope.setState('INIT_DEPLOYMENT');
        applicationServices.deployApplication.deploy([], angular.toJson(deployApplicationRequest), function() {
          $scope.environment.status = 'INIT_DEPLOYMENT';
          // the deployed version is the current one
          $scope.environment.deployedVersion = $scope.environment.currentVersionName;
          $scope.setEnvironment($scope.environment);
        }, function() {
          $scope.reloadEnvironment();
        });
      };

      $scope.doUpdate = function() {
        $scope.setState('INIT_DEPLOYMENT');

        applicationServices.deploymentUpdate({
          applicationId: $scope.application.id,
          applicationEnvironmentId: $scope.environment.id
        }, undefined, function(data) {
          if (data.error === null) {
            $scope.environment.status = 'UPDATE_IN_PROGRESS';
            $scope.setEnvironment($scope.environment);
          } else {
            $scope.environment.status = 'UPDATE_FAILURE';
            $scope.setEnvironment($scope.environment);
            toaster.pop(
              'error',
              $translate.instant('DEPLOYMENT.STATUS.UPDATE_FAILURE'),
              $translate.instant('DEPLOYMENT.TOASTER_STATUS.UPDATE_FAILURE', {
                envName : $scope.environment.name,
                appName : $scope.application.name
              }),
              0, 'trustedHtml', null
            );
          }
        }, function() {
          $scope.reloadEnvironment();
        });
      };

      /**
      * DEPLOYMENT PROPERTIES
      **/
      function refreshOrchestratorDeploymentPropertyDefinitions() {
        return $alresource('rest/latest/orchestrators/:orchestratorId/deployment-property-definitions')
        .get({orchestratorId: $scope.deploymentTopologyDTO.topology.orchestratorId}, function (result) {
          if (result.data) {
            $scope.orchestratorDeploymentPropertyDefinitions = result.data;
          }
        });
      }

      $scope.updateDeploymentProperty = function (propertyDefinition, propertyName, propertyValue) {
        if ((_.defined($scope.deploymentTopologyDTO.topology.providerDeploymentProperties) && propertyValue === $scope.deploymentTopologyDTO.topology.providerDeploymentProperties[propertyName]) || (_.undefined($scope.deploymentTopologyDTO.topology.providerDeploymentProperties) && _.undefined(propertyValue))) {
          return; // no change
        }
        var deploymentPropertyObject = {
          'definitionId': propertyName,
          'value': propertyValue
        };

        return applicationServices.checkProperty({
          orchestratorId: $scope.deploymentTopologyDTO.topology.orchestratorId
        }, angular.toJson(deploymentPropertyObject), function (data) {
          if (data.error === null) {
            if(_.undefined($scope.deploymentTopologyDTO.topology.providerDeploymentProperties)) {
              $scope.deploymentTopologyDTO.topology.providerDeploymentProperties = {};
            }
            $scope.deploymentTopologyDTO.topology.providerDeploymentProperties[propertyName] = propertyValue;
            // Update deployment setup when properties change
            deploymentTopologyServices.updateInputProperties({
                appId: $scope.application.id,
                envId: $scope.environment.id
              }, angular.toJson({
                providerDeploymentProperties: $scope.deploymentTopologyDTO.topology.providerDeploymentProperties
              }), function (result) {
                if (!result.error) {
                  $scope.updateScopeDeploymentTopologyDTO(result.data);
                }
              }
            );
          }
        }).$promise;
      };

      // the topology deployment is updatable if:
      // - the status is one of DEPLOYED , UPDATED,
      // - the current selectedlocation is the same as the one of the deployed topology
      $scope.isUpdatable = function() {
        return _.includes(['DEPLOYED', 'UPDATED'], $scope.environment.status) &&
               _.definedPath($scope.deploymentTopologyDTO, 'locationPolicies._A4C_ALL') &&
               _.get($scope.deploymentTopologyDTO, 'locationPolicies._A4C_ALL') === _.get($scope.deployedTopology, 'topology.locationGroups._A4C_ALL.policies[0].locationId');
      };

      $scope.$watch('deploymentTopologyDTO.topology.orchestratorId', function(newValue){
        if(_.undefined(newValue)){
          return;
        }
        refreshOrchestratorDeploymentPropertyDefinitions();
      });
    }
  ]);
});
<|endoftext|>


<commit_before>/*!
 * Froala Instagram Plugin
 * Written by EvabioZ (evabioz@gmail.com)
 * Tested with Froala v2.0.5 (https://www.froala.com/wysiwyg-editor)
 */

(function (factory) {
    if (typeof define === 'function' && define.amd) {
        // AMD. Register as an anonymous module.
        define(['jquery'], factory);
    } else if (typeof module === 'object' && module.exports) {
        // Node/CommonJS
        module.exports = function( root, jQuery ) {
            if ( jQuery === undefined ) {
                // require('jQuery') returns a factory that requires window to
                // build a jQuery instance, we normalize how we use modules
                // that require this pattern but the window provided is a noop
                // if it's defined (how jquery works)
                if ( typeof window !== 'undefined' ) {
                    jQuery = require('jquery');
                }
                else {
                    jQuery = require('jquery')(root);
                }
            }
            factory(jQuery);
            return jQuery;
        };
    } else {
        // Browser globals
        factory(jQuery);
    }
}(function ($) {

  'use strict';

  var urlRe = /^(http|https):\/\/(instagr\.am|instagram\.com|www\.instagram\.com)\/p\/([^\/?]+)/;

  // Define popup template.
  $.extend($.FroalaEditor.POPUP_TEMPLATES, {
    "instagram.insert": '[_BUTTONS_][_INPUT_LAYER_]'
  });

  $.extend($.FroalaEditor.DEFAULTS, {
    instagramEmbedVersion: 7,
    instagramHelpText: 'Paste a URL to generate code'
  });

  $.merge($.FroalaEditor.DEFAULTS.htmlAllowedAttrs, [
    'onload'
  ]);

  // The custom popup is defined inside a plugin (new or existing).
  $.FroalaEditor.PLUGINS.instagram = function (editor) {

    // Create custom popup.
    function initPopup () {
      // Popup buttons.
      var popup_buttons = '';

      // Create the list of buttons.
      if (editor.opts.popupButtons && editor.opts.popupButtons.length > 0) {
        popup_buttons += '
';
        popup_buttons += editor.button.buildList(editor.opts.popupButtons);
        popup_buttons += '
';
      }

      var tab_idx = 0;
      var input_layer = '
';
      input_layer += '

';
      if (editor.opts.instagramHelpText){
        input_layer += ''+editor.language.translate(editor.opts.instagramHelpText)+'';
      }
      input_layer += '
<input name="href" type="text" placeholder="https://www.instagram.com/p/" tabIndex="' + (++tab_idx) + '">
';
      input_layer += '
<input name="captioned" type="checkbox" checked="checked" />With Captioned
';
      input_layer += '
<button class="fr-command fr-submit" data-cmd="linkInstagramInsert" href="#" tabIndex="' + (++tab_idx) + '" type="button">' + editor.language.translate('Insert') + '</button>

';

      // Load popup template.
      var template = {
        buttons: popup_buttons,
        input_layer: input_layer
      };

      // Create popup.
      return editor.popups.create('instagram.insert', template);
    }

    // Show the popup
    function showPopup () {
      // Get the popup object defined above.
      var $popup = editor.popups.get('instagram.insert');

      // If popup doesn't exist then create it.
      // To improve performance it is best to create the popup when it is first needed
      // and not when the editor is initialized.
      if (!$popup) $popup = initPopup();

      //reset popup
      resetPopup();

      // Set the editor toolbar as the popup's container.
      editor.popups.setContainer('instagram.insert', editor.$tb);

      // This will trigger the refresh event assigned to the popup.
      // editor.popups.refresh('instagram.insert');

      // This custom popup is opened by pressing a button from the editor's toolbar.
      // Get the button's object in order to place the popup relative to it.
      var $btn = editor.$tb.find('.fr-command[data-cmd="instagram"]');

      // Set the popup's position.
      var left = $btn.offset().left + $btn.outerWidth() / 2;
      var top = $btn.offset().top + (editor.opts.toolbarBottom ? 10 : $btn.outerHeight() - 10);

      // Show the custom popup.
      // The button's outerHeight is required in case the popup needs to be displayed above it.
      editor.popups.show('instagram.insert', left, top, $btn.outerHeight());
    }

    function resetPopup(){
      var $popup = editor.popups.get('instagram.insert');
      var $errors = $popup.find('ul.errorlist');
      var $input = $popup.find('input[type="text"][name="href"]');
      var $checkbox = $popup.find('input[type="checkbox"][name="captioned"]');
      $errors.hide();
      $errors.html('');
      $input.val('').trigger('change');
      $checkbox.prop('checked', true).trigger('checked');
    }

    // Hide the custom popup.
    function hidePopup () {
      editor.popups.hide('instagram.insert');
    }

    function showError(error){
      var $popup = editor.popups.get('instagram.insert');
      var $errors = $popup.find('ul.errorlist');
      var $input = $popup.find('input[type="text"][name="href"]');
      $errors.html('
'+error+'
').fadeIn();
      $input.one('keyup', function(){
        $errors.fadeOut();
      });
    }

    function insert(url, captioned){
      // Make sure we have focus.
      editor.events.focus(true);
      editor.selection.restore();

      //Trim off the whitespace.
      var clean = $.trim(url);

      if (clean === ''){
        showError('The URL is invalid. Please enter a valid URL.');
        return false;
      }

      //Escape whitespace
      clean = clean.replace(/ /g, '%20');

      var matches = clean.match(urlRe);
      if (!matches || matches.length < 4){
        showError('The URL is invalid. Please enter a valid URL.');
        return false;
      }

      // Get article information
      $.ajax({
        url: "https://api.instagram.com/oembed/",
        dataType: "jsonp",
        data: { url: matches[0] },
        success: function(response) {
          var url = matches[0] + (captioned ? '/embed/captioned/?v=' : '/embed/?v=') + editor.opts.instagramEmbedVersion;
          var onload = "$(window).on('message',$.proxy(function(e){if(this.contentWindow!==e.originalEvent.source)return;var obj=$.parseJSON(e.originalEvent.data);if(obj.type==='MEASURE')$(this).height(obj.details.height||500);},this))";
          editor.html.insert('

', true);
          var $instagram_embed = editor.$el.find('.fr-instagram');
          editor.popups.hide('instagram.insert');
          editor.events.trigger('instagram.inserted', [$instagram_embed, matches[0], matches[3]]);
        }
      });

      return false;
    }

    function insertCallback () {
      var $popup = editor.popups.get('instagram.insert');
      var url = $popup.find('input[type="text"][name="href"]').val();
      var captioned = $popup.find('input[type="checkbox"][name="captioned"]').is(':checked');

      var t = $(editor.original_window).scrollTop();
      insert(url, captioned);
      $(editor.original_window).scrollTop(t);
    }

    // Methods visible outside the plugin.
    return {
      showPopup: showPopup,
      hidePopup: hidePopup,
      insertCallback: insertCallback,
      resetPopup: resetPopup
    }
  };

  // Define an icon and command for the button that opens the custom popup.
  $.FroalaEditor.DefineIcon('instagramBtnIcon', {NAME: 'instagram'});
  $.FroalaEditor.RegisterCommand('instagram', {
    title: 'Insert Instagram',
    icon: 'instagramBtnIcon',
    undo: false,
    focus: true,
    popup: true,
    refreshOnCallback: false,
    callback: function () {
      if (!this.popups.isVisible('instagram.insert')) {
        this.instagram.showPopup();
      }
      else {
        if (this.$el.find('.fr-marker')) {
          this.events.disableBlur();
          this.selection.restore();
        }
        this.popups.hide('instagram.insert');
      }
    }
  });

  // Define custom popup insert button command.
  $.FroalaEditor.RegisterCommand('linkInstagramInsert', {
    focus: false,
    refreshAfterCallback: false,
    callback: function () {
      this.instagram.insertCallback();
    }
  })

}));
<commit_msg>Fixed<commit_after>/*!
 * Froala Instagram Plugin
 * Written by EvabioZ (evabioz@gmail.com)
 * Tested with Froala v2.0.5 (https://www.froala.com/wysiwyg-editor)
 */

(function (factory) {
    if (typeof define === 'function' && define.amd) {
        // AMD. Register as an anonymous module.
        define(['jquery'], factory);
    } else if (typeof module === 'object' && module.exports) {
        // Node/CommonJS
        module.exports = function( root, jQuery ) {
            if ( jQuery === undefined ) {
                // require('jQuery') returns a factory that requires window to
                // build a jQuery instance, we normalize how we use modules
                // that require this pattern but the window provided is a noop
                // if it's defined (how jquery works)
                if ( typeof window !== 'undefined' ) {
                    jQuery = require('jquery');
                }
                else {
                    jQuery = require('jquery')(root);
                }
            }
            factory(jQuery);
            return jQuery;
        };
    } else {
        // Browser globals
        factory(jQuery);
    }
}(function ($) {

  'use strict';

  var urlRe = /^(http|https):\/\/(instagr\.am|instagram\.com|www\.instagram\.com)\/p\/([^\/?]+)/;

  // Define popup template.
  $.extend($.FroalaEditor.POPUP_TEMPLATES, {
    "instagram.insert": '[_BUTTONS_][_INPUT_LAYER_]'
  });

  $.extend($.FroalaEditor.DEFAULTS, {
    instagramEmbedVersion: 7,
    instagramHelpText: 'Paste a URL to generate code'
  });

  $.merge($.FroalaEditor.DEFAULTS.htmlAllowedAttrs, [
    'onload'
  ]);

  // The custom popup is defined inside a plugin (new or existing).
  $.FroalaEditor.PLUGINS.instagram = function (editor) {

    // Create custom popup.
    function initPopup () {
      // Popup buttons.
      var popup_buttons = '';

      // Create the list of buttons.
      if (editor.opts.popupButtons && editor.opts.popupButtons.length > 0) {
        popup_buttons += '
';
        popup_buttons += editor.button.buildList(editor.opts.popupButtons);
        popup_buttons += '
';
      }

      var tab_idx = 0;
      var input_layer = '
';
      input_layer += '

';
      if (editor.opts.instagramHelpText){
        input_layer += ''+editor.language.translate(editor.opts.instagramHelpText)+'';
      }
      input_layer += '
<input name="href" type="text" placeholder="https://www.instagram.com/p/" tabIndex="' + (++tab_idx) + '">
';
      input_layer += '
<input name="captioned" type="checkbox" checked="checked" />With Captioned
';
      input_layer += '
<button class="fr-command fr-submit" data-cmd="linkInstagramInsert" href="#" tabIndex="' + (++tab_idx) + '" type="button">' + editor.language.translate('Insert') + '</button>

';

      // Load popup template.
      var template = {
        buttons: popup_buttons,
        input_layer: input_layer
      };

      // Create popup.
      return editor.popups.create('instagram.insert', template);
    }

    // Show the popup
    function showPopup () {
      // Get the popup object defined above.
      var $popup = editor.popups.get('instagram.insert');

      // If popup doesn't exist then create it.
      // To improve performance it is best to create the popup when it is first needed
      // and not when the editor is initialized.
      if (!$popup) $popup = initPopup();

      //reset popup
      resetPopup();

      // Set the editor toolbar as the popup's container.
      editor.popups.setContainer('instagram.insert', editor.$tb);

      // This will trigger the refresh event assigned to the popup.
      // editor.popups.refresh('instagram.insert');

      // This custom popup is opened by pressing a button from the editor's toolbar.
      // Get the button's object in order to place the popup relative to it.
      var $btn = editor.$tb.find('.fr-command[data-cmd="instagram"]');

      // Set the popup's position.
      var left = $btn.offset().left + $btn.outerWidth() / 2;
      var top = $btn.offset().top + (editor.opts.toolbarBottom ? 10 : $btn.outerHeight() - 10);

      // Show the custom popup.
      // The button's outerHeight is required in case the popup needs to be displayed above it.
      editor.popups.show('instagram.insert', left, top, $btn.outerHeight());
    }

    function resetPopup(){
      var $popup = editor.popups.get('instagram.insert');
      var $errors = $popup.find('ul.errorlist');
      var $input = $popup.find('input[type="text"][name="href"]');
      var $checkbox = $popup.find('input[type="checkbox"][name="captioned"]');
      $errors.hide();
      $errors.html('');
      $input.val('').trigger('change');
      $checkbox.prop('checked', true).trigger('checked');
    }

    // Hide the custom popup.
    function hidePopup () {
      editor.popups.hide('instagram.insert');
    }

    function showError(error){
      var $popup = editor.popups.get('instagram.insert');
      var $errors = $popup.find('ul.errorlist');
      var $input = $popup.find('input[type="text"][name="href"]');
      $errors.html('
'+error+'
').fadeIn();
      $input.one('keyup', function(){
        $errors.fadeOut();
      });
    }

    function insert(url, captioned){
      // Make sure we have focus.
      editor.events.focus(true);
      editor.selection.restore();

      //Trim off the whitespace.
      var clean = $.trim(url);

      if (clean === ''){
        showError('The URL is invalid. Please enter a valid URL.');
        return false;
      }

      //Escape whitespace
      clean = clean.replace(/ /g, '%20');

      var matches = clean.match(urlRe);
      if (!matches || matches.length < 4){
        showError('The URL is invalid. Please enter a valid URL.');
        return false;
      }

      // Rendering
      var url = matches[0] + (captioned ? '/embed/captioned/?v=' : '/embed/?v=') + editor.opts.instagramEmbedVersion;
      var onload = "$(window).on('message',$.proxy(function(e){if(this.contentWindow!==e.originalEvent.source)return;var obj=$.parseJSON(e.originalEvent.data);if(obj.type==='MEASURE')$(this).height(obj.details.height||500);},this))";
      editor.html.insert('

', true);
      var $instagram_embed = editor.$el.find('.fr-instagram');
      editor.popups.hide('instagram.insert');
      editor.events.trigger('instagram.inserted', [$instagram_embed, matches[0], matches[3]]);

      return false;
    }

    function insertCallback () {
      var $popup = editor.popups.get('instagram.insert');
      var url = $popup.find('input[type="text"][name="href"]').val();
      var captioned = $popup.find('input[type="checkbox"][name="captioned"]').is(':checked');

      var t = $(editor.original_window).scrollTop();
      insert(url, captioned);
      $(editor.original_window).scrollTop(t);
    }

    // Methods visible outside the plugin.
    return {
      showPopup: showPopup,
      hidePopup: hidePopup,
      insertCallback: insertCallback,
      resetPopup: resetPopup
    }
  };

  // Define an icon and command for the button that opens the custom popup.
  $.FroalaEditor.DefineIcon('instagramBtnIcon', {NAME: 'instagram'});
  $.FroalaEditor.RegisterCommand('instagram', {
    title: 'Insert Instagram',
    icon: 'instagramBtnIcon',
    undo: false,
    focus: true,
    popup: true,
    refreshOnCallback: false,
    callback: function () {
      if (!this.popups.isVisible('instagram.insert')) {
        this.instagram.showPopup();
      }
      else {
        if (this.$el.find('.fr-marker')) {
          this.events.disableBlur();
          this.selection.restore();
        }
        this.popups.hide('instagram.insert');
      }
    }
  });

  // Define custom popup insert button command.
  $.FroalaEditor.RegisterCommand('linkInstagramInsert', {
    focus: false,
    refreshAfterCallback: false,
    callback: function () {
      this.instagram.insertCallback();
    }
  })

}));
<|endoftext|>


<commit_before>// View model for the projects page
function pageViewModel(gvm) {
    gvm.userId=-1;
    gvm.currentprojectid = -1;
    gvm.currentselectedlist = -1;
    // Page specific i18n bindings
    gvm.title = ko.computed(function(){i18n.setLocale(gvm.lang()); return gvm.app() + ' - ' + i18n.__("ProjecttypeTitle");}, gvm);
    gvm.pageHeader = ko.computed(function(){i18n.setLocale(gvm.lang()); return i18n.__("ProjecttypeTitle");}, gvm);
    gvm.projectname = ko.computed(function(){i18n.setLocale(gvm.lang()); return i18n.__("ProjectName");}, gvm);
    gvm.homeManual = ko.computed(function(){i18n.setLocale(gvm.lang()); return i18n.__("HomeManual");}, gvm);
    gvm.foundProjects = ko.computed(function(){i18n.setLocale(gvm.lang()); return i18n.__("FoundProjects");}, gvm);
    gvm.selectCourse = ko.computed(function(){i18n.setLocale(gvm.lang()); return i18n.__("SelectCourse");}, gvm);

    // Pagination i18n bindings
    gvm.addBtn = ko.computed(function(){i18n.setLocale(gvm.lang()); return i18n.__("AddBtn")}, gvm);

    // Table i18n bindings
    gvm.codeTableTitle = ko.computed(function(){i18n.setLocale(gvm.lang()); return i18n.__("CodeTableTitle");}, gvm);
    gvm.nameTableTitle = ko.computed(function(){i18n.setLocale(gvm.lang()); return i18n.__("NameTableTitle");}, gvm);
    gvm.descTableTitle = ko.computed(function(){i18n.setLocale(gvm.lang()); return i18n.__("DescTableTitle");}, gvm);
    gvm.actionTableTitle = ko.computed(function(){i18n.setLocale(gvm.lang()); return i18n.__("ActionTableTitle");}, gvm);

    gvm.availableLocations = ko.observableArray([]);
    gvm.availableTrainings = ko.observableArray([]);
    gvm.availableCourses = ko.observableArray([]);

    gvm.currentCourseId = null;

    gvm.updateDropdowns = function() {
        $.getJSON('api/lastdropdownchoice/' + gvm.userId, function(data) {
            if(!$.isEmptyObject(data)) {
                $.each(data, function(i, item) {
                    $(".btn-location span:first").text(item.location);
                    $(".btn-training span:first").text(item.training);
                    $(".btn-course span:first").text(item.course);
                    gvm.updateLocations();
                    loadTablePage(item.courseid, 1);
                });
            } else {
                gvm.updateLocations();
            }
        });
    }

    gvm.saveLastSelectedDropdowns = function() {
        data = {};
        data["location"] = $(".btn-location span:first").text();
        data["training"] = $(".btn-training span:first").text();
        data["course"] = $(".btn-course span:first").text();
        data["courseid"] = gvm.currentCourseId;
        data["user"] = gvm.userId;
        console.log(data);
        $.ajax({
            type: "POST",
            url: "/api/savedropdowns",
            data: data,
            success: function() {
                console.log("success");
            }
        })
    }

    /*
     * Update the location dropdown list
     */
    gvm.updateLocations = function() {
        $.getJSON('/api/locations', function(data) {
            gvm.availableLocations.removeAll();
            $.each(data, function(i, item) {
                /* Put item in list */
                gvm.availableLocations.push(item);

                /* Add listener to listitem */
                $("#locbtn-" + item.id).click(function(){
                    gvm.currentCourseId = null;
                    gvm.updateTrainings(item.id);
                    $(".btn-location span:first").text($(this).text());
                });
            });
        });
    };

    /*
     * Update the training data
     */
    gvm.updateTrainings = function(id) {
        $.getJSON('/api/trainings/' + id, function(data) {
            gvm.availableTrainings.removeAll();
            $.each(data, function(i, item) {
                gvm.availableTrainings.push(item);

                /* Add listener to listitem */
                $("#trainingbtn-" + item.id).click(function(){
                    gvm.currentCourseId = null;
                    gvm.updateCourses(item.id);
                    $(".btn-training span:first").text($(this).text());
                });
            });
        });
    }

    /*
     * Update available courses
     */
    gvm.updateCourses = function(id) {
        $.getJSON('/api/courses/' + id, function(data) {
            gvm.availableCourses.removeAll();
            $.each(data, function(i, item) {
                gvm.availableCourses.push(item);

                /* Add listener to listitem */
                $("#coursebtn-" + item.id).click(function(){
                    $(".btn-course span:first").text($(this).text());
                    gvm.currentCourseId = item.id;
                    gvm.saveLastSelectedDropdowns();
                    loadTablePage(item.id, 1);
                });
            });
        });
    }

    // The table data observable array
    gvm.tabledata = ko.observableArray([]);

    // Add data to the table
    gvm.addTableData = function(id, code, name, desc) {
        // Push data
        var tblOject = {tid: id, tcode: code, tname: name, tdesc: desc};
        gvm.tabledata.push(tblOject);

        // Attach delete handler to delete button
        $('#removebtn-' + id).bind('click', function(event, data){
            // Delete the table item
            deleteTableItem(id, tblOject);
            event.stopPropagation();
        });

        // Attach edit handler to edit button
        $('#editbtn-' + id).bind('click', function(event, data){
            // Edit the table item
            showEditProjectTypeModal(code, name, desc, id);
            event.stopPropagation();
        });

        //Attach manage handler to manage competences, subcompetences and indicators to manage button
        $('#managebtn-' + id).bind('click', function(event, data) {
            //TODO
        });

        $('#studentbtn-' + id).bind('click', function(event, data) {
            showCoupleStudentListModal(id);
            gvm.currentprojectid = id;
            gvm.currentselectedlist = -1;
            event.stopPropagation();
            loadCoupleDropdown();
        });
    }

    gvm.clearTable = function() {
        gvm.tabledata.removeAll();
    }
}

/*
 * Delete item from table given the id.
 */
function deleteTableItem(id, tblOject) {
    showYesNoModal("Bent u zeker dat u dit item wil verwijderen?", function(val){
        if(val){
            $.ajax({
                url: "/api/project/" + id,
                type: "DELETE",
                success: function() {
                    viewModel.tabledata.remove(tblOject);
                }
            });
        }
    });
}

/*
 * Add a new projecttype
 */
function addNewProjecttypeForm(serialData, callback) {
    if(viewModel.currentCourseId != null) {
        $.ajax({
            url: "/api/project/" + viewModel.currentCourseId,
            type: "POST",
            data: serialData,
            success: function(data) {
                viewModel.addTableData(data['id'], data['code'], data['name'], data['description']);
                callback(true);
            },
            error: function(data) {
                callback(false);
            }
        });
    } else {
        alert("No course selected");
    }

}

/*
 * Add a new projecttype
 */
function addNewProjecttypeRaw(code, name, description, callback) {
    addNewProjecttypeForm("code=" + encodeURIComponent(code) + "&name=" + encodeURIComponent(name) + "&description=" + encodeURIComponent(description), callback);
}

/*
 * Update the projecttype
 * @param {type} id
 * @param {type} code
 * @param {type} name
 * @param {type} description
 * @param {type} callback
 * @returns {undefined}
 */
function updateProjecttypeForm(id, serialData, callback) {
    $.ajax({
        url: "/api/project/" + id,
        type: "PUT",
        data: serialData,
        success: function(data) {
            //viewModel.addTableData(data['id'], data['code'], data['name'], data['description']);
            loadTablePage(viewModel.currentCourseId, 1); //TODO now it is refreshing table after updating but it redirects to pagenr 1
            callback(true);
        },
        error: function(data) {
            callback(false);
        }
    });
}

/**
 * update project type
 * @param {type} id
 * @param {type} code
 * @param {type} name
 * @param {type} description
 * @param {type} callback
 * @returns {undefined}
 */
function updateProjecttypeRaw(id, code, name, description, callback) {
    updateProjecttypeForm(id, "code=" + encodeURIComponent(code) + "&name=" + encodeURIComponent(name) + "&description=" + encodeURIComponent(description), callback);
}

/*
 * Load page of the table
 */
function loadTablePage(courseid, pagenr)
{
    $.getJSON('/api/projects/' + courseid + '/page/' + pagenr, function(data){

        /* Clear current table page */
        viewModel.clearTable()

        // Load table data
        $.each(data.data, function(i, item) {
            viewModel.addTableData(item.id, item.code, item.name, item.description);
        });

        /* Let previous en next buttons work */
        if(data.prev == "none"){
            $('#pager-prev-btn').addClass('disabled');
        } else {
            $('#pager-prev-btn').removeClass('disabled');
            $('#pager-prev-btn a').click(function(){
                loadTablePage(data.prev);
            });
        }

        if(data.next == "none"){
            $('#pager-next-btn').addClass('disabled');
        } else {
            $('#pager-next-btn').removeClass('disabled');
            $('#pager-next-btn a').click(function(){
                loadTablePage(data.next);
            });
        }

        // Number of pager buttons
        var numItems = $('.pager-nr-btn').length;

        /* Calculate for the pager buttons */
        var lowPage = Math.floor(pagenr/numItems) + 1;

        $('.pager-nr-btn').each(function() {
            /* calculate current page number */
            var thispagenr = lowPage++;

            /* Add the page number */
            $(this).html('' + thispagenr + '');

            /* Add active class to current page */
            if(thispagenr == pagenr) {
                $(this).addClass('active');
            } else {
                $(this).removeClass('active');
            }

            /* Disable inactive classes and bind handlers to active classes */
            if(thispagenr > data.pagecount) {
                $(this).addClass('disabled');
            } else {
                /* Add click listener for button */
                $(this).click(function() {
                    loadTablePage(courseid, thispagenr);
                });
            }
        });
    });

}

/**
 * Show a new projecttype modal.
 * @returns {undefined}
 */
function showNewProjectTypeModal()
{
    resetGeneralModal();
    setGeneralModalTitle(i18n.__("AddNewProjectTypeTitle"));
    setGeneralModalBody('<form id="newprojectform"> \

 \
                <input type="text" class="form-control input-lg" placeholder="' + i18n.__('CodeTableTitle') + '" " name="code"> \

 \

 \
                <input type="text" class="form-control input-lg" placeholder="' + i18n.__('NameTableTitle') + '" name="name"> \

 \

 \
                <input type="text" class="form-control input-lg" placeholder="' + i18n.__('DescTableTitle') + '" name="description"> \

 \
        </form>');

    addGeneralModalButton(i18n.__("AddBtn"), function(){
       addNewProjecttypeForm($('#newprojectform').serialize(), function(result){
            hideModal();
        });
    });

    showGeneralModal();
}

/**
 * Show the edit projecttype modal.
 * @param {type} code
 * @param {type} name
 * @param {type} description
 * @param {type} tid
 * @returns {undefined}
 */
function showEditProjectTypeModal(code, name, description, tid)
{
  resetGeneralModal();
    setGeneralModalTitle(i18n.__("EditProjectTitle"));
    setGeneralModalBody('<form id="updateprojectform"> \

 \
                <input type="text" class="form-control input-lg" placeholder="' + i18n.__('CodeTableTitle') + '" " name="code" value="' + code + '"> \

 \

 \
                <input type="text" class="form-control input-lg" placeholder="' + i18n.__('NameTableTitle') + '" name="name" value="' + name + '"> \

 \

 \
                <input type="text" class="form-control input-lg" placeholder="' + i18n.__('DescTableTitle') + '" name="description" value="' + description + '"> \

 \
        </form>');
    $.getJSON()

    addGeneralModalButton(i18n.__("SaveBtn"), function(){
        updateProjecttypeForm(tid, $('#updateprojectform').serialize(), function(result){
            hideModal();
        });
    });

    addGeneralModalButton(i18n.__("CancelBtn"), function(){
        hideModal();
    })

    showGeneralModal();
}

function showCoupleStudentListModal(projectid) {
    viewModel.currentselectedlist = -1;
    resetGeneralModal();
    setGeneralModalTitle(i18n.__("CoupleStudentList"));
    setGeneralModalBody(
        '
' +
            '<button class="btn btn-default dropdown-toggle" type="button" id="dropdownStudLists" data-toggle="dropdown" aria-expanded="true">' +
                'Dropdown' +
                '' +
            '</button>' +
            '
' +
            '
' +
        '
');

    addGeneralModalButton(i18n.__("SaveBtn"), function() {
        updateListForm(viewModel.currentselectedlist, $('#coupleform').serialize(), function(result){
            hideModal();
        });
    });

    addGeneralModalButton(i18n.__("CancelBtn"), function(){
        hideModal();
    })
    showGeneralModal();
}

function loadCoupleDropdown() {
    $.getJSON('/api/studentlists/' + viewModel.userId, function(data) {
        $.each(data, function(i, item) {
            $("#ddlLists").append('
' + item.name + '
')
            $("#dropdownitem-" + item.id).click(function(){
                $(this).parent().parent().parent().removeClass("open");
                $(this).parent().parent().parent().find(".btn").html($(this).text() + '');
                viewModel.currentselectedlist = item.id;
            });
        });
    });
    $("#dropdownStudLists").click(function() {
        $(this).parent().toggleClass("open");
    });
}

function updateListForm(id, serialData, callback) {
    $.ajax({
        url: "/api/project/" + viewModel.currentprojectid + "/studentlist/" + id,
        type: "POST",
        data: serialData,
        success: function(data) {
            callback(true);
        },
        error: function(data) {
            callback(false);
        }
    });
}

function initPage() {
    // Add button handlers
    $('#addProjectTypeBtn').click(function(){
        showNewProjectTypeModal();
    });

    $.getJSON('/api/currentuser', function(data) {
        viewModel.userId = data.id;
        viewModel.updateDropdowns();
    });
}<commit_msg>coupling between project and studentlists<commit_after>// View model for the projects page
function pageViewModel(gvm) {
    gvm.userId=-1;
    gvm.currentprojectid = -1;
    gvm.currentselectedlist = -1;
    // Page specific i18n bindings
    gvm.title = ko.computed(function(){i18n.setLocale(gvm.lang()); return gvm.app() + ' - ' + i18n.__("ProjecttypeTitle");}, gvm);
    gvm.pageHeader = ko.computed(function(){i18n.setLocale(gvm.lang()); return i18n.__("ProjecttypeTitle");}, gvm);
    gvm.projectname = ko.computed(function(){i18n.setLocale(gvm.lang()); return i18n.__("ProjectName");}, gvm);
    gvm.homeManual = ko.computed(function(){i18n.setLocale(gvm.lang()); return i18n.__("HomeManual");}, gvm);
    gvm.foundProjects = ko.computed(function(){i18n.setLocale(gvm.lang()); return i18n.__("FoundProjects");}, gvm);
    gvm.selectCourse = ko.computed(function(){i18n.setLocale(gvm.lang()); return i18n.__("SelectCourse");}, gvm);

    // Pagination i18n bindings
    gvm.addBtn = ko.computed(function(){i18n.setLocale(gvm.lang()); return i18n.__("AddBtn")}, gvm);

    // Table i18n bindings
    gvm.codeTableTitle = ko.computed(function(){i18n.setLocale(gvm.lang()); return i18n.__("CodeTableTitle");}, gvm);
    gvm.nameTableTitle = ko.computed(function(){i18n.setLocale(gvm.lang()); return i18n.__("NameTableTitle");}, gvm);
    gvm.descTableTitle = ko.computed(function(){i18n.setLocale(gvm.lang()); return i18n.__("DescTableTitle");}, gvm);
    gvm.actionTableTitle = ko.computed(function(){i18n.setLocale(gvm.lang()); return i18n.__("ActionTableTitle");}, gvm);

    gvm.availableLocations = ko.observableArray([]);
    gvm.availableTrainings = ko.observableArray([]);
    gvm.availableCourses = ko.observableArray([]);

    gvm.currentCourseId = null;
    gvm.currentLocationId = null;
    gvm.currentTrainingid = null;

    gvm.updateDropdowns = function() {
        $.getJSON('api/lastdropdownchoice/' + gvm.userId, function(data) {
            if(!$.isEmptyObject(data)) {
                $.each(data, function(i, item) {
                    $(".btn-location span:first").text(item.location);
                    $(".btn-training span:first").text(item.training);
                    $(".btn-course span:first").text(item.course);
                    gvm.updateLocations();
                    gvm.updateTrainings(item.locationid)
                    loadTablePage(item.courseid, 1);
                });
            } else {
                gvm.updateLocations();
            }
        });
    }

    gvm.saveLastSelectedDropdowns = function() {
        data = {};
        data["location"] = $(".btn-location span:first").text();
        data["locationid"] = gvm.currentLocationId;
        data["training"] = $(".btn-training span:first").text();
        data["trainingid"] = gvm.currentTrainingid;
        data["course"] = $(".btn-course span:first").text();
        data["courseid"] = gvm.currentCourseId;
        data["user"] = gvm.userId;
        console.log(data);
        $.ajax({
            type: "POST",
            url: "/api/savedropdowns",
            data: data,
            success: function() {
                console.log("success");
            }
        })
    }

    /*
     * Update the location dropdown list
     */
    gvm.updateLocations = function() {
        $.getJSON('/api/locations', function(data) {
            gvm.availableLocations.removeAll();
            $.each(data, function(i, item) {
                /* Put item in list */
                gvm.availableLocations.push(item);

                /* Add listener to listitem */
                $("#locbtn-" + item.id).click(function(){
                    gvm.currentLocationId = item.id;
                    gvm.currentTrainingid = null;
                    gvm.currentCourseId = null;
                    gvm.updateTrainings(item.id);
                    $(".btn-location span:first").text($(this).text());
                });
            });
        });
    };

    /*
     * Update the training data
     */
    gvm.updateTrainings = function(id) {
        $.getJSON('/api/trainings/' + id, function(data) {
            gvm.availableTrainings.removeAll();
            $.each(data, function(i, item) {
                gvm.availableTrainings.push(item);

                /* Add listener to listitem */
                $("#trainingbtn-" + item.id).click(function(){
                    gvm.currentTrainingid = null;
                    gvm.currentCourseId = null;
                    gvm.updateCourses(item.id);
                    $(".btn-training span:first").text($(this).text());
                });
            });
        });
    }

    /*
     * Update available courses
     */
    gvm.updateCourses = function(id) {
        $.getJSON('/api/courses/' + id, function(data) {
            gvm.availableCourses.removeAll();
            $.each(data, function(i, item) {
                gvm.availableCourses.push(item);

                /* Add listener to listitem */
                $("#coursebtn-" + item.id).click(function(){
                    $(".btn-course span:first").text($(this).text());
                    gvm.currentCourseId = item.id;
                    loadTablePage(item.id, 1);
                });
            });
        });
    }

    // The table data observable array
    gvm.tabledata = ko.observableArray([]);

    // Add data to the table
    gvm.addTableData = function(id, code, name, desc) {
        // Push data
        var tblOject = {tid: id, tcode: code, tname: name, tdesc: desc};
        gvm.tabledata.push(tblOject);

        // Attach delete handler to delete button
        $('#removebtn-' + id).bind('click', function(event, data){
            // Delete the table item
            deleteTableItem(id, tblOject);
            event.stopPropagation();
        });

        // Attach edit handler to edit button
        $('#editbtn-' + id).bind('click', function(event, data){
            // Edit the table item
            showEditProjectTypeModal(code, name, desc, id);
            event.stopPropagation();
        });

        //Attach manage handler to manage competences, subcompetences and indicators to manage button
        $('#managebtn-' + id).bind('click', function(event, data) {
            //TODO
        });

        $('#studentbtn-' + id).bind('click', function(event, data) {
            showCoupleStudentListModal(id);
            gvm.currentprojectid = id;
            gvm.currentselectedlist = -1;
            event.stopPropagation();
            loadCoupleDropdown();
        });
    }

    gvm.clearTable = function() {
        gvm.tabledata.removeAll();
    }
}

/*
 * Delete item from table given the id.
 */
function deleteTableItem(id, tblOject) {
    showYesNoModal("Bent u zeker dat u dit item wil verwijderen?", function(val){
        if(val){
            $.ajax({
                url: "/api/project/" + id,
                type: "DELETE",
                success: function() {
                    viewModel.tabledata.remove(tblOject);
                }
            });
        }
    });
}

/*
 * Add a new projecttype
 */
function addNewProjecttypeForm(serialData, callback) {
    if(viewModel.currentCourseId != null) {
        $.ajax({
            url: "/api/project/" + viewModel.currentCourseId,
            type: "POST",
            data: serialData,
            success: function(data) {
                viewModel.addTableData(data['id'], data['code'], data['name'], data['description']);
                callback(true);
            },
            error: function(data) {
                callback(false);
            }
        });
    } else {
        alert("No course selected");
    }

}

/*
 * Add a new projecttype
 */
function addNewProjecttypeRaw(code, name, description, callback) {
    addNewProjecttypeForm("code=" + encodeURIComponent(code) + "&name=" + encodeURIComponent(name) + "&description=" + encodeURIComponent(description), callback);
}

/*
 * Update the projecttype
 * @param {type} id
 * @param {type} code
 * @param {type} name
 * @param {type} description
 * @param {type} callback
 * @returns {undefined}
 */
function updateProjecttypeForm(id, serialData, callback) {
    $.ajax({
        url: "/api/project/" + id,
        type: "PUT",
        data: serialData,
        success: function(data) {
            //viewModel.addTableData(data['id'], data['code'], data['name'], data['description']);
            loadTablePage(viewModel.currentCourseId, 1); //TODO now it is refreshing table after updating but it redirects to pagenr 1
            callback(true);
        },
        error: function(data) {
            callback(false);
        }
    });
}

/**
 * update project type
 * @param {type} id
 * @param {type} code
 * @param {type} name
 * @param {type} description
 * @param {type} callback
 * @returns {undefined}
 */
function updateProjecttypeRaw(id, code, name, description, callback) {
    updateProjecttypeForm(id, "code=" + encodeURIComponent(code) + "&name=" + encodeURIComponent(name) + "&description=" + encodeURIComponent(description), callback);
}

/*
 * Load page of the table
 */
function loadTablePage(courseid, pagenr)
{
    $.getJSON('/api/projects/' + courseid + '/page/' + pagenr, function(data){

        /* Clear current table page */
        viewModel.clearTable()

        // Load table data
        $.each(data.data, function(i, item) {
            viewModel.addTableData(item.id, item.code, item.name, item.description);
        });

        /* Let previous en next buttons work */
        if(data.prev == "none"){
            $('#pager-prev-btn').addClass('disabled');
        } else {
            $('#pager-prev-btn').removeClass('disabled');
            $('#pager-prev-btn a').click(function(){
                loadTablePage(data.prev);
            });
        }

        if(data.next == "none"){
            $('#pager-next-btn').addClass('disabled');
        } else {
            $('#pager-next-btn').removeClass('disabled');
            $('#pager-next-btn a').click(function(){
                loadTablePage(data.next);
            });
        }

        // Number of pager buttons
        var numItems = $('.pager-nr-btn').length;

        /* Calculate for the pager buttons */
        var lowPage = Math.floor(pagenr/numItems) + 1;

        $('.pager-nr-btn').each(function() {
            /* calculate current page number */
            var thispagenr = lowPage++;

            /* Add the page number */
            $(this).html('' + thispagenr + '');

            /* Add active class to current page */
            if(thispagenr == pagenr) {
                $(this).addClass('active');
            } else {
                $(this).removeClass('active');
            }

            /* Disable inactive classes and bind handlers to active classes */
            if(thispagenr > data.pagecount) {
                $(this).addClass('disabled');
            } else {
                /* Add click listener for button */
                $(this).click(function() {
                    loadTablePage(courseid, thispagenr);
                });
            }
        });
    });

}

/**
 * Show a new projecttype modal.
 * @returns {undefined}
 */
function showNewProjectTypeModal()
{
    resetGeneralModal();
    setGeneralModalTitle(i18n.__("AddNewProjectTypeTitle"));
    setGeneralModalBody('<form id="newprojectform"> \

 \
                <input type="text" class="form-control input-lg" placeholder="' + i18n.__('CodeTableTitle') + '" " name="code"> \

 \

 \
                <input type="text" class="form-control input-lg" placeholder="' + i18n.__('NameTableTitle') + '" name="name"> \

 \

 \
                <input type="text" class="form-control input-lg" placeholder="' + i18n.__('DescTableTitle') + '" name="description"> \

 \
        </form>');

    addGeneralModalButton(i18n.__("AddBtn"), function(){
       addNewProjecttypeForm($('#newprojectform').serialize(), function(result){
            hideModal();
        });
    });

    showGeneralModal();
}

/**
 * Show the edit projecttype modal.
 * @param {type} code
 * @param {type} name
 * @param {type} description
 * @param {type} tid
 * @returns {undefined}
 */
function showEditProjectTypeModal(code, name, description, tid)
{
  resetGeneralModal();
    setGeneralModalTitle(i18n.__("EditProjectTitle"));
    setGeneralModalBody('<form id="updateprojectform"> \

 \
                <input type="text" class="form-control input-lg" placeholder="' + i18n.__('CodeTableTitle') + '" " name="code" value="' + code + '"> \

 \

 \
                <input type="text" class="form-control input-lg" placeholder="' + i18n.__('NameTableTitle') + '" name="name" value="' + name + '"> \

 \

 \
                <input type="text" class="form-control input-lg" placeholder="' + i18n.__('DescTableTitle') + '" name="description" value="' + description + '"> \

 \
        </form>');
    $.getJSON()

    addGeneralModalButton(i18n.__("SaveBtn"), function(){
        updateProjecttypeForm(tid, $('#updateprojectform').serialize(), function(result){
            hideModal();
        });
    });

    addGeneralModalButton(i18n.__("CancelBtn"), function(){
        hideModal();
    })

    showGeneralModal();
}

function showCoupleStudentListModal(projectid) {
    viewModel.currentselectedlist = -1;
    resetGeneralModal();
    setGeneralModalTitle(i18n.__("CoupleStudentList"));
    setGeneralModalBody(
        '
' +
            '<button class="btn btn-default dropdown-toggle" type="button" id="dropdownStudLists" data-toggle="dropdown" aria-expanded="true">' +
                'Dropdown' +
                '' +
            '</button>' +
            '
' +
            '
' +
        '
');

    addGeneralModalButton(i18n.__("SaveBtn"), function() {
        updateListForm(viewModel.currentselectedlist, $('#coupleform').serialize(), function(result){
            hideModal();
        });
    });

    addGeneralModalButton(i18n.__("CancelBtn"), function(){
        hideModal();
    })
    showGeneralModal();
}

function loadCoupleDropdown() {
    $.getJSON('/api/studentlists/' + viewModel.userId, function(data) {
        $.each(data, function(i, item) {
            $("#ddlLists").append('
' + item.name + '
')
            $("#dropdownitem-" + item.id).click(function(){
                $(this).parent().parent().parent().removeClass("open");
                $(this).parent().parent().parent().find(".btn").html($(this).text() + '');
                viewModel.currentselectedlist = item.id;
            });
        });
    });
    $("#dropdownStudLists").click(function() {
        $(this).parent().toggleClass("open");
    });
}

function updateListForm(id, serialData, callback) {
    $.ajax({
        url: "/api/project/" + viewModel.currentprojectid + "/studentlist/" + id,
        type: "POST",
        data: serialData,
        success: function(data) {
            callback(true);
        },
        error: function(data) {
            callback(false);
        }
    });
}

function initPage() {
    // Add button handlers
    $('#addProjectTypeBtn').click(function(){
        showNewProjectTypeModal();
    });

    $.getJSON('/api/currentuser', function(data) {
        viewModel.userId = data.id;
        viewModel.updateDropdowns();
    });
}<|endoftext|>


<commit_before>jsio('from shared.javascript import Class, bind')

jsio('import shared.keys')
jsio('import shared.mutations')

jsio('import net.protocols.rtjp')

exports = Class(net.protocols.rtjp.RTJPProtocol, function(supr) {

	this.init = function(id, redisClient) {
		supr(this, 'init')
		this._id = id
		this._redisClient = redisClient
		this._requestHandlers = {}

		this._setupHandlers()
	}

	this.connectionLost = function() {
		this._log('connection lost - closing redis client')
		this._redisClient.close()
	}

	this.getId = function() { return this._id }

	this._setupHandlers = function() {
		this._queryChannelHandler = bind(this, function(channelBytes, messageBytes) {
			var message = messageBytes.toString()

			this.sendFrame('FIN_EVENT_QUERY_MUTATED', message)
		})

		this._itemChannelHandler = bind(this, function(channel, mutationBytes) {
			var mutationInfo = shared.mutations.parseMutationBytes(mutationBytes)
			if (mutationInfo.originId == this._id) { return }
			this.sendFrame('FIN_EVENT_ITEM_MUTATED', mutationInfo.json)
		})

		this.handleRequest('FIN_REQUEST_SUBSCRIBE', bind(this, function(args) {
			var itemId = args.id,
				propName = args.prop,
				channel = shared.keys.getItemPropertyChannel(itemId, propName)

			this._redisClient.subscribeTo(channel, this._itemChannelHandler)
			// fake an item mutation event
			this.server.getItemProperty(itemId, propName, bind(this, function(value, key) {
				var mutation = { op: 'set', id: itemId, prop: propName, args: [value] }

				logger.log("Retrieved data", key, value)
				this.sendFrame('FIN_EVENT_ITEM_MUTATED', JSON.stringify(mutation))
			}))
		}))

		this.handleRequest('FIN_REQUEST_UNSUBSCRIBE', bind(this, function(channel) {
			this._redisClient.unsubscribeFrom(channel)
		}))

		this.handleRequest('FIN_REQUEST_QUERY', bind(this, function(queryJSON) {
			var channel = shared.keys.getQueryChannel(queryJSON)

			this._redisClient.subscribeTo(channel, this._queryChannelHandler)

			this.server.getQuerySet(queryJSON, bind(this, function(membersBytes) {
				var members = []
				for (var i=0, memberBytes; memberBytes = membersBytes[i]; i++) {
					members.push(memberBytes.toString())
				}

				var mutation = { op: 'sadd', args: members, id: shared.keys.getQueryChannel(queryJSON) }

				this.sendFrame('FIN_EVENT_QUERY_MUTATED', JSON.stringify(mutation))
			}))
		}))

		this.handleRequest('FIN_REQUEST_CREATE_ITEM', bind(this, function(request) {
			this.server.createItem(request.data, this, bind(this, function(itemData) {
				var response = { _requestId: request._requestId, data: itemData }
				this.sendFrame('FIN_RESPONSE', response)
			}))
		}))

		this.handleRequest('FIN_REQUEST_MUTATE_ITEM', bind(this, function(mutation){
			this.server.mutateItem(mutation, this)
		}))

		// TODO: get Reduction handler to work
		this.handleRequest('FIN_REQUEST_ADD_REDUCTION', bind(this, function(args) {
			var itemSetId = args.id,
				reductionId = args.reductionId
			this.server.addItemSetReduction(itemSetId, reductionId, this._itemSetSubs[itemSetId])
		}))
	}

/* Requests
 **********/
	this.handleRequest = function(requestName, callback) {
		this._requestHandlers[requestName] = callback
	}

	this.frameReceived = function(id, name, args) {
		this._log('recv', id, name, JSON.stringify(args))
		if (!this._requestHandlers[name]) {
			logger.warn('Received request without handler', name)
			return
		}
		this._requestHandlers[name](args)
	}

/* Util
 ******/
	this.sendFrame = function(name, args) {
		this._log('send', name, JSON.stringify(args))
		try {
			supr(this, 'sendFrame', arguments)
		} catch(e) {
			logger.error("when writing", e, name, JSON.stringify(args))
		}
	}

	this._log = function() {
		var args = Array.prototype.slice.call(arguments)
		if (this.transport._socket) {
			if (this.transport._socket._session) {
				args.unshift(this.transport._socket._session.key)
			}
		}
		logger.log.apply(logger, args)
	}
})
<commit_msg>Add todo q<commit_after>jsio('from shared.javascript import Class, bind')

jsio('import shared.keys')
jsio('import shared.mutations')

jsio('import net.protocols.rtjp')

exports = Class(net.protocols.rtjp.RTJPProtocol, function(supr) {

	this.init = function(id, redisClient) {
		supr(this, 'init')
		this._id = id
		this._redisClient = redisClient
		this._requestHandlers = {}

		this._setupHandlers()
	}

	this.connectionLost = function() {
		this._log('connection lost - closing redis client')
		// TODO do we need to unsubscribe from redis channels?
		this._redisClient.close()
	}

	this.getId = function() { return this._id }

	this._setupHandlers = function() {
		this._queryChannelHandler = bind(this, function(channelBytes, messageBytes) {
			var message = messageBytes.toString()

			this.sendFrame('FIN_EVENT_QUERY_MUTATED', message)
		})

		this._itemChannelHandler = bind(this, function(channel, mutationBytes) {
			var mutationInfo = shared.mutations.parseMutationBytes(mutationBytes)
			if (mutationInfo.originId == this._id) { return }
			this.sendFrame('FIN_EVENT_ITEM_MUTATED', mutationInfo.json)
		})

		this.handleRequest('FIN_REQUEST_SUBSCRIBE', bind(this, function(args) {
			var itemId = args.id,
				propName = args.prop,
				channel = shared.keys.getItemPropertyChannel(itemId, propName)

			this._redisClient.subscribeTo(channel, this._itemChannelHandler)
			// fake an item mutation event
			this.server.getItemProperty(itemId, propName, bind(this, function(value, key) {
				var mutation = { op: 'set', id: itemId, prop: propName, args: [value] }

				logger.log("Retrieved data", key, value)
				this.sendFrame('FIN_EVENT_ITEM_MUTATED', JSON.stringify(mutation))
			}))
		}))

		this.handleRequest('FIN_REQUEST_UNSUBSCRIBE', bind(this, function(channel) {
			this._redisClient.unsubscribeFrom(channel)
		}))

		this.handleRequest('FIN_REQUEST_QUERY', bind(this, function(queryJSON) {
			var channel = shared.keys.getQueryChannel(queryJSON)

			this._redisClient.subscribeTo(channel, this._queryChannelHandler)

			this.server.getQuerySet(queryJSON, bind(this, function(membersBytes) {
				var members = []
				for (var i=0, memberBytes; memberBytes = membersBytes[i]; i++) {
					members.push(memberBytes.toString())
				}

				var mutation = { op: 'sadd', args: members, id: shared.keys.getQueryChannel(queryJSON) }

				this.sendFrame('FIN_EVENT_QUERY_MUTATED', JSON.stringify(mutation))
			}))
		}))

		this.handleRequest('FIN_REQUEST_CREATE_ITEM', bind(this, function(request) {
			this.server.createItem(request.data, this, bind(this, function(itemData) {
				var response = { _requestId: request._requestId, data: itemData }
				this.sendFrame('FIN_RESPONSE', response)
			}))
		}))

		this.handleRequest('FIN_REQUEST_MUTATE_ITEM', bind(this, function(mutation){
			this.server.mutateItem(mutation, this)
		}))

		// TODO: get Reduction handler to work
		this.handleRequest('FIN_REQUEST_ADD_REDUCTION', bind(this, function(args) {
			var itemSetId = args.id,
				reductionId = args.reductionId
			this.server.addItemSetReduction(itemSetId, reductionId, this._itemSetSubs[itemSetId])
		}))
	}

/* Requests
 **********/
	this.handleRequest = function(requestName, callback) {
		this._requestHandlers[requestName] = callback
	}

	this.frameReceived = function(id, name, args) {
		this._log('recv', id, name, JSON.stringify(args))
		if (!this._requestHandlers[name]) {
			logger.warn('Received request without handler', name)
			return
		}
		this._requestHandlers[name](args)
	}

/* Util
 ******/
	this.sendFrame = function(name, args) {
		this._log('send', name, JSON.stringify(args))
		try {
			supr(this, 'sendFrame', arguments)
		} catch(e) {
			logger.error("when writing", e, name, JSON.stringify(args))
		}
	}

	this._log = function() {
		var args = Array.prototype.slice.call(arguments)
		if (this.transport._socket) {
			if (this.transport._socket._session) {
				args.unshift(this.transport._socket._session.key)
			}
		}
		logger.log.apply(logger, args)
	}
})
<|endoftext|>


<commit_before>/**
 * ownCloud - Belgian eID IDP Integration
 *
 * This file is licensed under the Affero General Public License version 3 or
 * later. See the COPYING file.
 *
 * @author Bert Maerten <maerten.bert@outlook.com>
 * @copyright Bert Maerten 2015
 */

(function ($, OC) {

    $(document).ready(function () {
        alert('document.ready()');

        $('#identities td.remove > img').click(function () {
            alert('row.remove()');

            var row = $(this).parent().parent();
            var identity = $.trim(row.text());

            //$('#form .msg').html(t('core', 'Saving...')).removeClass('success').removeClass('error').stop(true, true).show(); //OC.msg.startSaving('#form .msg'); /* OC.msg.startSaving(selector) & OC.msg.startAction(selector, message) in core/js/js.js*/
            //$.ajax({
            //    type: 'POST',
            //    url: OC.filePath('beididp','ajax','remove.eid.php'),
            //    data: {identity: identity},
            //    success: function (data, textStatus, jqXHR) {
            //        $('#form .msg').html('success').addClass('success').removeClass('error').stop(true, true).delay(3000).fadeOut(900).show(); //OC.msg.finishedSaving('#form .msg', data); /* OC.msg.finishedSaving(selector, data) & OC.msg.finishedAction(selector, data)  in core/js/js.js*/
            //        row.remove();
            //    },
            //    error: function (jqXHR, textStatus, errorThrown) {
            //        $('#form .msg').html('error').addClass('error').removeClass('success').show(); //OC.msg.finishedSaving('#form .msg', data);
            //    }
            //});

            $('#form .msg').html(t('core', 'Saving...')).removeClass('success').removeClass('error').stop(true, true).show(); //OC.msg.startSaving('#form .msg');
            $.post(
                OC.filePath('beididp', 'ajax', 'remove.eid.php'),
                {identity: identity},
                function (result) {
                    if (result.status === 'success') {
                        $('#form .msg').html(result.data.message).addClass('success').removeClass('error').stop(true, true).delay(3000).fadeOut(900).show(); //OC.msg.finishedSaving('#form .msg', result);
                        row.remove();
                    } else {
                        $('#form .msg').html(result.data.message).addClass('error').removeClass('success').show(); //OC.msg.finishedSaving('#form .msg', result);
                    }
                }
            );
        });

        //V2 - get identity; send identity to server; get identities and remove the recieved one; save identities; remove identity from view
        //$('#identities').on('click', 'td.remove > img', function () {
        //    alert('row.remove()');
        //
        //    var row = $(this).parent().parent();
        //    var identity = $.trim(row.text());
        //
        //    //$('#form .msg').html(t('core', 'Saving...')).removeClass('success').removeClass('error').stop(true, true).show();
        //    $.ajax({
        //        type: 'POST',
        //        url: OC.filePath('beididp','ajax','remove.eid.php'),
        //        data: {identity: identity},
        //        success: function (data, textStatus, jqXHR) {
        //            //$('#form .msg').html('success').addClass('success').removeClass('error').stop(true, true).delay(3000).fadeOut(900).show();
        //            row.remove();
        //        },
        //        error: function (jqXHR, textStatus, errorThrown) {
        //            //$('#form .msg').html('error').addClass('error').removeClass('success').show();
        //        }
        //    });
        //
        //    //$('#form .msg').html(t('core', 'Saving...')).removeClass('success').removeClass('error').stop(true, true).show();
        //    $.post(
        //        OC.filePath('beididp', 'ajax', 'remove.eid.php'),
        //        {identity: identity},
        //        function (data) {
        //            if (data.status === 'success') {
        //                //$('#form .msg').html('success').addClass('success').removeClass('error').stop(true, true).delay(3000).fadeOut(900).show();
        //                row.remove();
        //            } else {
        //                //$('#form .msg').html('error').addClass('error').removeClass('success').show();
        //            }
        //        }
        //    );
        //});

        //V1 - remove identity from view; send leftover identities to server; save identities
        //$('#identities').on('click', 'td.remove > img', function () {
        //    alert('row.remove()');
        //
        //    //remove identity from view,
        //    var row = $(this).parent().parent();
        //    row.remove();
        //
        //    //debug: select usefull data (only remaining identities, nothing else)
        //    //$("#identities").css( "border", "3px solid green" );
        //    //$("#identities tbody tr td:nth-child(1)").css( "color", "red" );
        //
        //    //store remaining identities in array
        //    var identities = [];
        //    $('#identities tbody tr td:nth-child(1)').each(function () {
        //        identities.push($(this).text());
        //    });
        //
        //    //debug: display content of array
        //    //$.each(identities, function(index, value) {
        //    //    alert('index: ' + index + ', value: ' + value);
        //    //});
        //
        //    //serialize identities
        //    //var serialized1 = identities.serialize();
        //    //var serialized2 = identities.serializeArray();
        //    //var serialized3 = JSON.stringify(identities);
        //
        //    //debug: display serialized identities
        //    //alert(serialized1);
        //    //alert(serialized2);
        //    //alert(serialized3);
        //
        //    //send identities to be removed from storage
        //    //$('#form .msg').html(t('core', 'Saving...')).removeClass('success').removeClass('error').stop(true, true).show();
        //    $.ajax({
        //        type: 'POST',
        //        url: OC.filePath('beididp','ajax','remove.eid.php'),
        //        data: {identities: identities},
        //        success: function (data, textStatus, jqXHR) {
        //            //$('#form .msg').html('success').addClass('success').removeClass('error').stop(true, true).delay(3000).fadeOut(900).show();
        //            row.remove();
        //        },
        //        error: function (jqXHR, textStatus, errorThrown) {
        //            //$('#form .msg').html('error').addClass('error').removeClass('success').show();
        //        }
        //    });
        //
        //    //$('#form .msg').html(t('core', 'Saving...')).removeClass('success').removeClass('error').stop(true, true).show();
        //    $.post(
        //        OC.filePath('beididp', 'ajax', 'remove.eid.php'),
        //        identities,
        //        function (data) {
        //            if (data.status === 'success') {
        //                //$('#form .msg').html('success').addClass('success').removeClass('error').stop(true, true).delay(3000).fadeOut(900).show();
        //                row.remove();
        //            } else {
        //                //$('#form .msg').html('error').addClass('error').removeClass('success').show();
        //            }
        //        }
        //    );
        //});

        //Failed attempts

//        //OC.msg.startSaving('#form .msg');
//        $.ajax({
//            url: OC.filePath('beididp','ajax','remove.eid.php'),
//            dataType: 'json',
//            contentType: 'application/json; charset=UTF-8',
//            type: 'post',
//            data: {identities: JSON.stringify(identities)},
//            success: function (result) {
//                alert('Success');
//                //$('#form .msg').html("success");
//                $('#form .msg').text("success");
//                $('#form .msg').text(result.data.message);
//                //OC.msg.finishedSaving('#form .msg', result);
//                //$('#output').html(OC.filePath('beididp','templates','eid.php'));
//            },
//            error: function (result) {
//                alert('Error');
//                //$('#form .msg').html("error");
//                $('#form .msg').text("error");
//                $('#form .msg').text(result.data.message);
//                //OC.msg.finishedSaving('#form .msg', result);
//                //$('#output').html(OC.filePath('beididp','templates','eid.php'));
//            },
//            complete: function (result) {
//                alert('Complete');
//                //$('#form .msg').html("complete");
//                $('#form .msg').text("complete");
//                $('#form .msg').text(result.data.message);
//                //OC.msg.finishedSaving('#form .msg', result);
//                //$('#output').html(OC.filePath('beididp','templates','eid.php'));
//            }
//        });

//        $.post(
//            OC.filePath('beididp','ajax','remove.eid.php'),
//            post,
//            function (data) {
//                OC.msg.finishedSaving('#form .msg', data);
//            }
//        );

//        $.post(
//            OC.filePath('beididp','ajax','remove.eid.php'),
//            {identities: identities},
//            function (result) {
//                if (result.status != 'success') {
//                    OC.Notification.show(t('admin', result.data.message));
//                } else {
//                    alert('Alert: Error');
//                }
//            }
//        );

//        $.post(
//            OC.filePath('beididp','ajax','remove.eid.php'),
//            {ids: identities},
//            function (data) {
//                if (data.status != 'success') {
//                    alert("Error : " + data.data.message);
//                } else {
//                    alert("Success");
//                }
//        }, 'json');

//        $.post(
//            OC.filePath('beididp','ajax','remove.eid.php'),
//            post,
//            function (data) {
//                if (data.status == "success") {
//                    alert("Success");
//                } else {
//                    alert("Error : " + data.data.message);
//                }
//        });

//        $.post(OC.filePath('beididp','ajax','remove.eid.php'), post, function (data) {
//            $('#form .msg').text('Finished: ' + data);
//            alert('Finished: ' + data);
//        });

//        $.post(OC.filePath('beididp', 'ajax', 'remove.eid.php'), data, function (result) {
//            OC.msg.finishedSaving('#form .msg', result);
//        });

//        $.post(OC.filePath('beididp', 'ajax', 'remove.eid.php', function () {
//            alert("success");
//        })
//            .done(function () {
//                alert("second success");
//            })
//            .fail(function () {
//                alert("error");
//            })
//            .always(function () {
//                alert("finished");
//            })
//        );

//        OC.msg.startSaving('#form .msg');
//        var post = $('#form').serialize();
//        $.post(OC.filePath('beididp', 'ajax', 'add.eid.php'), post, function (result) {
//            OC.msg.finishedSaving('#form .msg', result);
//        });
//
//        $.get(
//            OC.generateUrl('/owncloud/index.php/apps/beididp/templates/eid.php'),
//            function (result) {
//                alert("finish");
//            }
//        );

//        var post = $("#passwordform").serialize();
//        $.post(OC.generateUrl('/settings/personal/changepassword'), post, function (data) {
//            if (data.status === "success") {
//                $('#pass1').val('');
//                $('#pass2').val('');
//                $('#passwordchanged').show();
//            } else {
//                if (typeof (data.data) !== "undefined") {
//                    $('#passworderror').html(data.data.message);
//                } else {
//                    $('#passworderror').html(t('Unable to change password'));
//                }
//                $('#passworderror').show();
//            }
//        });

//        $.ajax({
//            url: OC.filePath('beididp', 'templates', 'eid.php'),
//            type: 'post',
//            data: {},
//            complete: function (result) {
//                $('#output').html(OC.filePath('beididp', 'templates', 'eid.php'));
//            },
//            error: function () {
//                $('#output').html(OC.filePath('beididp', 'templates', 'eid.php'));
//            }
//        });

//        $('#identities').on('click', 'td.remove > a', function () {
//            alert('Hello from your script file');
//            var row = $(this).parent().parent();
//            $.post(OC.generateUrl('settings/ajax/removeRootCertificate'), {
//                cert: row.data('name')
//            });
//            row.remove();
//            return true;
//        });

        //Other functions

        $('#submit').click(function () {
            alert('#submit.click()');
        });

//        $("#form").submit(function (event) {
//            event.preventDefault();
//        });

    });

})(jQuery, OC);
<commit_msg>Deleted 'failed ajax-request' attempt collection<commit_after>/**
 * ownCloud - Belgian eID IDP Integration
 *
 * This file is licensed under the Affero General Public License version 3 or
 * later. See the COPYING file.
 *
 * @author Bert Maerten <maerten.bert@outlook.com>
 * @copyright Bert Maerten 2015
 */

(function ($, OC) {

    $(document).ready(function () {
        alert('document.ready()');

        $('#identities td.remove > img').click(function () {
            alert('row.remove()');

            var row = $(this).parent().parent();
            var identity = $.trim(row.text());

            //$('#form .msg').html(t('core', 'Saving...')).removeClass('success').removeClass('error').stop(true, true).show(); //OC.msg.startSaving('#form .msg'); /* OC.msg.startSaving(selector) & OC.msg.startAction(selector, message) in core/js/js.js*/
            //$.ajax({
            //    type: 'POST',
            //    url: OC.filePath('beididp','ajax','remove.eid.php'),
            //    data: {identity: identity},
            //    success: function (data, textStatus, jqXHR) {
            //        $('#form .msg').html('success').addClass('success').removeClass('error').stop(true, true).delay(3000).fadeOut(900).show(); //OC.msg.finishedSaving('#form .msg', data); /* OC.msg.finishedSaving(selector, data) & OC.msg.finishedAction(selector, data)  in core/js/js.js*/
            //        row.remove();
            //    },
            //    error: function (jqXHR, textStatus, errorThrown) {
            //        $('#form .msg').html('error').addClass('error').removeClass('success').show(); //OC.msg.finishedSaving('#form .msg', data);
            //    }
            //});

            $('#form .msg').html(t('core', 'Saving...')).removeClass('success').removeClass('error').stop(true, true).show(); //OC.msg.startSaving('#form .msg');
            $.post(
                OC.filePath('beididp', 'ajax', 'remove.eid.php'),
                {identity: identity},
                function (result) {
                    if (result.status === 'success') {
                        $('#form .msg').html(result.data.message).addClass('success').removeClass('error').stop(true, true).delay(3000).fadeOut(900).show(); //OC.msg.finishedSaving('#form .msg', result);
                        row.remove();
                    } else {
                        $('#form .msg').html(result.data.message).addClass('error').removeClass('success').show(); //OC.msg.finishedSaving('#form .msg', result);
                    }
                }
            );
        });

        //V2 - get identity; send identity to server; get identities and remove the recieved one; save identities; remove identity from view
        //$('#identities').on('click', 'td.remove > img', function () {
        //    alert('row.remove()');
        //
        //    var row = $(this).parent().parent();
        //    var identity = $.trim(row.text());
        //
        //    //$('#form .msg').html(t('core', 'Saving...')).removeClass('success').removeClass('error').stop(true, true).show();
        //    $.ajax({
        //        type: 'POST',
        //        url: OC.filePath('beididp','ajax','remove.eid.php'),
        //        data: {identity: identity},
        //        success: function (data, textStatus, jqXHR) {
        //            //$('#form .msg').html('success').addClass('success').removeClass('error').stop(true, true).delay(3000).fadeOut(900).show();
        //            row.remove();
        //        },
        //        error: function (jqXHR, textStatus, errorThrown) {
        //            //$('#form .msg').html('error').addClass('error').removeClass('success').show();
        //        }
        //    });
        //
        //    //$('#form .msg').html(t('core', 'Saving...')).removeClass('success').removeClass('error').stop(true, true).show();
        //    $.post(
        //        OC.filePath('beididp', 'ajax', 'remove.eid.php'),
        //        {identity: identity},
        //        function (data) {
        //            if (data.status === 'success') {
        //                //$('#form .msg').html('success').addClass('success').removeClass('error').stop(true, true).delay(3000).fadeOut(900).show();
        //                row.remove();
        //            } else {
        //                //$('#form .msg').html('error').addClass('error').removeClass('success').show();
        //            }
        //        }
        //    );
        //});

        //V1 - remove identity from view; send leftover identities to server; save identities
        //$('#identities').on('click', 'td.remove > img', function () {
        //    alert('row.remove()');
        //
        //    //remove identity from view,
        //    var row = $(this).parent().parent();
        //    row.remove();
        //
        //    //debug: select usefull data (only remaining identities, nothing else)
        //    //$("#identities").css( "border", "3px solid green" );
        //    //$("#identities tbody tr td:nth-child(1)").css( "color", "red" );
        //
        //    //store remaining identities in array
        //    var identities = [];
        //    $('#identities tbody tr td:nth-child(1)').each(function () {
        //        identities.push($(this).text());
        //    });
        //
        //    //debug: display content of array
        //    //$.each(identities, function(index, value) {
        //    //    alert('index: ' + index + ', value: ' + value);
        //    //});
        //
        //    //serialize identities
        //    //var serialized1 = identities.serialize();
        //    //var serialized2 = identities.serializeArray();
        //    //var serialized3 = JSON.stringify(identities);
        //
        //    //debug: display serialized identities
        //    //alert(serialized1);
        //    //alert(serialized2);
        //    //alert(serialized3);
        //
        //    //send identities to be removed from storage
        //    //$('#form .msg').html(t('core', 'Saving...')).removeClass('success').removeClass('error').stop(true, true).show();
        //    $.ajax({
        //        type: 'POST',
        //        url: OC.filePath('beididp','ajax','remove.eid.php'),
        //        data: {identities: identities},
        //        success: function (data, textStatus, jqXHR) {
        //            //$('#form .msg').html('success').addClass('success').removeClass('error').stop(true, true).delay(3000).fadeOut(900).show();
        //            row.remove();
        //        },
        //        error: function (jqXHR, textStatus, errorThrown) {
        //            //$('#form .msg').html('error').addClass('error').removeClass('success').show();
        //        }
        //    });
        //
        //    //$('#form .msg').html(t('core', 'Saving...')).removeClass('success').removeClass('error').stop(true, true).show();
        //    $.post(
        //        OC.filePath('beididp', 'ajax', 'remove.eid.php'),
        //        identities,
        //        function (data) {
        //            if (data.status === 'success') {
        //                //$('#form .msg').html('success').addClass('success').removeClass('error').stop(true, true).delay(3000).fadeOut(900).show();
        //                row.remove();
        //            } else {
        //                //$('#form .msg').html('error').addClass('error').removeClass('success').show();
        //            }
        //        }
        //    );
        //});

        //Other functions

        $('#submit').click(function () {
            alert('#submit.click()');
        });

        //$("#form").submit(function (event) {
        //    event.preventDefault();
        //});

    });

})(jQuery, OC);
<|endoftext|>