<commit_before>define([
  'jquery',
  'backbone'
], function($, Backbone) {

  'use strict';

  const topics = {
    'report-a-bug-or-error-on-gfw': {
      name: 'Report a bug or error on GFW',
      placeholder: 'Explain the bug or error and tell us where on the website you encountered it. What browser (e.g., Chrome version 50.0.2661.94 m) and operating system (e.g., Windows 8.1) do you use?',
    },
    'provide-feedback': {
      name: 'Provide feedback',
      placeholder: 'Tell us about your experience with GFW! Examples: How can we improve GFW? Why did you visit GFW? How do you use GFW? If and how is the information provided by GFW useful for your work? Are there any additional features and/or data that would be useful?  Was anything confusing or difficult to use?  Etc...',
    },
    'media-request': {
      name: 'Media request',
      placeholder: 'How can we help you?',
    },
    'data-related-inquiry': {
      name: 'Data-related inquiry or suggestion',
      placeholder: 'How can we help you?',
    },
    'gfw-commodities-inquiry': {
      name: 'GFW Commodities inquiry',
      placeholder: 'How can we help you?',
    },
    'gfw-fires-inquiry': {
      name: 'GFW Fires inquiry',
      placeholder: 'How can we help you?',
    },
    'gfw-climate-inquiry': {
      name: 'GFW Climate inquiry',
      placeholder: 'How can we help you?',
    },
    'gfw-water-inquiry': {
      name: 'GFW Water inquiry',
      placeholder: 'How can we help you?',
    },
    'general-inquiry': {
      name: 'General inquiry',
      placeholder: 'How can we help you?',
    },
  }

  const constraints = {
    'contact-email': {
      presence: true,
      email: true
    },
    'contact-topic': {
      presence: true
    },
    'contact-message': {
      presence: true
    }
  };

  var ContacUsView = Backbone.View.extend({

    el: '#contact_us',

    events: {
      'click .js-btn-submit': 'actionSubmit',
      'change input, textarea, select': 'changeInput',
    },

    initialize: function() {
      this.$spinner = this.$el.find('.m-spinner');
      this.$form = this.$el.find('#contact-form');
      this.$step = this.$el.find('.step');
      this.$stepBtn = this.$el.find('.step-btn');
      this.$contactMessage = this.$el.find('#contact-message');
    },

    actionSubmit(e) {
      e && e.preventDefault();
      (this.validate(e)) ? this.sendForm() : this.updateForm();
    },

    // Send the data to the API
    sendForm() {
      // Production send request
      // Send request
      this.$spinner.addClass('-start');
      var xhr = new XMLHttpRequest();

      xhr.open('POST', window.gfw.config.GFW_API_HOST + '/emails');
      xhr.setRequestHeader('Content-Type', 'application/json; charset=utf-8');

      xhr.onload = function() {
        if (xhr.status === 200 || xhr.status === 201) {
          this.changeStep('success');
          this.resetForm();
          this.$spinner.removeClass('-start');
        } else {
          this.changeStep('error');
          this.$spinner.removeClass('-start');
        }
      }.bind(this);

      xhr.onerror = () => {
        this.changeStep('error');
        this.$spinner.removeClass('-start');
      }

      xhr.send(JSON.stringify(this.serialize(this.$form[0])));

      // // Develop Send request
      // // Comment this code if this is going to pro
      // if (true) {
      //   this.changeStep('success');
      //   this.$spinner.removeClass('-start');
      // } else {
      //   this.changeStep('error');
      //   this.$spinner.removeClass('-start');
      // }
    },

    updateForm() {
      this.$form.find('input, textarea, select').removeClass('-error');
      this.$form.find('label').removeClass('-error');
      for (var key in this.errors) {
        var $input = this.$form.find('#'+key);
        var $label = this.$form.find('label[for='+key+']');
        $input.addClass('-error');
        $label.addClass('-error');
      }
    },

    resetForm() {
      this.$form.find('input, textarea, select').val(null);
    },

    serialize(form) {
    	if (!form || form.nodeName !== "FORM") {
    		return;
    	}
    	let obj = {};
    	for (let i = form.elements.length - 1; i >= 0; i = i - 1) {
    		if (form.elements[i].name === "") {
    			continue;
    		}
    		switch (form.elements[i].nodeName) {
    		case 'INPUT':
    			switch (form.elements[i].type) {
    			case 'text':
    			case 'email':
    			case 'hidden':
    			case 'password':
    			case 'button':
    			case 'reset':
    			case 'submit':
    				obj[form.elements[i].name] = form.elements[i].value;
    				break;
    			case 'checkbox':
    			case 'radio':
            if (form.elements[i].checked) {
              obj[form.elements[i].name] = form.elements[i].value;
            } else if (!obj[form.elements[i].name]) {
              obj[form.elements[i].name] = false;
            }
    				break;
    			case 'file':
    				break;
    			}
    			break;
    		case 'TEXTAREA':
    			obj[form.elements[i].name] = form.elements[i].value;
    			break;
    		case 'SELECT':
    			switch (form.elements[i].type) {
    			case 'select-one':
    				obj[form.elements[i].name] = form.elements[i].value;
    				break;
    			case 'select-multiple':
    				for (let j = form.elements[i].options.length - 1; j >= 0; j = j - 1) {
    					if (form.elements[i].options[j].selected) {
    						obj[form.elements[i].name] = form.elements[i].options[j].value;
    					}
    				}
    				break;
    			}
    			break;
    		case 'BUTTON':
    			switch (form.elements[i].type) {
    			case 'reset':
    			case 'submit':
    			case 'button':
    				obj[form.elements[i].name] = form.elements[i].value;
    				break;
    			}
    			break;
    		}
    	}
    	return obj;
    },

    validate(e) {
      e && e.preventDefault();
      let attributes = this.serialize(this.$form[0]);

      // Validate form, if is valid the response will be undefined
      this.errors = validate(attributes, constraints);
      return ! !!this.errors;
    },

    validateInput(name, value) {
      let errors = validate.single(value, constraints[name]);
      if (!!errors && this.errors) {
        this.errors[name] = errors[0];
      } else {
        this.errors && this.errors[name] && delete this.errors[name];
      }
    },

    changeInput(e) {
      e && e.preventDefault();
      this.validateInput(e.currentTarget.name, e.currentTarget.value);
      this.updateForm();
    },

    changeStep(step) {
      this.$step.removeClass('-active');
      this.$stepBtn.removeClass('-active');

      // Set actives
      this.$el.find('.step[data-step="'+step+'"]').addClass('-active');
      this.$el.find('.step-btn[data-step="'+step+'"]').addClass('-active');
    },

    changeTopic(e) {
      var topic = e.currentTarget.value;
      if (!!topic) {
        var placeholder = topics[topic]['placeholder'];
        this.$contactMessage.attr('placeholder', placeholder);
      }
    }

  });

  return ContacUsView;
});
<commit_msg>Add event on topic change<commit_after>define([
  'jquery',
  'backbone'
], function($, Backbone) {

  'use strict';

  const topics = {
    'report-a-bug-or-error-on-gfw': {
      name: 'Report a bug or error on GFW',
      placeholder: 'Explain the bug or error and tell us where on the website you encountered it. What browser (e.g., Chrome version 50.0.2661.94 m) and operating system (e.g., Windows 8.1) do you use?',
    },
    'provide-feedback': {
      name: 'Provide feedback',
      placeholder: 'Tell us about your experience with GFW! Examples: How can we improve GFW? Why did you visit GFW? How do you use GFW? If and how is the information provided by GFW useful for your work? Are there any additional features and/or data that would be useful?  Was anything confusing or difficult to use?  Etc...',
    },
    'media-request': {
      name: 'Media request',
      placeholder: 'How can we help you?',
    },
    'data-related-inquiry': {
      name: 'Data-related inquiry or suggestion',
      placeholder: 'How can we help you?',
    },
    'gfw-commodities-inquiry': {
      name: 'GFW Commodities inquiry',
      placeholder: 'How can we help you?',
    },
    'gfw-fires-inquiry': {
      name: 'GFW Fires inquiry',
      placeholder: 'How can we help you?',
    },
    'gfw-climate-inquiry': {
      name: 'GFW Climate inquiry',
      placeholder: 'How can we help you?',
    },
    'gfw-water-inquiry': {
      name: 'GFW Water inquiry',
      placeholder: 'How can we help you?',
    },
    'general-inquiry': {
      name: 'General inquiry',
      placeholder: 'How can we help you?',
    },
  }

  const constraints = {
    'contact-email': {
      presence: true,
      email: true
    },
    'contact-topic': {
      presence: true
    },
    'contact-message': {
      presence: true
    }
  };

  var ContacUsView = Backbone.View.extend({

    el: '#contact_us',

    events: {
      'click .js-btn-submit': 'actionSubmit',
      'change input, textarea, select': 'changeInput',
      'change #contact-topic': 'changeTopic'
    },

    initialize: function() {
      this.$spinner = this.$el.find('.m-spinner');
      this.$form = this.$el.find('#contact-form');
      this.$step = this.$el.find('.step');
      this.$stepBtn = this.$el.find('.step-btn');
      this.$contactMessage = this.$el.find('#contact-message');
    },

    actionSubmit(e) {
      e && e.preventDefault();
      (this.validate(e)) ? this.sendForm() : this.updateForm();
    },

    // Send the data to the API
    sendForm() {
      // Production send request
      // Send request
      this.$spinner.addClass('-start');
      var xhr = new XMLHttpRequest();

      xhr.open('POST', window.gfw.config.GFW_API_HOST + '/emails');
      xhr.setRequestHeader('Content-Type', 'application/json; charset=utf-8');

      xhr.onload = function() {
        if (xhr.status === 200 || xhr.status === 201) {
          this.changeStep('success');
          this.resetForm();
          this.$spinner.removeClass('-start');
        } else {
          this.changeStep('error');
          this.$spinner.removeClass('-start');
        }
      }.bind(this);

      xhr.onerror = () => {
        this.changeStep('error');
        this.$spinner.removeClass('-start');
      }

      xhr.send(JSON.stringify(this.serialize(this.$form[0])));

      // // Develop Send request
      // // Comment this code if this is going to pro
      // if (true) {
      //   this.changeStep('success');
      //   this.$spinner.removeClass('-start');
      // } else {
      //   this.changeStep('error');
      //   this.$spinner.removeClass('-start');
      // }
    },

    updateForm() {
      this.$form.find('input, textarea, select').removeClass('-error');
      this.$form.find('label').removeClass('-error');
      for (var key in this.errors) {
        var $input = this.$form.find('#'+key);
        var $label = this.$form.find('label[for='+key+']');
        $input.addClass('-error');
        $label.addClass('-error');
      }
    },

    resetForm() {
      this.$form.find('input, textarea, select').val(null);
    },

    serialize(form) {
    	if (!form || form.nodeName !== "FORM") {
    		return;
    	}
    	let obj = {};
    	for (let i = form.elements.length - 1; i >= 0; i = i - 1) {
    		if (form.elements[i].name === "") {
    			continue;
    		}
    		switch (form.elements[i].nodeName) {
    		case 'INPUT':
    			switch (form.elements[i].type) {
    			case 'text':
    			case 'email':
    			case 'hidden':
    			case 'password':
    			case 'button':
    			case 'reset':
    			case 'submit':
    				obj[form.elements[i].name] = form.elements[i].value;
    				break;
    			case 'checkbox':
    			case 'radio':
            if (form.elements[i].checked) {
              obj[form.elements[i].name] = form.elements[i].value;
            } else if (!obj[form.elements[i].name]) {
              obj[form.elements[i].name] = false;
            }
    				break;
    			case 'file':
    				break;
    			}
    			break;
    		case 'TEXTAREA':
    			obj[form.elements[i].name] = form.elements[i].value;
    			break;
    		case 'SELECT':
    			switch (form.elements[i].type) {
    			case 'select-one':
    				obj[form.elements[i].name] = form.elements[i].value;
    				break;
    			case 'select-multiple':
    				for (let j = form.elements[i].options.length - 1; j >= 0; j = j - 1) {
    					if (form.elements[i].options[j].selected) {
    						obj[form.elements[i].name] = form.elements[i].options[j].value;
    					}
    				}
    				break;
    			}
    			break;
    		case 'BUTTON':
    			switch (form.elements[i].type) {
    			case 'reset':
    			case 'submit':
    			case 'button':
    				obj[form.elements[i].name] = form.elements[i].value;
    				break;
    			}
    			break;
    		}
    	}
    	return obj;
    },

    validate(e) {
      e && e.preventDefault();
      let attributes = this.serialize(this.$form[0]);

      // Validate form, if is valid the response will be undefined
      this.errors = validate(attributes, constraints);
      return ! !!this.errors;
    },

    validateInput(name, value) {
      let errors = validate.single(value, constraints[name]);
      if (!!errors && this.errors) {
        this.errors[name] = errors[0];
      } else {
        this.errors && this.errors[name] && delete this.errors[name];
      }
    },

    changeInput(e) {
      e && e.preventDefault();
      this.validateInput(e.currentTarget.name, e.currentTarget.value);
      this.updateForm();
    },

    changeStep(step) {
      this.$step.removeClass('-active');
      this.$stepBtn.removeClass('-active');

      // Set actives
      this.$el.find('.step[data-step="'+step+'"]').addClass('-active');
      this.$el.find('.step-btn[data-step="'+step+'"]').addClass('-active');
    },

    changeTopic(e) {
      var topic = e.currentTarget.value;
      if (!!topic) {
        var placeholder = topics[topic]['placeholder'];
        this.$contactMessage.attr('placeholder', placeholder);
      }
    }

  });

  return ContacUsView;
});
<|endoftext|>


