<commit_before>define([
  'angular',
  'jquery',
  'lodash',
  'moment',
],
function (angular, $, _, moment) {
  'use strict';

  var module = angular.module('grafana.services');

  module.factory('dashboardSrv', function(contextSrv)  {

    function DashboardModel (data, meta) {
      if (!data) {
        data = {};
      }

      this.id = data.id || null;
      this.title = data.title || 'No Title';
      this.autoUpdate = data.autoUpdate;
      this.description = data.description;
      this.tags = data.tags || [];
      this.style = data.style || "dark";
      this.timezone = data.timezone || '';
      this.editable = data.editable !== false;
      this.hideControls = data.hideControls || false;
      this.sharedCrosshair = data.sharedCrosshair || false;
      this.rows = data.rows || [];
      this.time = data.time || { from: 'now-6h', to: 'now' };
      this.timepicker = data.timepicker || {};
      this.templating = this._ensureListExist(data.templating);
      this.annotations = this._ensureListExist(data.annotations);
      this.refresh = data.refresh;
      this.snapshot = data.snapshot;
      this.schemaVersion = data.schemaVersion || 0;
      this.version = data.version || 0;
      this.links = data.links || [];
      this.gnetId = data.gnetId || null;
      this._updateSchema(data);
      this._initMeta(meta);
    }

    var p = DashboardModel.prototype;

    p._initMeta = function(meta) {
      meta = meta || {};

      meta.canShare = meta.canShare !== false;
      meta.canSave = meta.canSave !== false;
      meta.canStar = meta.canStar !== false;
      meta.canEdit = meta.canEdit !== false;

      if (!this.editable) {
        meta.canEdit = false;
        meta.canDelete = false;
        meta.canSave = false;
        this.hideControls = true;
      }

      this.meta = meta;
    };

    // cleans meta data and other non peristent state
    p.getSaveModelClone = function() {
      var copy = $.extend(true, {}, this);
      delete copy.meta;
      return copy;
    };

    p._ensureListExist = function (data) {
      if (!data) { data = {}; }
      if (!data.list) { data.list = []; }
      return data;
    };

    p.getNextPanelId = function() {
      var i, j, row, panel, max = 0;
      for (i = 0; i < this.rows.length; i++) {
        row = this.rows[i];
        for (j = 0; j < row.panels.length; j++) {
          panel = row.panels[j];
          if (panel.id > max) { max = panel.id; }
        }
      }
      return max + 1;
    };

    p.forEachPanel = function(callback) {
      var i, j, row;
      for (i = 0; i < this.rows.length; i++) {
        row = this.rows[i];
        for (j = 0; j < row.panels.length; j++) {
          callback(row.panels[j], j, row, i);
        }
      }
    };

    p.getPanelById = function(id) {
      for (var i = 0; i < this.rows.length; i++) {
        var row = this.rows[i];
        for (var j = 0; j < row.panels.length; j++) {
          var panel = row.panels[j];
          if (panel.id === id) {
            return panel;
          }
        }
      }
      return null;
    };

    p.rowSpan = function(row) {
      return _.reduce(row.panels, function(p,v) {
        return p + v.span;
      },0);
    };

    p.addPanel = function(panel, row) {
      var rowSpan = this.rowSpan(row);
      var panelCount = row.panels.length;
      var space = (12 - rowSpan) - panel.span;
      panel.id = this.getNextPanelId();

      // try to make room of there is no space left
      if (space <= 0) {
        if (panelCount === 1) {
          row.panels[0].span = 6;
          panel.span = 6;
        }
        else if (panelCount === 2) {
          row.panels[0].span = 4;
          row.panels[1].span = 4;
          panel.span = 4;
        }
      }

      row.panels.push(panel);
    };

    p.isSubmenuFeaturesEnabled = function() {
      var visableTemplates = _.filter(this.templating.list, function(template) {
        return template.hideVariable === undefined || template.hideVariable === false;
      });

      return visableTemplates.length > 0 || this.annotations.list.length > 0 || this.links.length > 0;
    };

    p.getPanelInfoById = function(panelId) {
      var result = {};
      _.each(this.rows, function(row) {
        _.each(row.panels, function(panel, index) {
          if (panel.id === panelId) {
            result.panel = panel;
            result.row = row;
            result.index = index;
          }
        });
      });

      if (!result.panel) {
        return null;
      }

      return result;
    };

    p.duplicatePanel = function(panel, row) {
      var rowIndex = _.indexOf(this.rows, row);
      var newPanel = angular.copy(panel);
      newPanel.id = this.getNextPanelId();

      delete newPanel.repeat;
      delete newPanel.repeatIteration;
      delete newPanel.repeatPanelId;
      delete newPanel.scopedVars;

      var currentRow = this.rows[rowIndex];
      currentRow.panels.push(newPanel);
      return newPanel;
    };

    p.formatDate = function(date, format) {
      date = moment.isMoment(date) ? date : moment(date);
      format = format || 'YYYY-MM-DD HH:mm:ss';
      this.timezone = this.getTimezone();

      return this.timezone === 'browser' ?
        moment(date).format(format) :
        moment.utc(date).format(format);
    };

    p.getRelativeTime = function(date) {
      date = moment.isMoment(date) ? date : moment(date);

      return this.timezone === 'browser' ?
        moment(date).fromNow() :
        moment.utc(date).fromNow();
    };

    p.getNextQueryLetter = function(panel) {
      var letters = 'ABCDEFGHIJKLMNOPQRSTUVWXYZ';

      return _.find(letters, function(refId) {
        return _.every(panel.targets, function(other) {
          return other.refId !== refId;
        });
      });
    };

    p.isTimezoneUtc = function() {
      return this.getTimezone() === 'utc';
    };

    p.getTimezone = function() {
      return this.timezone ? this.timezone : contextSrv.user.timezone;
    };

    p._updateSchema = function(old) {
      var i, j, k;
      var oldVersion = this.schemaVersion;
      var panelUpgrades = [];
      this.schemaVersion = 13;

      if (oldVersion === this.schemaVersion) {
        return;
      }

      // version 2 schema changes
      if (oldVersion < 2) {

        if (old.services) {
          if (old.services.filter) {
            this.time = old.services.filter.time;
            this.templating.list = old.services.filter.list || [];
          }
          delete this.services;
        }

        panelUpgrades.push(function(panel) {
          // rename panel type
          if (panel.type === 'graphite') {
            panel.type = 'graph';
          }

          if (panel.type !== 'graph') {
            return;
          }

          if (_.isBoolean(panel.legend)) { panel.legend = { show: panel.legend }; }

          if (panel.grid) {
            if (panel.grid.min) {
              panel.grid.leftMin = panel.grid.min;
              delete panel.grid.min;
            }

            if (panel.grid.max) {
              panel.grid.leftMax = panel.grid.max;
              delete panel.grid.max;
            }
          }

          if (panel.y_format) {
            panel.y_formats[0] = panel.y_format;
            delete panel.y_format;
          }

          if (panel.y2_format) {
            panel.y_formats[1] = panel.y2_format;
            delete panel.y2_format;
          }
        });
      }

      // schema version 3 changes
      if (oldVersion < 3) {
        // ensure panel ids
        var maxId = this.getNextPanelId();
        panelUpgrades.push(function(panel) {
          if (!panel.id) {
            panel.id = maxId;
            maxId += 1;
          }
        });
      }

      // schema version 4 changes
      if (oldVersion < 4) {
        // move aliasYAxis changes
        panelUpgrades.push(function(panel) {
          if (panel.type !== 'graph') { return; }
          _.each(panel.aliasYAxis, function(value, key) {
            panel.seriesOverrides = [{ alias: key, yaxis: value }];
          });
          delete panel.aliasYAxis;
        });
      }

      if (oldVersion < 6) {
        // move pulldowns to new schema
        var annotations = _.findWhere(old.pulldowns, { type: 'annotations' });

        if (annotations) {
          this.annotations = {
            list: annotations.annotations || [],
          };
        }

        // update template variables
        for (i = 0 ; i < this.templating.list.length; i++) {
          var variable = this.templating.list[i];
          if (variable.datasource === void 0) { variable.datasource = null; }
          if (variable.type === 'filter') { variable.type = 'query'; }
          if (variable.type === void 0) { variable.type = 'query'; }
          if (variable.allFormat === void 0) { variable.allFormat = 'glob'; }
        }
      }

      if (oldVersion < 7) {
        if (old.nav && old.nav.length) {
          this.timepicker = old.nav[0];
          delete this.nav;
        }

        // ensure query refIds
        panelUpgrades.push(function(panel) {
          _.each(panel.targets, function(target) {
            if (!target.refId) {
              target.refId = this.getNextQueryLetter(panel);
            }
          }, this);
        });
      }

      if (oldVersion < 8) {
        panelUpgrades.push(function(panel) {
          _.each(panel.targets, function(target) {
            // update old influxdb query schema
            if (target.fields && target.tags && target.groupBy) {
              if (target.rawQuery) {
                delete target.fields;
                delete target.fill;
              } else {
                target.select = _.map(target.fields, function(field) {
                  var parts = [];
                  parts.push({type: 'field', params: [field.name]});
                  parts.push({type: field.func, params: []});
                  if (field.mathExpr) {
                    parts.push({type: 'math', params: [field.mathExpr]});
                  }
                  if (field.asExpr) {
                    parts.push({type: 'alias', params: [field.asExpr]});
                  }
                  return parts;
                });
                delete target.fields;
                _.each(target.groupBy, function(part) {
                  if (part.type === 'time' && part.interval)  {
                    part.params = [part.interval];
                    delete part.interval;
                  }
                  if (part.type === 'tag' && part.key) {
                    part.params = [part.key];
                    delete part.key;
                  }
                });

                if (target.fill) {
                  target.groupBy.push({type: 'fill', params: [target.fill]});
                  delete target.fill;
                }
              }
            }
          });
        });
      }

      // schema version 9 changes
      if (oldVersion < 9) {
        // move aliasYAxis changes
        panelUpgrades.push(function(panel) {
          if (panel.type !== 'singlestat' && panel.thresholds !== "") { return; }

          if (panel.thresholds) {
            var k = panel.thresholds.split(",");

            if (k.length >= 3) {
              k.shift();
              panel.thresholds = k.join(",");
            }
          }
        });
      }

      // schema version 10 changes
      if (oldVersion < 10) {
        // move aliasYAxis changes
        panelUpgrades.push(function(panel) {
          if (panel.type !== 'table') { return; }

          _.each(panel.styles, function(style) {
            if (style.thresholds && style.thresholds.length >= 3) {
              var k = style.thresholds;
              k.shift();
              style.thresholds = k;
            }
          });
        });
      }

      if (oldVersion < 12) {
        // update template variables
        _.each(this.templating.list, function(templateVariable) {
          if (templateVariable.refresh) { templateVariable.refresh = 1; }
          if (!templateVariable.refresh) { templateVariable.refresh = 0; }
          if (templateVariable.hideVariable) {
            templateVariable.hide = 2;
          } else if (templateVariable.hideLabel) {
            templateVariable.hide = 1;
          } else {
            templateVariable.hide = 0;
          }
        });
      }

      if (oldVersion < 12) {
        // update graph yaxes changes
        panelUpgrades.push(function(panel) {
          if (panel.type !== 'graph') { return; }
          if (!panel.grid) { return; }

          if (!panel.yaxes) {
            panel.yaxes = [
              {
                show: panel['y-axis'],
                min: panel.grid.leftMin,
                max: panel.grid.leftMax,
                logBase: panel.grid.leftLogBase,
                format: panel.y_formats[0],
                label: panel.leftYAxisLabel,
              },
              {
                show: panel['y-axis'],
                min: panel.grid.rightMin,
                max: panel.grid.rightMax,
                logBase: panel.grid.rightLogBase,
                format: panel.y_formats[1],
                label: panel.rightYAxisLabel,
              }
            ];

            panel.xaxis = {
              show: panel['x-axis'],
            };

            delete panel.grid.leftMin;
            delete panel.grid.leftMax;
            delete panel.grid.leftLogBase;
            delete panel.grid.rightMin;
            delete panel.grid.rightMax;
            delete panel.grid.rightLogBase;
            delete panel.y_formats;
            delete panel.leftYAxisLabel;
            delete panel.rightYAxisLabel;
            delete panel['y-axis'];
            delete panel['x-axis'];
          }
        });
      }

      if (oldVersion < 13) {
        // update graph yaxes changes
        panelUpgrades.push(function(panel) {
          if (panel.type !== 'graph') { return; }

          panel.thresholds = [];
          var t1 = {}, t2 = {};

          if (panel.grid.threshold1 !== null) {
            t1.value = panel.grid.threshold1;
            if (panel.grid.thresholdLine) {
              t1.line = true;
              t1.lineColor = panel.grid.threshold1Color;
            } else {
              t1.fill = true;
              t1.fillColor = panel.grid.threshold1Color;
            }
          }

          if (panel.grid.threshold2 !== null) {
            t2.value = panel.grid.threshold2;
            if (panel.grid.thresholdLine) {
              t2.line = true;
              t2.lineColor = panel.grid.threshold2Color;
            } else {
              t2.fill = true;
              t2.fillColor = panel.grid.threshold2Color;
            }
          }

          if (_.isNumber(t1.value)) {
            if (_.isNumber(t2.value)) {
              if (t1.value > t2.value) {
                t1.op = t2.op = '<';
                panel.thresholds.push(t2);
                panel.thresholds.push(t1);
              } else {
                t1.op = t2.op = '>';
                panel.thresholds.push(t2);
                panel.thresholds.push(t1);
              }
            } else {
              t1.op = '>';
              panel.thresholds.push(t1);
            }
          }
        });
      }

      if (panelUpgrades.length === 0) {
        return;
      }

      for (i = 0; i < this.rows.length; i++) {
        var row = this.rows[i];
        for (j = 0; j < row.panels.length; j++) {
          for (k = 0; k < panelUpgrades.length; k++) {
            panelUpgrades[k].call(this, row.panels[j]);
          }
        }
      }
    };

    return {
      create: function(dashboard, meta) {
        return new DashboardModel(dashboard, meta);
      },
      setCurrent: function(dashboard) {
        this.currentDashboard = dashboard;
      },
      getCurrent: function() {
        return this.currentDashboard;
      },
    };
  });
});
<commit_msg>fix(threshold): remove old threshold properties<commit_after>define([
  'angular',
  'jquery',
  'lodash',
  'moment',
],
function (angular, $, _, moment) {
  'use strict';

  var module = angular.module('grafana.services');

  module.factory('dashboardSrv', function(contextSrv)  {

    function DashboardModel (data, meta) {
      if (!data) {
        data = {};
      }

      this.id = data.id || null;
      this.title = data.title || 'No Title';
      this.autoUpdate = data.autoUpdate;
      this.description = data.description;
      this.tags = data.tags || [];
      this.style = data.style || "dark";
      this.timezone = data.timezone || '';
      this.editable = data.editable !== false;
      this.hideControls = data.hideControls || false;
      this.sharedCrosshair = data.sharedCrosshair || false;
      this.rows = data.rows || [];
      this.time = data.time || { from: 'now-6h', to: 'now' };
      this.timepicker = data.timepicker || {};
      this.templating = this._ensureListExist(data.templating);
      this.annotations = this._ensureListExist(data.annotations);
      this.refresh = data.refresh;
      this.snapshot = data.snapshot;
      this.schemaVersion = data.schemaVersion || 0;
      this.version = data.version || 0;
      this.links = data.links || [];
      this.gnetId = data.gnetId || null;
      this._updateSchema(data);
      this._initMeta(meta);
    }

    var p = DashboardModel.prototype;

    p._initMeta = function(meta) {
      meta = meta || {};

      meta.canShare = meta.canShare !== false;
      meta.canSave = meta.canSave !== false;
      meta.canStar = meta.canStar !== false;
      meta.canEdit = meta.canEdit !== false;

      if (!this.editable) {
        meta.canEdit = false;
        meta.canDelete = false;
        meta.canSave = false;
        this.hideControls = true;
      }

      this.meta = meta;
    };

    // cleans meta data and other non peristent state
    p.getSaveModelClone = function() {
      var copy = $.extend(true, {}, this);
      delete copy.meta;
      return copy;
    };

    p._ensureListExist = function (data) {
      if (!data) { data = {}; }
      if (!data.list) { data.list = []; }
      return data;
    };

    p.getNextPanelId = function() {
      var i, j, row, panel, max = 0;
      for (i = 0; i < this.rows.length; i++) {
        row = this.rows[i];
        for (j = 0; j < row.panels.length; j++) {
          panel = row.panels[j];
          if (panel.id > max) { max = panel.id; }
        }
      }
      return max + 1;
    };

    p.forEachPanel = function(callback) {
      var i, j, row;
      for (i = 0; i < this.rows.length; i++) {
        row = this.rows[i];
        for (j = 0; j < row.panels.length; j++) {
          callback(row.panels[j], j, row, i);
        }
      }
    };

    p.getPanelById = function(id) {
      for (var i = 0; i < this.rows.length; i++) {
        var row = this.rows[i];
        for (var j = 0; j < row.panels.length; j++) {
          var panel = row.panels[j];
          if (panel.id === id) {
            return panel;
          }
        }
      }
      return null;
    };

    p.rowSpan = function(row) {
      return _.reduce(row.panels, function(p,v) {
        return p + v.span;
      },0);
    };

    p.addPanel = function(panel, row) {
      var rowSpan = this.rowSpan(row);
      var panelCount = row.panels.length;
      var space = (12 - rowSpan) - panel.span;
      panel.id = this.getNextPanelId();

      // try to make room of there is no space left
      if (space <= 0) {
        if (panelCount === 1) {
          row.panels[0].span = 6;
          panel.span = 6;
        }
        else if (panelCount === 2) {
          row.panels[0].span = 4;
          row.panels[1].span = 4;
          panel.span = 4;
        }
      }

      row.panels.push(panel);
    };

    p.isSubmenuFeaturesEnabled = function() {
      var visableTemplates = _.filter(this.templating.list, function(template) {
        return template.hideVariable === undefined || template.hideVariable === false;
      });

      return visableTemplates.length > 0 || this.annotations.list.length > 0 || this.links.length > 0;
    };

    p.getPanelInfoById = function(panelId) {
      var result = {};
      _.each(this.rows, function(row) {
        _.each(row.panels, function(panel, index) {
          if (panel.id === panelId) {
            result.panel = panel;
            result.row = row;
            result.index = index;
          }
        });
      });

      if (!result.panel) {
        return null;
      }

      return result;
    };

    p.duplicatePanel = function(panel, row) {
      var rowIndex = _.indexOf(this.rows, row);
      var newPanel = angular.copy(panel);
      newPanel.id = this.getNextPanelId();

      delete newPanel.repeat;
      delete newPanel.repeatIteration;
      delete newPanel.repeatPanelId;
      delete newPanel.scopedVars;

      var currentRow = this.rows[rowIndex];
      currentRow.panels.push(newPanel);
      return newPanel;
    };

    p.formatDate = function(date, format) {
      date = moment.isMoment(date) ? date : moment(date);
      format = format || 'YYYY-MM-DD HH:mm:ss';
      this.timezone = this.getTimezone();

      return this.timezone === 'browser' ?
        moment(date).format(format) :
        moment.utc(date).format(format);
    };

    p.getRelativeTime = function(date) {
      date = moment.isMoment(date) ? date : moment(date);

      return this.timezone === 'browser' ?
        moment(date).fromNow() :
        moment.utc(date).fromNow();
    };

    p.getNextQueryLetter = function(panel) {
      var letters = 'ABCDEFGHIJKLMNOPQRSTUVWXYZ';

      return _.find(letters, function(refId) {
        return _.every(panel.targets, function(other) {
          return other.refId !== refId;
        });
      });
    };

    p.isTimezoneUtc = function() {
      return this.getTimezone() === 'utc';
    };

    p.getTimezone = function() {
      return this.timezone ? this.timezone : contextSrv.user.timezone;
    };

    p._updateSchema = function(old) {
      var i, j, k;
      var oldVersion = this.schemaVersion;
      var panelUpgrades = [];
      this.schemaVersion = 13;

      if (oldVersion === this.schemaVersion) {
        return;
      }

      // version 2 schema changes
      if (oldVersion < 2) {

        if (old.services) {
          if (old.services.filter) {
            this.time = old.services.filter.time;
            this.templating.list = old.services.filter.list || [];
          }
          delete this.services;
        }

        panelUpgrades.push(function(panel) {
          // rename panel type
          if (panel.type === 'graphite') {
            panel.type = 'graph';
          }

          if (panel.type !== 'graph') {
            return;
          }

          if (_.isBoolean(panel.legend)) { panel.legend = { show: panel.legend }; }

          if (panel.grid) {
            if (panel.grid.min) {
              panel.grid.leftMin = panel.grid.min;
              delete panel.grid.min;
            }

            if (panel.grid.max) {
              panel.grid.leftMax = panel.grid.max;
              delete panel.grid.max;
            }
          }

          if (panel.y_format) {
            panel.y_formats[0] = panel.y_format;
            delete panel.y_format;
          }

          if (panel.y2_format) {
            panel.y_formats[1] = panel.y2_format;
            delete panel.y2_format;
          }
        });
      }

      // schema version 3 changes
      if (oldVersion < 3) {
        // ensure panel ids
        var maxId = this.getNextPanelId();
        panelUpgrades.push(function(panel) {
          if (!panel.id) {
            panel.id = maxId;
            maxId += 1;
          }
        });
      }

      // schema version 4 changes
      if (oldVersion < 4) {
        // move aliasYAxis changes
        panelUpgrades.push(function(panel) {
          if (panel.type !== 'graph') { return; }
          _.each(panel.aliasYAxis, function(value, key) {
            panel.seriesOverrides = [{ alias: key, yaxis: value }];
          });
          delete panel.aliasYAxis;
        });
      }

      if (oldVersion < 6) {
        // move pulldowns to new schema
        var annotations = _.findWhere(old.pulldowns, { type: 'annotations' });

        if (annotations) {
          this.annotations = {
            list: annotations.annotations || [],
          };
        }

        // update template variables
        for (i = 0 ; i < this.templating.list.length; i++) {
          var variable = this.templating.list[i];
          if (variable.datasource === void 0) { variable.datasource = null; }
          if (variable.type === 'filter') { variable.type = 'query'; }
          if (variable.type === void 0) { variable.type = 'query'; }
          if (variable.allFormat === void 0) { variable.allFormat = 'glob'; }
        }
      }

      if (oldVersion < 7) {
        if (old.nav && old.nav.length) {
          this.timepicker = old.nav[0];
          delete this.nav;
        }

        // ensure query refIds
        panelUpgrades.push(function(panel) {
          _.each(panel.targets, function(target) {
            if (!target.refId) {
              target.refId = this.getNextQueryLetter(panel);
            }
          }, this);
        });
      }

      if (oldVersion < 8) {
        panelUpgrades.push(function(panel) {
          _.each(panel.targets, function(target) {
            // update old influxdb query schema
            if (target.fields && target.tags && target.groupBy) {
              if (target.rawQuery) {
                delete target.fields;
                delete target.fill;
              } else {
                target.select = _.map(target.fields, function(field) {
                  var parts = [];
                  parts.push({type: 'field', params: [field.name]});
                  parts.push({type: field.func, params: []});
                  if (field.mathExpr) {
                    parts.push({type: 'math', params: [field.mathExpr]});
                  }
                  if (field.asExpr) {
                    parts.push({type: 'alias', params: [field.asExpr]});
                  }
                  return parts;
                });
                delete target.fields;
                _.each(target.groupBy, function(part) {
                  if (part.type === 'time' && part.interval)  {
                    part.params = [part.interval];
                    delete part.interval;
                  }
                  if (part.type === 'tag' && part.key) {
                    part.params = [part.key];
                    delete part.key;
                  }
                });

                if (target.fill) {
                  target.groupBy.push({type: 'fill', params: [target.fill]});
                  delete target.fill;
                }
              }
            }
          });
        });
      }

      // schema version 9 changes
      if (oldVersion < 9) {
        // move aliasYAxis changes
        panelUpgrades.push(function(panel) {
          if (panel.type !== 'singlestat' && panel.thresholds !== "") { return; }

          if (panel.thresholds) {
            var k = panel.thresholds.split(",");

            if (k.length >= 3) {
              k.shift();
              panel.thresholds = k.join(",");
            }
          }
        });
      }

      // schema version 10 changes
      if (oldVersion < 10) {
        // move aliasYAxis changes
        panelUpgrades.push(function(panel) {
          if (panel.type !== 'table') { return; }

          _.each(panel.styles, function(style) {
            if (style.thresholds && style.thresholds.length >= 3) {
              var k = style.thresholds;
              k.shift();
              style.thresholds = k;
            }
          });
        });
      }

      if (oldVersion < 12) {
        // update template variables
        _.each(this.templating.list, function(templateVariable) {
          if (templateVariable.refresh) { templateVariable.refresh = 1; }
          if (!templateVariable.refresh) { templateVariable.refresh = 0; }
          if (templateVariable.hideVariable) {
            templateVariable.hide = 2;
          } else if (templateVariable.hideLabel) {
            templateVariable.hide = 1;
          } else {
            templateVariable.hide = 0;
          }
        });
      }

      if (oldVersion < 12) {
        // update graph yaxes changes
        panelUpgrades.push(function(panel) {
          if (panel.type !== 'graph') { return; }
          if (!panel.grid) { return; }

          if (!panel.yaxes) {
            panel.yaxes = [
              {
                show: panel['y-axis'],
                min: panel.grid.leftMin,
                max: panel.grid.leftMax,
                logBase: panel.grid.leftLogBase,
                format: panel.y_formats[0],
                label: panel.leftYAxisLabel,
              },
              {
                show: panel['y-axis'],
                min: panel.grid.rightMin,
                max: panel.grid.rightMax,
                logBase: panel.grid.rightLogBase,
                format: panel.y_formats[1],
                label: panel.rightYAxisLabel,
              }
            ];

            panel.xaxis = {
              show: panel['x-axis'],
            };

            delete panel.grid.leftMin;
            delete panel.grid.leftMax;
            delete panel.grid.leftLogBase;
            delete panel.grid.rightMin;
            delete panel.grid.rightMax;
            delete panel.grid.rightLogBase;
            delete panel.y_formats;
            delete panel.leftYAxisLabel;
            delete panel.rightYAxisLabel;
            delete panel['y-axis'];
            delete panel['x-axis'];
          }
        });
      }

      if (oldVersion < 13) {
        // update graph yaxes changes
        panelUpgrades.push(function(panel) {
          if (panel.type !== 'graph') { return; }

          panel.thresholds = [];
          var t1 = {}, t2 = {};

          if (panel.grid.threshold1 !== null) {
            t1.value = panel.grid.threshold1;
            if (panel.grid.thresholdLine) {
              t1.line = true;
              t1.lineColor = panel.grid.threshold1Color;
            } else {
              t1.fill = true;
              t1.fillColor = panel.grid.threshold1Color;
            }
          }

          if (panel.grid.threshold2 !== null) {
            t2.value = panel.grid.threshold2;
            if (panel.grid.thresholdLine) {
              t2.line = true;
              t2.lineColor = panel.grid.threshold2Color;
            } else {
              t2.fill = true;
              t2.fillColor = panel.grid.threshold2Color;
            }
          }

          if (_.isNumber(t1.value)) {
            if (_.isNumber(t2.value)) {
              if (t1.value > t2.value) {
                t1.op = t2.op = '<';
                panel.thresholds.push(t2);
                panel.thresholds.push(t1);
              } else {
                t1.op = t2.op = '>';
                panel.thresholds.push(t2);
                panel.thresholds.push(t1);
              }
            } else {
              t1.op = '>';
              panel.thresholds.push(t1);
            }
          }

          delete panel.grid.threshold1;
          delete panel.grid.threshold1Color;
          delete panel.grid.threshold2;
          delete panel.grid.threshold2Color;
          delete panel.grid.thresholdLine;
        });
      }

      if (panelUpgrades.length === 0) {
        return;
      }

      for (i = 0; i < this.rows.length; i++) {
        var row = this.rows[i];
        for (j = 0; j < row.panels.length; j++) {
          for (k = 0; k < panelUpgrades.length; k++) {
            panelUpgrades[k].call(this, row.panels[j]);
          }
        }
      }
    };

    return {
      create: function(dashboard, meta) {
        return new DashboardModel(dashboard, meta);
      },
      setCurrent: function(dashboard) {
        this.currentDashboard = dashboard;
      },
      getCurrent: function() {
        return this.currentDashboard;
      },
    };
  });
});
<|endoftext|>


