<commit_before>// jqPlot doesn't work when chart_wrapper is inside a element that is hidden (display: none).
// Therefore, we have to move the .constraint_popup outside the view area (bottom: 8000px),
// and animate the shadowbox-outer to an opacity of 0.01, because fadeIn/fadeOut sets display: none at the end.

var ConstraintView = Backbone.View.extend({
  initialize : function() {
    _.bindAll(this, 'render', 'open_popup', 'render_total_cost_label');
    this.id = "constraint_"+this.model.get('id');
    this.dom_id = '#'+this.id;
    this.element = $(this.dom_id);
    this.arrow_element = $('.arrow', this.dom_id);

    this.element.bind('mousedown', this.open_popup);

    this.model.bind('change:result', this.render);
    this.model.view = this;
  },

  render : function() {
    if(this.model.get("key") == 'total_energy_cost') {
      this.render_total_cost_label();
    }
    var formatted_value = this.format_result();
    $('strong', this.dom_id).empty().append(formatted_value);
    this.updateArrows();
    return this;
  },

  // different behaviour unfortunately
  render_total_cost_label : function() {
    var value = this.model.get('result') * 1000000000;
    var scale = Metric.power_of_thousand(value);
    var unit  = I18n.t('units.currency.' + Metric.power_of_thousand_to_string(scale));
    var label = "(" + unit + ")";
    $('.header .sub_header', this.dom_id).html(label);
  },

  open_popup : function() {
    var constraint = $(this.dom_id);
    var constraint_id = this.model.get('id');
    var url = $(constraint).attr('href')+"?t="+timestamp();
    $(constraint).fancybox({
      'href' : url,
      'type' : 'iframe',
      height: 400,
      width: 600,
      padding: 0
    });
  },

  // Formats the result of calculate_result() for the end-user
  format_result : function() {
    var result = this.model.get('result');
    var key    = this.model.get('key');

    switch(key) {
      case 'total_energy_cost' :
        return Metric.euros_to_string(result * 1000000000);
      case 'household_energy_cost':
        return I18n.toCurrency(result, { precision: 0, unit: '€' });
      case 'total_primary_energy':
        // show + prefix if needed
        return Metric.ratio_as_percentage(result, true);
      case 'co2_reduction':
        return Metric.ratio_as_percentage(result, true);
      case 'net_energy_import':
        // 1 point precision
        return Metric.ratio_as_percentage(result, false, 1);
      case 'security_of_supply':
        return Metric.round_number(result, 1);
      case 'renewable_percentage':
        return Metric.ratio_as_percentage(result);
      case 'not_shown':
        // bio_footprint actually
        return '' + Metric.round_number(result, 1) +'x'+ App.settings.get("country").toUpperCase();
      case 'targets_met':
        return null;
      case 'score':
        return parseInt(result,10);
      default:
        return result;
    }
  },

  /**
   * Updates the arrows, if the difference is negative .
   * @param diff - the difference of old_value and new_value.
   */
  updateArrows : function() {
    diff = this.model.calculate_diff(this.model.get('result'),this.model.get('previous_result'));
    if (diff == undefined || diff == null) { return false; }
    var arrow_element = $('.arrow', this.dom_id);
    this.cleanArrows();
    var newClass;
    if (diff > 0) { newClass = 'arrow_up';}
    else if(diff < 0) { newClass = 'arrow_down'; }
    else { newClass = 'arrow_neutral'; }

    arrow_element.addClass(newClass);
    arrow_element.css('opacity', 1.0);

    // make sure the arrows take their original form after 30 seconds
    Util.cancelableAction("updateArrows" + this.model.get('id'), $.proxy(function() {
      arrow_element.animate({opacity: 0.0}, 1000);
    }, this), {'sleepTime': 30000});
  },

  /**
   * Clean the arrwos
   */
  cleanArrows:function() {
    var arrow_element = $('.arrow', this.dom_id);
    arrow_element.removeClass('arrow_neutral');
    arrow_element.removeClass('arrow_down');
    arrow_element.removeClass('arrow_up');
  }

});
<commit_msg>dashboard: round blackout hours value. closes #537<commit_after>// jqPlot doesn't work when chart_wrapper is inside a element that is hidden (display: none).
// Therefore, we have to move the .constraint_popup outside the view area (bottom: 8000px),
// and animate the shadowbox-outer to an opacity of 0.01, because fadeIn/fadeOut sets display: none at the end.

var ConstraintView = Backbone.View.extend({
  initialize : function() {
    _.bindAll(this, 'render', 'open_popup', 'render_total_cost_label');
    this.id = "constraint_"+this.model.get('id');
    this.dom_id = '#'+this.id;
    this.element = $(this.dom_id);
    this.arrow_element = $('.arrow', this.dom_id);

    this.element.bind('mousedown', this.open_popup);

    this.model.bind('change:result', this.render);
    this.model.view = this;
  },

  render : function() {
    if(this.model.get("key") == 'total_energy_cost') {
      this.render_total_cost_label();
    }
    var formatted_value = this.format_result();
    $('strong', this.dom_id).empty().append(formatted_value);
    this.updateArrows();
    return this;
  },

  // different behaviour unfortunately
  render_total_cost_label : function() {
    var value = this.model.get('result') * 1000000000;
    var scale = Metric.power_of_thousand(value);
    var unit  = I18n.t('units.currency.' + Metric.power_of_thousand_to_string(scale));
    var label = "(" + unit + ")";
    $('.header .sub_header', this.dom_id).html(label);
  },

  open_popup : function() {
    var constraint = $(this.dom_id);
    var constraint_id = this.model.get('id');
    var url = $(constraint).attr('href')+"?t="+timestamp();
    $(constraint).fancybox({
      'href' : url,
      'type' : 'iframe',
      height: 400,
      width: 600,
      padding: 0
    });
  },

  // Formats the result of calculate_result() for the end-user
  format_result : function() {
    var result = this.model.get('result');
    var key    = this.model.get('key');

    switch(key) {
      case 'total_energy_cost' :
        return Metric.euros_to_string(result * 1000000000);
      case 'household_energy_cost':
        return I18n.toCurrency(result, { precision: 0, unit: '€' });
      case 'total_primary_energy':
        // show + prefix if needed
        return Metric.ratio_as_percentage(result, true);
      case 'co2_reduction':
        return Metric.ratio_as_percentage(result, true);
      case 'net_energy_import':
        // 1 point precision
        return Metric.ratio_as_percentage(result, false, 1);
      case 'security_of_supply':
        return Metric.round_number(result, 1);
      case 'renewable_percentage':
        return Metric.ratio_as_percentage(result);
      case 'not_shown':
        // bio_footprint actually
        return '' + Metric.round_number(result, 1) +'x'+ App.settings.get("country").toUpperCase();
      case 'targets_met':
        return null;
      case 'blackout_hours':
        return Metric.round_number(result, 0);
      case 'score':
        return parseInt(result,10);
      default:
        return result;
    }
  },

  /**
   * Updates the arrows, if the difference is negative .
   * @param diff - the difference of old_value and new_value.
   */
  updateArrows : function() {
    diff = this.model.calculate_diff(this.model.get('result'),this.model.get('previous_result'));
    if (diff == undefined || diff == null) { return false; }
    var arrow_element = $('.arrow', this.dom_id);
    this.cleanArrows();
    var newClass;
    if (diff > 0) { newClass = 'arrow_up';}
    else if(diff < 0) { newClass = 'arrow_down'; }
    else { newClass = 'arrow_neutral'; }

    arrow_element.addClass(newClass);
    arrow_element.css('opacity', 1.0);

    // make sure the arrows take their original form after 30 seconds
    Util.cancelableAction("updateArrows" + this.model.get('id'), $.proxy(function() {
      arrow_element.animate({opacity: 0.0}, 1000);
    }, this), {'sleepTime': 30000});
  },

  /**
   * Clean the arrwos
   */
  cleanArrows:function() {
    var arrow_element = $('.arrow', this.dom_id);
    arrow_element.removeClass('arrow_neutral');
    arrow_element.removeClass('arrow_down');
    arrow_element.removeClass('arrow_up');
  }

});
<|endoftext|>


<commit_before>// jqPlot doesn't work when chart_wrapper is inside a element that is hidden (display: none).
// Therefore, we have to move the .constraint_popup outside the view area (bottom: 8000px),
// and animate the shadowbox-outer to an opacity of 0.01, because fadeIn/fadeOut sets display: none at the end.

var ConstraintView = Backbone.View.extend({
  initialize : function() {
    _.bindAll(this, 'render', 'open_popup', 'render_total_cost_label');
    this.id = "constraint_"+this.model.get('id');
    this.dom_id = '#'+this.id;
    this.element = $(this.dom_id);
    this.arrow_element = $('.arrow', this.dom_id);

    this.element.bind('mousedown', this.open_popup);

    this.model.bind('change:result', this.render);
    this.model.view = this;
  },

  render : function() {
    if(this.model.get("key") == 'total_energy_cost') {
      this.render_total_cost_label();
    }
    var formatted_value = this.format_result();
    $('strong', this.dom_id).empty().append(formatted_value);
    this.updateArrows();
    return this;
  },

  // different behaviour unfortunately
  render_total_cost_label : function() {
    var value = this.model.get('result') * 1000000000;
    var scale = Metric.power_of_thousand(value);
    var unit  = I18n.t('units.currency.' + Metric.power_of_thousand_to_string(scale));
    var label = "(" + unit + ")";
    $('.header .sub_header', this.dom_id).html(label);
  },

  open_popup : function() {
    var constraint = $(this.dom_id);
    var constraint_id = this.model.get('id');
    var url = $(constraint).attr('href')+"?t="+timestamp();
    $(constraint).fancybox({
      'href' : url,
      'type' : 'iframe',
      height: 400,
      width: 600,
      padding: 0
    });
  },

  // Formats the result of calculate_result() for the end-user
  format_result : function() {
    var result = this.model.get('result');
    var key    = this.model.get('key');

    switch(key) {
      case 'total_energy_cost' :
        return Metric.euros_to_string(result * 1000000000);
      case 'household_energy_cost':
        return Metric.euros_to_string(result);
      case 'total_primary_energy':
        // show + prefix if needed
        return Metric.ratio_as_percentage(result, true);
      case 'co2_reduction':
        return Metric.ratio_as_percentage(result, true);
      case 'net_energy_import':
        // 1 point precision
        return Metric.ratio_as_percentage(result, false, 1);
      case 'renewable_percentage':
        return Metric.ratio_as_percentage(result);
      case 'not_shown':
        // bio_footprint actually
        return '' + Metric.round_number(result, 1) +'x'+ App.settings.get("country").toUpperCase();
      case 'targets_met':
        return null;
      case 'score':
        return parseInt(result,10);
      default:
        return result;
    }
  },

  /**
   * Updates the arrows, if the difference is negative .
   * @param diff - the difference of old_value and new_value.
   */
  updateArrows : function() {
    diff = this.model.calculate_diff(this.model.get('result'),this.model.get('previous_result'));
    if (diff == undefined || diff == null) { return false; }
    var arrow_element = $('.arrow', this.dom_id);
    this.cleanArrows();
    var newClass;
    if (diff > 0) { newClass = 'arrow_up';}
    else if(diff < 0) { newClass = 'arrow_down'; }
    else { newClass = 'arrow_neutral'; }

    arrow_element.addClass(newClass);
    arrow_element.css('opacity', 1.0);

    // make sure the arrows take their original form after 30 seconds
    Util.cancelableAction("updateArrows" + this.model.get('id'), $.proxy(function() {
      arrow_element.animate({opacity: 0.0}, 1000);
    }, this), {'sleepTime': 30000});
  },

  /**
   * Clean the arrwos
   */
  cleanArrows:function() {
    var arrow_element = $('.arrow', this.dom_id);
    arrow_element.removeClass('arrow_neutral');
    arrow_element.removeClass('arrow_down');
    arrow_element.removeClass('arrow_up');
  }

});
<commit_msg>Don't lose significant figures in household cost.<commit_after>// jqPlot doesn't work when chart_wrapper is inside a element that is hidden (display: none).
// Therefore, we have to move the .constraint_popup outside the view area (bottom: 8000px),
// and animate the shadowbox-outer to an opacity of 0.01, because fadeIn/fadeOut sets display: none at the end.