<commit_before>(function (app) {

  "use strict"

  app.controller("ChapterController", ChapterController);

  ChapterController.$inject = ["$window", "$scope", "$filter", "entityService", "publishService","vdsMultirangeViews", "vdsUtils", "video"];
  /**
   * Defines the categories controller for the categories page.
   */

  function ChapterController($window, $scope, $filter, entityService, publishService, vdsMultirangeViews, vdsUtils, video) {

    //Init
    $scope.video = video.data.entity;
    $scope.duration = 60*60|| $scope.video.metadata.duration;
    $scope.isCollapsed = true;
    $scope.selectRow = null;
    //Copy of object to edit or add
    $scope.modelToEdit= {};
    // Backup of an existing object to cancel its edition
    $scope.backUpRow = {};

    //Init object for player
    $scope.videoPlayer = angular.copy($scope.video);
    delete $scope.videoPlayer.chapter;

    //If no chapter, add timecodes with empty values and sort them
    if(!$scope.video.chapter){
      $scope.video.chapter = [];
      var indexTimecodes = $scope.video.timecodes;
      angular.forEach(indexTimecodes, function(value, key) {
        if(key!=0)
        $scope.video.chapter.push({'value':parseInt(key)/($scope.duration * 1000), 'name':"", 'description':""});
      });
    }
    var orderBy = $filter('orderBy');
    $scope.video.chapter = orderBy($scope.video.chapter, '+value',false);

    //If no cut add it
    if(!$scope.video.cut) $scope.video.cut = [];

    var updateRange = function(){
       $scope.ranges = $scope.video.chapter.concat($scope.video.cut);
       orderBy( $scope.ranges, '+value', false);
    }
    $scope.ranges; updateRange();

    // Search a value, by time or value and return or delete it
    var search = function(value, type, action){
      var searchObj = []
      if (value === parseFloat(value))
        searchObj = $filter('filter')($scope.video.chapter, {value:value}, true);
      else if(type)
        searchObj = $filter('filter')($scope.video.cut, {type:type}, true);

      if(searchObj.length > 0){
        //return
        if(!action) return searchObj[0];
        else {
          //or Delete
          if(value) $scope.video.chapter.splice($scope.video.chapter.indexOf(searchObj[0]),1);
          else if(type) $scope.video.cut.splice($scope.video.cut.indexOf(searchObj[0]),1);
          updateRange();
          return true;
        };
      }
      else return false;
    }

    //Open a new value
    $scope.openNew = function(){
      $scope.modelToEdit = {value:0};
      if($scope.selectRow){
        $scope.selectRow.select= false;
        $scope.selectRow = null;
      }
      $scope.isCollapsed = false;
    };

    //Open an value to edit
    $scope.openEdit = function(){
      if($scope.isCollapsed){
        //set backup
        angular.copy($scope.selectRow, $scope.backUpRow);
        //copy
        $scope.modelToEdit = $scope.selectRow;
        $scope.isCollapsed = false;
      }
      // close edit on toggle
      else {
        $scope.cancel();
      }
    };

    // on Submit Edit Form
    $scope.submit = function(){
      $scope.isCollapsed = true;

      if (!$scope.selectRow) {
        //ADD the new model
        $scope.video.chapter.push($scope.modelToEdit);
        updateRange();
      } else {
        $scope.selectRow.select = false;
      }
      //Save
      $scope.saveChapter();
    }

    // on cancel Edit Form
    $scope.cancel = function(){
      // copy backup
      angular.copy($scope.backUpRow, $scope.selectRow);
      $scope.isCollapsed = true;
    }

    $scope.remove = function () {
      var searchObj = search($scope.selectRow.value, null, true);
      //
      if(searchObj){
        //If remove a cut by clicking the remove button, set th state button cut manually
        if($scope.selectRow.type == "begin") $scope.beginIsInArray = false;
        if($scope.selectRow.type == "end") $scope.endIsInArray = false;
        $scope.selectRow.select= false;
        $scope.selectRow = null;
        $scope.saveChapter();
      }
    };

    //Select or deselect a line by clicking
    $scope.select= function (value) {
      if ($scope.isCollapsed) {
        $scope.selectRow = null;
        for (var i = 0; i <  $scope.ranges.length ; i++) {
          if ( $scope.ranges[i].value == value && ! $scope.ranges[i].select && !$scope.selectRow) {
             $scope.ranges[i].select = true;
            $scope.selectRow =  $scope.ranges[i];
          } else {
             $scope.ranges[i].select = false;
          }
        }
      } else {// if close by toggle, close edit form
        $scope.cancel();
        $scope.select(value);
      }
    };

    /**
     * Slider
     */

    $scope.slider = {
        views: vdsMultirangeViews.TIME($scope.duration),
        view: 0
    };

    $scope.changeSliderView = function(event, direction) {
        var indexView = $scope.slider.view + direction;
        0 > indexView ? indexView = 0 : indexView >= $scope.slider.views.length && (indexView = $scope.slider.views.length - 1),
        $scope.slider.view = indexView;
    }

    /**
     * CUT
     */

    //Init begin
    var begin;
    //At start, if begin exist, init with it, else init to 0
    if(begin = search(null, 'begin')){
      $scope.beginRange = begin;
      $scope.beginIsInArray = true;
    } else {
      $scope.beginRange = {'value':0, 'name':$filter('translate')('UI.BEGIN'), 'description':"", 'type':'begin'};
      $scope.beginIsInArray = false;
    }
    //Toggle Begin
    $scope.toggleBegin = function(){
      if(!$scope.beginIsInArray){
        // Add begin Object to range array
        $scope.video.cut.push($scope.beginRange);
        updateRange();
      }else{
        //search and delete
        search(null, 'begin', true);
      }
      //Save
      $scope.saveChapter();
    }

    //Init end
    var end;
    //At start, if end exist, init with it, else init to 1
    if(end = search(null, 'end')){
      $scope.endRange = end;
      $scope.endIsInArray = true;
    } else {
      $scope.endRange = {'value':1, 'name':$filter('translate')('UI.END'), 'description':"", 'type':'end'};
      $scope.endIsInArray = false;
    }
    //Toggle End
    $scope.toggleEnd = function(){
      if(!$scope.endIsInArray){
        $scope.video.cut.push($scope.endRange);
        updateRange();
      }else {
        //search and delete
        search(null, 'end', true);
      }
      $scope.saveChapter();
    }

    //Save chapter and cut
    $scope.saveChapter = function(){
      //Validate if end is after begin
      if($scope.endIsInArray && $scope.beginIsInArray && $scope.endRange.value <= $scope.beginRange.value){
        //else delete end in range
        search(null, 'end', true);
        //and reset end
        $scope.endRange.value = 1;
        $scope.endIsInArray = false;
      }

      $scope.video.chapter = orderBy($scope.video.chapter, '+value',false);
      $scope.video.cut = orderBy($scope.video.cut, '+value',false);

      //CALL SAVE HTTP
      entityService.updateEntity('video', $scope.video.id, {
        chapter: $scope.video.chapter,
        cut: $scope.video.cut
      }).success(function (data, status, headers, config) {

      }).error(function (data, status, headers, config) {
        $scope.$emit("setAlert", 'danger', $filter('translate')('CHAPTER.SAVE_ERROR'), 4000);
        if (status === 401)
          $scope.$parent.logout();
      });
    }
    $scope.back = function(){
      $window.history.back();
    }

    /**
     *
     *  Time
    */
    var changebyRange = true;
    $scope.updateTime = function(){
      if(changebyRange){
      var d = new Date(parseInt($scope.modelToEdit.value* $scope.duration)* 1000);
      var utc = d.getTime() + (d.getTimezoneOffset() * 60000);
      var nd = new Date(utc);
      $scope.editTime = nd;
      } else changebyRange = true;
    }
    $scope.updateRange = function(){
      if($scope.myForm.time.$valid && $scope.editTime){
        var d = new Date($scope.editTime.getTime());
        var local = d.getTime() - (d.getTimezoneOffset() * 60000);
        changebyRange = false;
        $scope.modelToEdit.value = local/($scope.duration *1000);
      }
    }
    $scope.$watch('modelToEdit.value', function(newValue, oldValue) {
      $scope.updateTime();
    });
    $scope.editTime = new Date(Date.UTC(1970, 0, 1, 0, 0, 0 ));

  }
})(angular.module("ov.publish"));<commit_msg>DEBUG: Delete duration test value<commit_after>(function (app) {

  "use strict"

  app.controller("ChapterController", ChapterController);

  ChapterController.$inject = ["$window", "$scope", "$filter", "entityService", "publishService","vdsMultirangeViews", "vdsUtils", "video"];
  /**
   * Defines the categories controller for the categories page.
   */

  function ChapterController($window, $scope, $filter, entityService, publishService, vdsMultirangeViews, vdsUtils, video) {

    //Init
    $scope.video = video.data.entity;
    $scope.duration = $scope.video.metadata.duration;
    $scope.isCollapsed = true;
    $scope.selectRow = null;
    //Copy of object to edit or add
    $scope.modelToEdit= {};
    // Backup of an existing object to cancel its edition
    $scope.backUpRow = {};

    //Init object for player
    $scope.videoPlayer = angular.copy($scope.video);
    delete $scope.videoPlayer.chapter;

    //If no chapter, add timecodes with empty values and sort them
    if(!$scope.video.chapter){
      $scope.video.chapter = [];
      var indexTimecodes = $scope.video.timecodes;
      angular.forEach(indexTimecodes, function(value, key) {
        if(key!=0)
        $scope.video.chapter.push({'value':parseInt(key)/($scope.duration * 1000), 'name':"", 'description':""});
      });
    }
    var orderBy = $filter('orderBy');
    $scope.video.chapter = orderBy($scope.video.chapter, '+value',false);

    //If no cut add it
    if(!$scope.video.cut) $scope.video.cut = [];

    var updateRange = function(){
       $scope.ranges = $scope.video.chapter.concat($scope.video.cut);
       orderBy( $scope.ranges, '+value', false);
    }
    $scope.ranges; updateRange();

    // Search a value, by time or value and return or delete it
    var search = function(value, type, action){
      var searchObj = []
      if (value === parseFloat(value))
        searchObj = $filter('filter')($scope.video.chapter, {value:value}, true);
      else if(type)
        searchObj = $filter('filter')($scope.video.cut, {type:type}, true);

      if(searchObj.length > 0){
        //return
        if(!action) return searchObj[0];
        else {
          //or Delete
          if(value) $scope.video.chapter.splice($scope.video.chapter.indexOf(searchObj[0]),1);
          else if(type) $scope.video.cut.splice($scope.video.cut.indexOf(searchObj[0]),1);
          updateRange();
          return true;
        };
      }
      else return false;
    }

    //Open a new value
    $scope.openNew = function(){
      $scope.modelToEdit = {value:0};
      if($scope.selectRow){
        $scope.selectRow.select= false;
        $scope.selectRow = null;
      }
      $scope.isCollapsed = false;
    };

    //Open an value to edit
    $scope.openEdit = function(){
      if($scope.isCollapsed){
        //set backup
        angular.copy($scope.selectRow, $scope.backUpRow);
        //copy
        $scope.modelToEdit = $scope.selectRow;
        $scope.isCollapsed = false;
      }
      // close edit on toggle
      else {
        $scope.cancel();
      }
    };

    // on Submit Edit Form
    $scope.submit = function(){
      $scope.isCollapsed = true;

      if (!$scope.selectRow) {
        //ADD the new model
        $scope.video.chapter.push($scope.modelToEdit);
        updateRange();
      } else {
        $scope.selectRow.select = false;
      }
      //Save
      $scope.saveChapter();
    }

    // on cancel Edit Form
    $scope.cancel = function(){
      // copy backup
      angular.copy($scope.backUpRow, $scope.selectRow);
      $scope.isCollapsed = true;
    }

    $scope.remove = function () {
      var searchObj = search($scope.selectRow.value, null, true);
      //
      if(searchObj){
        //If remove a cut by clicking the remove button, set th state button cut manually
        if($scope.selectRow.type == "begin") $scope.beginIsInArray = false;
        if($scope.selectRow.type == "end") $scope.endIsInArray = false;
        $scope.selectRow.select= false;
        $scope.selectRow = null;
        $scope.saveChapter();
      }
    };

    //Select or deselect a line by clicking
    $scope.select= function (value) {
      if ($scope.isCollapsed) {
        $scope.selectRow = null;
        for (var i = 0; i <  $scope.ranges.length ; i++) {
          if ( $scope.ranges[i].value == value && ! $scope.ranges[i].select && !$scope.selectRow) {
             $scope.ranges[i].select = true;
            $scope.selectRow =  $scope.ranges[i];
          } else {
             $scope.ranges[i].select = false;
          }
        }
      } else {// if close by toggle, close edit form
        $scope.cancel();
        $scope.select(value);
      }
    };

    /**
     * Slider
     */

    $scope.slider = {
        views: vdsMultirangeViews.TIME($scope.duration),
        view: 0
    };

    $scope.changeSliderView = function(event, direction) {
        var indexView = $scope.slider.view + direction;
        0 > indexView ? indexView = 0 : indexView >= $scope.slider.views.length && (indexView = $scope.slider.views.length - 1),
        $scope.slider.view = indexView;
    }

    /**
     * CUT
     */

    //Init begin
    var begin;
    //At start, if begin exist, init with it, else init to 0
    if(begin = search(null, 'begin')){
      $scope.beginRange = begin;
      $scope.beginIsInArray = true;
    } else {
      $scope.beginRange = {'value':0, 'name':$filter('translate')('UI.BEGIN'), 'description':"", 'type':'begin'};
      $scope.beginIsInArray = false;
    }
    //Toggle Begin
    $scope.toggleBegin = function(){
      if(!$scope.beginIsInArray){
        // Add begin Object to range array
        $scope.video.cut.push($scope.beginRange);
        updateRange();
      }else{
        //search and delete
        search(null, 'begin', true);
      }
      //Save
      $scope.saveChapter();
    }

    //Init end
    var end;
    //At start, if end exist, init with it, else init to 1
    if(end = search(null, 'end')){
      $scope.endRange = end;
      $scope.endIsInArray = true;
    } else {
      $scope.endRange = {'value':1, 'name':$filter('translate')('UI.END'), 'description':"", 'type':'end'};
      $scope.endIsInArray = false;
    }
    //Toggle End
    $scope.toggleEnd = function(){
      if(!$scope.endIsInArray){
        $scope.video.cut.push($scope.endRange);
        updateRange();
      }else {
        //search and delete
        search(null, 'end', true);
      }
      $scope.saveChapter();
    }

    //Save chapter and cut
    $scope.saveChapter = function(){
      //Validate if end is after begin
      if($scope.endIsInArray && $scope.beginIsInArray && $scope.endRange.value <= $scope.beginRange.value){
        //else delete end in range
        search(null, 'end', true);
        //and reset end
        $scope.endRange.value = 1;
        $scope.endIsInArray = false;
      }

      $scope.video.chapter = orderBy($scope.video.chapter, '+value',false);
      $scope.video.cut = orderBy($scope.video.cut, '+value',false);

      //CALL SAVE HTTP
      entityService.updateEntity('video', $scope.video.id, {
        chapter: $scope.video.chapter,
        cut: $scope.video.cut
      }).success(function (data, status, headers, config) {

      }).error(function (data, status, headers, config) {
        $scope.$emit("setAlert", 'danger', $filter('translate')('CHAPTER.SAVE_ERROR'), 4000);
        if (status === 401)
          $scope.$parent.logout();
      });
    }
    $scope.back = function(){
      $window.history.back();
    }

    /**
     *
     *  Time
    */
    var changebyRange = true;
    $scope.updateTime = function(){
      if(changebyRange){
      var d = new Date(parseInt($scope.modelToEdit.value* $scope.duration)* 1000);
      var utc = d.getTime() + (d.getTimezoneOffset() * 60000);
      var nd = new Date(utc);
      $scope.editTime = nd;
      } else changebyRange = true;
    }
    $scope.updateRange = function(){
      if($scope.myForm.time.$valid && $scope.editTime){
        var d = new Date($scope.editTime.getTime());
        var local = d.getTime() - (d.getTimezoneOffset() * 60000);
        changebyRange = false;
        $scope.modelToEdit.value = local/($scope.duration *1000);
      }
    }
    $scope.$watch('modelToEdit.value', function(newValue, oldValue) {
      $scope.updateTime();
    });
    $scope.editTime = new Date(Date.UTC(1970, 0, 1, 0, 0, 0 ));

  }
})(angular.module("ov.publish"));<|endoftext|>