<commit_before>// <details> polyfill
// http://caniuse.com/#feat=details

// FF Support for HTML5's <details> and <summary>
// https://bugzilla.mozilla.org/show_bug.cgi?id=591737

// http://www.sitepoint.com/fixing-the-details-element/

(function () {

  // Add event construct for modern browsers or IE
  // which fires the callback with a pre-converted target reference
  function addEvent(node, type, callback) {
    if (node.addEventListener) {
      node.addEventListener(type, function (e) {
        callback(e, e.target);
      }, false);
    } else if (node.attachEvent) {
      node.attachEvent('on' + type, function (e) {
        callback(e, e.srcElement);
      });
    }
  }

  // Handle cross-modal click events
  function addClickEvent(node, callback) {
    // Prevent space(32) from scrolling the page
    addEvent(node, 'keypress', function (e, target) {
      if (e.keyCode === 32) {
        if (e.preventDefault) {
          e.preventDefault();
        }
        else { e.returnValue = false; }
      }
    });
    // When the key comes up - check if it is enter(13) or space(32)
    addEvent(node, 'keyup', function (e, target) {
      if (e.keyCode === 13 || e.keyCode === 32) { callback(e, target); }
    });
    addEvent(node, 'mouseup', function (e, target) {
      callback(e, target);
    });
  }

  // Get the nearest ancestor element of a node that matches a given tag name
  function getAncestor(node, match) {
    do {
      if (!node || node.nodeName.toLowerCase() === match) {
        break;
      }
    } while (node = node.parentNode);

    return node;
  }

  // Create a started flag so we can prevent the initialisation
  // function firing from both DOMContentLoaded and window.onload
  var started = false;

  // Initialisation function
  function addDetailsPolyfill(list) {

    // If this has already happened, just return
    // else set the flag so it doesn't happen again
    if (started) {
      return;
    }
    started = true;

    // Get the collection of details elements, but if that's empty
    // then we don't need to bother with the rest of the scripting
    if ((list = document.getElementsByTagName('details')).length === 0) {
      return;
    }

    // else iterate through them to apply their initial state
    var n = list.length, i = 0;
    for (n; i < n; i++) {
      var details = list[i];

      // Detect native implementations
      details.__native = typeof(details.open) == 'boolean';

      // Save shortcuts to the inner summary and content elements
      details.__summary = details.getElementsByTagName('summary').item(0);
      details.__content = details.getElementsByTagName('div').item(0);

      // If the content doesn't have an ID, assign it one now
      // which we'll need for the summary's aria-controls assignment
      if (!details.__content.id) {
        details.__content.id = 'details-content-' + i;
      }

      // Add ARIA role="group" to details
      details.setAttribute('role', 'group');

      // Add role=button to summary
      details.__summary.setAttribute('role', 'button');

      // Add aria-controls
      details.__summary.setAttribute('aria-controls', details.__content.id);

      // Set tabindex so the summary is keyboard accessible
      // details.__summary.setAttribute('tabindex', 0);
      // http://www.saliences.com/browserBugs/tabIndex.html
      details.__summary.tabIndex = 0;

      // Detect initial open/closed state

      // Native support - has 'open' attribute
      if (details.open === true) {
        details.__summary.setAttribute('aria-expanded', 'true');
        details.__content.setAttribute('aria-hidden', 'false');
        details.__content.style.display = 'block';
      }

      // Native support - doesn't have 'open' attribute
      if (details.open === false) {
        details.__summary.setAttribute('aria-expanded', 'false');
        details.__content.setAttribute('aria-hidden', 'true');
        details.__content.style.display = 'none';
      }

      // If this is not a native implementation
      if (!details.__native) {

        // Add an arrow
        var twisty = document.createElement('i');

        // Check for the 'open' attribute
        // If open exists, but isn't supported it won't have a value
        if (details.getAttribute('open') === "") {
          details.__summary.setAttribute('aria-expanded', 'true');
          details.__content.setAttribute('aria-hidden', 'false');
        }

        // If open doesn't exist - it will be null or undefined
        if (details.getAttribute('open') == null || details.getAttribute('open') == "undefined" ) {
          details.__summary.setAttribute('aria-expanded', 'false');
          details.__content.setAttribute('aria-hidden', 'true');
          details.__content.style.display = 'none';
        }

      }

      // Create a circular reference from the summary back to its
      // parent details element, for convenience in the click handler
      details.__summary.__details = details;

      // If this is not a native implementation, create an arrow
      // inside the summary
      if (!details.__native) {

        var twisty = document.createElement('i');

        if (details.getAttribute('open') === "") {
          twisty.className = 'arrow arrow-open';
          twisty.appendChild(document.createTextNode('\u25bc'));
        } else {
          twisty.className = 'arrow arrow-closed';
          twisty.appendChild(document.createTextNode('\u25ba'));
        }

        details.__summary.__twisty = details.__summary.insertBefore(twisty, details.__summary.firstChild);
        details.__summary.__twisty.setAttribute('aria-hidden', 'true');

      }
    }

    // Define a statechange function that updates aria-expanded and style.display
    // Also update the arrow position
    function statechange(summary) {

      var expanded = summary.__details.__summary.getAttribute('aria-expanded') == 'true';
      var hidden = summary.__details.__content.getAttribute('aria-hidden') == 'true';

      summary.__details.__summary.setAttribute('aria-expanded', (expanded ? 'false' : 'true'));
      summary.__details.__content.setAttribute('aria-hidden', (hidden ? 'false' : 'true'));
      summary.__details.__content.style.display = (expanded ? 'none' : 'block');

      if (summary.__twisty) {
        summary.__twisty.firstChild.nodeValue = (expanded ? '\u25ba' : '\u25bc');
        summary.__twisty.setAttribute('class', (expanded ? 'arrow arrow-closed' : 'arrow arrow-open'));
      }

      return true;
    }

    // Bind a click event to handle summary elements
    addClickEvent(document, function(e, summary) {
      if (!(summary = getAncestor(summary, 'summary'))) {
        return true;
      }
      return statechange(summary);
    });
  }

  // Bind two load events for modern and older browsers
  // If the first one fires it will set a flag to block the second one
  // but if it's not supported then the second one will fire
  addEvent(document, 'DOMContentLoaded', addDetailsPolyfill);
  addEvent(window, 'load', addDetailsPolyfill);

})();
<commit_msg>Fix spaces within form fields<commit_after>// <details> polyfill
// http://caniuse.com/#feat=details