var ConstraintView = Backbone.View.extend({
  initialize : function() {
    _.bindAll(this, 'render', 'open_popup', 'render_total_cost_label');
    this.id = "constraint_"+this.model.get('id');
    this.dom_id = '#'+this.id;
    this.element = $(this.dom_id);
    this.arrow_element = $('.arrow', this.dom_id);

    this.element.bind('mousedown', this.open_popup);

    this.model.bind('change:result', this.render);
    this.model.view = this;
  },

  render : function() {
    if(this.model.get("key") == 'total_energy_cost') {
      this.render_total_cost_label();
    }
    var formatted_value = this.format_result();
    $('strong', this.dom_id).empty().append(formatted_value);
    this.updateArrows();
    return this;
  },

  // different behaviour unfortunately
  render_total_cost_label : function() {
    var value = this.model.get('result') * 1000000000;
    var scale = Metric.power_of_thousand(value);
    var unit  = I18n.t('units.currency.' + Metric.power_of_thousand_to_string(scale));
    var label = "(" + unit + ")";
    $('.header .sub_header', this.dom_id).html(label);
  },

  open_popup : function() {
    var constraint = $(this.dom_id);
    var constraint_id = this.model.get('id');
    var url = $(constraint).attr('href')+"?t="+timestamp();
    $(constraint).fancybox({
      'href' : url,
      'type' : 'iframe',
      height: 400,
      width: 600,
      padding: 0
    });
  },

  // Formats the result of calculate_result() for the end-user
  format_result : function() {
    var result = this.model.get('result');
    var key    = this.model.get('key');

    switch(key) {
      case 'total_energy_cost' :
        return Metric.euros_to_string(result * 1000000000);
      case 'household_energy_cost':
        return '€' + Math.round(result);
      case 'total_primary_energy':
        // show + prefix if needed
        return Metric.ratio_as_percentage(result, true);
      case 'co2_reduction':
        return Metric.ratio_as_percentage(result, true);
      case 'net_energy_import':
        // 1 point precision
        return Metric.ratio_as_percentage(result, false, 1);
      case 'renewable_percentage':
        return Metric.ratio_as_percentage(result);
      case 'not_shown':
        // bio_footprint actually
        return '' + Metric.round_number(result, 1) +'x'+ App.settings.get("country").toUpperCase();
      case 'targets_met':
        return null;
      case 'score':
        return parseInt(result,10);
      default:
        return result;
    }
  },

  /**
   * Updates the arrows, if the difference is negative .
   * @param diff - the difference of old_value and new_value.
   */
  updateArrows : function() {
    diff = this.model.calculate_diff(this.model.get('result'),this.model.get('previous_result'));
    if (diff == undefined || diff == null) { return false; }
    var arrow_element = $('.arrow', this.dom_id);
    this.cleanArrows();
    var newClass;
    if (diff > 0) { newClass = 'arrow_up';}
    else if(diff < 0) { newClass = 'arrow_down'; }
    else { newClass = 'arrow_neutral'; }

    arrow_element.addClass(newClass);
    arrow_element.css('opacity', 1.0);

    // make sure the arrows take their original form after 30 seconds
    Util.cancelableAction("updateArrows" + this.model.get('id'), $.proxy(function() {
      arrow_element.animate({opacity: 0.0}, 1000);
    }, this), {'sleepTime': 30000});
  },

  /**
   * Clean the arrwos
   */
  cleanArrows:function() {
    var arrow_element = $('.arrow', this.dom_id);
    arrow_element.removeClass('arrow_neutral');
    arrow_element.removeClass('arrow_down');
    arrow_element.removeClass('arrow_up');
  }

});
<|endoftext|>


<commit_before>'use strict';
angular.module('arethusa.core').directive('resizable', [
  '$window',
  '$document',
  function ($window, $document) {
    return {
      restrict: 'AEC',
      link: function (scope, element, attrs) {
        var maxSize = $window.innerWidth;
        var maxPos = maxSize - 400;
        var main = angular.element(document.getElementById('main-body'));
        var win = angular.element($window);

        element.on('mousedown', function (event) {
          event.preventDefault();
          $document.on('mousemove', mousemove);
          $document.on('mouseup', mouseup);
        });

        // This is very unstable and chaotic.
        // We substract 0.5 in the last step to deal with a viewport with
        // a width that is not a round number.
        // There is a possibility that the divs that are resized shrinked by
        // this though.
        //
        // A better solution might be to really recompute the size of
        // the resized diffs - right now we are moving them around step
        // by step.
        function mousemove(event) {
          var x = Math.floor(event.pageX);
          var el = element.parent();
          var leftPos = Math.round(el.position().left);
          var width = Math.round(el.width());
          var border = leftPos + width;
          var diff = x - leftPos;
          var newSize = width - diff;
          el.width(newSize);
          main.width(main.width() + diff - 0.5);
        }

        function mouseup() {
          win.trigger('resize');
          $document.unbind('mousemove', mousemove);
          $document.unbind('mouseup', mouseup);
        }
      }
    };
  }
]);
<commit_msg>Delete cover-up value in resizable directive<commit_after>'use strict';
angular.module('arethusa.core').directive('resizable', [
  '$window',
  '$document',
  function ($window, $document) {
    return {
      restrict: 'AEC',
      link: function (scope, element, attrs) {
        var maxSize = $window.innerWidth;
        var maxPos = maxSize - 400;
        var main = angular.element(document.getElementById('main-body'));
        var win = angular.element($window);

        element.on('mousedown', function (event) {
          event.preventDefault();
          $document.on('mousemove', mousemove);
          $document.on('mouseup', mouseup);
        });

        // This is very unstable and chaotic.
        // We substract 0.5 in the last step to deal with a viewport with
        // a width that is not a round number.
        // There is a possibility that the divs that are resized shrinked by
        // this though.
        //
        // A better solution might be to really recompute the size of
        // the resized diffs - right now we are moving them around step
        // by step.
        function mousemove(event) {
          var x = Math.floor(event.pageX);
          var el = element.parent();
          var leftPos = Math.round(el.position().left);
          var width = Math.round(el.width());
          var border = leftPos + width;
          var diff = x - leftPos;
          var newSize = width - diff;
          el.width(newSize);
          main.width(main.width() + diff);
        }

        function mouseup() {
          win.trigger('resize');
          $document.unbind('mousemove', mousemove);
          $document.unbind('mouseup', mouseup);
        }
      }
    };
  }
]);
<|endoftext|>


<commit_before>app.directive("paginationButtons", function() {
  return {
    templateUrl: 'views/directives/paginationButtons.html',
    restrict: 'E',
    $scope: {
      'pageSettings': '='
    },
    link: function($scope, element, attr) {

      $scope.pages = [];

      element.on('click', function(elem) {
        var target = $(elem.target);
        if (target.find(">:first-child").is("input")) {
          $scope.$apply(function() {
            $scope.pageSettings.pageSize = target.find("input")[0].id;
          });
        } else if (target.hasClass("btn")) {
          $scope.$apply(function() {
            if (target[0].id === 'previous') {
              $scope.pageSettings.pageNumber = ($scope.pageSettings.pageNumber == 0 ? 0 : $scope.pageSettings.pageNumber - 1);
            } else if (target[0].id === 'next') {
              $scope.pageSettings.pageNumber = ($scope.pageSettings.pageNumber == $scope.pageSettings.totalPages ? $scope.pageSettings.pageNumber : $scope.pageSettings.pageNumber + 1);
            } else {
              console.log(target[0].id);
              $scope.pageSettings.pageNumber = target[0].id;
            }
          });
        }
      });

      $scope.$watch('pageSettings', function(newVal) {
        console.log(newVal);
        element.removeClass('active');
        if (!$scope.pageSettings && newVal === $scope.pageSettings.pageSize) {
          element.addClass('active');
        }
        if ($scope.pageSettings.totalPages) {
          setPageArray($scope.pageSettings.totalPages);
        }
      });

      $scope.isActive = function(index) {
        var isActive = false;
        if (index !== 'previous' || index !== 'next') {
          isActive = $scope.pageSettings.pageNumber === (index - 1);
        }
        return isActive;
      }

      var setPageArray = function(num) {
        $scope.pages.length = 0;
        for (i = 0; i < num; i++) {
          $scope.pages.push({[i]: i + 1});
        }
      };
    }
  };
});<commit_msg>Fixed off by one error<commit_after>app.directive("paginationButtons", function() {
  return {
    templateUrl: 'views/directives/paginationButtons.html',
    restrict: 'E',
    $scope: {
      'pageSettings': '='
    },
    link: function($scope, element, attr) {

      $scope.pages = [];

      element.on('click', function(elem) {
        var target = $(elem.target);
        if (target.find(">:first-child").is("input")) {
          $scope.$apply(function() {
            $scope.pageSettings.pageSize = target.find("input")[0].id;
          });
        } else if (target.hasClass("btn")) {
          $scope.$apply(function() {
            if (target[0].id === 'previous') {
              $scope.pageSettings.pageNumber = ($scope.pageSettings.pageNumber == 0 ? 0 : $scope.pageSettings.pageNumber - 1);
            } else if (target[0].id === 'next') {
              $scope.pageSettings.pageNumber = ($scope.pageSettings.pageNumber == $scope.pageSettings.totalPages - 1 ? $scope.pageSettings.pageNumber : $scope.pageSettings.pageNumber + 1);
            } else {
              console.log(target[0].id);
              $scope.pageSettings.pageNumber = target[0].id - 1;
            }
          });
        }
      });

      $scope.$watch('pageSettings', function(newVal) {
        console.log(newVal);
        element.removeClass('active');
        if (!$scope.pageSettings && newVal === $scope.pageSettings.pageSize) {
          element.addClass('active');
        }
        if ($scope.pageSettings.totalPages) {
          setPageArray($scope.pageSettings.totalPages);
        }
      });

      $scope.isActive = function(index) {
        var isActive = false;
        if (index !== 'previous' || index !== 'next') {
          isActive = $scope.pageSettings.pageNumber === (index - 1);
        }
        return isActive;
      }

      var setPageArray = function(num) {
        $scope.pages.length = 0;
        for (i = 0; i < num; i++) {
          $scope.pages.push({[i]: i + 1});
        }
      };
    }
  };
});<|endoftext|>