<commit_before>// adapted from Jim W's code: http://stackoverflow.com/a/17494943
// change layout based on amount of Y scroll
var minimizeTriggerPosition=-1;

function moveThings() {
    // video position is used as reference point
    var vid = document.getElementById('video-frame');

    // desktop view involves moving around lots of things
    if(window.innerWidth > 960) {
        var minimizeTrigger = document.getElementById('phoneme-explanation');
        var videoLimitElement = document.getElementById('whats-next');
        var videoLimit = findPosY(videoLimitElement) - 700;

        // adjust top margin to TfCS header position (header stops being fixed at 1242px)
        var marginTop;
        if(window.innerWidth > 1242){
            marginTop = 125;
        }else{
            marginTop = 75;
        }

        if(minimizeTriggerPosition<0)minimizeTriggerPosition=findPosY(minimizeTrigger);

        if(pageYOffset>minimizeTriggerPosition-300){
            jQuery('#video-navigation').addClass('minimized');
            jQuery('#video-frame').addClass('minimized');
            jQuery('#video').addClass('minimized');
            jQuery('.entry-content').addClass('shifted');
            vid.style.top=marginTop+'px';
            if(pageYOffset>videoLimit){
                vid.style.top=(marginTop-pageYOffset+videoLimit)+'px';
            }
        }else{
            jQuery('#video-navigation').removeClass('minimized');
            jQuery('#video-frame').removeClass('minimized');
            jQuery('#video').removeClass('minimized');
            jQuery('.entry-content').removeClass('shifted');
            vid.style.top=0;
        }
    }else{
        // mobile view is much simpler
        if(pageYOffset>document.getElementsByClassName("exercise")[0].offsetTop){
            jQuery('.video-navigation-mobile').addClass('minimized');
        }else{
            jQuery('.video-navigation-mobile').removeClass('minimized');
        }

        // things need to be reset when window shrinks from desktop view to mobile view
        jQuery('#video-navigation').removeClass('minimized');
        jQuery('#video-frame').removeClass('minimized');
        jQuery('#video').removeClass('minimized');
        jQuery('.entry-content').removeClass('shifted');
        vid.style.top=0;
    }
}