// FF Support for HTML5's <details> and <summary>
// https://bugzilla.mozilla.org/show_bug.cgi?id=591737

// http://www.sitepoint.com/fixing-the-details-element/

(function () {

  // Add event construct for modern browsers or IE
  // which fires the callback with a pre-converted target reference
  function addEvent(node, type, callback) {
    if (node.addEventListener) {
      node.addEventListener(type, function (e) {
        callback(e, e.target);
      }, false);
    } else if (node.attachEvent) {
      node.attachEvent('on' + type, function (e) {
        callback(e, e.srcElement);
      });
    }
  }

  // Handle cross-modal click events
  function addClickEvent(node, callback) {
    // Prevent space(32) from scrolling the page
    addEvent(node, 'keypress', function (e, target) {
      if (target.nodeName === "SUMMARY") {
        if (e.keyCode === 32) {
          if (e.preventDefault) {
            e.preventDefault();
          } else {
            e.returnValue = false;
          }
        }
      }
    });
    // When the key comes up - check if it is enter(13) or space(32)
    addEvent(node, 'keyup', function (e, target) {
      if (e.keyCode === 13 || e.keyCode === 32) { callback(e, target); }
    });
    addEvent(node, 'mouseup', function (e, target) {
      callback(e, target);
    });
  }

  // Get the nearest ancestor element of a node that matches a given tag name
  function getAncestor(node, match) {
    do {
      if (!node || node.nodeName.toLowerCase() === match) {
        break;
      }
    } while (node = node.parentNode);

    return node;
  }

  // Create a started flag so we can prevent the initialisation
  // function firing from both DOMContentLoaded and window.onload
  var started = false;

  // Initialisation function
  function addDetailsPolyfill(list) {

    // If this has already happened, just return
    // else set the flag so it doesn't happen again
    if (started) {
      return;
    }
    started = true;

    // Get the collection of details elements, but if that's empty
    // then we don't need to bother with the rest of the scripting
    if ((list = document.getElementsByTagName('details')).length === 0) {
      return;
    }

    // else iterate through them to apply their initial state
    var n = list.length, i = 0;
    for (n; i < n; i++) {
      var details = list[i];

      // Detect native implementations
      details.__native = typeof(details.open) == 'boolean';

      // Save shortcuts to the inner summary and content elements
      details.__summary = details.getElementsByTagName('summary').item(0);
      details.__content = details.getElementsByTagName('div').item(0);

      // If the content doesn't have an ID, assign it one now
      // which we'll need for the summary's aria-controls assignment
      if (!details.__content.id) {
        details.__content.id = 'details-content-' + i;
      }

      // Add ARIA role="group" to details
      details.setAttribute('role', 'group');

      // Add role=button to summary
      details.__summary.setAttribute('role', 'button');

      // Add aria-controls
      details.__summary.setAttribute('aria-controls', details.__content.id);

      // Set tabindex so the summary is keyboard accessible
      // details.__summary.setAttribute('tabindex', 0);
      // http://www.saliences.com/browserBugs/tabIndex.html
      details.__summary.tabIndex = 0;

      // Detect initial open/closed state

      // Native support - has 'open' attribute
      if (details.open === true) {
        details.__summary.setAttribute('aria-expanded', 'true');
        details.__content.setAttribute('aria-hidden', 'false');
        details.__content.style.display = 'block';
      }

      // Native support - doesn't have 'open' attribute
      if (details.open === false) {
        details.__summary.setAttribute('aria-expanded', 'false');
        details.__content.setAttribute('aria-hidden', 'true');
        details.__content.style.display = 'none';
      }

      // If this is not a native implementation
      if (!details.__native) {

        // Add an arrow
        var twisty = document.createElement('i');

        // Check for the 'open' attribute
        // If open exists, but isn't supported it won't have a value
        if (details.getAttribute('open') === "") {
          details.__summary.setAttribute('aria-expanded', 'true');
          details.__content.setAttribute('aria-hidden', 'false');
        }

        // If open doesn't exist - it will be null or undefined
        if (details.getAttribute('open') == null || details.getAttribute('open') == "undefined" ) {
          details.__summary.setAttribute('aria-expanded', 'false');
          details.__content.setAttribute('aria-hidden', 'true');
          details.__content.style.display = 'none';
        }

      }

      // Create a circular reference from the summary back to its
      // parent details element, for convenience in the click handler
      details.__summary.__details = details;

      // If this is not a native implementation, create an arrow
      // inside the summary
      if (!details.__native) {

        var twisty = document.createElement('i');

        if (details.getAttribute('open') === "") {
          twisty.className = 'arrow arrow-open';
          twisty.appendChild(document.createTextNode('\u25bc'));
        } else {
          twisty.className = 'arrow arrow-closed';
          twisty.appendChild(document.createTextNode('\u25ba'));
        }

        details.__summary.__twisty = details.__summary.insertBefore(twisty, details.__summary.firstChild);
        details.__summary.__twisty.setAttribute('aria-hidden', 'true');

      }
    }

    // Define a statechange function that updates aria-expanded and style.display
    // Also update the arrow position
    function statechange(summary) {

      var expanded = summary.__details.__summary.getAttribute('aria-expanded') == 'true';
      var hidden = summary.__details.__content.getAttribute('aria-hidden') == 'true';

      summary.__details.__summary.setAttribute('aria-expanded', (expanded ? 'false' : 'true'));
      summary.__details.__content.setAttribute('aria-hidden', (hidden ? 'false' : 'true'));
      summary.__details.__content.style.display = (expanded ? 'none' : 'block');

      if (summary.__twisty) {
        summary.__twisty.firstChild.nodeValue = (expanded ? '\u25ba' : '\u25bc');
        summary.__twisty.setAttribute('class', (expanded ? 'arrow arrow-closed' : 'arrow arrow-open'));
      }

      return true;
    }

    // Bind a click event to handle summary elements
    addClickEvent(document, function(e, summary) {
      if (!(summary = getAncestor(summary, 'summary'))) {
        return true;
      }
      return statechange(summary);
    });
  }

  // Bind two load events for modern and older browsers
  // If the first one fires it will set a flag to block the second one
  // but if it's not supported then the second one will fire
  addEvent(document, 'DOMContentLoaded', addDetailsPolyfill);
  addEvent(window, 'load', addDetailsPolyfill);

})();
<|endoftext|>