<commit_before>define(['text!./search-filter-dates.html', 'app', 'directives/forms/km-date'], function(template, app) { 'use strict';

    app.directive('searchFilterDates', ["$location", function ($location) {
        return {
            restrict: 'EAC',
            template: template,
            replace: true,
            scope: {
                  title: '@title',
                  query: '=query'
            },
            link: function ($scope) {

                var now = new Date();

                $scope.dates = [
                    { text: 'Any', date: '' },
                    { text: 'Last day', date: new Date(new Date(now).setDate(now.getDate()-1)).toISOString() },
                    { text: 'Last week', date: new Date(new Date(now).setDate(now.getDate()-7)).toISOString() },
                    { text: 'Last two weeks', date: new Date(new Date(now).setDate(now.getDate()-14)).toISOString() },
                    { text: 'Last month', date: new Date(new Date(now).setMonth(now.getMonth()-1)).toISOString() },
                    { text: 'Last two months', date: new Date(new Date(now).setMonth(now.getMonth()-2)).toISOString() },
                    { text: 'Last six months', date: new Date(new Date(now).setMonth(now.getMonth()-6)).toISOString() },
                    { text: 'Last year', date: new Date(new Date(now).setMonth(now.getMonth()-12)).toISOString() },
                ];

                $scope.since = $location.search().startDate;
                $scope.until = $location.search().endDate;

                $scope.$watch('since', updateQuery);
                $scope.$watch('until', updateQuery);

                if(!$scope.since && !$scope.until)
                    $scope.selectedDate = $scope.dates[0];

                function updateQuery () {

                    if($scope.since || $scope.until) {
                        var since = $scope.since ? $scope.since + 'T00:00:00.000Z' : '*';
                        var until = $scope.until ? $scope.until + 'T23:59:59.999Z' : '*';

                        $scope.query = ' ( createdDate_s:[ ' + since + ' TO ' + until + ' ] ) ';
                    } else {
                        $scope.query = '*:*';
                    }

                    $location.search("startDate", $scope.since || null);
                    $location.search("endDate",   $scope.until || null);
                }

                $scope.$watch('selectedDate', function (_new, _old) {

                    if(_new==_old)
                        return;

                    $scope.since = $scope.selectedDate.date ? new Date($scope.selectedDate.date).toISOString().substr(0, 10) : null;
                    $scope.until = null;
                });

                $scope.updateQuery = updateQuery;
            }
        };
    }]);
});
<commit_msg>removed unused var and added parent directive<commit_after>define(['text!./search-filter-dates.html', 'app', 'directives/forms/km-date'], function(template, app) { 'use strict';

    app.directive('searchFilterDates', ["$location", function ($location) {
        return {
            restrict: 'EAC',
            template: template,
            replace: true,
            require : '^search',
            scope: {
                  title: '@title',
            },
            link : function ($scope, $element, $attr, searchCtrl)//jshint ignore:line
            {

                var now = new Date();

                $scope.dates = [
                    { text: 'Any', date: '' },
                    { text: 'Last day', date: new Date(new Date(now).setDate(now.getDate()-1)).toISOString() },
                    { text: 'Last week', date: new Date(new Date(now).setDate(now.getDate()-7)).toISOString() },
                    { text: 'Last two weeks', date: new Date(new Date(now).setDate(now.getDate()-14)).toISOString() },
                    { text: 'Last month', date: new Date(new Date(now).setMonth(now.getMonth()-1)).toISOString() },
                    { text: 'Last two months', date: new Date(new Date(now).setMonth(now.getMonth()-2)).toISOString() },
                    { text: 'Last six months', date: new Date(new Date(now).setMonth(now.getMonth()-6)).toISOString() },
                    { text: 'Last year', date: new Date(new Date(now).setMonth(now.getMonth()-12)).toISOString() },
                ];

                $scope.since = $location.search().startDate;
                $scope.until = $location.search().endDate;

                $scope.$watch('since', updateQuery);
                $scope.$watch('until', updateQuery);

                if(!$scope.since && !$scope.until)
                    $scope.selectedDate = $scope.dates[0];

                function updateQuery () {

                    if($scope.since || $scope.until) {
                        var since = $scope.since ? $scope.since + 'T00:00:00.000Z' : '*';
                        var until = $scope.until ? $scope.until + 'T23:59:59.999Z' : '*';

                        $scope.query = ' ( createdDate_s:[ ' + since + ' TO ' + until + ' ] ) ';
                    } else {
                        $scope.query = '*:*';
                    }

                    $location.search("startDate", $scope.since || null);
                    $location.search("endDate",   $scope.until || null);
                }

                $scope.$watch('selectedDate', function (_new, _old) {

                    if(_new==_old)
                        return;

                    $scope.since = $scope.selectedDate.date ? new Date($scope.selectedDate.date).toISOString().substr(0, 10) : null;
                    $scope.until = null;
                });

                $scope.updateQuery = updateQuery;
            }
        };
    }]);
});
<|endoftext|>


<commit_before>/**
 * Makes a list sortable
 *
 * Example:
 *

 *
{{item.name}}<button class="btn btn-mini btn-danger" style="float:right;" ng-click="remove(item)">X</button>

 *

 * <button ng-click="add()">Add</button>
 *
 * the add function defined in an sorounding controller:
 * $scope.add = function() {
 *     $scope.layer_list.push({"id": 99, "name": "New"});
 * }
 *
 * layer_list is a list of dicts
 * insiede the directive you must work with sortable_array
 * instead of the outer list layer_list
 *
 * if you wish to use functions inside the directive like
 * remove, they must be defined inside the directive
 *
 * ToDo:
 * figger out how to access methods of directive from
 * outside like add so the outer list layer_list hasn't
 * to manipulate by controller but by directive
 */

angular.module('mapproxy_gui.directives', []).
directive('sortable', function() {
    return {
        restrict: 'A',
        replace: false,
        require: 'ngModel',
        link: function(scope, element, attrs, ngModelCtrl) {

            scope.dragStart = function(e, ui) {
                ui.item.data('start', ui.item.index());
            };

            scope.dragEnd = function(e, ui) {
                //old item list index
                var start = ui.item.data('start');
                //new item list index
                var end = ui.item.index();
                scope.items = ngModelCtrl.$modelValue;

                if(angular.isUndefined(scope.items)) {
                    scope.items = [];
                }
                //rearrange list
                scope.items.splice(end, 0,
                    scope.items.splice(start, 1)[0]);

                //tell angular $scope has changed
                scope.$apply()
            };

            scope.remove = function(item) {
                scope.items = ngModelCtrl.$modelValue;
                scope.items.splice(scope.items.indexOf(item), 1);
                if(scope.items.length == 0) {
                    ngModelCtrl.$setViewValue(undefined);
                }
            };

            var sortable_element = $(element).sortable({
                start: scope.dragStart,
                update: scope.dragEnd
            });
        }
    };
}).

/* Drag&Drop directives */
directive('draggable', function() {
    return {
        // A = attribute, E = Element, C = Class and M = HTML Comment
        restrict:'A',
        require: '?ngModel',
        scope: 'element',
        //The link function is responsible for registering DOM listeners as well as updating the DOM.
        link: function(scope, element, attrs, ngModelCtrl) {

            if(angular.isDefined(ngModelCtrl)) {
                scope.remove = function() {
                    var item = angular.fromJson(attrs.itemData);
                    var source_list = ngModelCtrl.$modelValue ? ngModelCtrl.$modelValue : [];
                    var found = false;
                    angular.forEach(source_list, function(source_item) {
                        if(!found) {
                            if(angular.equals(source_item, item)) {
                                source_list.splice(source_list.indexOf(source_item), 1);
                                found = true;
                            }
                        }
                    })
                    if(source_list.length == 0) {
                        ngModelCtrl.$setViewValue(undefined);
                    }
                };
            }

            $(element).draggable({
                helper: 'clone',
                cursor: 'move',
                revert: false
            });
        }
    };
}).

/**
 * Insertable directive
 *
 * Usable as attribute: <div insertable ...
 * requires ng-model
 *
 * change: function
 * - fired on value change.
 * - must provide a callback parameter for callback function
 * - callback(true) accept change
 * - callback(false) reject change
 *
 * allow-array: boolean
 * - true to allow insert arrays
 * accepts: string - comma seppareted string for list
 * - classname(s) of elements allowed to insert
 */
 //TODO: allow setting accepts