window.onscroll=function(){
    moveThings();
};

window.onresize=function(){
    moveThings();
};

function findPosY(obj) {
    var curtop = 0;
    if (typeof (obj.offsetParent) != 'undefined' && obj.offsetParent) {
        while (obj.offsetParent) {
            curtop += obj.offsetTop;
            obj = obj.offsetParent;
        }
        curtop += obj.offsetTop;
    }
    else if (obj.y)
        curtop += obj.y;
    return curtop;
}

/**
 * jQuery.browser.mobile (http://detectmobilebrowser.com/)
 *
 * jQuery.browser.mobile will be true if the browser is a mobile device
 *
 **/
(function(a){(jQuery.browser=jQuery.browser||{}).mobile=/(android|bb\d+|meego).+mobile|avantgo|bada\/|blackberry|blazer|compal|elaine|fennec|hiptop|iemobile|ip(hone|od)|iris|kindle|lge |maemo|midp|mmp|mobile.+firefox|netfront|opera m(ob|in)i|palm( os)?|phone|p(ixi|re)\/|plucker|pocket|psp|series(4|6)0|symbian|treo|up\.(browser|link)|vodafone|wap|windows ce|xda|xiino/i.test(a)||/1207|6310|6590|3gso|4thp|50[1-6]i|770s|802s|a wa|abac|ac(er|oo|s\-)|ai(ko|rn)|al(av|ca|co)|amoi|an(ex|ny|yw)|aptu|ar(ch|go)|as(te|us)|attw|au(di|\-m|r |s )|avan|be(ck|ll|nq)|bi(lb|rd)|bl(ac|az)|br(e|v)w|bumb|bw\-(n|u)|c55\/|capi|ccwa|cdm\-|cell|chtm|cldc|cmd\-|co(mp|nd)|craw|da(it|ll|ng)|dbte|dc\-s|devi|dica|dmob|do(c|p)o|ds(12|\-d)|el(49|ai)|em(l2|ul)|er(ic|k0)|esl8|ez([4-7]0|os|wa|ze)|fetc|fly(\-|_)|g1 u|g560|gene|gf\-5|g\-mo|go(\.w|od)|gr(ad|un)|haie|hcit|hd\-(m|p|t)|hei\-|hi(pt|ta)|hp( i|ip)|hs\-c|ht(c(\-| |_|a|g|p|s|t)|tp)|hu(aw|tc)|i\-(20|go|ma)|i230|iac( |\-|\/)|ibro|idea|ig01|ikom|im1k|inno|ipaq|iris|ja(t|v)a|jbro|jemu|jigs|kddi|keji|kgt( |\/)|klon|kpt |kwc\-|kyo(c|k)|le(no|xi)|lg( g|\/(k|l|u)|50|54|\-[a-w])|libw|lynx|m1\-w|m3ga|m50\/|ma(te|ui|xo)|mc(01|21|ca)|m\-cr|me(rc|ri)|mi(o8|oa|ts)|mmef|mo(01|02|bi|de|do|t(\-| |o|v)|zz)|mt(50|p1|v )|mwbp|mywa|n10[0-2]|n20[2-3]|n30(0|2)|n50(0|2|5)|n7(0(0|1)|10)|ne((c|m)\-|on|tf|wf|wg|wt)|nok(6|i)|nzph|o2im|op(ti|wv)|oran|owg1|p800|pan(a|d|t)|pdxg|pg(13|\-([1-8]|c))|phil|pire|pl(ay|uc)|pn\-2|po(ck|rt|se)|prox|psio|pt\-g|qa\-a|qc(07|12|21|32|60|\-[2-7]|i\-)|qtek|r380|r600|raks|rim9|ro(ve|zo)|s55\/|sa(ge|ma|mm|ms|ny|va)|sc(01|h\-|oo|p\-)|sdk\/|se(c(\-|0|1)|47|mc|nd|ri)|sgh\-|shar|sie(\-|m)|sk\-0|sl(45|id)|sm(al|ar|b3|it|t5)|so(ft|ny)|sp(01|h\-|v\-|v )|sy(01|mb)|t2(18|50)|t6(00|10|18)|ta(gt|lk)|tcl\-|tdg\-|tel(i|m)|tim\-|t\-mo|to(pl|sh)|ts(70|m\-|m3|m5)|tx\-9|up(\.b|g1|si)|utst|v400|v750|veri|vi(rg|te)|vk(40|5[0-3]|\-v)|vm40|voda|vulc|vx(52|53|60|61|70|80|81|83|85|98)|w3c(\-| )|webc|whit|wi(g |nc|nw)|wmlb|wonu|x700|yas\-|your|zeto|zte\-/i.test(a.substr(0,4))})(navigator.userAgent||navigator.vendor||window.opera);

// add current page's title (which should be the phoneme) to navigation menu
jQuery(document).ready(function($) {
    $('.current-phoneme').html(document.title);
    $("div#video-phoneme-explanation").html($("div#phoneme-explanation").html())

    $('.trigger-hover').on('click mouseover', function() {
        $('button.recorder').css("background-color", "#ffc438");
        $('button.recorder').addClass("button-hover-effect");
        setTimeout(function() {
            $('button.recorder').removeClass("button-hover-effect");
            $('button.recorder').css("background-color", "#f0f0f0");
        }, 300);
    });

    // smooth scroll to inner links instead of jumps
    $('a[href^="#"]').on('click',function (e) {
        e.preventDefault();

        var target = this.hash;
        var $target = $(target);

        $('html, body').stop().animate({
            'scrollTop': ($target.offset().top)
        }, 500, 'swing', function () {
            window.location.hash = target;
        });
    });
});

<commit_msg>mobile navigation tweak<commit_after>// adapted from Jim W's code: http://stackoverflow.com/a/17494943
// change layout based on amount of Y scroll
var minimizeTriggerPosition=-1;

function moveThings() {
    // video position is used as reference point
    var vid = document.getElementById('video-frame');

    // desktop view involves moving around lots of things
    if(window.innerWidth > 960) {
        var minimizeTrigger = document.getElementById('phoneme-explanation');
        var videoLimitElement = document.getElementById('whats-next');
        var videoLimit = findPosY(videoLimitElement) - 700;

        // adjust top margin to TfCS header position (header stops being fixed at 1242px)
        var marginTop;
        if(window.innerWidth > 1242){
            marginTop = 125;
        }else{
            marginTop = 75;
        }

        if(minimizeTriggerPosition<0)minimizeTriggerPosition=findPosY(minimizeTrigger);

        if(pageYOffset>minimizeTriggerPosition-300){
            jQuery('#video-navigation').addClass('minimized');
            jQuery('#video-frame').addClass('minimized');
            jQuery('#video').addClass('minimized');
            jQuery('.entry-content').addClass('shifted');
            vid.style.top=marginTop+'px';
            if(pageYOffset>videoLimit){
                vid.style.top=(marginTop-pageYOffset+videoLimit)+'px';
            }
        }else{
            jQuery('#video-navigation').removeClass('minimized');
            jQuery('#video-frame').removeClass('minimized');
            jQuery('#video').removeClass('minimized');
            jQuery('.entry-content').removeClass('shifted');
            vid.style.top=0;
        }
    }else{
        // mobile view is much simpler
        if(pageYOffset>document.getElementsByClassName("exercise")[0].offsetTop){
            jQuery('.video-navigation-mobile').addClass('minimized');
        }else{
            jQuery('.video-navigation-mobile').removeClass('minimized');
        }

        if(pageYOffset>minimizeTriggerPosition-300){
            jQuery('#video').addClass('minimized');
        } else {
            jQuery('#video').removeClass('minimized');
        }

        // things need to be reset when window shrinks from desktop view to mobile view
        // jQuery('#video-navigation').removeClass('minimized');
        // jQuery('#video-frame').removeClass('minimized');
        // jQuery('#video').removeClass('minimized');
        // jQuery('.entry-content').removeClass('shifted');
        // vid.style.top=0;
    }
}

window.onscroll=function(){
    moveThings();
};

window.onresize=function(){
    moveThings();
};

function findPosY(obj) {
    var curtop = 0;
    if (typeof (obj.offsetParent) != 'undefined' && obj.offsetParent) {
        while (obj.offsetParent) {
            curtop += obj.offsetTop;
            obj = obj.offsetParent;
        }
        curtop += obj.offsetTop;
    }
    else if (obj.y)
        curtop += obj.y;
    return curtop;
}

/**
 * jQuery.browser.mobile (http://detectmobilebrowser.com/)
 *
 * jQuery.browser.mobile will be true if the browser is a mobile device
 *
 **/