<commit_before>define(['jquery', 'underscore', 'backbone', 'text!templates/imageUploader/uploaderview.html',
  'utility/s3upload'],
  function($, _, Backbone, Template, S3Upload) {

  var UploaderView = Backbone.View.extend({
    tagName: 'div',
    template: _.template( Template ),
    events: {
      'change #files' : 'uploadFileToS3'
    },

    initialize:function () {
      this.render();
    },

    render: function() {
      this.$el.html(this.template());
      return this;
    },

    uploadFileToS3 : function (){
      var s3upload = new S3Upload({
        file_dom_selector: this.$el.find('#files'),
        s3_sign_put_url: '/api/sign_s3',
        onProgress: function(percent, message) {
            $('#status').html('Upload progress: ' + percent + '% ' + message);
        },
        onFinishS3Put: function(public_url) {
            this.$el.find('#status').html('Upload completed. Uploaded to: '+ public_url);
            this.$el.find("#avatar_url").val(public_url);
            this.$el.find("#preview").html('');
        },
        onError: function(status) {
            $this.$el.find('#status').html('Upload error: ' + status);
        }
      });
    }
  });
  return UploaderView;
});
<commit_msg>new uploader<commit_after>define(['jquery', 'underscore', 'backbone', 'text!templates/imageUploader/uploaderview.html',
  'utility/s3upload'],
  function($, _, Backbone, Template, S3Upload) {

  var UploaderView = Backbone.View.extend({
    tagName: 'div',
    template: _.template( Template ),
    events: {
      'change #files' : 'uploadFileToS3'
    },

    initialize:function () {
      this.render();
    },

    render: function() {
      this.$el.html(this.template());
      return this;
    },

    uploadFileToS3 : function (){
      S3 = new S3Upload();
      var s3upload = S3({
        file_dom_selector: this.$el.find('#files'),
        s3_sign_put_url: '/api/sign_s3',
        onProgress: function(percent, message) {
            $('#status').html('Upload progress: ' + percent + '% ' + message);
        },
        onFinishS3Put: function(public_url) {
            this.$el.find('#status').html('Upload completed. Uploaded to: '+ public_url);
            this.$el.find("#avatar_url").val(public_url);
            this.$el.find("#preview").html('');
        },
        onError: function(status) {
            $this.$el.find('#status').html('Upload error: ' + status);
        }
      });
    }
  });
  return UploaderView;
});
<|endoftext|>