directive('droppable', function($parse) {
    return {
        restrict: 'A',
        require: 'ngModel',
        link: function(scope, element, attrs, ngModelCtrl) {
            //create a new not isolated scope
            scope = scope.$new(false)

            scope.checkExist = function(item) {
                var exist = false;
                if(scope.use_key) {
                    item = item[scope.use_key];
                }
                //because angular add a unique $$hashKey to objects
                angular.forEach(scope.items, function(scope_item) {
                    //angular.forEach doesn't support break
                    if(!exist) {
                        exist = angular.equals(scope_item, item);
                    }
                });
                if(!exist) {
                    scope.to_insert.push(item);
                }
            };
            scope.checkClass = function(elem) {
                var found = false;

                if(scope.accepts.length == 0) return true

                angular.forEach(scope.accepts, function(accept) {
                    if(!found) {
                        found = elem.hasClass(accept);
                    }
                });
                return found;
            };
            scope.insertItems = function() {
                if(angular.isUndefined(scope.items)) {
                    scope.items = [];
                }
                if(attrs.allowArray) {
                    scope.items = scope.items.concat(scope.to_insert);
                } else {
                    scope.items = scope.to_insert[0];
                }
                var insert_scope = angular.element(scope.j_ui).scope();
                if(angular.isFunction(insert_scope.remove)) {
                    insert_scope.remove();
                }
                delete(scope.j_ui);
                scope.$apply(function() {
                    ngModelCtrl.$setViewValue(scope.items);
                });
            };
            scope.remove = function(item) {
                if(angular.isUndefined(scope.items) || angular.isUndefined(item)) {
                    return;
                }

                if(attrs.allowArray) {
                    scope.items.splice(scope.items.indexOf(item), 1);
                    if(scope.items.length == 0) {
                        scope.items = undefined;
                    }
                } else {
                    scope.items = undefined;
                }

                scope.$apply(function() {
                    ngModelCtrl.$setViewValue(scope.items);
                });
            };
            scope.changeCallback = function(change) {
                if(change) {
                    scope.insertItems();
                } else {
                    scope.j_ui.draggable('option', 'revert', true);
                }
            };
            scope.dropHandler = function(event,ui) {

                //get current items from model
                scope.items = ngModelCtrl.$modelValue;
                scope.inserted = false;
                scope.j_ui = $(ui.draggable);
                //only process draggable elements
                if(!scope.j_ui.hasClass('ui-draggable')) {
                    return;
                }

                //check element class against accepts
                if(!scope.checkClass(scope.j_ui)) {
                    scope.j_ui.draggable('option', 'revert', true);
                    return;
                }
                //get data (string) of dopped element and convert it to an object
                scope.new_item = angular.fromJson(scope.j_ui.attr('item-data'));

                scope.to_insert = [];

                //check for data
                if(!angular.isUndefined(scope.new_item)) {

                    //check for existing items
                    if(angular.isArray(scope.new_item)) {

                        angular.forEach(scope.new_item, scope.checkExist);
                    } else {

                        scope.checkExist(scope.new_item);
                    }
                    //look if something to insert
                    if(scope.to_insert.length > 0) {

                        //run callback if present
                        if(angular.isFunction(scope.change)) {

                            scope.change(scope.$parent, {callback: scope.changeCallback, new_data: scope.new_item});
                        } else {

                            scope.insertItems();
                        }
                    } else {

                        scope.j_ui.draggable('option', 'revert', true);
                    }
                }
            };

            scope.accepts = angular.isUndefined(attrs.accepts) ? [] : attrs.accepts.split(',');
            scope.rejects = angular.isUndefined(attrs.rejects) ? [] : attrs.rejects.split(',');

            scope.use_key = attrs.useKeyForValue;

            //look for callback function
            scope.change = angular.isUndefined(attrs.changeCallback) ? undefined : $parse(attrs.changeCallback);

            $(element).droppable({
                drop: scope.dropHandler
            });
        }
    };
}).

directive('toggleGroup', function() {
    return {
        restrict: 'A',
        controller: toggleGroupCtrl
    };
}).

directive('toggleElement', function() {
    return {
        restrict: 'A',
        require: '^toggleGroup',
        link: function(scope, element, attrs, toggleGroupCTRL) {
            toggleGroupCTRL.addElement(element);
            $(element).click(function() {
                toggleGroupCTRL.getToggleFunc()(element);
            });
        }
    }
}).

directive('tabs', function() {
    return {
        restrict: 'A',
        transclude: true,
        scope: {},
        controller: tabsCtrl,
        template:
            '
' +
            '
' +
            '
'+
            '{{pane.header}}' +
            '
' +
            '
' +
            '

' +
            '
',
        replace: true
    };
}).

directive('pane', function() {
    return {
        require: '^tabs',
        restrict: 'A',
        transclude: true,
        scope: { header: '@' },
        link: function(scope, element, attrs, tabsCtrl) {
            tabsCtrl.addPane(scope);
        },
        template:
            '

',
        replace: true
    };
}).

directive('askDialog', function($parse) {
    return {
        restrict: 'A',
        link: function(scope, element, attrs) {

            scope.openDialog = function() {
                $('#dialog_' + scope.dialog_id).dialog({
                    resizeable: false,
                    width: 400,
                    height: 200,
                    model: true,
                    buttons: {
                        "Yes": function() {
                            $(this).dialog("close");
                            scope.callback(scope);
                        },
                        "No": function() {
                            $(this).dialog("close");
                        }
                    }
                });
            };
            scope.dialog_id = scope.$id;
            scope.callback = $parse(attrs.callback);
            var dialog = '

'+ attrs.dialogText +'

';
            element.after(dialog);

            element.bind('click', scope.openDialog);
        }
    };
}).

directive('labeledControlGroup', function() {
    return {
        restrict: 'A',
        replace: true,
        transclude: true,
        template: '
' +
                      '{{text}}:' +
                      '
' +
                          '' +
                          '' +
                      '
' +
                  '
',
        scope: 'element',
        link: function(scope, element, attrs) {
            scope.showWarning = function() {
                if(scope.warning) {
                    element.addClass('warning');
                    $('#tooltip_'+ scope.$id).tooltip({
                        placement: 'right',
                        title: scope.warningMsg
                    });
                    return true;
                } else {
                    element.removeClass('warning');
                    return false;
                }
            };
            scope.warningMsg = function() {
                return attrs.warningMsg;
            };

            scope.name = attrs.nameFor;
            scope.text = attrs.text;
            if(angular.isDefined(attrs.$attr.warning)) {
                scope.warning_msg = attrs.warningMsg;
                attrs.$observe('warning', function(val) {
                    scope.warning = val == 'true';
                });
            }
        }
    };
});

/* Controller for directives */

// used by toggleGroup
var toggleGroupCtrl = function($scope, $element) {
    var toggle_elements = [];

    var toToggle = function(element) {
        switch(element.attr('toggle-element')) {
            case 'next':
                return $(element).next();
                break;
            default:
                return $(element);
        }
    };

    this.addElement = function(element) {
        toggle_elements.push(element);
    };
    this.getElementCount = function() {
        return toggle_elements.length;
    };

    this.multiShow = function(element) {
        toToggle(element).toggle();
    };
    this.hideOther = function(element) {
        angular.forEach(toggle_elements, function(t_element) {
            if (t_element == element) {
                toToggle(t_element).show();
            } else {
                toToggle(t_element).hide();
            }
        });
    };
    this.getToggleFunc = function() {
        switch($element.attr('mode')) {
            case 'multiShow':
                return this.multiShow;
                break;
            case 'hideOther':
            default:
                return this.hideOther;
        }
    };
}

// used by tabs
var tabsCtrl = function($scope, $element) {

    this.addPane = function(pane) {
        if (panes.length == 0) $scope.select(pane);
        panes.push(pane);
    };

    $scope.select = function(pane) {
        angular.forEach(panes, function(pane) {
            pane.selected = false;
        });
        pane.selected = true;
    };

    var panes = $scope.panes = [];
};
<commit_msg>Use own scope for each droppable element<commit_after>/**
 * Makes a list sortable
 *
 * Example:
 *

 *
{{item.name}}<button class="btn btn-mini btn-danger" style="float:right;" ng-click="remove(item)">X</button>

 *

 * <button ng-click="add()">Add</button>
 *
 * the add function defined in an sorounding controller:
 * $scope.add = function() {
 *     $scope.layer_list.push({"id": 99, "name": "New"});
 * }
 *
 * layer_list is a list of dicts
 * insiede the directive you must work with sortable_array
 * instead of the outer list layer_list
 *
 * if you wish to use functions inside the directive like
 * remove, they must be defined inside the directive
 *
 * ToDo:
 * figger out how to access methods of directive from
 * outside like add so the outer list layer_list hasn't
 * to manipulate by controller but by directive
 */

angular.module('mapproxy_gui.directives', []).
directive('sortable', function() {
    return {
        restrict: 'A',
        replace: false,
        require: 'ngModel',
        link: function(scope, element, attrs, ngModelCtrl) {

            scope.dragStart = function(e, ui) {
                ui.item.data('start', ui.item.index());
            };

            scope.dragEnd = function(e, ui) {
                //old item list index
                var start = ui.item.data('start');
                //new item list index
                var end = ui.item.index();
                scope.items = ngModelCtrl.$modelValue;

                if(angular.isUndefined(scope.items)) {
                    scope.items = [];
                }
                //rearrange list
                scope.items.splice(end, 0,
                    scope.items.splice(start, 1)[0]);

                //tell angular $scope has changed
                scope.$apply()
            };

            scope.remove = function(item) {
                scope.items = ngModelCtrl.$modelValue;
                scope.items.splice(scope.items.indexOf(item), 1);
                if(scope.items.length == 0) {
                    ngModelCtrl.$setViewValue(undefined);
                }
            };

            var sortable_element = $(element).sortable({
                start: scope.dragStart,
                update: scope.dragEnd
            });
        }
    };
}).

/* Drag&Drop directives */
directive('draggable', function() {
    return {
        // A = attribute, E = Element, C = Class and M = HTML Comment
        restrict:'A',
        require: '?ngModel',
        scope: 'element',
        //The link function is responsible for registering DOM listeners as well as updating the DOM.
        link: function(scope, element, attrs, ngModelCtrl) {

            if(angular.isDefined(ngModelCtrl)) {
                scope.remove = function() {
                    var item = angular.fromJson(attrs.itemData);
                    var source_list = ngModelCtrl.$modelValue ? ngModelCtrl.$modelValue : [];
                    var found = false;
                    angular.forEach(source_list, function(source_item) {
                        if(!found) {
                            if(angular.equals(source_item, item)) {
                                source_list.splice(source_list.indexOf(source_item), 1);
                                found = true;
                            }
                        }
                    })
                    if(source_list.length == 0) {
                        ngModelCtrl.$setViewValue(undefined);
                    }
                };
            }

            $(element).draggable({
                helper: 'clone',
                cursor: 'move',
                revert: false
            });
        }
    };
}).

/**
 * Insertable directive
 *
 * Usable as attribute: <div insertable ...
 * requires ng-model
 *
 * change: function
 * - fired on value change.
 * - must provide a callback parameter for callback function
 * - callback(true) accept change
 * - callback(false) reject change
 *
 * allow-array: boolean
 * - true to allow insert arrays
 * accepts: string - comma seppareted string for list
 * - classname(s) of elements allowed to insert
 */
 //TODO: allow setting accepts