(function(a){(jQuery.browser=jQuery.browser||{}).mobile=/(android|bb\d+|meego).+mobile|avantgo|bada\/|blackberry|blazer|compal|elaine|fennec|hiptop|iemobile|ip(hone|od)|iris|kindle|lge |maemo|midp|mmp|mobile.+firefox|netfront|opera m(ob|in)i|palm( os)?|phone|p(ixi|re)\/|plucker|pocket|psp|series(4|6)0|symbian|treo|up\.(browser|link)|vodafone|wap|windows ce|xda|xiino/i.test(a)||/1207|6310|6590|3gso|4thp|50[1-6]i|770s|802s|a wa|abac|ac(er|oo|s\-)|ai(ko|rn)|al(av|ca|co)|amoi|an(ex|ny|yw)|aptu|ar(ch|go)|as(te|us)|attw|au(di|\-m|r |s )|avan|be(ck|ll|nq)|bi(lb|rd)|bl(ac|az)|br(e|v)w|bumb|bw\-(n|u)|c55\/|capi|ccwa|cdm\-|cell|chtm|cldc|cmd\-|co(mp|nd)|craw|da(it|ll|ng)|dbte|dc\-s|devi|dica|dmob|do(c|p)o|ds(12|\-d)|el(49|ai)|em(l2|ul)|er(ic|k0)|esl8|ez([4-7]0|os|wa|ze)|fetc|fly(\-|_)|g1 u|g560|gene|gf\-5|g\-mo|go(\.w|od)|gr(ad|un)|haie|hcit|hd\-(m|p|t)|hei\-|hi(pt|ta)|hp( i|ip)|hs\-c|ht(c(\-| |_|a|g|p|s|t)|tp)|hu(aw|tc)|i\-(20|go|ma)|i230|iac( |\-|\/)|ibro|idea|ig01|ikom|im1k|inno|ipaq|iris|ja(t|v)a|jbro|jemu|jigs|kddi|keji|kgt( |\/)|klon|kpt |kwc\-|kyo(c|k)|le(no|xi)|lg( g|\/(k|l|u)|50|54|\-[a-w])|libw|lynx|m1\-w|m3ga|m50\/|ma(te|ui|xo)|mc(01|21|ca)|m\-cr|me(rc|ri)|mi(o8|oa|ts)|mmef|mo(01|02|bi|de|do|t(\-| |o|v)|zz)|mt(50|p1|v )|mwbp|mywa|n10[0-2]|n20[2-3]|n30(0|2)|n50(0|2|5)|n7(0(0|1)|10)|ne((c|m)\-|on|tf|wf|wg|wt)|nok(6|i)|nzph|o2im|op(ti|wv)|oran|owg1|p800|pan(a|d|t)|pdxg|pg(13|\-([1-8]|c))|phil|pire|pl(ay|uc)|pn\-2|po(ck|rt|se)|prox|psio|pt\-g|qa\-a|qc(07|12|21|32|60|\-[2-7]|i\-)|qtek|r380|r600|raks|rim9|ro(ve|zo)|s55\/|sa(ge|ma|mm|ms|ny|va)|sc(01|h\-|oo|p\-)|sdk\/|se(c(\-|0|1)|47|mc|nd|ri)|sgh\-|shar|sie(\-|m)|sk\-0|sl(45|id)|sm(al|ar|b3|it|t5)|so(ft|ny)|sp(01|h\-|v\-|v )|sy(01|mb)|t2(18|50)|t6(00|10|18)|ta(gt|lk)|tcl\-|tdg\-|tel(i|m)|tim\-|t\-mo|to(pl|sh)|ts(70|m\-|m3|m5)|tx\-9|up(\.b|g1|si)|utst|v400|v750|veri|vi(rg|te)|vk(40|5[0-3]|\-v)|vm40|voda|vulc|vx(52|53|60|61|70|80|81|83|85|98)|w3c(\-| )|webc|whit|wi(g |nc|nw)|wmlb|wonu|x700|yas\-|your|zeto|zte\-/i.test(a.substr(0,4))})(navigator.userAgent||navigator.vendor||window.opera);

// add current page's title (which should be the phoneme) to navigation menu
jQuery(document).ready(function($) {
    $('.current-phoneme').html(document.title);
    $("div#video-phoneme-explanation").html($("div#phoneme-explanation").html())

    $('.trigger-hover').on('click mouseover', function() {
        $('button.recorder').css("background-color", "#ffc438");
        $('button.recorder').addClass("button-hover-effect");
        setTimeout(function() {
            $('button.recorder').removeClass("button-hover-effect");
            $('button.recorder').css("background-color", "#f0f0f0");
        }, 300);
    });

    // smooth scroll to inner links instead of jumps
    $('a[href^="#"]').on('click',function (e) {
        e.preventDefault();

        var target = this.hash;
        var $target = $(target);

        $('html, body').stop().animate({
            'scrollTop': ($target.offset().top)
        }, 500, 'swing', function () {
            window.location.hash = target;
        });
    });
});

<|endoftext|>


<commit_before>L.DistortableImage = L.DistortableImage || {};

L.DistortableImage.Edit = L.Handler.extend({
	initialize: function(overlay) {
		this._overlay = overlay;
		this._mode = 0; // warp
	},

	addHooks: function() {
		var overlay = this._overlay,
			map = overlay._map,
			i;

		this._warpHandles = new L.LayerGroup();
		for (i = 0; i < 4; i++) {
			this._warpHandles.addLayer(new L.WarpHandle(overlay, i));
		}

		this._rotateHandles = new L.LayerGroup();
		for (i = 0; i < 4; i++) {
			this._rotateHandles.addLayer(new L.RotateHandle(overlay, i));
		}

		this._handles = [this._warpHandles, this._rotateHandles];

		/* TODO: Tell L>Draggable how to find the position of the image. */
		this._enableDragging();

		map.addLayer(this._warpHandles);

		/* TODO: Why doesn't this._overlay.on('click') work? */
		L.DomEvent.on(this._overlay._image, 'click', this._changeMode, this);
		L.DomEvent.on(this._overlay._image, 'click', this._showToolbar, this);
	},

	_changeMode: function() {
		var map = this._overlay._map;

		map.removeLayer(this._handles[this._mode]);

		/* Switch mode. */
		this._mode = (this._mode + 1) % 2;

		map.addLayer(this._handles[this._mode]);
	},

	removeHooks: function() {
		var map = this._overlay._map;

		map.removeLayer(this._handles[this._mode]);
	},

	_rotateBy: function(angle) {
		var overlay = this._overlay,
			map = overlay._map,
			center = map.latLngToLayerPoint(overlay.getCenter()),
			i, p, q;

		for (i = 0; i < 4; i++) {
			p = map.latLngToLayerPoint(overlay._corners[i]).subtract(center);
			q = new L.Point(
				Math.cos(angle)*p.x - Math.sin(angle)*p.y,
				Math.sin(angle)*p.x + Math.cos(angle)*p.y
			);
			overlay._corners[i] = map.layerPointToLatLng(q.add(center));
		}

		overlay._reset();
	},

	_scaleBy: function(scale) {
		var overlay = this._overlay,
			map = overlay._map,
			center = map.latLngToLayerPoint(overlay.getCenter()),
			i, p;

		for (i = 0; i < 4; i++) {
			p = map.latLngToLayerPoint(overlay._corners[i])
				.subtract(center)
				.multiplyBy(scale)
				.add(center);
			overlay._corners[i] = map.layerPointToLatLng(p);
		}

		overlay._reset();
	},

	_enableDragging: function() {
		var overlay = this._overlay,
			map = overlay._map;

		this.dragging = new L.Draggable(overlay._image);
		this.dragging.enable();

		/*
		 * Adjust default behavior of L.Draggable.
	     * By default, L.Draggable overwrites the CSS3 warp transform
	     *     that we want when it calls L.DomUtil.setPosition.
		 */
		this.dragging._updatePosition = function() {
			var delta = this._newPos.subtract(map.latLngToContainerPoint(overlay._corners[0])),
				currentPoint, i;

			this.fire('predrag');

			for (i = 0; i < 4; i++) {
				currentPoint = map.latLngToContainerPoint(overlay._corners[i]);
				overlay._corners[i] = map.containerPointToLatLng(currentPoint.add(delta));
			}
			overlay._reset();
			overlay.fire('update');

			this.fire('drag');
		};

		this.dragging.on('dragend', this._changeMode, this);
	},

	_showToolbar: function() {

	},

	// onclick: function() {
	// 	var map = this._map;

	// 	// first, delete existing buttons
	// 	$('#image-distort-transparency').parent().remove();
	// 	$('#image-distort-outline').parent().remove();
	// 	$('#image-distort-delete').parent().remove();

	// 	this.transparencyBtn = L.easyButton('fa-adjust',
	// 		 function () {
	// 			 var e = $('#'+$('#image-distort-outline')[0].getAttribute('parentImgId'))[0];
	// 			 if (e.opacity === 1) {
	// 				 L.setOpacity(e,0.7);
	// 				 e.setAttribute('opacity',0.7);
	// 			 } else {
	// 				 L.setOpacity(e,1);
	// 				 e.setAttribute('opacity',1);
	// 			 }
	// 		 },
	// 		'Toggle Image Transparency'
	// 	).getContainer(); //.children[0]

	// 	this.outlineBtn = L.easyButton('fa-square-o',
	// 																 function () {
	// 																	 this.scope.toggleOutline();
	// 																 },
	// 																 'Outline',
	// 																 map,
	// 																 this
	// 	);

	// 	this.deleteBtn = L.easyButton('fa-bitbucket',
	// 		function () {
	// 			map.removeLayer($(this.parentImgId));
	// 			for(var i=0; i < 4; i++) {
	// 				map.removeLayer(this.markers[i]);
	// 			}
	// 		},
	// 	 'Delete Image'
	// 	);
	// },

	toggleTransparency: function() {
		this.transparent = !this.transparent;
		if (this.transparent) {
			this.setOpacity(0.4);
		} else {
			this.setOpacity(1);
		}
	},

	toggleIsolate: function() {
		this.isolated = !this.isolated;
		if (this.isolated) {
			$.each($L.images,function(i,img) {
				img.hidden = false;
				img.setOpacity(1);
			});
		} else {
			$.each($L.images,function(i,img) {
				img.hidden = true;
				img.setOpacity(0);
			});
		}
		this.hidden = false;
		this.setOpacity(1);
	},

	toggleVisibility: function() {
		this.hidden = !this.hidden;
		if (this.hidden) {
			this.setOpacity(1);
		} else {
			this.setOpacity(0);
		}
	},

	// This overlaps somewhat with the changeMode() method.
	// Could consolidate.
	lock: function() {
		this.locked = true;
		this.off('dragstart');
		this.off('drag');
		this.draggable.disable();
		this.changeMode('locked');
	},

	unlock: function() {
		this.locked = false;
		this.draggable.enable();
		this.changeMode('distort');
	},

	deselect: function() {
		$L.selected = false;
		for (var i in this.markers) {
			// this isn't a good way to hide markers:
			this._overlay._map.removeLayer(this.markers[i]);
		}
		if (this.outlineBtn) {
			// delete existing buttons
			this.outlineBtn._container.remove();
			this.transparencyBtn._container.remove();
			this.deleteBtn._container.remove();
		}
		this.onDeselect();
	},

	select: function() {
		// deselect other images
		$.each($L.images,function(i,d) {
			d.deselect.apply(d);
		});

		// re-establish order
		$L.impose_order();
		$L.selected = this;
		// show corner markers
		for (var i in this.markers) {
			this.markers[i].addTo(this._overlay._map);
		}

		// create buttons
		this.transparencyBtn = L.easyButton('fa-adjust',
			L.bind(function() { this.toggleTransparency(); }, this),
			'Toggle Image Transparency',
			this._overlay._map,
			this
		);

		this.outlineBtn = L.easyButton('fa-square-o',
			L.bind(function() { this.toggleOutline(); }, this),
			'Outline',
			this._overlay._map,
			this
		);

		this.deleteBtn = L.easyButton('fa-bitbucket',
			L.bind(function () {
				this._overlay._map.removeLayer($(this.parentImgId));
				for (var i = 0; i < 4; i++) {
					this._overlay._map.removeLayer(this.markers[i]);
				}
			}, this),
		'Delete Image');

		this.bringToFront();
		this.onSelect();
	},

	toggleOutline: function() {
		this.outlined = !this.outlined;
		if (this.outlined) {
			this.setOpacity(0.4);
			$(this._image).css('border','1px solid red');
		} else {
			this.setOpacity(1);
			$(this._image).css('border', 'none');
		}
	}
});