<commit_before>define([
    'jquery',
    'underscore',
    'backbone',
    'views/navigationtree/NavigationTreeView',
    'views/projects/ViewNodeItemView',
    'views/testsuites/TestSuiteView',
    'views/testcases/TestCaseView',
    'models/project/ProjectModel',
    'models/testsuite/TestSuiteModel',
    'models/testcase/TestCaseModel',
    'collections/core/ExecutionTypesCollection',
    'text!templates/testplans/viewTestPlanTemplate.html',
    'text!templates/projects/projectNodeItemTemplate.html',
    'text!templates/testsuites/testSuiteNodeItemTemplate.html',
    'text!templates/testcases/testCaseNodeItemTemplate.html'
], function(
    $,
    _,
    Backbone,
    NavigationTreeView,
    ViewNodeItemView,
    TestSuiteView,
    TestCaseView,
    ProjectModel,
    TestSuiteModel,
    TestCaseModel,
    ExecutionTypesCollection,
    viewTestPlanTemplate,
    projectNodeItemTemplate,
    testSuiteNodeItemTemplate,
    testCaseNodeItemTemplate) {

    /**
     * Displays the navigation tree.
     */
    var ViewTestPlanView = Backbone.View.extend({
        el: $("#page"),

        events: {
            'click #save-testplan-btn': function() { alert('save!'); },
            'click #cancel-testplan-btn': function () { Backbone.history.navigate("#/planning", { trigger: false }); }
        },

        initialize: function(options) {
            _.bindAll(this,
                'render',
                'setProjectId',
                'setTestSuiteId',
                'setTestCaseId',
                'setTestPlanId',
                'updateNavigationTree',
                'displayLoading',
                'displayProject',
                'displayTestSuite',
                'displayTestCase');

            this.projectId = parseInt(options.projectId);
            this.testSuiteId = 0;
            this.testCaseId = 0;
            this.testPlanId = parseInt(options.testPlanId);

            // Views
            this.navigationTreeView = new NavigationTreeView({
                draggable: false,
                checkboxes: true,
                rootNodeUrl: '#/testplans/' + options.testPlanId + '/view',
                nodeUrlPrefix: '#/testplans'
            });
            this.viewNodeItemView = new ViewNodeItemView();
            this.testSuiteView = new TestSuiteView();
            this.testCaseView = new TestCaseView();

            // Collections
            this.executionTypesCollection = new ExecutionTypesCollection();

            // Events
            Backbone.on('nestor:navigationtree:project_changed', this.updateNavigationTree);
            Backbone.on('nestor:navigationtree_changed', this.updateNavigationTree);

            // For GC
            this.subviews = new Object();
            this.subviews.navigationTreeView = this.navigationTreeView;
            this.subviews.viewNodeItemView = this.viewNodeItemView;
            this.subviews.testSuiteView = this.testSuiteView;
            this.subviews.testCaseView = this.testCaseView;
        },

        render: function() {
            $('.item').removeClass('active');
            $('.item a[href="#/planning"]').parent().addClass('active');
            var compiledTemplate = _.template(viewTestPlanTemplate, {});
            this.$el.html(compiledTemplate);

            this.$('#content-main').empty();
            this.updateNavigationTree();
        },

        setProjectId: function(id) {
            var projectId = parseInt(id);
            // update project ID in models
            this.projectModel = new ProjectModel();
            this.projectModel.id = projectId;

            this.testSuiteModel = new TestSuiteModel();
            this.testSuiteModel.project_id = projectId;

            this.testCaseModel = new TestCaseModel();
            this.testCaseModel.project_id = projectId;

            this.navigationTreeView.projectId = projectId;

            if (this.projectId !== projectId/* || !$.trim($(this.navigationTreeView.el).html())*/) {
                this.projectId = projectId;
                Backbone.trigger('nestor:navigationtree:project_changed');
            }
        },

        setTestSuiteId: function(testSuiteId) {
            // update test suite ID in models
            this.testSuiteModel = new TestSuiteModel();
            this.testSuiteModel.project_id = this.projectId;
            this.testSuiteModel.id = testSuiteId;
            this.testSuiteId = testSuiteId;

            this.testCaseModel = new TestCaseModel();
            this.testCaseModel.project_id = this.projectId;
            this.testCaseModel.testsuite_id = testSuiteId;
        },

        setTestCaseId: function(testCaseId) {
            // update test suite ID in models
            this.testCaseModel = new TestCaseModel();
            this.testCaseModel.project_id = this.projectId;
            this.testCaseModel.testsuite_id = this.testSuiteId;
            this.testCaseModel.id = testCaseId;

            this.testCaseId = testCaseId;
        },

        setTestPlanId: function(testPlanId) {
            this.testPlanId = testPlanId;
        },

        updateNavigationTree: function(event) {
            console.log('Rendering navigation tree!');
            this.$('#navigation-tree').fancytree({});
            this.navigationTreeView.render({
                el: this.$('#navigation-tree')
            });
        },

        displayLoading: function() {
            this.$('#content-main').empty();
            this.$('#content-main').html('

');
        },

        /**
         * Display project node item on the right panel of the screen.
         */
        displayProject: function() {
            this.displayLoading();
            var self = this;
            this.projectModel.fetch({
                success: function(responseData) {
                    var project = self.projectModel;
                    var data = {
                        project: project,
                        _: _,
                        editable: false
                    };

                    var compiledTemplate = _.template(projectNodeItemTemplate, data);
                    self.viewNodeItemView.$el.html(compiledTemplate);
                    this.$('#content-main').empty();
                    this.$('#content-main').append(self.viewNodeItemView.el);
                    this.$('#navigation-tree').fancytree('getTree').getNodeByKey("1-" + project.get('id')).setActive();
                },
                error: function() {
                    throw new Error("Failed to fetch project");
                }
            });
        },

        /**
         * Display project node item on the right panel of the screen.
         */
        displayTestSuite: function() {
            var self = this;
            this.testSuiteModel.set('id', this.testSuiteId);
            this.testSuiteModel.fetch({
                success: function(responseData) {
                    var data = {
                        testsuite: self.testSuiteModel,
                        _: _,
                        editable: false
                    };

                    var compiledTemplate = _.template(testSuiteNodeItemTemplate, data);
                    self.viewNodeItemView.$el.html(compiledTemplate);
                    self.$('#content-main').empty();
                    self.$('#content-main').append(self.viewNodeItemView.el);
                },
                error: function() {
                    throw new Error("Failed to fetch test suite");
                }
            });
        },

        /**
         * Display project node item on the right panel of the screen.
         */
        displayTestCase: function() {
            var self = this;
            this.testCaseModel.set('project_id', this.projectId);
            this.testCaseModel.set('test_suite_id', this.testSuiteId);
            this.testCaseModel.set('id', this.testCaseId);
            this.testCaseModel.fetch({
                success: function(responseData) {
                    var data = {
                        testcase: self.testCaseModel,
                        _: _,
                        editable: false
                    };

                    var compiledTemplate = _.template(testCaseNodeItemTemplate, data);
                    self.viewNodeItemView.$el.html(compiledTemplate);
                    self.$('#content-main').empty();
                    self.$('#content-main').append(self.viewNodeItemView.el);
                },
                error: function() {
                    throw new Error("Failed to fetch test case");
                }
            });
        }

    });

    return ViewTestPlanView;

});<commit_msg>Prepare call to function to add test cases to test plan<commit_after>define([
    'jquery',
    'underscore',
    'backbone',
    'views/navigationtree/NavigationTreeView',
    'views/projects/ViewNodeItemView',
    'views/testsuites/TestSuiteView',
    'views/testcases/TestCaseView',
    'models/project/ProjectModel',
    'models/testsuite/TestSuiteModel',
    'models/testcase/TestCaseModel',
    'collections/core/ExecutionTypesCollection',
    'text!templates/testplans/viewTestPlanTemplate.html',
    'text!templates/projects/projectNodeItemTemplate.html',
    'text!templates/testsuites/testSuiteNodeItemTemplate.html',
    'text!templates/testcases/testCaseNodeItemTemplate.html'
], function(
    $,
    _,
    Backbone,
    NavigationTreeView,
    ViewNodeItemView,
    TestSuiteView,
    TestCaseView,
    ProjectModel,
    TestSuiteModel,
    TestCaseModel,
    ExecutionTypesCollection,
    viewTestPlanTemplate,
    projectNodeItemTemplate,
    testSuiteNodeItemTemplate,
    testCaseNodeItemTemplate) {

    /**
     * Displays the navigation tree.
     */
    var ViewTestPlanView = Backbone.View.extend({
        el: $("#page"),

        events: {
            'click #save-testplan-btn': 'addTestCasesToTestPlan',
            'click #cancel-testplan-btn': function () { Backbone.history.navigate("#/planning", { trigger: false }); }
        },

        initialize: function(options) {
            _.bindAll(this,
                'render',
                'setProjectId',
                'setTestSuiteId',
                'setTestCaseId',
                'setTestPlanId',
                'updateNavigationTree',
                'displayLoading',
                'displayProject',
                'displayTestSuite',
                'displayTestCase',
                'addTestCasesToTestPlan');

            this.projectId = parseInt(options.projectId);
            this.testSuiteId = 0;
            this.testCaseId = 0;
            this.testPlanId = parseInt(options.testPlanId);

            // Views
            this.navigationTreeView = new NavigationTreeView({
                draggable: false,
                checkboxes: true,
                rootNodeUrl: '#/testplans/' + options.testPlanId + '/view',
                nodeUrlPrefix: '#/testplans'
            });
            this.viewNodeItemView = new ViewNodeItemView();
            this.testSuiteView = new TestSuiteView();
            this.testCaseView = new TestCaseView();

            // Collections
            this.executionTypesCollection = new ExecutionTypesCollection();

            // Events
            Backbone.on('nestor:navigationtree:project_changed', this.updateNavigationTree);
            Backbone.on('nestor:navigationtree_changed', this.updateNavigationTree);

            // For GC
            this.subviews = new Object();
            this.subviews.navigationTreeView = this.navigationTreeView;
            this.subviews.viewNodeItemView = this.viewNodeItemView;
            this.subviews.testSuiteView = this.testSuiteView;
            this.subviews.testCaseView = this.testCaseView;
        },

        render: function() {
            $('.item').removeClass('active');
            $('.item a[href="#/planning"]').parent().addClass('active');
            var compiledTemplate = _.template(viewTestPlanTemplate, {});
            this.$el.html(compiledTemplate);

            this.$('#content-main').empty();
            this.updateNavigationTree();
        },

        setProjectId: function(id) {
            var projectId = parseInt(id);
            // update project ID in models
            this.projectModel = new ProjectModel();
            this.projectModel.id = projectId;

            this.testSuiteModel = new TestSuiteModel();
            this.testSuiteModel.project_id = projectId;

            this.testCaseModel = new TestCaseModel();
            this.testCaseModel.project_id = projectId;

            this.navigationTreeView.projectId = projectId;

            if (this.projectId !== projectId/* || !$.trim($(this.navigationTreeView.el).html())*/) {
                this.projectId = projectId;
                Backbone.trigger('nestor:navigationtree:project_changed');
            }
        },

        setTestSuiteId: function(testSuiteId) {
            // update test suite ID in models
            this.testSuiteModel = new TestSuiteModel();
            this.testSuiteModel.project_id = this.projectId;
            this.testSuiteModel.id = testSuiteId;
            this.testSuiteId = testSuiteId;

            this.testCaseModel = new TestCaseModel();
            this.testCaseModel.project_id = this.projectId;
            this.testCaseModel.testsuite_id = testSuiteId;
        },

        setTestCaseId: function(testCaseId) {
            // update test suite ID in models
            this.testCaseModel = new TestCaseModel();
            this.testCaseModel.project_id = this.projectId;
            this.testCaseModel.testsuite_id = this.testSuiteId;
            this.testCaseModel.id = testCaseId;

            this.testCaseId = testCaseId;
        },

        setTestPlanId: function(testPlanId) {
            this.testPlanId = testPlanId;
        },

        updateNavigationTree: function(event) {
            console.log('Rendering navigation tree!');
            this.$('#navigation-tree').fancytree({});
            this.navigationTreeView.render({
                el: this.$('#navigation-tree')
            });
        },

        displayLoading: function() {
            this.$('#content-main').empty();
            this.$('#content-main').html('

');
        },

        /**
         * Display project node item on the right panel of the screen.
         */
        displayProject: function() {
            this.displayLoading();
            var self = this;
            this.projectModel.fetch({
                success: function(responseData) {
                    var project = self.projectModel;
                    var data = {
                        project: project,
                        _: _,
                        editable: false
                    };

                    var compiledTemplate = _.template(projectNodeItemTemplate, data);
                    self.viewNodeItemView.$el.html(compiledTemplate);
                    this.$('#content-main').empty();
                    this.$('#content-main').append(self.viewNodeItemView.el);
                    this.$('#navigation-tree').fancytree('getTree').getNodeByKey("1-" + project.get('id')).setActive();
                },
                error: function() {
                    throw new Error("Failed to fetch project");
                }
            });
        },

        /**
         * Display project node item on the right panel of the screen.
         */
        displayTestSuite: function() {
            var self = this;
            this.testSuiteModel.set('id', this.testSuiteId);
            this.testSuiteModel.fetch({
                success: function(responseData) {
                    var data = {
                        testsuite: self.testSuiteModel,
                        _: _,
                        editable: false
                    };

                    var compiledTemplate = _.template(testSuiteNodeItemTemplate, data);
                    self.viewNodeItemView.$el.html(compiledTemplate);
                    self.$('#content-main').empty();
                    self.$('#content-main').append(self.viewNodeItemView.el);
                },
                error: function() {
                    throw new Error("Failed to fetch test suite");
                }
            });
        },

        /**
         * Display project node item on the right panel of the screen.
         */
        displayTestCase: function() {
            var self = this;
            this.testCaseModel.set('project_id', this.projectId);
            this.testCaseModel.set('test_suite_id', this.testSuiteId);
            this.testCaseModel.set('id', this.testCaseId);
            this.testCaseModel.fetch({
                success: function(responseData) {
                    var data = {
                        testcase: self.testCaseModel,
                        _: _,
                        editable: false
                    };

                    var compiledTemplate = _.template(testCaseNodeItemTemplate, data);
                    self.viewNodeItemView.$el.html(compiledTemplate);
                    self.$('#content-main').empty();
                    self.$('#content-main').append(self.viewNodeItemView.el);
                },
                error: function() {
                    throw new Error("Failed to fetch test case");
                }
            });
        },
        addTestCasesToTestPlan: function(evt) {
            console.log(evt);
        }

    });

    return ViewTestPlanView;

});<|endoftext|>


<commit_before>var _ = require('underscore');
var jsyaml = require('js-yaml');
var queue = require('queue-async');

var Backbone = require('backbone');
var File = require('../models/file');
var Folder = require('../models/folder');

var cookie = require('../cookie');
var util = require('../util');
var ignore = require('ignore');

module.exports = Backbone.Collection.extend({
  model: function(attributes, options) {
    // TODO: handle 'symlink' and 'submodule' type
    // TODO: coerce tree/folder to a single type
    switch(attributes.type) {
      case 'tree':
        return new Folder(attributes, options);
        break;
      case 'blob':
        return new File(attributes, options);
        break;
      default:
        return new File(attributes, options);
        break;
    }
  },

  initialize: function(models, options) {
    _.bindAll(this);

    this.repo = options.repo;
    this.branch = options.branch;
    this.sha = options.sha;

    // Sort files reverse alphabetically if path begins with '_posts/'
    this.comparator = function(a, b) {
      var typeA = a.get('type');
      var typeB = b.get('type');

      var pathA = a.get('path');
      var pathB = b.get('path');

      var regex = /^_posts\/.*$/

      if (typeA === typeB && typeA === 'file' && regex.test(pathA) && regex.test(pathB)) {
        // Reverse alphabetical
        return pathA < pathB ? 1 : -1;
      } else if (typeA === typeB) {
        // Alphabetical
        return pathA < pathB ? -1 : 1;
      } else {
        switch(typeA) {
          case 'tree':
          case 'folder':
            return -1;
            break;
          case 'file':
            return typeB === 'folder' || typeB === 'tree' ? 1 : -1;
            break;
        }
      }
    };
  },

  parse: function(resp, options) {
    return _.map(resp.tree, (function(file) {
      return  _.extend(file, {
        branch: this.branch,
        collection: this,
        repo: this.repo
      })
    }).bind(this));
  },

  parseConfig: function(config, options) {
    var content = config.get('content');

    // Attempt to parse YAML
    try {
      config = jsyaml.safeLoad(content);
    } catch(err) {
      console.log("Error parsing YAML");
      console.log(err);
    }

    if (config && config.prose) {
      // Load _config.yml, set parsed value on collection
      // Extend to capture settings from outside config.prose
      // while allowing override
      this.config = _.extend(config, {
        baseurl: config.baseurl,
        languages: config.languages
      }, config.prose);

      if (config.prose.ignore) {
        this.parseIgnore(config.prose.ignore);
      }

      if (config.prose.metadata) {
        var metadata = config.prose.metadata;

        // Serial queue to not break global scope JSONP callbacks
        var q = queue(1);

        _.each(metadata, function(raw, key) {
          q.defer(function(cb) {
            var subq = queue();
            var defaults;

            if (_.isObject(raw)) {
              defaults = raw;

              _.each(defaults, function(value, key) {
                var regex = /^https?:\/\//;

                // Parse JSON URL values
                if (value && value.field && value.field.options &&
                    _.isString(value.field.options) &&
                    regex.test(value.field.options)) {

                  subq.defer(function(cb) {
                    $.ajax({
                      cache: true,
                      dataType: 'jsonp',
                      jsonp: false,
                      jsonpCallback: value.field.options.split('?callback=')[1] || 'callback',
                      timeout: 5000,
                      url: value.field.options,
                      success: (function(d) {
                        value.field.options = _.compact(d);
                        cb();
                      }).bind(this)
                    });
                  });
                }

                if (value && value.field && value.field.value === "CURRENT_DATETIME") {
                  value.field.value = (new Date()).format('Y-m-d H:i O');
                }
              });
            } else if (_.isString(raw)) {
              try {
                defaults = jsyaml.safeLoad(raw);

                if (defaults.date === "CURRENT_DATETIME") {
                  var current = (new Date()).format('Y-m-d H:i O');
                  defaults.date = current;
                  raw = raw.replace("CURRENT_DATETIME", current);
                }
              } catch(err) {
                console.log("Error parsing default values.");
                console.log(err);
              }
            }

            subq.awaitAll(function() {
              metadata[key] = defaults;
              cb();
            });
          });
        });

        q.awaitAll((function() {
          // Save parsed config to the collection as it's used accross
          // files of the same collection and shouldn't be re-parsed each time
          this.defaults = metadata;

          if (_.isFunction(options.success)) options.success.apply(this, options.args);
        }).bind(this));
      } else {
        if (_.isFunction(options.success)) options.success.apply(this, options.args);
      }
    } else {
      if (_.isFunction(options.success)) options.success.apply(this, options.args);
    }
  },

  parseIgnore: function(ignorePatterns) {
    var ignoreFilter = ignore().addPattern(ignorePatterns).createFilter();
    this.filteredModel = new Backbone.Collection(this.filter(function(file) {
      return ignoreFilter(file.id);
    }));
  },

  fetch: function(options) {
    options = _.clone(options) || {};

    var success = options.success;
    var args = options.args;

    Backbone.Collection.prototype.fetch.call(this, _.extend(options, {
      success: (function(model, res, options) {
        var config = this.findWhere({ path: '_prose.yml' }) ||
          this.findWhere({ path: '_config.yml' });

        if (config) {
          config.fetch({
            success: (function() {
              this.parseConfig(config, { success: success, args: args });
            }).bind(this)
          });
        } else {
          if (_.isFunction(success)) success.apply(this, args);
        }

      }).bind(this)
    }));
  },

  restore: function(file, options) {
    options = options ? _.clone(options) : {};

    var path = file.filename;
    var success = options.success;

    $.ajax({
      type: 'GET',
      url: file.contents_url,
      headers: {
        Accept: 'application/vnd.github.v3.raw'
      },
      success: (function(res) {
        // initialize new File model with content
        var model = new File({
          branch: this.branch,
          collection: this,
          content: res,
          path: path,
          repo: this.repo
        });

        var name = util.extractFilename(path)[1];
        model.set('placeholder', t('actions.commits.created', { filename: name }));

        // add to collection on save
        model.save({
          success: (function(model, res, options) {
            // Update model attributes and add to collection
            model.set(res.content);
            this.add(model);

            if (_.isFunction(success)) success(model, res, options);
          }).bind(this),
          error: options.error
        });
      }).bind(this),
      error: options.error
    });
  },

  upload: function(file, content, path, options) {
    var success = options.success;

    var extension = file.type.split('/').pop();
    var uid;

    if (!path) {
      uid = file.name;

      if (this.assetsDirectory) {
        path = this.assetsDirectory + '/' + uid;
      } else {
        path = this.model.path ? this.model.path + '/' + uid : uid;
      }
    }

    // If path matches an existing file, confirm the overwrite is intentional
    // then set new content and update the existing file
    var model = this.findWhere({ path: path });

    if (model) {
      // TODO: confirm overwrite with UI prompt
      model.set('content', content);
      model.set('placeholder', t('actions.commits.updated', { filename: file.name }));
    } else {
      // initialize new File model with content
      model = new File({
        branch: this.branch,
        collection: this,
        content: content,
        path: path,
        repo: this.repo
      });

      model.set('placeholder', t('actions.commits.created', { filename: file.name }));
    }

    // add to collection on save
    model.save({
      success: (function(model, res, options) {
        // Update model attributes and add to collection
        model.set(res.content);
        this.add(model);

        if (_.isFunction(success)) success(model, res, options);
      }).bind(this),
      error: options.error
    });
  },

  url: function() {
    return this.repo.url() + '/git/trees/' + this.sha + '?recursive=1';
  }
});
<commit_msg>Simplify extending config object<commit_after>var _ = require('underscore');
var jsyaml = require('js-yaml');
var queue = require('queue-async');

var Backbone = require('backbone');
var File = require('../models/file');
var Folder = require('../models/folder');

var cookie = require('../cookie');
var util = require('../util');
var ignore = require('ignore');

module.exports = Backbone.Collection.extend({
  model: function(attributes, options) {
    // TODO: handle 'symlink' and 'submodule' type
    // TODO: coerce tree/folder to a single type
    switch(attributes.type) {
      case 'tree':
        return new Folder(attributes, options);
        break;
      case 'blob':
        return new File(attributes, options);
        break;
      default:
        return new File(attributes, options);
        break;
    }
  },

  initialize: function(models, options) {
    _.bindAll(this);

    this.repo = options.repo;
    this.branch = options.branch;
    this.sha = options.sha;

    // Sort files reverse alphabetically if path begins with '_posts/'
    this.comparator = function(a, b) {
      var typeA = a.get('type');
      var typeB = b.get('type');

      var pathA = a.get('path');
      var pathB = b.get('path');

      var regex = /^_posts\/.*$/

      if (typeA === typeB && typeA === 'file' && regex.test(pathA) && regex.test(pathB)) {
        // Reverse alphabetical
        return pathA < pathB ? 1 : -1;
      } else if (typeA === typeB) {
        // Alphabetical
        return pathA < pathB ? -1 : 1;
      } else {
        switch(typeA) {
          case 'tree':
          case 'folder':
            return -1;
            break;
          case 'file':
            return typeB === 'folder' || typeB === 'tree' ? 1 : -1;
            break;
        }
      }
    };
  },

  parse: function(resp, options) {
    return _.map(resp.tree, (function(file) {
      return  _.extend(file, {
        branch: this.branch,
        collection: this,
        repo: this.repo
      })
    }).bind(this));
  },

  parseConfig: function(config, options) {
    var content = config.get('content');

    // Attempt to parse YAML
    try {
      config = jsyaml.safeLoad(content);
    } catch(err) {
      console.log("Error parsing YAML");
      console.log(err);
    }

    if (config && config.prose) {
      // Load _config.yml, set parsed value on collection
      // Extend to capture settings from outside config.prose
      // while allowing override
      this.config = _.extend(config, config.prose);

      if (config.prose.ignore) {
        this.parseIgnore(config.prose.ignore);
      }

      if (config.prose.metadata) {
        var metadata = config.prose.metadata;

        // Serial queue to not break global scope JSONP callbacks
        var q = queue(1);

        _.each(metadata, function(raw, key) {
          q.defer(function(cb) {
            var subq = queue();
            var defaults;

            if (_.isObject(raw)) {
              defaults = raw;

              _.each(defaults, function(value, key) {
                var regex = /^https?:\/\//;

                // Parse JSON URL values
                if (value && value.field && value.field.options &&
                    _.isString(value.field.options) &&
                    regex.test(value.field.options)) {

                  subq.defer(function(cb) {
                    $.ajax({
                      cache: true,
                      dataType: 'jsonp',
                      jsonp: false,
                      jsonpCallback: value.field.options.split('?callback=')[1] || 'callback',
                      timeout: 5000,
                      url: value.field.options,
                      success: (function(d) {
                        value.field.options = _.compact(d);
                        cb();
                      }).bind(this)
                    });
                  });
                }

                if (value && value.field && value.field.value === "CURRENT_DATETIME") {
                  value.field.value = (new Date()).format('Y-m-d H:i O');
                }
              });
            } else if (_.isString(raw)) {
              try {
                defaults = jsyaml.safeLoad(raw);

                if (defaults.date === "CURRENT_DATETIME") {
                  var current = (new Date()).format('Y-m-d H:i O');
                  defaults.date = current;
                  raw = raw.replace("CURRENT_DATETIME", current);
                }
              } catch(err) {
                console.log("Error parsing default values.");
                console.log(err);
              }
            }

            subq.awaitAll(function() {
              metadata[key] = defaults;
              cb();
            });
          });
        });

        q.awaitAll((function() {
          // Save parsed config to the collection as it's used accross
          // files of the same collection and shouldn't be re-parsed each time
          this.defaults = metadata;

          if (_.isFunction(options.success)) options.success.apply(this, options.args);
        }).bind(this));
      } else {
        if (_.isFunction(options.success)) options.success.apply(this, options.args);
      }
    } else {
      if (_.isFunction(options.success)) options.success.apply(this, options.args);
    }
  },

  parseIgnore: function(ignorePatterns) {
    var ignoreFilter = ignore().addPattern(ignorePatterns).createFilter();
    this.filteredModel = new Backbone.Collection(this.filter(function(file) {
      return ignoreFilter(file.id);
    }));
  },

  fetch: function(options) {
    options = _.clone(options) || {};

    var success = options.success;
    var args = options.args;

    Backbone.Collection.prototype.fetch.call(this, _.extend(options, {
      success: (function(model, res, options) {
        var config = this.findWhere({ path: '_prose.yml' }) ||
          this.findWhere({ path: '_config.yml' });

        if (config) {
          config.fetch({
            success: (function() {
              this.parseConfig(config, { success: success, args: args });
            }).bind(this)
          });
        } else {
          if (_.isFunction(success)) success.apply(this, args);
        }

      }).bind(this)
    }));
  },

  restore: function(file, options) {
    options = options ? _.clone(options) : {};

    var path = file.filename;
    var success = options.success;

    $.ajax({
      type: 'GET',
      url: file.contents_url,
      headers: {
        Accept: 'application/vnd.github.v3.raw'
      },
      success: (function(res) {
        // initialize new File model with content
        var model = new File({
          branch: this.branch,
          collection: this,
          content: res,
          path: path,
          repo: this.repo
        });

        var name = util.extractFilename(path)[1];
        model.set('placeholder', t('actions.commits.created', { filename: name }));

        // add to collection on save
        model.save({
          success: (function(model, res, options) {
            // Update model attributes and add to collection
            model.set(res.content);
            this.add(model);

            if (_.isFunction(success)) success(model, res, options);
          }).bind(this),
          error: options.error
        });
      }).bind(this),
      error: options.error
    });
  },

  upload: function(file, content, path, options) {
    var success = options.success;

    var extension = file.type.split('/').pop();
    var uid;

    if (!path) {
      uid = file.name;

      if (this.assetsDirectory) {
        path = this.assetsDirectory + '/' + uid;
      } else {
        path = this.model.path ? this.model.path + '/' + uid : uid;
      }
    }

    // If path matches an existing file, confirm the overwrite is intentional
    // then set new content and update the existing file
    var model = this.findWhere({ path: path });

    if (model) {
      // TODO: confirm overwrite with UI prompt
      model.set('content', content);
      model.set('placeholder', t('actions.commits.updated', { filename: file.name }));
    } else {
      // initialize new File model with content
      model = new File({
        branch: this.branch,
        collection: this,
        content: content,
        path: path,
        repo: this.repo
      });

      model.set('placeholder', t('actions.commits.created', { filename: file.name }));
    }

    // add to collection on save
    model.save({
      success: (function(model, res, options) {
        // Update model attributes and add to collection
        model.set(res.content);
        this.add(model);

        if (_.isFunction(success)) success(model, res, options);
      }).bind(this),
      error: options.error
    });
  },

  url: function() {
    return this.repo.url() + '/git/trees/' + this.sha + '?recursive=1';
  }
});
<|endoftext|>