directive('droppable', function($parse) {
    return {
        restrict: 'A',
        require: 'ngModel',
        scope: 'element',
        link: function(scope, element, attrs, ngModelCtrl) {
            //create a new not isolated scope
            scope = scope.$new(false)

            scope.checkExist = function(item) {
                var exist = false;
                if(scope.use_key) {
                    item = item[scope.use_key];
                }
                //because angular add a unique $$hashKey to objects
                angular.forEach(scope.items, function(scope_item) {
                    //angular.forEach doesn't support break
                    if(!exist) {
                        exist = angular.equals(scope_item, item);
                    }
                });
                if(!exist) {
                    scope.to_insert.push(item);
                }
            };
            scope.checkClass = function(elem) {
                var found = false;

                if(scope.accepts.length == 0) return true

                angular.forEach(scope.accepts, function(accept) {
                    if(!found) {
                        found = elem.hasClass(accept);
                    }
                });
                return found;
            };
            scope.insertItems = function() {
                if(angular.isUndefined(scope.items)) {
                    scope.items = [];
                }
                if(attrs.allowArray) {
                    scope.items = scope.items.concat(scope.to_insert);
                } else {
                    scope.items = scope.to_insert[0];
                }
                var insert_scope = angular.element(scope.j_ui).scope();
                if(angular.isFunction(insert_scope.remove)) {
                    insert_scope.remove();
                }
                delete(scope.j_ui);
                scope.$apply(function() {
                    ngModelCtrl.$setViewValue(scope.items);
                });
            };
            scope.remove = function(item) {
                if(angular.isUndefined(scope.items) || angular.isUndefined(item)) {
                    return;
                }

                if(attrs.allowArray) {
                    scope.items.splice(scope.items.indexOf(item), 1);
                    if(scope.items.length == 0) {
                        scope.items = undefined;
                    }
                } else {
                    scope.items = undefined;
                }

                scope.$apply(function() {
                    ngModelCtrl.$setViewValue(scope.items);
                });
            };
            scope.changeCallback = function(change) {
                if(change) {
                    scope.insertItems();
                } else {
                    scope.j_ui.draggable('option', 'revert', true);
                }
            };
            scope.dropHandler = function(event,ui) {

                //get current items from model
                scope.items = ngModelCtrl.$modelValue;
                scope.inserted = false;
                scope.j_ui = $(ui.draggable);
                //only process draggable elements
                if(!scope.j_ui.hasClass('ui-draggable')) {
                    return;
                }

                //check element class against accepts
                if(!scope.checkClass(scope.j_ui)) {
                    scope.j_ui.draggable('option', 'revert', true);
                    return;
                }
                //get data (string) of dopped element and convert it to an object
                scope.new_item = angular.fromJson(scope.j_ui.attr('item-data'));

                scope.to_insert = [];

                //check for data
                if(!angular.isUndefined(scope.new_item)) {

                    //check for existing items
                    if(angular.isArray(scope.new_item)) {

                        angular.forEach(scope.new_item, scope.checkExist);
                    } else {

                        scope.checkExist(scope.new_item);
                    }
                    //look if something to insert
                    if(scope.to_insert.length > 0) {

                        //run callback if present
                        if(angular.isFunction(scope.change)) {
                            scope.change(scope.$parent, {callback: scope.changeCallback, new_data: scope.new_item});
                        } else {

                            scope.insertItems();
                        }
                    } else {

                        scope.j_ui.draggable('option', 'revert', true);
                    }
                }
            };

            scope.accepts = angular.isUndefined(attrs.accepts) ? [] : attrs.accepts.split(',');
            scope.rejects = angular.isUndefined(attrs.rejects) ? [] : attrs.rejects.split(',');

            scope.use_key = attrs.useKeyForValue;

            //look for callback function
            scope.change = angular.isUndefined(attrs.changeCallback) ? undefined : $parse(attrs.changeCallback);

            $(element).droppable({
                drop: scope.dropHandler
            });
        }
    };
}).

directive('toggleGroup', function() {
    return {
        restrict: 'A',
        controller: toggleGroupCtrl
    };
}).

directive('toggleElement', function() {
    return {
        restrict: 'A',
        require: '^toggleGroup',
        link: function(scope, element, attrs, toggleGroupCTRL) {
            toggleGroupCTRL.addElement(element);
            $(element).click(function() {
                toggleGroupCTRL.getToggleFunc()(element);
            });
        }
    }
}).

directive('tabs', function() {
    return {
        restrict: 'A',
        transclude: true,
        scope: {},
        controller: tabsCtrl,
        template:
            '
' +
            '
' +
            '
'+
            '{{pane.header}}' +
            '
' +
            '
' +
            '

' +
            '
',
        replace: true
    };
}).

directive('pane', function() {
    return {
        require: '^tabs',
        restrict: 'A',
        transclude: true,
        scope: { header: '@' },
        link: function(scope, element, attrs, tabsCtrl) {
            tabsCtrl.addPane(scope);
        },
        template:
            '

',
        replace: true
    };
}).

directive('askDialog', function($parse) {
    return {
        restrict: 'A',
        link: function(scope, element, attrs) {

            scope.openDialog = function() {
                $('#dialog_' + scope.dialog_id).dialog({
                    resizeable: false,
                    width: 400,
                    height: 200,
                    model: true,
                    buttons: {
                        "Yes": function() {
                            $(this).dialog("close");
                            scope.callback(scope);
                        },
                        "No": function() {
                            $(this).dialog("close");
                        }
                    }
                });
            };
            scope.dialog_id = scope.$id;
            scope.callback = $parse(attrs.callback);
            var dialog = '

'+ attrs.dialogText +'

';
            element.after(dialog);

            element.bind('click', scope.openDialog);
        }
    };
}).

directive('labeledControlGroup', function() {
    return {
        restrict: 'A',
        replace: true,
        transclude: true,
        template: '
' +
                      '{{text}}:' +
                      '
' +
                          '' +
                          '' +
                      '
' +
                  '
',
        scope: 'element',
        link: function(scope, element, attrs) {
            scope.showWarning = function() {
                if(scope.warning) {
                    element.addClass('warning');
                    $('#tooltip_'+ scope.$id).tooltip({
                        placement: 'right',
                        title: scope.warningMsg
                    });
                    return true;
                } else {
                    element.removeClass('warning');
                    return false;
                }
            };
            scope.warningMsg = function() {
                return attrs.warningMsg;
            };

            scope.name = attrs.nameFor;
            scope.text = attrs.text;
            if(angular.isDefined(attrs.$attr.warning)) {
                scope.warning_msg = attrs.warningMsg;
                attrs.$observe('warning', function(val) {
                    scope.warning = val == 'true';
                });
            }
        }
    };
});

/* Controller for directives */

// used by toggleGroup
var toggleGroupCtrl = function($scope, $element) {
    var toggle_elements = [];

    var toToggle = function(element) {
        switch(element.attr('toggle-element')) {
            case 'next':
                return $(element).next();
                break;
            default:
                return $(element);
        }
    };

    this.addElement = function(element) {
        toggle_elements.push(element);
    };
    this.getElementCount = function() {
        return toggle_elements.length;
    };

    this.multiShow = function(element) {
        toToggle(element).toggle();
    };
    this.hideOther = function(element) {
        angular.forEach(toggle_elements, function(t_element) {
            if (t_element == element) {
                toToggle(t_element).show();
            } else {
                toToggle(t_element).hide();
            }
        });
    };
    this.getToggleFunc = function() {
        switch($element.attr('mode')) {
            case 'multiShow':
                return this.multiShow;
                break;
            case 'hideOther':
            default:
                return this.hideOther;
        }
    };
}

// used by tabs
var tabsCtrl = function($scope, $element) {

    this.addPane = function(pane) {
        if (panes.length == 0) $scope.select(pane);
        panes.push(pane);
    };

    $scope.select = function(pane) {
        angular.forEach(panes, function(pane) {
            pane.selected = false;
        });
        pane.selected = true;
    };

    var panes = $scope.panes = [];
};
<|endoftext|>