L.DistortableImageOverlay.addInitHook(function() {
	this.editing = new L.DistortableImage.Edit(this);

	if (this.options.editable) {
		L.DomEvent.on(this._image, 'load', this.editing.enable, this.editing);
	}
});<commit_msg>Rename #_changeMode to #_toggleMode.<commit_after>L.DistortableImage = L.DistortableImage || {};

L.DistortableImage.Edit = L.Handler.extend({
	initialize: function(overlay) {
		this._overlay = overlay;
		this._mode = 0; // warp
	},

	addHooks: function() {
		var overlay = this._overlay,
			map = overlay._map,
			i;

		this._warpHandles = new L.LayerGroup();
		for (i = 0; i < 4; i++) {
			this._warpHandles.addLayer(new L.WarpHandle(overlay, i));
		}

		this._rotateHandles = new L.LayerGroup();
		for (i = 0; i < 4; i++) {
			this._rotateHandles.addLayer(new L.RotateHandle(overlay, i));
		}

		this._handles = [this._warpHandles, this._rotateHandles];

		/* TODO: Tell L.Draggable how to find the position of the image. */
		this._enableDragging();

		map.addLayer(this._warpHandles);

		/* TODO: Why doesn't this._overlay.on('click') work? */
		L.DomEvent.on(this._overlay._image, 'click', this._toggleMode, this);
		L.DomEvent.on(this._overlay._image, 'click', this._showToolbar, this);
	},

	_toggleMode: function() {
		var map = this._overlay._map;

		map.removeLayer(this._handles[this._mode]);

		/* Switch mode. */
		this._mode = (this._mode + 1) % 2;

		map.addLayer(this._handles[this._mode]);
	},

	removeHooks: function() {
		var map = this._overlay._map;

		map.removeLayer(this._handles[this._mode]);
	},

	_rotateBy: function(angle) {
		var overlay = this._overlay,
			map = overlay._map,
			center = map.latLngToLayerPoint(overlay.getCenter()),
			i, p, q;

		for (i = 0; i < 4; i++) {
			p = map.latLngToLayerPoint(overlay._corners[i]).subtract(center);
			q = new L.Point(
				Math.cos(angle)*p.x - Math.sin(angle)*p.y,
				Math.sin(angle)*p.x + Math.cos(angle)*p.y
			);
			overlay._corners[i] = map.layerPointToLatLng(q.add(center));
		}

		overlay._reset();
	},

	_scaleBy: function(scale) {
		var overlay = this._overlay,
			map = overlay._map,
			center = map.latLngToLayerPoint(overlay.getCenter()),
			i, p;

		for (i = 0; i < 4; i++) {
			p = map.latLngToLayerPoint(overlay._corners[i])
				.subtract(center)
				.multiplyBy(scale)
				.add(center);
			overlay._corners[i] = map.layerPointToLatLng(p);
		}

		overlay._reset();
	},

	_enableDragging: function() {
		var overlay = this._overlay,
			map = overlay._map;

		this.dragging = new L.Draggable(overlay._image);
		this.dragging.enable();

		/*
		 * Adjust default behavior of L.Draggable.
	     * By default, L.Draggable overwrites the CSS3 warp transform
	     *     that we want when it calls L.DomUtil.setPosition.
		 */
		this.dragging._updatePosition = function() {
			var delta = this._newPos.subtract(map.latLngToContainerPoint(overlay._corners[0])),
				currentPoint, i;

			this.fire('predrag');

			for (i = 0; i < 4; i++) {
				currentPoint = map.latLngToContainerPoint(overlay._corners[i]);
				overlay._corners[i] = map.containerPointToLatLng(currentPoint.add(delta));
			}
			overlay._reset();
			overlay.fire('update');

			this.fire('drag');
		};

		this.dragging.on('dragend', this._toggleMode, this);
	},

	_showToolbar: function() {

	},

	// onclick: function() {
	// 	var map = this._map;

	// 	// first, delete existing buttons
	// 	$('#image-distort-transparency').parent().remove();
	// 	$('#image-distort-outline').parent().remove();
	// 	$('#image-distort-delete').parent().remove();

	// 	this.transparencyBtn = L.easyButton('fa-adjust',
	// 		 function () {
	// 			 var e = $('#'+$('#image-distort-outline')[0].getAttribute('parentImgId'))[0];
	// 			 if (e.opacity === 1) {
	// 				 L.setOpacity(e,0.7);
	// 				 e.setAttribute('opacity',0.7);
	// 			 } else {
	// 				 L.setOpacity(e,1);
	// 				 e.setAttribute('opacity',1);
	// 			 }
	// 		 },
	// 		'Toggle Image Transparency'
	// 	).getContainer(); //.children[0]

	// 	this.outlineBtn = L.easyButton('fa-square-o',
	// 																 function () {
	// 																	 this.scope.toggleOutline();
	// 																 },
	// 																 'Outline',
	// 																 map,
	// 																 this
	// 	);

	// 	this.deleteBtn = L.easyButton('fa-bitbucket',
	// 		function () {
	// 			map.removeLayer($(this.parentImgId));
	// 			for(var i=0; i < 4; i++) {
	// 				map.removeLayer(this.markers[i]);
	// 			}
	// 		},
	// 	 'Delete Image'
	// 	);
	// },

	toggleTransparency: function() {
		this.transparent = !this.transparent;
		if (this.transparent) {
			this.setOpacity(0.4);
		} else {
			this.setOpacity(1);
		}
	},

	toggleIsolate: function() {
		this.isolated = !this.isolated;
		if (this.isolated) {
			$.each($L.images,function(i,img) {
				img.hidden = false;
				img.setOpacity(1);
			});
		} else {
			$.each($L.images,function(i,img) {
				img.hidden = true;
				img.setOpacity(0);
			});
		}
		this.hidden = false;
		this.setOpacity(1);
	},

	toggleVisibility: function() {
		this.hidden = !this.hidden;
		if (this.hidden) {
			this.setOpacity(1);
		} else {
			this.setOpacity(0);
		}
	},

	// This overlaps somewhat with the changeMode() method.
	// Could consolidate.
	lock: function() {
		this.locked = true;
		this.off('dragstart');
		this.off('drag');
		this.draggable.disable();
		this.changeMode('locked');
	},

	unlock: function() {
		this.locked = false;
		this.draggable.enable();
		this.changeMode('distort');
	},

	deselect: function() {
		$L.selected = false;
		for (var i in this.markers) {
			// this isn't a good way to hide markers:
			this._overlay._map.removeLayer(this.markers[i]);
		}
		if (this.outlineBtn) {
			// delete existing buttons
			this.outlineBtn._container.remove();
			this.transparencyBtn._container.remove();
			this.deleteBtn._container.remove();
		}
		this.onDeselect();
	},

	select: function() {
		// deselect other images
		$.each($L.images,function(i,d) {
			d.deselect.apply(d);
		});

		// re-establish order
		$L.impose_order();
		$L.selected = this;
		// show corner markers
		for (var i in this.markers) {
			this.markers[i].addTo(this._overlay._map);
		}

		// create buttons
		this.transparencyBtn = L.easyButton('fa-adjust',
			L.bind(function() { this.toggleTransparency(); }, this),
			'Toggle Image Transparency',
			this._overlay._map,
			this
		);

		this.outlineBtn = L.easyButton('fa-square-o',
			L.bind(function() { this.toggleOutline(); }, this),
			'Outline',
			this._overlay._map,
			this
		);

		this.deleteBtn = L.easyButton('fa-bitbucket',
			L.bind(function () {
				this._overlay._map.removeLayer($(this.parentImgId));
				for (var i = 0; i < 4; i++) {
					this._overlay._map.removeLayer(this.markers[i]);
				}
			}, this),
		'Delete Image');

		this.bringToFront();
		this.onSelect();
	},

	toggleOutline: function() {
		this.outlined = !this.outlined;
		if (this.outlined) {
			this.setOpacity(0.4);
			$(this._image).css('border','1px solid red');
		} else {
			this.setOpacity(1);
			$(this._image).css('border', 'none');
		}
	}
});

L.DistortableImageOverlay.addInitHook(function() {
	this.editing = new L.DistortableImage.Edit(this);

	if (this.options.editable) {
		L.DomEvent.on(this._image, 'load', this.editing.enable, this.editing);
	}
});<|endoftext|>


<commit_before>import React from 'react';
import { sendMessage } from './messageActions';

let myInput;

export default ({ dispatch }) => {
  return (
    <input
      type="text"
      ref={ (ref) => myInput = ref }
      onKeyUp={ ({ keyCode }) => {
        if(keyCode === 13) {
          dispatch(sendMessage(myInput.value));
        }
      } }
    />
  );
};
<commit_msg>empty the text box after sending the msg<commit_after>import React from 'react';
import { sendMessage } from './messageActions';

let myInput;

export default ({ dispatch }) => {
  return (
    <input
      type="text"
      ref={ (ref) => myInput = ref }
      onKeyUp={ ({ keyCode }) => {
        if(keyCode === 13) {
          dispatch(sendMessage(myInput.value));
          myInput.value = '';
        }
      } }
    />
  );
};
<|endoftext|>


<commit_before>'use strict';

var choiceId = 2; // used by the addChoice() function to keep track of IDs

function addElement(parentId, elementTag, elementId, html) {
    // Adds an element to the document
    var p = document.getElementById(parentId);
    var newElement = document.createElement(elementTag);
    newElement.setAttribute('id', elementId);
    newElement.innerHTML = html;
    p.appendChild(newElement);
}

function removeElement(elementId) {
    // Removes an element from the document
    console.log(elementId);
    var element = document.getElementById(elementId);
    element.removeChild(element);
}

function addChoice() {
    choiceId++; // increment fileId to get a unique ID for the new element
    var html = 'Choice ' + choiceId + ':
<input type="text" id="choice' + choiceId + '"><button type = "button" onclick="removeElement(choice' + choiceId + '); return false;">Remove</button>
';
    addElement('createpoll', 'b', 'choice' + choiceId, html);
};

<commit_msg>add poll choices<commit_after>'use strict';

var choiceId = 2; // used by the addChoice() function to keep track of IDs

function addElement(parentId, elementTag, elementId, html) {
    // Adds an element to the document
    var p = document.getElementById(parentId);
    var newElement = document.createElement(elementTag);
    newElement.setAttribute('id', elementId);
    newElement.innerHTML = html;
    p.appendChild(newElement);
}

function removeElement(elementId) {
    // Removes an element from the document
    console.log(elementId);
    var element = document.getElementById(elementId);
    console.log(element);
    element.removeChild(element);
}