<commit_before>;(function (angular, _, $) {
    'use strict';

    angular.module('Georeferencer.Geo').controller('Geo.CoreCtrl', CoreCtrl);

    /* @ngInject */
    function CoreCtrl (
            $state,
            $scope,
            $window,
            $stateParams,
            toastr,
            gettextCatalog,
            GeoState,
            MarkerAdded,
            MarkerRemoved,
            MarkerSelected,
            leafletData,
            LocationFound,
            LocationSelected,
            GeoCoder,
            GeoReference,
            HistoricalSearch
    ) {
        var vm = this;

        var buttons = {
            'new': {
                'show': true,
                'title': gettextCatalog.getString('Start over'),
                'css': function () {
                    return 'new-button';
                },
                'dispatch': function () {
                    $window.location.href = '/';
                }
            },
            'new_reference_point': {
                'show': true,
                'title': gettextCatalog.getString('New reference point'),
                'css': function () {
                    if (GeoState.checkPermissions('addImageMarker') || GeoState.checkPermissions('addMapMarker')) {
                        return 'new-point-button active';
                    }
                    return 'new-point-button';
                },
                'dispatch': function () {
                    if (!GeoState.checkPermissions('addImageMarker') && !GeoState.checkPermissions('addMapMarker')) {
                        GeoState.setPermissions('addImageMarker');
                    }
                }
            },
            'list': {
                'show': true,
                'title': gettextCatalog.getString('List'),
                'css': function () {
                    return vm.showList ? 'list-button active' : 'list-button';
                },
                'dispatch': function () {
                    if (!vm.showList && (GeoState.getMarkers().length < 1)) {
                        toastr.info(gettextCatalog.getString('Please add reference points first.'));
                    } else {
                        vm.showList = !vm.showList;
                    }
                }
            },
            'finish': {
                'show': true,
                'title': gettextCatalog.getString('Finish'),
                'css': function () {
                    return 'finish-button';
                },
                'dispatch': function () {
                    $('.finish-button').addClass('loading');
                    GeoReference.queuePreview().then(
                        function (response) {
                            $('.finish-button').removeClass('loading');
                            $state.go('finish');
                        }, function (response) {
                            $('.finish-button').removeClass('loading');
                            var error = response;
                            if (typeof(response.message) !== 'undefined') {
                                error = response.message;
                            }
                            toastr.warning(error);
                        }
                    );
                }
            },
            'preview': {
                'show': true,
                'title': gettextCatalog.getString('Preview'),
                'css': function () {
                    return 'preview-button middle';
                },
                'dispatch': function () {
                    $('.preview-button').addClass('loading');
                    GeoReference.queuePreview().then(
                        function (response) {
                            $('.preview-button').removeClass('loading');
                            $state.go('preview');
                        }, function (response) {
                            $('.preview-button').removeClass('loading');
                            var error = response;
                            if (typeof(response.message) !== 'undefined') {
                                error = response.message;
                            }
                            toastr.warning(error);
                        }
                    );
                }
            }
        };

        vm.showList = false;

        vm.menu = [];

        vm.markers = [];

        vm.locations = [];

        vm.search = {'query' : '', 'historic': false};

        vm.clearSearch = clearSearch;

        vm.removeMarker = removeMarker;

        vm.selectMarker = selectMarker;

        vm.selectLocation = selectLocation;

        vm.searchLocation = searchLocation;

        activate();

        function activate() {
            vm.markers = GeoState.getMarkers();
            MarkerAdded.subscribe(refreshMarkers.bind(vm));
            MarkerRemoved.subscribe(refreshMarkers.bind(vm));
            MarkerSelected.subscribe(focusMarker.bind(vm));
            LocationFound.subscribe(showLocations.bind(vm));

            var config = GeoState.getConfig();
            if ((typeof(config.buttons) !== 'undefined')) {
                buttons = _.merge(buttons, config.buttons);
            }
            _.forEach(
                buttons,
                function (button, key)  {
                    if (button.show) {
                        vm.menu.push(button);
                    }
                }
            );

            if ($stateParams.msg !== null) {
                toastr.warning($stateParams.msg);
            }

            var image = GeoState.getImage();
            vm.search.query = image.place;
        }

        function refreshMarkers(_e, markers) {
            this.markers = GeoState.getMarkers();
        }

        function showLocations(_e, locations) {
            this.locations = locations;
            if (locations.length < 1) {
                toastr.info(gettextCatalog.getString('No results found.'));
            }
            $scope.$applyAsync();
        }

        function removeMarker(marker) {
            GeoState.removeMarker(marker);
        }

        function focusMarker(_e, marker) {
            $('.lat-lng-list .marker_row').removeClass('selected');
            $('.lat-lng-list #' + marker.id + '_row').addClass('selected');
        }

        function selectMarker(marker) {
            MarkerSelected.trigger(marker);
        }

        function clearSearch() {
            vm.locations = [];
        }

        function selectLocation(location) {
            LocationSelected.trigger(location);
            vm.locations = [];
        }

        function searchLocation(event) {
            if (vm.search.historic) {
                HistoricalSearch.search(vm.search.query);
            } else {
                GeoCoder.geocode(vm.search.query);
            }
        }
    }
})(window.angular, window._, window.jQuery);
<commit_msg>show warning when "start over" is clicked. refs #24457<commit_after>;(function (angular, _, $) {
    'use strict';

    angular.module('Georeferencer.Geo').controller('Geo.CoreCtrl', CoreCtrl);

    /* @ngInject */
    function CoreCtrl (
            $state,
            $scope,
            $window,
            $stateParams,
            toastr,
            gettextCatalog,
            GeoState,
            MarkerAdded,
            MarkerRemoved,
            MarkerSelected,
            leafletData,
            LocationFound,
            LocationSelected,
            GeoCoder,
            GeoReference,
            HistoricalSearch
    ) {
        var vm = this;

        var buttons = {
            'new': {
                'show': true,
                'title': gettextCatalog.getString('Start over'),
                'css': function () {
                    return 'new-button';
                },
                'dispatch': function () {
                    if (confirm(gettextCatalog.getString('Are you sure? All your content will be removed!'))) {
                        $window.location.href = '/';
                    }
                }
            },
            'new_reference_point': {
                'show': true,
                'title': gettextCatalog.getString('New reference point'),
                'css': function () {
                    if (GeoState.checkPermissions('addImageMarker') || GeoState.checkPermissions('addMapMarker')) {
                        return 'new-point-button active';
                    }
                    return 'new-point-button';
                },
                'dispatch': function () {
                    if (!GeoState.checkPermissions('addImageMarker') && !GeoState.checkPermissions('addMapMarker')) {
                        GeoState.setPermissions('addImageMarker');
                    }
                }
            },
            'list': {
                'show': true,
                'title': gettextCatalog.getString('List'),
                'css': function () {
                    return vm.showList ? 'list-button active' : 'list-button';
                },
                'dispatch': function () {
                    if (!vm.showList && (GeoState.getMarkers().length < 1)) {
                        toastr.info(gettextCatalog.getString('Please add reference points first.'));
                    } else {
                        vm.showList = !vm.showList;
                    }
                }
            },
            'finish': {
                'show': true,
                'title': gettextCatalog.getString('Finish'),
                'css': function () {
                    return 'finish-button';
                },
                'dispatch': function () {
                    $('.finish-button').addClass('loading');
                    GeoReference.queuePreview().then(
                        function (response) {
                            $('.finish-button').removeClass('loading');
                            $state.go('finish');
                        }, function (response) {
                            $('.finish-button').removeClass('loading');
                            var error = response;
                            if (typeof(response.message) !== 'undefined') {
                                error = response.message;
                            }
                            toastr.warning(error);
                        }
                    );
                }
            },
            'preview': {
                'show': true,
                'title': gettextCatalog.getString('Preview'),
                'css': function () {
                    return 'preview-button middle';
                },
                'dispatch': function () {
                    $('.preview-button').addClass('loading');
                    GeoReference.queuePreview().then(
                        function (response) {
                            $('.preview-button').removeClass('loading');
                            $state.go('preview');
                        }, function (response) {
                            $('.preview-button').removeClass('loading');
                            var error = response;
                            if (typeof(response.message) !== 'undefined') {
                                error = response.message;
                            }
                            toastr.warning(error);
                        }
                    );
                }
            }
        };

        vm.showList = false;

        vm.menu = [];

        vm.markers = [];

        vm.locations = [];

        vm.search = {'query' : '', 'historic': false};

        vm.clearSearch = clearSearch;

        vm.removeMarker = removeMarker;

        vm.selectMarker = selectMarker;

        vm.selectLocation = selectLocation;

        vm.searchLocation = searchLocation;

        activate();

        function activate() {
            vm.markers = GeoState.getMarkers();
            MarkerAdded.subscribe(refreshMarkers.bind(vm));
            MarkerRemoved.subscribe(refreshMarkers.bind(vm));
            MarkerSelected.subscribe(focusMarker.bind(vm));
            LocationFound.subscribe(showLocations.bind(vm));

            var config = GeoState.getConfig();
            if ((typeof(config.buttons) !== 'undefined')) {
                buttons = _.merge(buttons, config.buttons);
            }
            _.forEach(
                buttons,
                function (button, key)  {
                    if (button.show) {
                        vm.menu.push(button);
                    }
                }
            );

            if ($stateParams.msg !== null) {
                toastr.warning($stateParams.msg);
            }

            var image = GeoState.getImage();
            vm.search.query = image.place;
        }

        function refreshMarkers(_e, markers) {
            this.markers = GeoState.getMarkers();
        }

        function showLocations(_e, locations) {
            this.locations = locations;
            if (locations.length < 1) {
                toastr.info(gettextCatalog.getString('No results found.'));
            }
            $scope.$applyAsync();
        }

        function removeMarker(marker) {
            GeoState.removeMarker(marker);
        }

        function focusMarker(_e, marker) {
            $('.lat-lng-list .marker_row').removeClass('selected');
            $('.lat-lng-list #' + marker.id + '_row').addClass('selected');
        }

        function selectMarker(marker) {
            MarkerSelected.trigger(marker);
        }

        function clearSearch() {
            vm.locations = [];
        }

        function selectLocation(location) {
            LocationSelected.trigger(location);
            vm.locations = [];
        }

        function searchLocation(event) {
            if (vm.search.historic) {
                HistoricalSearch.search(vm.search.query);
            } else {
                GeoCoder.geocode(vm.search.query);
            }
        }
    }
})(window.angular, window._, window.jQuery);
<|endoftext|>


<commit_before>/**
 * Created by Maya on 2.4.15.
 */
'use strict';

angular.module('registryApp.common').constant('HelpMessages', {
	cliche: {
		general: {
			environment: 'Docker container information.',
			resources: 'Tool execution resource requirements.',
			command: 'Static part of the command line is described using a list of strings and stdin/stdout redirection.',
			arguments: 'Additional command line arguments, if not bound to any input (e.g. dynamic number of threads).',
            dockerPull: 'Enter image repository and (optionally) tag. For example, "images.sbgenomics.com/jsmith/mytool:latest" or "ubuntu". We suggest using the SevenBridges image registry (images.sbgenomics.com) to speed up transfer of image data to compute nodes.',
            imageId: 'Optionally set to ID of the image to make sure same image is used every time.',
            cpu: 'Leave at 0 for multi-threaded tools or set 1 for single threaded tools.',
            memory: 'Amount of RAM (in MB) required by the tool.',
            baseCMD: 'Enter name of the executable and (optionally) sub-command and fixed arguments (e.g. “bamtools sort -bS”).',
            addBaseCMD: 'Add base command.',
            successCodes: 'Array of exit codes that signal successful run (defaults to just 0).',
            tempFailCodes: 'Array of retriable exit codes.',
            stdin: 'If a tool can only take input on stdin, set an expression (</>) here to reference the input file (e.g. $job.inputs.reads.path).',
            stdout: 'Enter file name to redirect standard output into. To construct a name based on inputs, use an expression (</>).',
            addArgument: 'Describe a command line argument that doesn\'t map directly to any of the tool inputs (e.g. —num-threads should have the "value" field set to "$job.allocatedResources.cpu" expression).',
			createFiles: 'Here you can enumerate files that need to be created in the job directory before the command line is executed. File content can be a literal string (e.g. bash wrapper script) or an expression. If the expression evaluates to a File structure (object with "class" and "path" properties, with value for "class" being "File"), this indicates that the file should be copied to the job directory. This is usually used to copy input files before creating indices.'
		},
		inputs: {
			properties: 'Define tool input ports.',
            addInput: 'Add new input port.',
            inputId: 'IDs must be unique for all input and output ports. Value of this port will be available in expressions as $job.inputs["port_id"]. Allowed characters are alphanum and _.',
            type: 'Represents input type.',
            itemType: 'Represents array item type.',
            label: 'Name to show when presenting the input on graphical interfaces.',
            description: 'Help text to show when presenting the input on graphical interfaces.',
            category: 'Category where this input will be grouped under.',
            inputBinding: 'Include this input into command line, and it will show in command line preview bellow.'
		},
		outputs: {
			properties: 'Define tool output ports.',
            outputId: 'Unique output id (required property).',
            addOutput: 'Add new output port.',
            type: 'Represents output type.',
            itemType: 'Represents array item type. Allowed characters are alphanum and _.',
            glob: 'File(s) matching this glob expression will be reported as output(s) on this port.',
            metadata: 'File metadata is a map of string->string. If value depends on tool inputs, use an expression (</>) \n\n like $job.inputs.reads.meta.sample. more info (link to advanced features -> metadata)',
            secondaryFiles: 'click + to enumerate index files that should accompany this output.',
            secondaryFilesInfo: 'If a tool creates index files, list them here using file naming rules: ".ext" means that ".ext" is appended \n\n to original file name; "^.ext" means ".ext" is appended to file base name (after original extension is removed).'
		},
        // inputBindings and outputBindings
        bindings: {
            position: 'An integer priority of the input on the command line (lower comes first).',
            prefix: 'Prefix for named arguments (e.g. —input-file or -i). If value is not supplied or false, the prefix will not be added. \n\n If value is True, only prefix will be added.',
            separatePrefix: 'Character to use as separator between prefix and value. \n\n "Space" means pass as separate arguments.',
            itemSeparator: 'If specified, cast items to string and pass them as single argument (separated with supplied character).',
            value: 'Enter an expression (</>) to transform the input value before passing it to the command line. \n\n Original value is available as $self variable.'
        },
		metadata: {
			metadata: 'Fill additional information about app.',
            label: 'Application display label.',
            description: 'Application description (markdown works).',
            toolkit: 'Application toolkit name (e.g. "samtools").',
            toolkitVersion: 'Application toolkit version.',
            homepage: 'Application homepage url.',
            categories: 'Categories where application should be listed.'
		},
		test: {
			allocatedResources: '',
			inputs: ''
		},
		script: {
			script: ''
		}
	},
	dyole: {

	},
	main: {

	},
	app: {

	}
});<commit_msg>CPU tooltip message fixed.<commit_after>/**
 * Created by Maya on 2.4.15.
 */
'use strict';

angular.module('registryApp.common').constant('HelpMessages', {
	cliche: {
		general: {
			environment: 'Docker container information.',
			resources: 'Tool execution resource requirements.',
			command: 'Static part of the command line is described using a list of strings and stdin/stdout redirection.',
			arguments: 'Additional command line arguments, if not bound to any input (e.g. dynamic number of threads).',
            dockerPull: 'Enter image repository and (optionally) tag. For example, "images.sbgenomics.com/jsmith/mytool:latest" or "ubuntu". We suggest using the SevenBridges image registry (images.sbgenomics.com) to speed up transfer of image data to compute nodes.',
            imageId: 'Optionally set to ID of the image to make sure same image is used every time.',
            cpu: 'Leave at 1 for multi-threaded tools or set 0 for single threaded tools.',
            memory: 'Amount of RAM (in MB) required by the tool.',
            baseCMD: 'Enter name of the executable and (optionally) sub-command and fixed arguments (e.g. “bamtools sort -bS”).',
            addBaseCMD: 'Add base command.',
            successCodes: 'Array of exit codes that signal successful run (defaults to just 0).',
            tempFailCodes: 'Array of retriable exit codes.',
            stdin: 'If a tool can only take input on stdin, set an expression (</>) here to reference the input file (e.g. $job.inputs.reads.path).',
            stdout: 'Enter file name to redirect standard output into. To construct a name based on inputs, use an expression (</>).',
            addArgument: 'Describe a command line argument that doesn\'t map directly to any of the tool inputs (e.g. —num-threads should have the "value" field set to "$job.allocatedResources.cpu" expression).',
			createFiles: 'Here you can enumerate files that need to be created in the job directory before the command line is executed. File content can be a literal string (e.g. bash wrapper script) or an expression. If the expression evaluates to a File structure (object with "class" and "path" properties, with value for "class" being "File"), this indicates that the file should be copied to the job directory. This is usually used to copy input files before creating indices.'
		},
		inputs: {
			properties: 'Define tool input ports.',
            addInput: 'Add new input port.',
            inputId: 'IDs must be unique for all input and output ports. Value of this port will be available in expressions as $job.inputs["port_id"]. Allowed characters are alphanum and _.',
            type: 'Represents input type.',
            itemType: 'Represents array item type.',
            label: 'Name to show when presenting the input on graphical interfaces.',
            description: 'Help text to show when presenting the input on graphical interfaces.',
            category: 'Category where this input will be grouped under.',
            inputBinding: 'Include this input into command line, and it will show in command line preview bellow.'
		},
		outputs: {
			properties: 'Define tool output ports.',
            outputId: 'Unique output id (required property).',
            addOutput: 'Add new output port.',
            type: 'Represents output type.',
            itemType: 'Represents array item type. Allowed characters are alphanum and _.',
            glob: 'File(s) matching this glob expression will be reported as output(s) on this port.',
            metadata: 'File metadata is a map of string->string. If value depends on tool inputs, use an expression (</>) \n\n like $job.inputs.reads.meta.sample. more info (link to advanced features -> metadata)',
            secondaryFiles: 'click + to enumerate index files that should accompany this output.',
            secondaryFilesInfo: 'If a tool creates index files, list them here using file naming rules: ".ext" means that ".ext" is appended \n\n to original file name; "^.ext" means ".ext" is appended to file base name (after original extension is removed).'
		},
        // inputBindings and outputBindings
        bindings: {
            position: 'An integer priority of the input on the command line (lower comes first).',
            prefix: 'Prefix for named arguments (e.g. —input-file or -i). If value is not supplied or false, the prefix will not be added. \n\n If value is True, only prefix will be added.',
            separatePrefix: 'Character to use as separator between prefix and value. \n\n "Space" means pass as separate arguments.',
            itemSeparator: 'If specified, cast items to string and pass them as single argument (separated with supplied character).',
            value: 'Enter an expression (</>) to transform the input value before passing it to the command line. \n\n Original value is available as $self variable.'
        },
		metadata: {
			metadata: 'Fill additional information about app.',
            label: 'Application display label.',
            description: 'Application description (markdown works).',
            toolkit: 'Application toolkit name (e.g. "samtools").',
            toolkitVersion: 'Application toolkit version.',
            homepage: 'Application homepage url.',
            categories: 'Categories where application should be listed.'
		},
		test: {
			allocatedResources: '',
			inputs: ''
		},
		script: {
			script: ''
		}
	},
	dyole: {

	},
	main: {

	},
	app: {

	}
});<|endoftext|>


<commit_before>'use strict';

/*globals accounting*/

angular.module('main')
.controller('ComparisonSearchCtrl', function($scope, $state, $stateParams, $location, $modal, $backend, conceptMaps, conceptMapKeys, results) {
    $scope.none = 'US-GAAP Taxonomy Concepts';

    $scope.entityIndex = -1;
    $scope.API_URL = $backend.API_URL;

    $scope.conceptMaps = angular.copy(conceptMaps);
    $scope.conceptMaps.push($scope.none);
    $scope.conceptMapKeys = conceptMapKeys;
    $scope.dimensions = [];
    $scope.data = [];
    $scope.columns = [];
    $scope.errornoresults = false;
    $scope.Statistics = {};

    $scope.selection.map = $stateParams.map || $scope.none;
    $scope.selection.concept = ($stateParams.concept ? $stateParams.concept.split(',') : []);
    var src = $location.search();

    Object.keys(src).forEach(function (param) {
        if (param.indexOf(':') !== -1) {
            if (param.substring(param.length - 9, param.length) === '::default') {
                var name = param.substring(0, param.length - 9);
                $scope.dimensions.forEach(function(d) {
                    if (d.name === name)
                    {
                        d.defaultValue = src[param];
                    }
                });
            }
            else {
                $scope.dimensions.push({ name: param, value: src[param] });
            }
            $scope.selection[param] = src[param];
        }
    });

    if (results.FactTable && results.FactTable.length > 0)
    {
        $scope.params = {
            $method: 'POST',
            tag: $scope.selection.tag,
            cik: $scope.selection.cik,
            fiscalYear: $scope.selection.fiscalYear,
            fiscalPeriod: $scope.selection.fiscalPeriod,
            sic: $scope.selection.sic,
            concept: $scope.selection.concept,
            map: ($scope.selection.map !== 'US-GAAP Taxonomy Concepts' ? $scope.selection.map : null),
            token: $scope.token
        };
        $scope.dimensions.forEach(function(dimension) {
            $scope.params[dimension.name] = dimension.value;
            if (dimension.defaultValue)
            {
                $scope.params[dimension.name + '::default'] = dimension.defaultValue;
            }
        });
        $scope.data = results.FactTable;

        $scope.columns.push('xbrl:Concept');
        $scope.columns.push('xbrl:Entity');
        $scope.columns.push('xbrl:Period');
        $scope.columns.push('bizql:FiscalPeriod');
        $scope.columns.push('bizql:FiscalYear');
        var insertIndex = 3;

        Object.keys($scope.data[0].Aspects).forEach(function (el) {
            switch (el)
            {
                case 'xbrl:Entity':
                    $scope.entityIndex = 1;
                    break;
                case 'xbrl:Concept':
                case 'xbrl:Period':
                case 'bizql:FiscalPeriod':
                case 'bizql:FiscalYear':
                    break;
                case 'dei:LegalEntityAxis':
                    $scope.columns.splice(insertIndex, 0, el);
                    insertIndex++;
                    break;
                default:
                    $scope.columns.splice(insertIndex, 0, el);
            }
        });
    }
    $scope.errornoresults = ($scope.data.length === 0);
    $scope.Statistics = results.Statistics;

    $scope.selectMap = function() {
        $scope.selection.concept = [];
    };

    $scope.addConceptKey = function(item) {
        if (item && $scope.selection.concept.indexOf(item) < 0) {
            $scope.selection.concept.push(item);
        }
        $scope.conceptMapKey = '';
    };

    $scope.deleteConceptKey = function(item) {
        $scope.selection.concept.splice($scope.selection.concept.indexOf(item), 1);
    };

    $scope.addDimension = function () {
        var modalInstance = $modal.open({
            templateUrl: 'dimension.html',
            controller: ['$scope', '$modalInstance', function ($scope, $modalInstance) {
                $scope.dimension = {};
                $scope.links = [
                    { 'Name' : 'Legal entity', 'Dimension' : 'dei:LegalEntityAxis', 'Filter' : 'ALL', 'Default' : 'sec:DefaultLegalEntity' },
                    { 'Name' : 'Business segment', 'Dimension' : 'us-gaap:StatementBusinessSegmentsAxis', 'Filter' : 'ALL', 'Default' : 'us-gaap:SegmentDomain' },
                    { 'Name' : 'Geographic area', 'Dimension' : 'us-gaap:StatementGeographicalAxis', 'Filter' : 'ALL', 'Default' : 'us-gaap:SegmentGeographicalDomain' },
                    { 'Name' : 'Scenario', 'Dimension' : 'us-gaap:StatementScenarioAxis', 'Filter' : 'ALL', 'Default' : 'us-gaap:ScenarioUnspecifiedDomain' }
                ];
                $scope.ok = function () {
                    $scope.dimension.attempted = true;
                    if(!$scope.dimension.form.$invalid) {
                        $modalInstance.close({
                            name: $scope.dimension.name,
                            value: $scope.dimension.value,
                            defaultValue: $scope.dimension.defaultValue
                        });
                    }
                };

                $scope.applyLink = function(l) {
                    $scope.dimension.name = l.Dimension;
                    $scope.dimension.value = l.Filter;
                    $scope.dimension.defaultValue = l.Default;
                };

                $scope.cancel = function () {
                    $modalInstance.dismiss('cancel');
                };
            }]
        });

        modalInstance.result.then(function (item) {
            if ($scope.dimensions.indexOf(item) < 0) {
                $scope.dimensions.push(item);
                $scope.selection[item.name] = item.value;
                if (item.defaultValue)
                {
                    $scope.selection[item.name + '::default'] = item.defaultValue;
                }
                $scope.selection.stamp=(new Date()).getTime();
            }
        });
    };

    $scope.deleteDimension = function(item) {
        var name = item.name;
        var def = item.defaultValue;
        $scope.dimensions.splice($scope.dimensions.indexOf(item), 1);
        delete $scope.selection[name];
        if (def)
        {
            delete $scope.selection[name + '::default'];
        }
        $scope.selection.stamp=(new Date()).getTime();
    };

    $scope.submit = function() {
        if ($scope.conceptMapKey) {
            $scope.addConceptKey($scope.conceptMapKey);
        }

        if ($scope.selection.concept.length === 0)
        {
            $scope.$emit('alert', 'Warning', 'Please choose concepts to compare.');
            return false;
        }
        $scope.selection.stamp=(new Date()).getTime();
    };

    $scope.trimURL = function(url) {
        if (url.length < 40) {
            return url;
        }
        return url.substr(0, 10) + '...' + url.substr(url.length - 30);
    };

    $scope.trim = function(item) {
        return angular.copy(item).splice(4, item.length - 5);
    };

    $scope.clear = function(item) {
        return item.replace('iso4217:', '').replace('xbrli:', '');
    };

    $scope.showText = function(html) {
        $scope.$emit('alert', 'Text Details', html);
    };

    $scope.showNumber = function(value) {
        return accounting.formatNumber(value);
    };

    $scope.isBlock = function(string) {
        if (!string) {
            return false;
        }
        return string.length > 60;
    };

    $scope.getUrl = function(format) {
        var str = $backend.API_URL + '/_queries/public/api/facts.jq';
        var params = angular.copy($scope.params);
        if (format) {
            params.format = format;
        }
        var qs = $scope.wwwFormUrlencoded(params);
        if (qs) {
            str += '?' + qs;
        }
        return str;
    };
});
<commit_msg>send rules parameter if concept map is chosen<commit_after>'use strict';