function addChoice() {
    choiceId++; // increment fileId to get a unique ID for the new element
    var html = 'Choice ' + choiceId + ':
<input type="text" id="choice' + choiceId + '"><button type = "button" onclick="removeElement(choice' + choiceId + '); return false;">Remove</button>
';
    addElement('createpoll', 'b', 'choice' + choiceId, html);
};

<|endoftext|>


<commit_before>define(['app', 'text!./km-document-validation.html'], function(app, template) { 'use strict';

	app.directive('kmDocumentValidation', ["$timeout", function ($timeout)
	{
		return {
			restrict: 'EAC',
			template: template,
			replace: true,
			transclude: true,
			require : "?^mdTabs",
			scope: {
				report : '=ngModel',
			},
			link: function ($scope, $element, attribs, mdTabsCtrl) {

				//====================
				//
				//====================
				function lookup(field){

					return $element.parents("form[name='editForm']:first").find("label[for='" + field + "']:first");
				}

				//====================
				//
				//====================
				$scope.jumpTo = function(field) {

					if(!mdTabsCtrl) {
						return;
					}

					var qLabel = lookup(field);
					var tabId  = qLabel.parents("md-tab-content:first").attr("id") || "";

					var tabIndex = parseInt(tabId.replace(/.*-(\d+)$/, "$1"))-1;

					if(tabIndex>=0)
					{
						mdTabsCtrl.select(tabIndex);

						var qBody = $element.parents("body:last");

						$timeout(function jumpTo(){
							qBody.stop().animate({ scrollTop : qLabel.offset().top-50 }, 300);
						},100);
					}
				};

				//====================
				//
				//====================
				$scope.getLabel = function(field) {

					var qLabel = lookup(field);

					if (qLabel.size() != 0)// jshint ignore:line
						return qLabel.text();

					return field;
				};

				//====================
				//
				//====================
				$scope.isValid = function() {
					return $scope.report && (!$scope.report.errors || $scope.report.errors.length == 0);// jshint ignore:line
				};

				//====================
				//
				//====================
				$scope.hasErrors = function() {
					return $scope.report && $scope.report.errors && $scope.report.errors.length != 0;// jshint ignore:line
				};

				//====================
				//
				//====================
				$scope.getTranslation = function(code) {
					if (code==null || code==""            ) return "Unknown error"; // jshint ignore:line
					if (code == "Error.Mandatory"         ) return "Field is mandatory";
					if (code == "Error.InvalidValue"      ) return "The value specified is invalid";
					if (code == "Error.InvalidProperty"   ) return "This value cannot be specified";
					if (code == "Error.UnspecifiedLocale" ) return "A language is use but not speficied in your document";
					if (code == "Error.UnexpectedTerm"    ) return "A specified term cannot be used";
					if (code == "Error.InvalidType"       ) return "The fields type is invalid";
					return code;
				};
			}
		};
	}]);

});
<commit_msg>Fix label not always found<commit_after>define(['app', 'text!./km-document-validation.html'], function(app, template) { 'use strict';

	app.directive('kmDocumentValidation', ["$timeout", function ($timeout)
	{
		return {
			restrict: 'EAC',
			template: template,
			replace: true,
			transclude: true,
			require : "?^mdTabs",
			scope: {
				report : '=ngModel',
			},
			link: function ($scope, $element, attribs, mdTabsCtrl) {

				//====================
				//
				//====================
				function lookup(field){

					return $element.parents('body').find('form[name="editForm"]:first').find('label[for="' + field + '"]:first');
				}

				//====================
				//
				//====================
				$scope.jumpTo = function(field) {

					if(!mdTabsCtrl) {
						return;
					}

					var qLabel = lookup(field);
					var tabId  = qLabel.parents("md-tab-content:first").attr("id") || "";

					var tabIndex = parseInt(tabId.replace(/.*-(\d+)$/, "$1"))-1;

					if(tabIndex>=0)
					{
						mdTabsCtrl.select(tabIndex);

						var qBody = $element.parents("body:last");

						$timeout(function jumpTo(){
							qBody.stop().animate({ scrollTop : qLabel.offset().top-50 }, 300);
						},100);
					}
				};

				//====================
				//
				//====================
				$scope.getLabel = function(field) {

					var qLabel = lookup(field);

					if (qLabel.size() != 0)// jshint ignore:line
						return qLabel.text();

					return field;
				};

				//====================
				//
				//====================
				$scope.isValid = function() {
					return $scope.report && (!$scope.report.errors || $scope.report.errors.length == 0);// jshint ignore:line
				};

				//====================
				//
				//====================
				$scope.hasErrors = function() {
					return $scope.report && $scope.report.errors && $scope.report.errors.length != 0;// jshint ignore:line
				};

				//====================
				//
				//====================
				$scope.getTranslation = function(code) {
					if (code==null || code==""            ) return "Unknown error"; // jshint ignore:line
					if (code == "Error.Mandatory"         ) return "Field is mandatory";
					if (code == "Error.InvalidValue"      ) return "The value specified is invalid";
					if (code == "Error.InvalidProperty"   ) return "This value cannot be specified";
					if (code == "Error.UnspecifiedLocale" ) return "A language is use but not speficied in your document";
					if (code == "Error.UnexpectedTerm"    ) return "A specified term cannot be used";
					if (code == "Error.InvalidType"       ) return "The fields type is invalid";
					return code;
				};
			}
		};
	}]);

});
<|endoftext|>


<commit_before>import { PureComponent, createElement } from 'react';
import { withRouter } from 'react-router';

import PropTypes from 'prop-types';

import googleImage from 'assets/partners/google.png';
import ndcImage from 'assets/partners/ndcp.png';
import wriImage from 'assets/partners/wri_simple.png';
import climateAnalyticsImage from 'assets/partners/climate-analytics.png';
import climateActionTrackerImage from 'assets/partners/climate-action-tracker.png';
import worldBankImage from 'assets/partners/the-world-bank_simple.png';
import ccImage from 'assets/partners/unfccc_simple.jpg';
import gizImage from 'assets/partners/giz_simple.png';
import actsImage from 'assets/partners/acts_simple.png';
import dieImage from 'assets/partners/die_simple.jpg';
import seiImage from 'assets/partners/sei.png';

import Component from './footer-component';

const basePartners = [
  {
    link: 'http://climateactiontracker.org/',
    orderingString: 'action',
    img: {
      alt: 'Climate action',
      src: climateActionTrackerImage,
      customClass: 'rectangular'
    }
  },
  {
    link: 'http://climateanalytics.org/',
    orderingString: 'analytics',
    img: {
      alt: 'Climate analytics',
      src: climateAnalyticsImage,
      customClass: 'narrow'
    }
  },
  {
    link: 'https://www.giz.de/en/html/index.html',
    orderingString: 'giz',
    img: {
      alt: 'Giz',
      src: gizImage
    }
  },
  {
    link: 'http://www.ndcpartnership.org/',
    orderingString: 'ndc',
    img: {
      alt: 'NDC Partnership',
      src: ndcImage,
      customClass: 'narrow'
    }
  },
  {
    link: 'http://newsroom.unfccc.int/',
    orderingString: 'unfcc',
    img: {
      alt: 'UNFCCC',
      src: ccImage,
      customClass: 'rectangular'
    }
  },
  {
    link: 'http://www.worldbank.org/',
    orderingString: 'worldbank',
    img: {
      alt: 'The world bank',
      src: worldBankImage
    }
  },
  {
    link: 'http://www.wri.org/',
    orderingString: 'worldresources',
    img: {
      alt: 'WRI',
      src: wriImage
    }
  }
];

const ndcPartners = [
  {
    link: 'http://www.acts-net.org/',
    orderingString: 'acts',
    img: {
      alt: 'African Center for Technology Studies',
      src: actsImage,
      customClass: 'rectangular'
    }
  },
  {
    link: 'https://www.sei-international.org/',
    orderingString: 'sei',
    img: {
      alt: 'Stockholm Environment Institute',
      src: seiImage,
      customClass: 'narrower'
    }
  },
  {
    link: 'https://www.die-gdi.de',
    orderingString: 'gdi',
    img: {
      alt: 'German Development Institute',
      src: dieImage,
      customClass: 'rectangular'
    }
  }
];

const espPartners = [
  {
    link: 'https://www.google.com/intl/en/about/',
    orderingString: 'google',
    img: {
      alt: 'Google',
      src: googleImage,
      customClass: 'narrow'
    }
  }
];

const alphabetically = (a, b) => {
  if (a.orderingString < b.orderingString) return -1;
  if (a.orderingString > b.orderingString) return 1;
  return 0;
};

const parsedPath = pathname => {
  if (pathname === '/ghg-emissions' || pathname === '/ndcs-sdg') {
    return 'ghg & ndcs-sdg';
  }
  if (pathname.includes('/countries') || pathname.includes('/ndcs')) {
    return 'countries & ndcs';
  }
  if (pathname.includes('/pathways')) return 'pathways';
  return 'default';
};

const getLogos = pathname => {
  const path = parsedPath(pathname);
  switch (path) {
    case 'ghg & ndcs-sdg':
      return [...basePartners];
    case 'countries & ndcs':
      return [...basePartners, ...ndcPartners].sort(alphabetically);
    case 'pathways':
      return [...basePartners, ...espPartners].sort(alphabetically);
    default:
      return [...basePartners, ...ndcPartners, ...espPartners].sort(
        alphabetically
      );
  }
};

class FooterContainer extends PureComponent {
  render() {
    const partners = getLogos(this.props.location.pathname);
    const includePartners = !location.pathname.includes('/about');
    return createElement(Component, {
      ...this.props,
      partners,
      includePartners
    });
  }
}

FooterContainer.propTypes = {
  location: PropTypes.object
};

export default withRouter(FooterContainer);
<commit_msg>Replace simple version of logos in the footer<commit_after>import { PureComponent, createElement } from 'react';
import { withRouter } from 'react-router';

import PropTypes from 'prop-types';

import googleImage from 'assets/partners/google.png';
import ndcImage from 'assets/partners/ndcp.png';
import wriImage from 'assets/partners/wri.png';
import climateAnalyticsImage from 'assets/partners/climate-analytics.png';
import climateActionTrackerImage from 'assets/partners/climate-action-tracker.png';
import worldBankImage from 'assets/partners/the-world-bank.png';
import ccImage from 'assets/partners/unfccc.jpg';
import gizImage from 'assets/partners/giz.png';
import actsImage from 'assets/partners/acts.png';
import dieImage from 'assets/partners/die.jpg';
import seiImage from 'assets/partners/sei.png';

import Component from './footer-component';

const basePartners = [
  {
    link: 'http://climateactiontracker.org/',
    orderingString: 'action',
    img: {
      alt: 'Climate action',
      src: climateActionTrackerImage,
      customClass: 'narrow'
    }
  },
  {
    link: 'http://climateanalytics.org/',
    orderingString: 'analytics',
    img: {
      alt: 'Climate analytics',
      src: climateAnalyticsImage,
      customClass: 'narrow'
    }
  },
  {
    link: 'https://www.giz.de/en/html/index.html',
    orderingString: 'giz',
    img: {
      alt: 'Giz',
      src: gizImage,
      customClass: 'narrower'
    }
  },
  {
    link: 'http://www.ndcpartnership.org/',
    orderingString: 'ndc',
    img: {
      alt: 'NDC Partnership',
      src: ndcImage,
      customClass: 'narrow'
    }
  },
  {
    link: 'http://newsroom.unfccc.int/',
    orderingString: 'unfcc',
    img: {
      alt: 'UNFCCC',
      src: ccImage,
      customClass: 'narrower'
    }
  },
  {
    link: 'http://www.worldbank.org/',
    orderingString: 'worldbank',
    img: {
      alt: 'The World Bank',
      src: worldBankImage,
      customClass: 'narrower'
    }
  },
  {
    link: 'http://www.wri.org/',
    orderingString: 'worldresources',
    img: {
      alt: 'WRI',
      src: wriImage,
      customClass: 'narrower'
    }
  }
];

const ndcPartners = [
  {
    link: 'http://www.acts-net.org/',
    orderingString: 'acts',
    img: {
      alt: 'African Center for Technology Studies',
      src: actsImage,
      customClass: 'narrow'
    }
  },
  {
    link: 'https://www.sei-international.org/',
    orderingString: 'sei',
    img: {
      alt: 'Stockholm Environment Institute',
      src: seiImage,
      customClass: 'narrower'
    }
  },
  {
    link: 'https://www.die-gdi.de',
    orderingString: 'gdi',
    img: {
      alt: 'German Development Institute',
      src: dieImage,
      customClass: 'narrower'
    }
  }
];

const espPartners = [
  {
    link: 'https://www.google.com/intl/en/about/',
    orderingString: 'google',
    img: {
      alt: 'Google',
      src: googleImage,
      customClass: 'narrow'
    }
  }
];

const alphabetically = (a, b) => {
  if (a.orderingString < b.orderingString) return -1;
  if (a.orderingString > b.orderingString) return 1;
  return 0;
};

const parsedPath = pathname => {
  if (pathname === '/ghg-emissions' || pathname === '/ndcs-sdg') {
    return 'ghg & ndcs-sdg';
  }
  if (pathname.includes('/countries') || pathname.includes('/ndcs')) {
    return 'countries & ndcs';
  }
  if (pathname.includes('/pathways')) return 'pathways';
  return 'default';
};

const getLogos = pathname => {
  const path = parsedPath(pathname);
  switch (path) {
    case 'ghg & ndcs-sdg':
      return [...basePartners];
    case 'countries & ndcs':
      return [...basePartners, ...ndcPartners].sort(alphabetically);
    case 'pathways':
      return [...basePartners, ...espPartners].sort(alphabetically);
    default:
      return [...basePartners, ...ndcPartners, ...espPartners].sort(
        alphabetically
      );
  }
};

class FooterContainer extends PureComponent {
  render() {
    const partners = getLogos(this.props.location.pathname);
    const includePartners = !location.pathname.includes('/about');
    return createElement(Component, {
      ...this.props,
      partners,
      includePartners
    });
  }
}

FooterContainer.propTypes = {
  location: PropTypes.object
};

export default withRouter(FooterContainer);
<|endoftext|>


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

  angular
    .module('Portfolio')
    .factory('projectData', projectData);

  projectData.$inject = ['$http'];

  /* @ngInject */
  function projectData($http) {
    var service = {
      all: getAll,
      getFirst: getFirst
    };

    return service;

    function getAll() {
      return $http({
        method: 'GET',
        url: 'data/projects.json'
      });
    }

    // ----- EXPERIMENTAL RAILS API -----
    // function getFirst() {
    //     return $http({
    //         method: 'GET',
    //         url: 'http://localhost:3000/contacts/1'
    //     });
    // }
  }
})();
<commit_msg>forgot to comment small part out.<commit_after>(function() {
  'use strict';

  angular
    .module('Portfolio')
    .factory('projectData', projectData);

  projectData.$inject = ['$http'];

  /* @ngInject */
  function projectData($http) {
    var service = {
      all: getAll
    //   getFirst: getFirst // rails api.
    };

    return service;

    function getAll() {
      return $http({
        method: 'GET',
        url: 'data/projects.json'
      });
    }

    // ----- EXPERIMENTAL RAILS API -----
    // function getFirst() {
    //     return $http({
    //         method: 'GET',
    //         url: 'http://localhost:3000/contacts/1'
    //     });
    // }
  }
})();
<|endoftext|>


<commit_before>'use strict';

var servicesModule = require('./_index.js');

/**
 * @ngInject
 */
function FollowersMapTemplateService($filter) {

  var service = {};

  service.genStaticTwitterFollower = function(followers , i) {
    var result = "";

    result ='
'
            +   '
'
            +        ''
            +    '
'
            +     '
'
            +        '
'
            +            ''
            +            '
'
            +                ''+followers.name[i]+'
'
            +               '@'+followers.screenname[i]+''
            +            '
'
            +       '
'
            +       '
'
            +            '
'
            +               'Tweets
'+followers.tweetcount[i]+''
            +            '
'
            +            '
'
            +                'Followings
'+followers.following[i]+''
            +            '
'
            +            '
'
            +                'Followers
'+followers.followers[i]+''
            +            '
'
            +        '
'
            +    '
'
            +'
'

    return result;

  };
 service.genStaticTwitterFollowing = function(following , i) {
    var textstatus = $filter('tweetHashtag')($filter('tweetMention')($filter('tweetTextLink')(following.latesttweet[i])));
    var result = "";

    result = '
'
            +   '
'
            +        ''
            +    '
'
            +     '
'
            +        '
'
            +            ''
            +            '
'
            +                ''+following.name[i]+'
'
            +               '@'+following.screenname[i]+''
            +            '
'
            +       '
'
            +       '
'
            +'
'+textstatus+'
'
            +            '
'
            +               'Tweets
'+following.tweetcount[i]+''
            +            '
'
            +            '
'
            +                'Followings
'+following.following[i]+''
            +            '
'
            +            '
'
            +                'Followers
'+following.followers[i]+''
            +            '
'
            +        '
'
            +    '
'
            +'
'

    return result;

  };

  return service;

}

servicesModule.service('FollowersMapTemplateService', ['$filter', FollowersMapTemplateService]);
<commit_msg>Removed scroll added padding for tweet text<commit_after>'use strict';

var servicesModule = require('./_index.js');

/**
 * @ngInject
 */
function FollowersMapTemplateService($filter) {

  var service = {};

  service.genStaticTwitterFollower = function(followers , i) {
    var result = "";

    result ='
'
            +   '
'
            +        ''
            +    '
'
            +     '
'
            +        '
'
            +            ''
            +            '
'
            +                ''+followers.name[i]+'
'
            +               '@'+followers.screenname[i]+''
            +            '
'
            +       '
'
            +       '
'
            +            '
'
            +               'Tweets
'+followers.tweetcount[i]+''
            +            '
'
            +            '
'
            +                'Followings
'+followers.following[i]+''
            +            '
'
            +            '
'
            +                'Followers
'+followers.followers[i]+''
            +            '
'
            +        '
'
            +    '
'
            +'
'

    return result;

  };
 service.genStaticTwitterFollowing = function(following , i) {
    var textstatus = $filter('tweetHashtag')($filter('tweetMention')($filter('tweetTextLink')(following.latesttweet[i])));
    var result = "";

    result = '
'
            +   '
'
            +        ''
            +    '
'
            +     '
'
            +        '
'
            +            ''
            +            '
'
            +                ''+following.name[i]+'
'
            +               '@'+following.screenname[i]+''
            +            '
'
            +       '
'
            +       '
'
            +       '
'+textstatus+'
'
            +        '
'
            +       '
'
            +            '
'
            +               'Tweets
'+following.tweetcount[i]+''
            +            '
'
            +            '
'
            +                'Followings
'+following.following[i]+''
            +            '
'
            +            '
'
            +                'Followers
'+following.followers[i]+''
            +            '
'
            +        '
'
            +    '
'
            +'
'

    return result;

  };

  return service;

}

servicesModule.service('FollowersMapTemplateService', ['$filter', FollowersMapTemplateService]);
<|endoftext|>


<commit_before>import { shallow } from 'enzyme';
import React from 'react';
import assert from 'assert';
import FeaturedProject from './featured-project';

describe('FeaturedProject', () => {
  it('should render without crashing', () => {
    shallow(<FeaturedProject />);
  });

  it('should have a section as container', () => {
    const wrapper = shallow(<FeaturedProject />);
    assert.strictEqual(wrapper.type(), 'section');
  });

  it('should have an h1 tag containing the text "Featured Project"', () => {
    const wrapper = shallow(<FeaturedProject />);
    const title = wrapper.find('h1');
    assert.strictEqual(title.contains(
Featured Project
), true);
  });

  it('should have an img tag with src and alt properties', () => {
    const wrapper = shallow(<FeaturedProject />);
    const { alt, src } = wrapper.find('img').props();
    assert.equal(wrapper.find('img').length, 1);
    assert.ok(alt.length > 0, 'alt attribute is empty');
    assert.ok(src.length > 0, 'src attribute is empty');
  });

  it('should have a link to the featured project', () => {
    const wrapper = shallow(<FeaturedProject />);
    assert.strictEqual(wrapper.find('Link').length, 1);
  });
});
<commit_msg>Account for Addition of Classname in Test<commit_after>import { shallow } from 'enzyme';
import React from 'react';
import assert from 'assert';
import FeaturedProject from './featured-project';

describe('FeaturedProject', () => {
  it('should render without crashing', () => {
    shallow(<FeaturedProject />);
  });

  it('should have a section as container', () => {
    const wrapper = shallow(<FeaturedProject />);
    assert.strictEqual(wrapper.type(), 'section');
  });

  it('should have an h1 tag containing the text "Featured Project"', () => {
    const wrapper = shallow(<FeaturedProject />);
    const title = wrapper.find('h1');
    assert.strictEqual(title.text(), 'Featured Project');
  });

  it('should have an img tag with src and alt properties', () => {
    const wrapper = shallow(<FeaturedProject />);
    const { alt, src } = wrapper.find('img').props();
    assert.equal(wrapper.find('img').length, 1);
    assert.ok(alt.length > 0, 'alt attribute is empty');
    assert.ok(src.length > 0, 'src attribute is empty');
  });

  it('should have a link to the featured project', () => {
    const wrapper = shallow(<FeaturedProject />);
    assert.strictEqual(wrapper.find('Link').length, 1);
  });
});
<|endoftext|>