/*globals accounting*/

angular.module('main')
.controller('ComparisonSearchCtrl', function($scope, $state, $stateParams, $location, $modal, $backend, conceptMaps, conceptMapKeys, results) {
    $scope.none = 'US-GAAP Taxonomy Concepts';

    $scope.entityIndex = -1;
    $scope.API_URL = $backend.API_URL;

    $scope.conceptMaps = angular.copy(conceptMaps);
    $scope.conceptMaps.push($scope.none);
    $scope.conceptMapKeys = conceptMapKeys;
    $scope.dimensions = [];
    $scope.data = [];
    $scope.columns = [];
    $scope.errornoresults = false;
    $scope.Statistics = {};

    $scope.selection.map = $stateParams.map || $scope.none;
    $scope.selection.concept = ($stateParams.concept ? $stateParams.concept.split(',') : []);
    var src = $location.search();

    Object.keys(src).forEach(function (param) {
        if (param.indexOf(':') !== -1) {
            if (param.substring(param.length - 9, param.length) === '::default') {
                var name = param.substring(0, param.length - 9);
                $scope.dimensions.forEach(function(d) {
                    if (d.name === name)
                    {
                        d.defaultValue = src[param];
                    }
                });
            }
            else {
                $scope.dimensions.push({ name: param, value: src[param] });
            }
            $scope.selection[param] = src[param];
        }
    });

    if (results.FactTable && results.FactTable.length > 0)
    {
        $scope.params = {
            $method: 'POST',
            tag: $scope.selection.tag,
            cik: $scope.selection.cik,
            fiscalYear: $scope.selection.fiscalYear,
            fiscalPeriod: $scope.selection.fiscalPeriod,
            sic: $scope.selection.sic,
            concept: $scope.selection.concept,
            map: ($scope.selection.map !== 'US-GAAP Taxonomy Concepts' ? $scope.selection.map : null),
            rules: ($scope.selection.map !== 'US-GAAP Taxonomy Concepts' ? $scope.selection.map : null),
            token: $scope.token
        };
        $scope.dimensions.forEach(function(dimension) {
            $scope.params[dimension.name] = dimension.value;
            if (dimension.defaultValue)
            {
                $scope.params[dimension.name + '::default'] = dimension.defaultValue;
            }
        });
        $scope.data = results.FactTable;

        $scope.columns.push('xbrl:Concept');
        $scope.columns.push('xbrl:Entity');
        $scope.columns.push('xbrl:Period');
        $scope.columns.push('bizql:FiscalPeriod');
        $scope.columns.push('bizql:FiscalYear');
        var insertIndex = 3;

        Object.keys($scope.data[0].Aspects).forEach(function (el) {
            switch (el)
            {
                case 'xbrl:Entity':
                    $scope.entityIndex = 1;
                    break;
                case 'xbrl:Concept':
                case 'xbrl:Period':
                case 'bizql:FiscalPeriod':
                case 'bizql:FiscalYear':
                    break;
                case 'dei:LegalEntityAxis':
                    $scope.columns.splice(insertIndex, 0, el);
                    insertIndex++;
                    break;
                default:
                    $scope.columns.splice(insertIndex, 0, el);
            }
        });
    }
    $scope.errornoresults = ($scope.data.length === 0);
    $scope.Statistics = results.Statistics;

    $scope.selectMap = function() {
        $scope.selection.concept = [];
    };

    $scope.addConceptKey = function(item) {
        if (item && $scope.selection.concept.indexOf(item) < 0) {
            $scope.selection.concept.push(item);
        }
        $scope.conceptMapKey = '';
    };

    $scope.deleteConceptKey = function(item) {
        $scope.selection.concept.splice($scope.selection.concept.indexOf(item), 1);
    };

    $scope.addDimension = function () {
        var modalInstance = $modal.open({
            templateUrl: 'dimension.html',
            controller: ['$scope', '$modalInstance', function ($scope, $modalInstance) {
                $scope.dimension = {};
                $scope.links = [
                    { 'Name' : 'Legal entity', 'Dimension' : 'dei:LegalEntityAxis', 'Filter' : 'ALL', 'Default' : 'sec:DefaultLegalEntity' },
                    { 'Name' : 'Business segment', 'Dimension' : 'us-gaap:StatementBusinessSegmentsAxis', 'Filter' : 'ALL', 'Default' : 'us-gaap:SegmentDomain' },
                    { 'Name' : 'Geographic area', 'Dimension' : 'us-gaap:StatementGeographicalAxis', 'Filter' : 'ALL', 'Default' : 'us-gaap:SegmentGeographicalDomain' },
                    { 'Name' : 'Scenario', 'Dimension' : 'us-gaap:StatementScenarioAxis', 'Filter' : 'ALL', 'Default' : 'us-gaap:ScenarioUnspecifiedDomain' }
                ];
                $scope.ok = function () {
                    $scope.dimension.attempted = true;
                    if(!$scope.dimension.form.$invalid) {
                        $modalInstance.close({
                            name: $scope.dimension.name,
                            value: $scope.dimension.value,
                            defaultValue: $scope.dimension.defaultValue
                        });
                    }
                };

                $scope.applyLink = function(l) {
                    $scope.dimension.name = l.Dimension;
                    $scope.dimension.value = l.Filter;
                    $scope.dimension.defaultValue = l.Default;
                };

                $scope.cancel = function () {
                    $modalInstance.dismiss('cancel');
                };
            }]
        });

        modalInstance.result.then(function (item) {
            if ($scope.dimensions.indexOf(item) < 0) {
                $scope.dimensions.push(item);
                $scope.selection[item.name] = item.value;
                if (item.defaultValue)
                {
                    $scope.selection[item.name + '::default'] = item.defaultValue;
                }
                $scope.selection.stamp=(new Date()).getTime();
            }
        });
    };

    $scope.deleteDimension = function(item) {
        var name = item.name;
        var def = item.defaultValue;
        $scope.dimensions.splice($scope.dimensions.indexOf(item), 1);
        delete $scope.selection[name];
        if (def)
        {
            delete $scope.selection[name + '::default'];
        }
        $scope.selection.stamp=(new Date()).getTime();
    };

    $scope.submit = function() {
        if ($scope.conceptMapKey) {
            $scope.addConceptKey($scope.conceptMapKey);
        }

        if ($scope.selection.concept.length === 0)
        {
            $scope.$emit('alert', 'Warning', 'Please choose concepts to compare.');
            return false;
        }
        $scope.selection.stamp=(new Date()).getTime();
    };

    $scope.trimURL = function(url) {
        if (url.length < 40) {
            return url;
        }
        return url.substr(0, 10) + '...' + url.substr(url.length - 30);
    };

    $scope.trim = function(item) {
        return angular.copy(item).splice(4, item.length - 5);
    };

    $scope.clear = function(item) {
        return item.replace('iso4217:', '').replace('xbrli:', '');
    };

    $scope.showText = function(html) {
        $scope.$emit('alert', 'Text Details', html);
    };

    $scope.showNumber = function(value) {
        return accounting.formatNumber(value);
    };

    $scope.isBlock = function(string) {
        if (!string) {
            return false;
        }
        return string.length > 60;
    };

    $scope.getUrl = function(format) {
        var str = $backend.API_URL + '/_queries/public/api/facts.jq';
        var params = angular.copy($scope.params);
        if (format) {
            params.format = format;
        }
        var qs = $scope.wwwFormUrlencoded(params);
        if (qs) {
            str += '?' + qs;
        }
        return str;
    };
});
<|endoftext|>