<commit_before>// ***********************************************//
//                      views
// ***********************************************//

require('akvo-flow/core');
require('akvo-flow/views/survey-group-views');
require('akvo-flow/views/survey-details-views');

FLOW.ApplicationView = Ember.View.extend({
	templateName: 'application'
});

// localisation helper
Ember.Handlebars.registerHelper('t', function(i18nKey, options) {
  return Ember.String.loc(i18nKey);
});

// date format helper
Ember.Handlebars.registerHelper("date", function(property) {
  var d = new Date(parseInt(Ember.get(this, property),10));
  var m_names = new Array("Jan", "Feb", "Mar", "Apr", "May", "Jun", "Jul", "Aug", "Sep", "Oct", "Nov", "Dec");

  var curr_date = d.getDate();
  var curr_month = d.getMonth();
  var curr_year = d.getFullYear();
  return (curr_date + " " + m_names[curr_month] + " " + curr_year);
});

// ********************************************************//
//                      main navigation
// ********************************************************//

FLOW.NavigationView = Em.View.extend({
	templateName: 'navigation',
	selectedBinding: 'controller.selected',

	onLanguageChange:function(){
		this.rerender();
	}.observes('FLOW.languageControl.dashboardLanguage'),

	NavItemView: Ember.View.extend({
		tagName: 'li',
		classNameBindings: 'isActive:current navItem'.w(),

		navItem: function() {
			return this.get('item');
		}.property('item').cacheable(),

		isActive: function() {
			return this.get('item') === this.get('parentView.selected');
		}.property('item', 'parentView.selected').cacheable()
	})
});

// ********************************************************//
//                      standard views
// ********************************************************//

// home screen view
FLOW.NavHomeView = Ember.View.extend({ templateName: 'navHome/nav-home'});

// surveys views
FLOW.NavSurveysView = Ember.View.extend({ templateName: 'navSurveys/nav-surveys'});
FLOW.NavSurveysMainView = Ember.View.extend({ templateName: 'navSurveys/nav-surveys-main'});
FLOW.NavSurveysEditView = Ember.View.extend({ templateName: 'navSurveys/nav-surveys-edit'});

// devices views
FLOW.NavDevicesView = Ember.View.extend({ templateName: 'navDevices/nav-devices'});
FLOW.CurrentDevicesView = Ember.View.extend({ templateName: 'navDevices/current-devices'});
FLOW.AssignSurveysOverviewView = Ember.View.extend({ templateName: 'navDevices/assign-survey-overview'});
FLOW.EditSurveyAssignmentView = Ember.View.extend({ templateName: 'navDevices/edit-survey-assignment'});

// data views
FLOW.NavDataView = Ember.View.extend({ templateName: 'navData/nav-data'});
FLOW.InspectDataView = Ember.View.extend({ templateName: 'navData/inspect-data'});
FLOW.ImportSurveyView = Ember.View.extend({ templateName: 'navData/import-survey'});
FLOW.ExcelImportView = Ember.View.extend({ templateName: 'navData/excel-import'});
FLOW.ExcelExportView = Ember.View.extend({ templateName: 'navData/excel-export'});

// reports views
FLOW.NavReportsView = Ember.View.extend({ templateName: 'navReports/nav-reports'});

// maps views
FLOW.NavMapsView = Ember.View.extend({
  templateName: "navMaps/nav-maps",
  didInsertElement: function() {
    var map = new mxn.Mapstraction("flowMap", "google"),
        latlon = new mxn.LatLonPoint(-0.703107, 36.765747);

    map.setCenterAndZoom(latlon, 8);

    map.addControls({
        pan: true,
        zoom: 'small',
        map_type: true
    });

    // Markers
    locales = Ember.ArrayController.create({
      content: FLOW.store.findAll(FLOW.Placemark),
      contentArrayDidChange: function (model, index) {
        var htmlContent, marker, pm, point, mark;

        pm = this.objectAt(index);
        point = new mxn.LatLonPoint(pm.get('latitude'), pm.get('longitude'));
        mark = new mxn.Marker(point);

        mark.setLabel(pm.get('collectionDate').toString());
        mark.setInfoBubble(pm.get('id'));

        map.addMarker(mark);

        return this;
      }
    });
  }
});

// users views
FLOW.NavUsersView = Ember.View.extend({	templateName: 'navUsers/nav-users'});

// admin views
FLOW.NavAdminView = Ember.View.extend({	templateName: 'navAdmin/nav-admin'});

// ********************************************************//
//             Subnavigation for the Data tabs
// ********************************************************//
FLOW.DatasubnavView = Em.View.extend({
	templateName: 'navData/data-subnav',
	selectedBinding: 'controller.selected',
	NavItemView: Ember.View.extend({
		tagName: 'li',
		classNameBindings: 'isActive:active'.w(),

		isActive: function() {
			return this.get('item') === this.get('parentView.selected');
		}.property('item', 'parentView.selected').cacheable()
	})
});

FLOW.DevicesSubnavView = Em.View.extend({
	templateName: 'navDevices/devices-subnav',
	selectedBinding: 'controller.selected',
	NavItemView: Ember.View.extend({
		tagName: 'li',
		classNameBindings: 'isActive:active'.w(),

		isActive: function() {
			return this.get('item') === this.get('parentView.selected');
		}.property('item', 'parentView.selected').cacheable()
	})
});

FLOW.DevicesTableHeaderView = Em.View.extend({
	templateName: 'navDevices/current-devices-table-header',
	tagName:'tr',
	//selectedBinding:'controller.selected',

	NavItemView: Ember.View.extend({
		tagName: 'th',
		item:null,

		classNameBindings: ['isActiveAsc:sorting_asc','isActiveDesc:sorting_desc'],

		isActiveAsc: function() {
			return (this.get('item') === FLOW.deviceControl.get('selected'))&&(FLOW.deviceControl.get('sortAscending')===true);
		}.property('item', 'FLOW.deviceControl.selected','FLOW.deviceControl.sortAscending').cacheable(),

		isActiveDesc: function() {
			return (this.get('item') === FLOW.deviceControl.get('selected'))&&(FLOW.deviceControl.get('sortAscending')===false);
		}.property('item', 'FLOW.deviceControl.selected','FLOW.deviceControl.sortAscending').cacheable(),

		sort:function(){
			if ((this.get('isActiveAsc'))||(this.get('isActiveDesc'))) {
				FLOW.deviceControl.toggleProperty('sortAscending');
			}
			else {
				FLOW.deviceControl.set('sortProperties',[this.get('item')]);
				FLOW.deviceControl.set('selected',this.get('item'));
			}
		}
	})
});

FLOW.CurrentDevicesTabView = Em.View.extend({
	showDeleteDevicesDialogue: function(){
		console.log("show dialogue");
	},

	doDeleteDevices: function(){

	}
});

<commit_msg>Enable zoom with mouse-wheel<commit_after>// ***********************************************//
//                      views
// ***********************************************//

require('akvo-flow/core');
require('akvo-flow/views/survey-group-views');
require('akvo-flow/views/survey-details-views');

FLOW.ApplicationView = Ember.View.extend({
	templateName: 'application'
});

// localisation helper
Ember.Handlebars.registerHelper('t', function(i18nKey, options) {
  return Ember.String.loc(i18nKey);
});

// date format helper
Ember.Handlebars.registerHelper("date", function(property) {
  var d = new Date(parseInt(Ember.get(this, property),10));
  var m_names = new Array("Jan", "Feb", "Mar", "Apr", "May", "Jun", "Jul", "Aug", "Sep", "Oct", "Nov", "Dec");

  var curr_date = d.getDate();
  var curr_month = d.getMonth();
  var curr_year = d.getFullYear();
  return (curr_date + " " + m_names[curr_month] + " " + curr_year);
});

// ********************************************************//
//                      main navigation
// ********************************************************//

FLOW.NavigationView = Em.View.extend({
	templateName: 'navigation',
	selectedBinding: 'controller.selected',

	onLanguageChange:function(){
		this.rerender();
	}.observes('FLOW.languageControl.dashboardLanguage'),

	NavItemView: Ember.View.extend({
		tagName: 'li',
		classNameBindings: 'isActive:current navItem'.w(),

		navItem: function() {
			return this.get('item');
		}.property('item').cacheable(),

		isActive: function() {
			return this.get('item') === this.get('parentView.selected');
		}.property('item', 'parentView.selected').cacheable()
	})
});

// ********************************************************//
//                      standard views
// ********************************************************//

// home screen view
FLOW.NavHomeView = Ember.View.extend({ templateName: 'navHome/nav-home'});

// surveys views
FLOW.NavSurveysView = Ember.View.extend({ templateName: 'navSurveys/nav-surveys'});
FLOW.NavSurveysMainView = Ember.View.extend({ templateName: 'navSurveys/nav-surveys-main'});
FLOW.NavSurveysEditView = Ember.View.extend({ templateName: 'navSurveys/nav-surveys-edit'});

// devices views
FLOW.NavDevicesView = Ember.View.extend({ templateName: 'navDevices/nav-devices'});
FLOW.CurrentDevicesView = Ember.View.extend({ templateName: 'navDevices/current-devices'});
FLOW.AssignSurveysOverviewView = Ember.View.extend({ templateName: 'navDevices/assign-survey-overview'});
FLOW.EditSurveyAssignmentView = Ember.View.extend({ templateName: 'navDevices/edit-survey-assignment'});

// data views
FLOW.NavDataView = Ember.View.extend({ templateName: 'navData/nav-data'});
FLOW.InspectDataView = Ember.View.extend({ templateName: 'navData/inspect-data'});
FLOW.ImportSurveyView = Ember.View.extend({ templateName: 'navData/import-survey'});
FLOW.ExcelImportView = Ember.View.extend({ templateName: 'navData/excel-import'});
FLOW.ExcelExportView = Ember.View.extend({ templateName: 'navData/excel-export'});

// reports views
FLOW.NavReportsView = Ember.View.extend({ templateName: 'navReports/nav-reports'});

// maps views
FLOW.NavMapsView = Ember.View.extend({
  templateName: "navMaps/nav-maps",
  didInsertElement: function() {
    var map = new mxn.Mapstraction("flowMap", "google"),
        latlon = new mxn.LatLonPoint(-0.703107, 36.765747);

    map.addControls({
        pan: true,
        zoom: 'small',
        map_type: true
    });

    map.setCenterAndZoom(latlon, 8);
    map.enableScrollWheelZoom();

    // Markers
    Ember.ArrayController.create({
      content: FLOW.store.findAll(FLOW.Placemark),
      contentArrayDidChange: function (model, index) {
        var htmlContent, marker, pm, point, mark;

        pm = this.objectAt(index);
        point = new mxn.LatLonPoint(pm.get('latitude'), pm.get('longitude'));
        mark = new mxn.Marker(point);

        mark.setLabel(pm.get('collectionDate').toString());
        mark.setInfoBubble(pm.get('id'));

        map.addMarker(mark, true);

        return this;
      }
    });
  }
});

// users views
FLOW.NavUsersView = Ember.View.extend({	templateName: 'navUsers/nav-users'});

// admin views
FLOW.NavAdminView = Ember.View.extend({	templateName: 'navAdmin/nav-admin'});

// ********************************************************//
//             Subnavigation for the Data tabs
// ********************************************************//
FLOW.DatasubnavView = Em.View.extend({
	templateName: 'navData/data-subnav',
	selectedBinding: 'controller.selected',
	NavItemView: Ember.View.extend({
		tagName: 'li',
		classNameBindings: 'isActive:active'.w(),

		isActive: function() {
			return this.get('item') === this.get('parentView.selected');
		}.property('item', 'parentView.selected').cacheable()
	})
});

FLOW.DevicesSubnavView = Em.View.extend({
	templateName: 'navDevices/devices-subnav',
	selectedBinding: 'controller.selected',
	NavItemView: Ember.View.extend({
		tagName: 'li',
		classNameBindings: 'isActive:active'.w(),

		isActive: function() {
			return this.get('item') === this.get('parentView.selected');
		}.property('item', 'parentView.selected').cacheable()
	})
});

FLOW.DevicesTableHeaderView = Em.View.extend({
	templateName: 'navDevices/current-devices-table-header',
	tagName:'tr',
	//selectedBinding:'controller.selected',

	NavItemView: Ember.View.extend({
		tagName: 'th',
		item:null,

		classNameBindings: ['isActiveAsc:sorting_asc','isActiveDesc:sorting_desc'],

		isActiveAsc: function() {
			return (this.get('item') === FLOW.deviceControl.get('selected'))&&(FLOW.deviceControl.get('sortAscending')===true);
		}.property('item', 'FLOW.deviceControl.selected','FLOW.deviceControl.sortAscending').cacheable(),

		isActiveDesc: function() {
			return (this.get('item') === FLOW.deviceControl.get('selected'))&&(FLOW.deviceControl.get('sortAscending')===false);
		}.property('item', 'FLOW.deviceControl.selected','FLOW.deviceControl.sortAscending').cacheable(),

		sort:function(){
			if ((this.get('isActiveAsc'))||(this.get('isActiveDesc'))) {
				FLOW.deviceControl.toggleProperty('sortAscending');
			}
			else {
				FLOW.deviceControl.set('sortProperties',[this.get('item')]);
				FLOW.deviceControl.set('selected',this.get('item'));
			}
		}
	})
});

FLOW.CurrentDevicesTabView = Em.View.extend({
	showDeleteDevicesDialogue: function(){
		console.log("show dialogue");
	},

	doDeleteDevices: function(){

	}
});

<|endoftext|>


<commit_before>define(["sprd/util/ProductUtil", "underscore"], function(ProductUtil, _) {

    var designPrintTypesCache = {};

    var PrintValidator = {

        canBePrintedOnProduct: function(design, product) {
            product = product || this.$.product;
            var printAreas = product.get("productType.printAreas");

            var printArea = _.find(printAreas.$items, function(printArea) {
                return PrintValidator.canBePrinted(design, product, null, printArea);
            });

            return !!printArea;
        },

        canBePrinted: function(design, product, printTypes, printArea) {
            product = product || this.$.product;

            if(!product) {
                return false;
            }

            printArea = printArea || product.$.view.getDefaultPrintArea();
            var appearance = product.$.appearance;

            if (!(design && product && appearance && (printTypes || design.$.printTypes))) {
                return false;
            }

            var cacheId = [design.$.id, product.$.view.$.id, printArea.$.id, product.$.appearance.$.id].join("-");
            if (!printTypes && !designPrintTypesCache[cacheId]) {
                designPrintTypesCache[cacheId] = ProductUtil.getPossiblePrintTypesForDesignOnPrintArea(design, printArea, appearance);
            }

            var possiblePrintTypes = printTypes || designPrintTypesCache[cacheId];
            if (possiblePrintTypes.length === 0) {
                return false;
            }

            if (!printArea) {
                return false;
            }

            if (!design.isVectorDesign()) {
                // no errors to expect caused by size
                return true;
            }

            if (printArea.hasSoftBoundary()) {
                // will be clipped, so no max bound error to expect
                return true;
            }

            // check if we have a shrinkable type, as then the minimum scale doesn't play a role
            var digitalPrintType = _.find(possiblePrintTypes, function(printType) {
                return printType.isShrinkable();
            });

            if (digitalPrintType) {
                return true;
            }

            var minimumScale = (design.get("restrictions.minimumScale") || 100) / 100;

            // check minimum scale
            var hardBoundaryError = minimumScale * design.get("size.width") > printArea.width() || minimumScale * design.get("size.height") > printArea.height();

            return !hardBoundaryError;
        },

        canBePrintedSinglePrintType: function(design, printType, printArea) {
            if (!design) {
                throw new Error("No design supplied to check printability with.");
            }

            if (!printArea) {
                return false;
            }

            if (!design.isVectorDesign()) {
                // no errors to expect caused by size
                return true;
            }

            if (printArea.hasSoftBoundary()) {
                // will be clipped, so no max bound error to expect
                return true;
            }

            if (printType.isShrinkable()) {
                return true;
            }

            var minimumScale = (design.get("restrictions.minimumScale") || 100) / 100;

            // check minimum scale
            var hardBoundaryError = minimumScale * design.get("size.width") > printArea.width() || minimumScale * design.get("size.height") > printArea.height();

            return !hardBoundaryError;
        }
    };
    return PrintValidator;

});<commit_msg>inherit PrintValidator from Base to have doc generation support<commit_after>define(["sprd/util/ProductUtil", "underscore", "js/core/Base"], function(ProductUtil, _, Base) {

    var designPrintTypesCache = {};

    return Base.inherit({}, {

        canBePrintedOnProduct: function(design, product) {
            product = product || this.$.product;
            var printAreas = product.get("productType.printAreas");
            var self = this;

            var printArea = _.find(printAreas.$items, function(printArea) {
                return self.canBePrinted(design, product, null, printArea);
            });

            return !!printArea;
        },

        canBePrinted: function(design, product, printTypes, printArea) {
            product = product || this.$.product;

            if (!product) {
                return false;
            }

            printArea = printArea || product.$.view.getDefaultPrintArea();
            var appearance = product.$.appearance;

            if (!(design && product && appearance && (printTypes || design.$.printTypes))) {
                return false;
            }

            var cacheId = [design.$.id, product.$.view.$.id, printArea.$.id, product.$.appearance.$.id].join("-");
            if (!printTypes && !designPrintTypesCache[cacheId]) {
                designPrintTypesCache[cacheId] = ProductUtil.getPossiblePrintTypesForDesignOnPrintArea(design, printArea, appearance);
            }

            var possiblePrintTypes = printTypes || designPrintTypesCache[cacheId];
            if (possiblePrintTypes.length === 0) {
                return false;
            }

            if (!printArea) {
                return false;
            }

            if (!design.isVectorDesign()) {
                // no errors to expect caused by size
                return true;
            }

            if (printArea.hasSoftBoundary()) {
                // will be clipped, so no max bound error to expect
                return true;
            }

            // check if we have a shrinkable type, as then the minimum scale doesn't play a role
            var digitalPrintType = _.find(possiblePrintTypes, function(printType) {
                return printType.isShrinkable();
            });

            if (digitalPrintType) {
                return true;
            }

            var minimumScale = (design.get("restrictions.minimumScale") || 100) / 100;

            // check minimum scale
            var hardBoundaryError = minimumScale * design.get("size.width") > printArea.width() || minimumScale * design.get("size.height") > printArea.height();

            return !hardBoundaryError;
        },

        canBePrintedSinglePrintType: function(design, printType, printArea) {
            if (!design) {
                throw new Error("No design supplied to check printability with.");
            }

            if (!printArea) {
                return false;
            }

            if (!design.isVectorDesign()) {
                // no errors to expect caused by size
                return true;
            }

            if (printArea.hasSoftBoundary()) {
                // will be clipped, so no max bound error to expect
                return true;
            }

            if (printType.isShrinkable()) {
                return true;
            }

            var minimumScale = (design.get("restrictions.minimumScale") || 100) / 100;

            // check minimum scale
            var hardBoundaryError = minimumScale * design.get("size.width") > printArea.width() || minimumScale * design.get("size.height") > printArea.height();

            return !hardBoundaryError;
        }
    });

});<|endoftext|>


<commit_before>import Ember from "ember";
import { getStyles, getLayout, measureText } from "dom-ruler";
import fontLoaded from "../system/font-loaded";

const get = Ember.get;
const set = Ember.set;
const scheduleOnce = Ember.run.scheduleOnce;
const once = Ember.run.once;
const isEmpty = Ember.isEmpty;
const alias = Ember.computed.alias;
const computed = Ember.computed;
const observer = Ember.observer;
const on = Ember.on;

// jQuery is not loaded in fastboot
let trim = Ember.K;
if (Ember.$) {
  trim = Ember.$.trim;
}

function withUnits(number) {
  const unitlessNumber = parseFloat(number + '', 10) + '';
  if (unitlessNumber === number + '') {
    return `${number}px`;
  }
  return number;
}

/**
  This mixin provides common functionality for automatically
  resizing view depending on the contents of the view. To
  make your view resize, you need to set the `autoresize`
  property to `true`, and let the mixin know whether it
  can resize the height of width.

  In addition, `autoResizeText` is a required property for
  this mixin. It is already provided for `Ember.TextField` and
  `Ember.TextArea`.

  @class AutoResize
  @extends Ember.Mixin
  @since Ember 1.0.0-rc3
 */
export default Ember.Mixin.create(/** @scope AutoResize.prototype */{

  /**
    Add `ember-auto-resize` so additional
    styling can be applied indicating that
    the text field will automatically resize.

    @property classNameBindings
   */
  classNameBindings: ['autoresize:ember-auto-resize'],

  /**
    Whether the view using this mixin should
    autoresize it's contents. To enable autoresizing
    using the view's default resizing, set
    the attribute in your template.

    ```handlebars
    {{input autoresize=true}}
    ```

    @property autoresize
    @type Boolean
    @default false
   */
  autoresize: computed({
    get() {},
    set(_, value) {
      if (typeof document === 'undefined') {
        return false;
      }
      return value;
    }
  }),

  /**
    The current dimensions of the view being
    resized in terms of an object hash that
    includes a `width` and `height` property.

    @property dimensions
    @default null
    @type Object
   */
  dimensions: null,

  /**
    Whether the auto resize mixin should resize
    the width of this view.

    @property shouldResizeWidth
    @default false
    @type Boolean
   */
  shouldResizeWidth: false,

  /**
    Whether the auto resize mixin should resize
    the height of this view.

    @property shouldResizeHeight
    @default false
    @type Boolean
   */
  shouldResizeHeight: false,

  /**
    If set, this property will dictate how much
    the view is allowed to resize horizontally
    until it either falls back to scrolling or
    resizing vertically.

    @property maxWidth
    @default null
    @type Number
   */
  maxWidth: alias('max-width'),

  /**
    If set, this property dictates how much
    the view is allowed to resize vertically.
    If this is not set and the view is allowed
    to resize vertically, it will do so infinitely.

    @property maxHeight
    @default null
    @type Number
   */
  maxHeight: alias('max-height'),

  /**
    A required property that should alias the
    property that should trigger recalculating
    the dimensions of the view.

    @property autoResizeText
    @required
    @type String
   */
  autoResizeText: null,

  /**
    Whether the autoResizeText has been sanitized
    and should be treated as HTML.

    @property ignoreEscape
    @default false
    @type Boolean
   */
  ignoreEscape: false,

  /**
    Whether whitespace should be treated as significant
    contrary to any styles on the view.

    @property significantWhitespace
    @default false
    @type Boolean
   */
  significantWhitespace: false,

  /**
    Schedule measuring the view's size.
    This happens automatically when the
    `autoResizeText` property changes.

    @method scheduleMeasurement
   */
  scheduleMeasurement: on('init', observer('autoResizeText', function () {
    if (get(this, 'autoresize')) {
      once(this, 'measureSize');
    }
  })),

  /**
    Detect when a font is loaded and resize the box.

    @private
    @method fontFamilyLoaded
   */
  fontFamilyLoaded: on('didInsertElement', function () {
    let styles = getStyles(get(this, 'element'));
    let fontFamilies = styles.fontFamily.split(',');
    Ember.A(fontFamilies).forEach((fontFamily) => {
      fontLoaded(trim(fontFamily)).then(() => {
        this.scheduleMeasurement();
      }, function () {});
    });
  }),

  /**
    Measures the size of the text of the element.

    @method measureSize
   */
  measureSize() {
    const element = get(this, 'element');
    if (element == null) { return; }

    const text = get(this, 'autoResizeText');

    if (isEmpty(text) || get(this, 'isDestroying')) {
      set(this, 'measuredSize', { width: 0, height: 0 });
    }

    // Provide extra styles that will restrict
    // width / height growth
    var styles  = {};

    if (get(this, 'shouldResizeWidth')) {
      if (get(this, 'maxWidth') != null) {
        styles.maxWidth = withUnits(get(this, 'maxWidth'));
      }
    } else {
      styles.maxWidth = getLayout(element).width + 'px';
    }

    if (get(this, 'shouldResizeHeight')) {
      if (get(this, 'maxHeight') != null) {
        styles.maxHeight = withUnits(get(this, 'maxHeight'));
      }
    } else {
      styles.maxHeight = getLayout(element).height + 'px';
    }

    function measureRows(rows) {
      var html = '';
      for (var i = 0, len = parseInt(rows, 10); i < len; i++) {
        html += '
';
      }
      return measureText(html, styles, { template: element, escape: false }).height;
    }

    // Handle 'rows' attribute on <textarea>s
    if (get(this, 'rows')) {
      styles.minHeight = measureRows(get(this, 'rows')) + 'px';
    }

    // Handle 'max-rows' attribute on <textarea>s
    if (get(this, 'max-rows') && get(this, 'maxHeight') == null) {
      set(this, 'maxHeight', measureRows(get(this, 'max-rows')));
      styles.maxHeight = get(this, 'maxHeight') + 'px';
    }

    // Force white-space to pre-wrap to make
    // whitespace significant
    if (get(this, 'significantWhitespace')) {
      styles.whiteSpace = 'pre-wrap';
    }

    // Create a signature so we can cache the max width and height
    const signature = styles.maxWidth + styles.maxHeight;
    if (signature !== this._signature) {
      const maxDimensions = measureText('', {
        width: styles.maxWidth,
        height: styles.maxHeight,
      }, { template: element });
      this._signature = signature;
      this._maxWidth = maxDimensions.width;
      this._maxHeight = maxDimensions.height;
    }

    const size = measureText(text, styles, {
      template: element,
      escape: !get(this, 'ignoreEscape'),
    });

    if (styles.maxWidth)  { size.maxWidth = this._maxWidth; }
    if (styles.maxHeight) { size.maxHeight = this._maxHeight; }
    set(this, 'measuredSize', size);
  },

  /**
    Alter the `dimensions` property of the
    view to conform to the measured size of
    the view.

    @method measuredSizeDidChange
   */
  measuredSizeDidChange: on('didInsertElement', observer('measuredSize', function () {
    let size = get(this, 'measuredSize');
    if (size == null) { return; }

    let { maxWidth, maxHeight } = size;
    let layoutDidChange = false;
    let dimensions = {};

    if (get(this, 'shouldResizeWidth')) {
      // Account for off-by-one error in FireFox
      // (specifically, input elements have 1px
      //  of scroll when this isn't applied)
      // TODO: sniff for this bug and fix it!
      size.width += 1;

      if (maxWidth != null &&
          size.width > maxWidth) {
        dimensions.width = maxWidth;
      } else {
        dimensions.width = size.width;
      }
      layoutDidChange = true;
    }

    if (get(this, 'shouldResizeHeight')) {
      if (maxHeight != null &&
          size.height > maxHeight) {
        dimensions.height = maxHeight;
      } else {
        dimensions.height = size.height;
      }
      layoutDidChange = true;
    }

    set(this, 'dimensions', dimensions);

    if (layoutDidChange) {
      scheduleOnce('render', this, 'dimensionsDidChange');
    }
  })),

  /**
    Retiles the view at the end of the render queue.
    @method dimensionsDidChange
   */
  dimensionsDidChange() {
    var dimensions = get(this, 'dimensions');
    var styles = {};

    for (let key in dimensions) {
      if (!dimensions.hasOwnProperty(key)) { continue; }
      styles[key] = dimensions[key] + 'px';
    }

    if (get(this, 'maxHeight') == null) {
      styles.overflow = 'hidden';
    }

    var $element = this.$();
    if ($element) {
      $element.css(styles);
    }
  }

});
<commit_msg>Remove deprecated Ember.K<commit_after>import Ember from "ember";
import { getStyles, getLayout, measureText } from "dom-ruler";
import fontLoaded from "../system/font-loaded";

const get = Ember.get;
const set = Ember.set;
const scheduleOnce = Ember.run.scheduleOnce;
const once = Ember.run.once;
const isEmpty = Ember.isEmpty;
const alias = Ember.computed.alias;
const computed = Ember.computed;
const observer = Ember.observer;
const on = Ember.on;

// jQuery is not loaded in fastboot
let trim = function() {};
if (Ember.$) {
  trim = Ember.$.trim;
}

function withUnits(number) {
  const unitlessNumber = parseFloat(number + '', 10) + '';
  if (unitlessNumber === number + '') {
    return `${number}px`;
  }
  return number;
}

/**
  This mixin provides common functionality for automatically
  resizing view depending on the contents of the view. To
  make your view resize, you need to set the `autoresize`
  property to `true`, and let the mixin know whether it
  can resize the height of width.

  In addition, `autoResizeText` is a required property for
  this mixin. It is already provided for `Ember.TextField` and
  `Ember.TextArea`.

  @class AutoResize
  @extends Ember.Mixin
  @since Ember 1.0.0-rc3
 */
export default Ember.Mixin.create(/** @scope AutoResize.prototype */{

  /**
    Add `ember-auto-resize` so additional
    styling can be applied indicating that
    the text field will automatically resize.

    @property classNameBindings
   */
  classNameBindings: ['autoresize:ember-auto-resize'],

  /**
    Whether the view using this mixin should
    autoresize it's contents. To enable autoresizing
    using the view's default resizing, set
    the attribute in your template.

    ```handlebars
    {{input autoresize=true}}
    ```

    @property autoresize
    @type Boolean
    @default false
   */
  autoresize: computed({
    get() {},
    set(_, value) {
      if (typeof document === 'undefined') {
        return false;
      }
      return value;
    }
  }),

  /**
    The current dimensions of the view being
    resized in terms of an object hash that
    includes a `width` and `height` property.

    @property dimensions
    @default null
    @type Object
   */
  dimensions: null,

  /**
    Whether the auto resize mixin should resize
    the width of this view.

    @property shouldResizeWidth
    @default false
    @type Boolean
   */
  shouldResizeWidth: false,

  /**
    Whether the auto resize mixin should resize
    the height of this view.

    @property shouldResizeHeight
    @default false
    @type Boolean
   */
  shouldResizeHeight: false,

  /**
    If set, this property will dictate how much
    the view is allowed to resize horizontally
    until it either falls back to scrolling or
    resizing vertically.

    @property maxWidth
    @default null
    @type Number
   */
  maxWidth: alias('max-width'),

  /**
    If set, this property dictates how much
    the view is allowed to resize vertically.
    If this is not set and the view is allowed
    to resize vertically, it will do so infinitely.

    @property maxHeight
    @default null
    @type Number
   */
  maxHeight: alias('max-height'),

  /**
    A required property that should alias the
    property that should trigger recalculating
    the dimensions of the view.

    @property autoResizeText
    @required
    @type String
   */
  autoResizeText: null,

  /**
    Whether the autoResizeText has been sanitized
    and should be treated as HTML.

    @property ignoreEscape
    @default false
    @type Boolean
   */
  ignoreEscape: false,

  /**
    Whether whitespace should be treated as significant
    contrary to any styles on the view.

    @property significantWhitespace
    @default false
    @type Boolean
   */
  significantWhitespace: false,

  /**
    Schedule measuring the view's size.
    This happens automatically when the
    `autoResizeText` property changes.

    @method scheduleMeasurement
   */
  scheduleMeasurement: on('init', observer('autoResizeText', function () {
    if (get(this, 'autoresize')) {
      once(this, 'measureSize');
    }
  })),

  /**
    Detect when a font is loaded and resize the box.

    @private
    @method fontFamilyLoaded
   */
  fontFamilyLoaded: on('didInsertElement', function () {
    let styles = getStyles(get(this, 'element'));
    let fontFamilies = styles.fontFamily.split(',');
    Ember.A(fontFamilies).forEach((fontFamily) => {
      fontLoaded(trim(fontFamily)).then(() => {
        this.scheduleMeasurement();
      }, function () {});
    });
  }),

  /**
    Measures the size of the text of the element.

    @method measureSize
   */
  measureSize() {
    const element = get(this, 'element');
    if (element == null) { return; }

    const text = get(this, 'autoResizeText');

    if (isEmpty(text) || get(this, 'isDestroying')) {
      set(this, 'measuredSize', { width: 0, height: 0 });
    }

    // Provide extra styles that will restrict
    // width / height growth
    var styles  = {};

    if (get(this, 'shouldResizeWidth')) {
      if (get(this, 'maxWidth') != null) {
        styles.maxWidth = withUnits(get(this, 'maxWidth'));
      }
    } else {
      styles.maxWidth = getLayout(element).width + 'px';
    }

    if (get(this, 'shouldResizeHeight')) {
      if (get(this, 'maxHeight') != null) {
        styles.maxHeight = withUnits(get(this, 'maxHeight'));
      }
    } else {
      styles.maxHeight = getLayout(element).height + 'px';
    }

    function measureRows(rows) {
      var html = '';
      for (var i = 0, len = parseInt(rows, 10); i < len; i++) {
        html += '
';
      }
      return measureText(html, styles, { template: element, escape: false }).height;
    }

    // Handle 'rows' attribute on <textarea>s
    if (get(this, 'rows')) {
      styles.minHeight = measureRows(get(this, 'rows')) + 'px';
    }

    // Handle 'max-rows' attribute on <textarea>s
    if (get(this, 'max-rows') && get(this, 'maxHeight') == null) {
      set(this, 'maxHeight', measureRows(get(this, 'max-rows')));
      styles.maxHeight = get(this, 'maxHeight') + 'px';
    }

    // Force white-space to pre-wrap to make
    // whitespace significant
    if (get(this, 'significantWhitespace')) {
      styles.whiteSpace = 'pre-wrap';
    }

    // Create a signature so we can cache the max width and height
    const signature = styles.maxWidth + styles.maxHeight;
    if (signature !== this._signature) {
      const maxDimensions = measureText('', {
        width: styles.maxWidth,
        height: styles.maxHeight,
      }, { template: element });
      this._signature = signature;
      this._maxWidth = maxDimensions.width;
      this._maxHeight = maxDimensions.height;
    }

    const size = measureText(text, styles, {
      template: element,
      escape: !get(this, 'ignoreEscape'),
    });

    if (styles.maxWidth)  { size.maxWidth = this._maxWidth; }
    if (styles.maxHeight) { size.maxHeight = this._maxHeight; }
    set(this, 'measuredSize', size);
  },

  /**
    Alter the `dimensions` property of the
    view to conform to the measured size of
    the view.

    @method measuredSizeDidChange
   */
  measuredSizeDidChange: on('didInsertElement', observer('measuredSize', function () {
    let size = get(this, 'measuredSize');
    if (size == null) { return; }

    let { maxWidth, maxHeight } = size;
    let layoutDidChange = false;
    let dimensions = {};

    if (get(this, 'shouldResizeWidth')) {
      // Account for off-by-one error in FireFox
      // (specifically, input elements have 1px
      //  of scroll when this isn't applied)
      // TODO: sniff for this bug and fix it!
      size.width += 1;

      if (maxWidth != null &&
          size.width > maxWidth) {
        dimensions.width = maxWidth;
      } else {
        dimensions.width = size.width;
      }
      layoutDidChange = true;
    }

    if (get(this, 'shouldResizeHeight')) {
      if (maxHeight != null &&
          size.height > maxHeight) {
        dimensions.height = maxHeight;
      } else {
        dimensions.height = size.height;
      }
      layoutDidChange = true;
    }

    set(this, 'dimensions', dimensions);

    if (layoutDidChange) {
      scheduleOnce('render', this, 'dimensionsDidChange');
    }
  })),

  /**
    Retiles the view at the end of the render queue.
    @method dimensionsDidChange
   */
  dimensionsDidChange() {
    var dimensions = get(this, 'dimensions');
    var styles = {};

    for (let key in dimensions) {
      if (!dimensions.hasOwnProperty(key)) { continue; }
      styles[key] = dimensions[key] + 'px';
    }

    if (get(this, 'maxHeight') == null) {
      styles.overflow = 'hidden';
    }

    var $element = this.$();
    if ($element) {
      $element.css(styles);
    }
  }

});
<|endoftext|>


<commit_before>this.addEventListener("install", function (event) {
      self.skipWaiting(
        caches.open('v2').then(function (cache) {
         return cache.addAll(['/html/',
          '/html/index.html',
          '/html/js/911.js',
          '/html/img/trapped_lady.jpg',
          '/html/img/screaming.jpg',
          '/html/img/location4.jpg',
          '/html/img/embrace3.jpg'
          ]);
        })
        );
    });

this.addEventListener('activate', function(event) {
  var cacheWhitelist = ['v1'];

  event.waitUntil(
    caches.keys().then(function(keyList) {
      return Promise.all(keyList.map(function(key) {
        if (cacheWhitelist.indexOf(key) === -1) {
          return caches.delete(key);
        }
      }));
    })
  );
});

this.addEventListener('fetch', function (event) {
	event.respondWith(
    caches.match(event.request).then(function(response) {
      return response;
    })

    );
});<commit_msg>waitUntil<commit_after>this.addEventListener("install", function (event) {
      event.waitUntil(
        caches.open('v2').then(function (cache) {
         return cache.addAll(['/html/',
          '/html/index.html',
          '/html/js/911.js',
          '/html/img/trapped_lady.jpg',
          '/html/img/screaming.jpg',
          '/html/img/location4.jpg',
          '/html/img/embrace3.jpg'
          ]);
        })
        );
    });

this.addEventListener('activate', function(event) {
  var cacheWhitelist = ['v1'];

  event.waitUntil(
    caches.keys().then(function(keyList) {
      return Promise.all(keyList.map(function(key) {
        if (cacheWhitelist.indexOf(key) === -1) {
          return caches.delete(key);
        }
      }));
    })
  );
});

this.addEventListener('fetch', function (event) {
	event.respondWith(
    caches.match(event.request).then(function(response) {
      return response;
    })

    );
});<|endoftext|>


<commit_before><commit_msg>Update REPL help<commit_after><|endoftext|>


<commit_before>"use strict";
(function(context){

	var matchType = function (inputArray, matchArray){
		var runningMatch = true;
		for (var key in matchArray) {
			if (typeof inputArray[key] === "object" && typeof matchArray[key] === "object") {
				runningMatch = matchType(inputArray[key], matchArray[key]) && runningMatch;
			}
			else if (typeof inputArray[key] !== matchArray[key]) {
				runningMatch = false;
			}
		}
		return runningMatch;
	}

	context.overload = context.overload || function(){
		var executionContext = this;
		var inputs = arguments;
		if (arguments.length === 1){
			inputs = arguments[0];
		}
        //inputs = Array.prototype.slice.call(inputs, 0);

		var exeArgs = [];
        var exefake = function (){};
        exefake.use = exefake.args = function(){return exefake;};

		var exe = function () {
			for (var key in exeArgs ) {
				var matchAndRun = exeArgs[key]
				if (matchType(arguments, matchAndRun.match)){
					return matchAndRun.execute.apply(this, arguments);
				}
			}
		};
		var argsFn = function() {
			var useArgs = arguments;

			return {use: function(callback){
				exeArgs.push({match: useArgs, execute: callback});
				if (inputs.length && matchType(inputs, useArgs)) {
					callback.apply(executionContext, inputs);
					return exefake;
				}
				else {
					return exe;
				}

			}};
		};
		exe.args = argsFn;
        return exe;
	}

    context.overload.define = context.overload.define || function (obj) {
        if (typeof obj === 'function') {
            try {
                return context.overload.define(new obj());
            }
            catch (err) {
                console.log("Class definition does not have a null constructor");
                return;
            }
        }
        else if (typeof obj !== 'object') {
            return;
        }
        else {
            var objectDefinition = {};

            var objKeys = Object.keys(obj);
            for (var i = 0; i < objKeys.length; i++) {
                var thisKey = objKeys[i];
                objectDefinition[thisKey] = typeof obj[thisKey];
            }
            if (obj.__proto__) {
                var inheritedDefs = context.overload.define(obj.__proto__);
                var inheritedKeys = Object.keys(inheritedDefs);
                for (var i = 0; i < inheritedKeys.length; i++){
                    var inheritedKey = inheritedKeys[i]
                    objectDefinition[inheritedKey] = objectDefinition[inheritedKey] || inheritedDefs[inheritedKey];
                }
            }

            return objectDefinition;
        }
    }

	if (typeof module != 'undefined' && module.exports) {module.exports = context["overload"];}
})(this)<commit_msg>changed space to tabs<commit_after>"use strict";
(function(context){

	var matchType = function (inputArray, matchArray){
		var runningMatch = true;
		for (var key in matchArray) {
			if (typeof inputArray[key] === "object" && typeof matchArray[key] === "object") {
				runningMatch = matchType(inputArray[key], matchArray[key]) && runningMatch;
			}
			else if (typeof inputArray[key] !== matchArray[key]) {
				runningMatch = false;
			}
		}
		return runningMatch;
	}

	context.overload = context.overload || function(){
		var executionContext = this;
		var inputs = arguments;
		if (arguments.length === 1){
			inputs = arguments[0];
		}
		//inputs = Array.prototype.slice.call(inputs, 0);

		var exeArgs = [];
		var exefake = function (){};
		exefake.use = exefake.args = function(){return exefake;};

		var exe = function () {
			for (var key in exeArgs ) {
				var matchAndRun = exeArgs[key]
				if (matchType(arguments, matchAndRun.match)){
					return matchAndRun.execute.apply(this, arguments);
				}
			}
		};
		var argsFn = function() {
			var useArgs = arguments;

			return {use: function(callback){
				exeArgs.push({match: useArgs, execute: callback});
				if (inputs.length && matchType(inputs, useArgs)) {
					callback.apply(executionContext, inputs);
					return exefake;
				}
				else {
					return exe;
				}

			}};
		};
		exe.args = argsFn;
		return exe;
	}

	context.overload.define = context.overload.define || function (obj) {
		if (typeof obj === 'function') {
			try {
				return context.overload.define(new obj());
			}
			catch (err) {
				console.log("Class definition does not have a null constructor");
				return;
			}
		}
		else if (typeof obj !== 'object') {
			return;
		}
		else {
			var objectDefinition = {};

			var objKeys = Object.keys(obj);
			for (var i = 0; i < objKeys.length; i++) {
				var thisKey = objKeys[i];
				objectDefinition[thisKey] = typeof obj[thisKey];
			}
			if (obj.__proto__) {
				var inheritedDefs = context.overload.define(obj.__proto__);
				var inheritedKeys = Object.keys(inheritedDefs);
				for (var i = 0; i < inheritedKeys.length; i++){
					var inheritedKey = inheritedKeys[i]
					objectDefinition[inheritedKey] = objectDefinition[inheritedKey] || inheritedDefs[inheritedKey];
				}
			}

			return objectDefinition;
		}
	}

	if (typeof module != 'undefined' && module.exports) {module.exports = context["overload"];}
})(this)<|endoftext|>


<commit_before>import { actionTypes } from '../actions/actions';
import Immutable from 'immutable';
import { createReducer } from 'redux-immutablejs'
import won from '../won-es6';
import {
    getIn,
    generateIdString,
} from '../utils';
import config from '../config';

const initialState = Immutable.fromJS({
});

export default function(allToasts = initialState, action = {}) {
    switch(action.type) {
        case actionTypes.toasts.test:
            allToasts = pushNewToast(allToasts, "Error Toast", won.WON.errorToast);
            allToasts = pushNewToast(allToasts, "Warning Toast", won.WON.warnToast);
            allToasts = pushNewToast(allToasts, "Info Toast", won.WON.infoToast);
            return allToasts;

        case actionTypes.logout:
            return initialState;

        case actionTypes.loginFailed:
            if(getIn(action, ['payload', 'loginError']) === 'invalid privateId') {
                return pushNewToast(
                    allToasts,
                    'Sorry, we couldn\'t find the private ID (the one in your url-bar). ' +
                    'Try reloading the page or ' +

                    '' +
                    //'' +
                      'removing the ID' +
                    '.',
                    won.WON.errorToast,
                    {htmlEnabled: true}
                )
            } else {
                return allToasts;
            }

        case actionTypes.lostConnection:
            return pushNewToast(allToasts, "Lost connection - progress " +
                "can't be saved any more. Make sure your " +
                "internet-connection is working, then click \"Reconnect\"", won.WON.warnToast);
        //INFO TOASTS: won.WON.infoToast

        //WARN TOASTS: won.WON.warnToast
        //ERROR TOASTS: won.WON.errorToast
        case actionTypes.messages.closeNeed.failed:
            return pushNewToast(allToasts, "Closing Need failed", won.WON.errorToast);

        case actionTypes.messages.chatMessage.failure:
            return pushNewToast(allToasts, "Sending Chat Message failed", won.WON.errorToast);

        //SPECIFIC TOAST ACTIONS
        case actionTypes.toasts.delete:
            return allToasts.deleteIn([action.payload.get("id")]);

        default:
            return allToasts;
    }
}

/**
 *
 * @param allToasts
 * @param msg
 * @param type
 * @param options
 *   * htmlEnabled: set this to true only if it's really necessary and never
 *   with non-static text (e.g. never use this with toasts that show need-contents
 *   as this would open the possibility for XSS-attacks)
 * @returns {*}
 */
function pushNewToast(allToasts, msg, type, options) {
    const options_ = Object.assign({
        htmlEnabled: false,
    }, options);

    let toastType = type;
    if(!toastType){
        toastType = won.WON.infoToast;
    }

    const id = generateIdString(6);
    return allToasts.setIn([id], Immutable.fromJS({
        id: id,
        type: toastType,
        msg: msg,
        htmlEnabled: _options.htmlEnabled,
    }));
}

<commit_msg>Fixed variable name in toast-reducer.<commit_after>import { actionTypes } from '../actions/actions';
import Immutable from 'immutable';
import { createReducer } from 'redux-immutablejs'
import won from '../won-es6';
import {
    getIn,
    generateIdString,
} from '../utils';
import config from '../config';

const initialState = Immutable.fromJS({
});

export default function(allToasts = initialState, action = {}) {
    switch(action.type) {
        case actionTypes.toasts.test:
            allToasts = pushNewToast(allToasts, "Error Toast", won.WON.errorToast);
            allToasts = pushNewToast(allToasts, "Warning Toast", won.WON.warnToast);
            allToasts = pushNewToast(allToasts, "Info Toast", won.WON.infoToast);
            return allToasts;

        case actionTypes.logout:
            return initialState;

        case actionTypes.loginFailed:
            if(getIn(action, ['payload', 'loginError']) === 'invalid privateId') {
                return pushNewToast(
                    allToasts,
                    'Sorry, we couldn\'t find the private ID (the one in your url-bar). ' +
                    'Try reloading the page or ' +

                    '' +
                    //'' +
                      'removing the ID' +
                    '.',
                    won.WON.errorToast,
                    {htmlEnabled: true}
                )
            } else {
                return allToasts;
            }

        case actionTypes.lostConnection:
            return pushNewToast(allToasts, "Lost connection - progress " +
                "can't be saved any more. Make sure your " +
                "internet-connection is working, then click \"Reconnect\"", won.WON.warnToast);
        //INFO TOASTS: won.WON.infoToast

        //WARN TOASTS: won.WON.warnToast
        //ERROR TOASTS: won.WON.errorToast
        case actionTypes.messages.closeNeed.failed:
            return pushNewToast(allToasts, "Closing Need failed", won.WON.errorToast);

        case actionTypes.messages.chatMessage.failure:
            return pushNewToast(allToasts, "Sending Chat Message failed", won.WON.errorToast);

        //SPECIFIC TOAST ACTIONS
        case actionTypes.toasts.delete:
            return allToasts.deleteIn([action.payload.get("id")]);

        default:
            return allToasts;
    }
}

/**
 *
 * @param allToasts
 * @param msg
 * @param type
 * @param options
 *   * htmlEnabled: set this to true only if it's really necessary and never
 *   with non-static text (e.g. never use this with toasts that show need-contents
 *   as this would open the possibility for XSS-attacks)
 * @returns {*}
 */
function pushNewToast(allToasts, msg, type, options) {
    const options_ = Object.assign({
        htmlEnabled: false,
    }, options);

    let toastType = type;
    if(!toastType){
        toastType = won.WON.infoToast;
    }

    const id = generateIdString(6);
    return allToasts.setIn([id], Immutable.fromJS({
        id: id,
        type: toastType,
        msg: msg,
        htmlEnabled: options_.htmlEnabled,
    }));
}

<|endoftext|>


<commit_before>/**
 *  locale-notification.js
 *  Cordova LocalNotification Plugin
 *
 *  Created by Sebastian Katzer (github.com/katzer) on 10/08/2013.
 *  Copyright 2013 Sebastian Katzer. All rights reserved.
 *  GPL v2 licensed
 */

var LocalNotification = function () {

};

LocalNotification.prototype = {
    /**
     * Fügt einen neuen Eintrag zur Registry hinzu.
     *
     * @param {Object} options
     * @return {Number} Die ID der Notification
     */
    add: function (options) {
        var defaults = {
            date:       false,
            message:    '',
            title:      '',
            badge:      0,
            id:         0,
            sound:      '', // nur iOS
            background: '',
            foreground: ''
        };

        var callbackFn = function (cmd) {
            eval(cmd);
        };

        for (var key in defaults) {
            if (options[key] !== undefined) {
                defaults[key] = options[key];
            }
        }

        if (defaults.id) {
            defaults.id = defaults.id.toString();
        }

        if (typeof defaults.date == 'object') {
            defaults.date = Math.round(defaults.date.getTime()/1000);
        }

        cordova.exec(callbackFn, null, 'LocalNotification', 'add', [defaults]);

        return defaults.id;
    },

    /**
     * Entfernt die angegebene Notification.
     *
     * @param {String} id
     */
    cancel: function (id) {
        cordova.exec(null, null, 'LocalNotification', 'cancel', [id.toString()]);
    },

    /**
     * Entfernt alle registrierten Notifications.
     */
    cancelAll: function () {
        cordova.exec(null, null, 'LocalNotification', 'cancelAll', []);
    }
};

var plugin = new LocalNotification();

module.exports = plugin;
<commit_msg>Icon can be specified by name through interface.<commit_after>/**
 *  locale-notification.js
 *  Cordova LocalNotification Plugin
 *
 *  Created by Sebastian Katzer (github.com/katzer) on 10/08/2013.
 *  Copyright 2013 Sebastian Katzer. All rights reserved.
 *  GPL v2 licensed
 */

var LocalNotification = function () {

};

LocalNotification.prototype = {
    /**
     * Fügt einen neuen Eintrag zur Registry hinzu.
     *
     * @param {Object} options
     * @return {Number} Die ID der Notification
     */
    add: function (options) {
        var defaults = {
            date:       false,
            message:    '',
            title:      '',
            badge:      0,
            id:         0,
            icon:       'icon', // nur Android
            sound:      '', // nur iOS
            background: '',
            foreground: ''
        };

        var callbackFn = function (cmd) {
            eval(cmd);
        };

        for (var key in defaults) {
            if (options[key] !== undefined) {
                defaults[key] = options[key];
            }
        }

        if (defaults.id) {
            defaults.id = defaults.id.toString();
        }

        if (typeof defaults.date == 'object') {
            defaults.date = Math.round(defaults.date.getTime()/1000);
        }

        cordova.exec(callbackFn, null, 'LocalNotification', 'add', [defaults]);

        return defaults.id;
    },

    /**
     * Entfernt die angegebene Notification.
     *
     * @param {String} id
     */
    cancel: function (id) {
        cordova.exec(null, null, 'LocalNotification', 'cancel', [id.toString()]);
    },

    /**
     * Entfernt alle registrierten Notifications.
     */
    cancelAll: function () {
        cordova.exec(null, null, 'LocalNotification', 'cancelAll', []);
    }
};

var plugin = new LocalNotification();

module.exports = plugin;
<|endoftext|>


<commit_before>/*
 * Copyright 2014 Thoughtworks Inc.
 *
 * Licensed under the Apache License, Version 2.0 (the "License");
 * you may not use this file except in compliance with the License.
 * You may obtain a copy of the License at
 *
 *     http://www.apache.org/licenses/LICENSE-2.0
 *
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS,
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 * See the License for the specific language governing permissions and
 * limitations under the License.
 */
define([
    'flight/lib/component',
    'component/mixins/with_auth_token_from_hash',
  ],
  function(defineComponent, withAuthTokemFromHash) {
    'use strict';
    return defineComponent(issuesExporter, withAuthTokemFromHash);

    function issuesExporter() {
      var issuesToExport = [];

      var csvLink = '';

      this.mountExportCsvLink = function(ev, data) {
        $('#export_csv').attr('disabled', true);
        var repositoriesUrls = this.getRepositoriesUrlsFromIssues(data.issues);
        issuesToExport = data.issues;
        this.getEventsFromProjects(repositoriesUrls);
      };

      this.clearLink = function() {
        csvLink = '';
      };

      this.linkToCsv = function(data) {
        var issuesCsv = this.issuesToCsv(data);
        if (csvLink === '') {
          issuesCsv.splice(0, 0, csvHeader());
        }

        csvLink += encodeURIComponent(issuesCsv.join('\n') + '\n');
        return 'data:text/csv;charset=utf8,' + csvLink;
      };

      this.validIssuesToExport = function(issues) {
        return _.filter(issues, function(issue) {
          return issue.projectName !== undefined;
        });
      };

      this.issuesToCsv = function(issues) {
        var issuesCsv = _.map(this.validIssuesToExport(issues), function(issue) {
          return ['\"' + issue.projectName + "\"",
            issue.number,
            "\"" + issue.title + "\"",
            issue.state,
            issue.kanbanState,
            "\"" + issue.body.replace(/(\r\n|\n|\r)/g, " ") + "\"",
            "\"" + _.map(issue.labels, function(label) {
              return label.name;
            }) + "\"",
            issue.created_at,
            issue.dev_at,
            issue.closed_at,
            daysBetween(issue.created_at, issue.closed_at),
            daysBetween(issue.dev_at, issue.closed_at)
          ].join(';');
        });

        return issuesCsv;
      };

      function daysBetween(earlierDate, lateDate) {
        if ((earlierDate && lateDate) && (lateDate > earlierDate)) {
          var leadTime,
            millisecondsInDay = 86400000;

          leadTime = (new Date(lateDate) - new Date(earlierDate)) / millisecondsInDay;
          leadTime = parseInt(leadTime);

          return leadTime;
        } else {
          return "";
        }
      };

      function csvHeader() {
        return ["Source", "Github ID", "Title", "Status", "Kanban State", "Description", "Tags", "Create at", "Dev at", "Closed at", "Lead Time", "Cycle Time"].join(';');
      };

      this.getEventsFromProjects = function(projectsUrl) {
        var events = [];
        var self = this;

        function getEvents(url) {
          $.get(url, function(data, textStatus, request) {
            events = events.concat(data);

            try {
              var header = request.getResponseHeader('Link');
              var next = header.match(/<.*?>; rel="next"/)[0].match(/https.*[0-9]+/)[0];
              if (next) {
                getEvents(next);
              }
            } catch (err) {}
          });
        }

        $.each(projectsUrl, function(index, val) {
          getEvents(val + 'issues/events?per_page=100&access_token=' + this.getCurrentAuthToken());
        }.bind(self));

        $(document).one('ajaxStop', function() {
          self.createCsvUri(self.addDevDateForIssues(issuesToExport, events));
        });
      };

      this.groupEventsByIssuesId = function(events) {
        return _.groupBy(events, function(event) {
          return event.issue.id;
        });
      };

      this.excludeNonLabeledEvents = function(mappedEvents) {
        return _.object(_.map(mappedEvents, function(issueEvents, key) {
          return [key, _.filter(issueEvents, function(event) {
            return event.event == 'labeled';
          })]
        }));
      };

      this.getOnlyDevelopmentIssueEvents = function(labeledEvents) {
        return _.object(_.map(labeledEvents, function(issueEvents, key) {
          return [key, _.filter(issueEvents, function(event) {
            return event.label.name == '2 - Development';
          })]
        }));
      };

      this.getEarliestDevelopmentIssueEvents = function(developmentEvents) {
        return _.object(_.map(developmentEvents, function(events, key) {
          return [key, _.first(_.sortBy(events, function(e) {
            return e.created_at;
          }))]
        }));
      };

      this.mergeEventsWithIssues = function(issues, events) {
        return _.each(issues, function(issue) {
          if (events[issue.id]) {
            issue.dev_at = events[issue.id].created_at;
          }
        });
      };

      this.getRepositoriesUrlsFromIssues = function(issues) {
        return _.uniq(_.pluck(issues, 'repoUrl'));
      };

      this.addDevDateForIssues = function(issues, events) {
        var groupedEventsByIssueId = {},
          labeledEvents = {},
          developmentEvents = {},
          earlierstDevelopemntIssuesEvent = {},
          issuesWithDevDate = {};

        groupedEventsByIssueId = this.groupEventsByIssuesId(events);
        labeledEvents = this.excludeNonLabeledEvents(groupedEventsByIssueId);
        developmentEvents = this.getOnlyDevelopmentIssueEvents(labeledEvents);
        earlierstDevelopemntIssuesEvent = this.getEarliestDevelopmentIssueEvents(developmentEvents);
        issuesWithDevDate = this.mergeEventsWithIssues(issues, earlierstDevelopemntIssuesEvent);

        return issuesWithDevDate;
      };

      this.createCsvUri = function(issuesWithDevDate) {
        var uri = this.linkToCsv(issuesWithDevDate);

        var downloadLink = document.createElement("a");
        downloadLink.href = uri;
        downloadLink.download = "data.csv";

        document.body.appendChild(downloadLink);
        downloadLink.click();
        document.body.removeChild(downloadLink);
        $("#export_csv").attr("disabled", false);
        issuesToExport = [];
        this.trigger('data:issues:clearExportCsvLink');

      };

      this.after('initialize', function() {
        this.on('data:issues:mountExportCsvLink', this.mountExportCsvLink);
        this.on('data:issues:clearExportCsvLink', this.clearLink);
      });
    }
  }
);<commit_msg>Remove description column from CSV report.<commit_after>/*
 * Copyright 2014 Thoughtworks Inc.
 *
 * Licensed under the Apache License, Version 2.0 (the "License");
 * you may not use this file except in compliance with the License.
 * You may obtain a copy of the License at
 *
 *     http://www.apache.org/licenses/LICENSE-2.0
 *
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS,
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 * See the License for the specific language governing permissions and
 * limitations under the License.
 */
define([
    'flight/lib/component',
    'component/mixins/with_auth_token_from_hash',
  ],
  function(defineComponent, withAuthTokemFromHash) {
    'use strict';
    return defineComponent(issuesExporter, withAuthTokemFromHash);

    function issuesExporter() {
      var issuesToExport = [];

      var csvLink = '';

      this.mountExportCsvLink = function(ev, data) {
        $('#export_csv').attr('disabled', true);
        var repositoriesUrls = this.getRepositoriesUrlsFromIssues(data.issues);
        issuesToExport = data.issues;
        this.getEventsFromProjects(repositoriesUrls);
      };

      this.clearLink = function() {
        csvLink = '';
      };

      this.linkToCsv = function(data) {
        var issuesCsv = this.issuesToCsv(data);
        if (csvLink === '') {
          issuesCsv.splice(0, 0, csvHeader());
        }

        csvLink += encodeURIComponent(issuesCsv.join('\n') + '\n');
        return 'data:text/csv;charset=utf8,' + csvLink;
      };

      this.validIssuesToExport = function(issues) {
        return _.filter(issues, function(issue) {
          return issue.projectName !== undefined;
        });
      };

      this.issuesToCsv = function(issues) {
        var issuesCsv = _.map(this.validIssuesToExport(issues), function(issue) {
          return ['\"' + issue.projectName + "\"",
            issue.number,
            "\"" + issue.title + "\"",
            issue.state,
            issue.kanbanState,
            "\"" + _.map(issue.labels, function(label) {
              return label.name;
            }) + "\"",
            issue.created_at,
            issue.dev_at,
            issue.closed_at,
            daysBetween(issue.created_at, issue.closed_at),
            daysBetween(issue.dev_at, issue.closed_at)
          ].join(';');
        });

        return issuesCsv;
      };

      function daysBetween(earlierDate, lateDate) {
        if ((earlierDate && lateDate) && (lateDate > earlierDate)) {
          var leadTime,
            millisecondsInDay = 86400000;

          leadTime = (new Date(lateDate) - new Date(earlierDate)) / millisecondsInDay;
          leadTime = parseInt(leadTime);

          return leadTime;
        } else {
          return "";
        }
      };

      function csvHeader() {
        return ["Source", "Github ID", "Title", "Status", "Kanban State", "Tags", "Create at", "Dev at", "Closed at", "Lead Time", "Cycle Time"].join(';');
      };

      this.getEventsFromProjects = function(projectsUrl) {
        var events = [];
        var self = this;

        function getEvents(url) {
          $.get(url, function(data, textStatus, request) {
            events = events.concat(data);

            try {
              var header = request.getResponseHeader('Link');
              var next = header.match(/<.*?>; rel="next"/)[0].match(/https.*[0-9]+/)[0];
              if (next) {
                getEvents(next);
              }
            } catch (err) {}
          });
        }

        $.each(projectsUrl, function(index, val) {
          getEvents(val + 'issues/events?per_page=100&access_token=' + this.getCurrentAuthToken());
        }.bind(self));

        $(document).one('ajaxStop', function() {
          self.createCsvUri(self.addDevDateForIssues(issuesToExport, events));
        });
      };

      this.groupEventsByIssuesId = function(events) {
        return _.groupBy(events, function(event) {
          return event.issue.id;
        });
      };

      this.excludeNonLabeledEvents = function(mappedEvents) {
        return _.object(_.map(mappedEvents, function(issueEvents, key) {
          return [key, _.filter(issueEvents, function(event) {
            return event.event == 'labeled';
          })]
        }));
      };

      this.getOnlyDevelopmentIssueEvents = function(labeledEvents) {
        return _.object(_.map(labeledEvents, function(issueEvents, key) {
          return [key, _.filter(issueEvents, function(event) {
            return event.label.name == '2 - Development';
          })]
        }));
      };

      this.getEarliestDevelopmentIssueEvents = function(developmentEvents) {
        return _.object(_.map(developmentEvents, function(events, key) {
          return [key, _.first(_.sortBy(events, function(e) {
            return e.created_at;
          }))]
        }));
      };

      this.mergeEventsWithIssues = function(issues, events) {
        return _.each(issues, function(issue) {
          if (events[issue.id]) {
            issue.dev_at = events[issue.id].created_at;
          }
        });
      };

      this.getRepositoriesUrlsFromIssues = function(issues) {
        return _.uniq(_.pluck(issues, 'repoUrl'));
      };

      this.addDevDateForIssues = function(issues, events) {
        var groupedEventsByIssueId = {},
          labeledEvents = {},
          developmentEvents = {},
          earlierstDevelopemntIssuesEvent = {},
          issuesWithDevDate = {};

        groupedEventsByIssueId = this.groupEventsByIssuesId(events);
        labeledEvents = this.excludeNonLabeledEvents(groupedEventsByIssueId);
        developmentEvents = this.getOnlyDevelopmentIssueEvents(labeledEvents);
        earlierstDevelopemntIssuesEvent = this.getEarliestDevelopmentIssueEvents(developmentEvents);
        issuesWithDevDate = this.mergeEventsWithIssues(issues, earlierstDevelopemntIssuesEvent);

        return issuesWithDevDate;
      };

      this.createCsvUri = function(issuesWithDevDate) {
        var uri = this.linkToCsv(issuesWithDevDate);

        var downloadLink = document.createElement("a");
        downloadLink.href = uri;
        downloadLink.download = "data.csv";

        document.body.appendChild(downloadLink);
        downloadLink.click();
        document.body.removeChild(downloadLink);
        $("#export_csv").attr("disabled", false);
        issuesToExport = [];
        this.trigger('data:issues:clearExportCsvLink');

      };

      this.after('initialize', function() {
        this.on('data:issues:mountExportCsvLink', this.mountExportCsvLink);
        this.on('data:issues:clearExportCsvLink', this.clearLink);
      });
    }
  }
);
<|endoftext|>


<commit_before>// ***********************************************//
//                      Navigation views
// ***********************************************//

require('akvo-flow/core');
require('akvo-flow/views/survey-group-views');
require('akvo-flow/views/survey-details-views');
require('akvo-flow/views/question-view');
require('akvo-flow/views/map-views');
require('akvo-flow/views/devices-views');

FLOW.ApplicationView = Ember.View.extend({
	templateName: 'application'
});

// ***********************************************//
//                      Handlebar helpers
// ***********************************************//

// localisation helper
Ember.Handlebars.registerHelper('t', function(i18nKey, options) {
  return Ember.String.loc(i18nKey);
});

// date format helper
Ember.Handlebars.registerHelper("date", function(property) {
  var d = new Date(parseInt(Ember.get(this, property),10));
  var m_names = new Array("Jan", "Feb", "Mar", "Apr", "May", "Jun", "Jul", "Aug", "Sep", "Oct", "Nov", "Dec");

  var curr_date = d.getDate();
  var curr_month = d.getMonth();
  var curr_year = d.getFullYear();
  return (curr_date + " " + m_names[curr_month] + " " + curr_year);
});

// format used in devices table
Ember.Handlebars.registerHelper("date1", function(property) {
  var d, curr_date,curr_month,curr_year,curr_hour,curr_min,monthString,dateString,hourString,minString;
  if (Ember.get(this, property)!==null){
    d = new Date(parseInt(Ember.get(this, property),10));
    curr_date = d.getDate();
    curr_month = d.getMonth()+1;
    curr_year = d.getFullYear();
    curr_hour =d.getHours();
    curr_min =d.getMinutes();

    if (curr_month<10){monthString="0"+curr_month.toString();}
    else { monthString=curr_month.toString();}

    if (curr_date<10){dateString="0"+curr_date.toString();}
    else {dateString=curr_date.toString();}

    if (curr_hour<10) {hourString="0"+curr_hour.toString();}
    else { hourString=curr_hour.toString();}

    if (curr_min<10) {minString="0"+curr_min.toString();}
    else { minString=curr_min.toString();}

    return (curr_year + "-" + monthString + "-" + dateString + "  " + hourString + ":" + minString);
  } else {return "";}
});

// ********************************************************//
//                      main navigation
// ********************************************************//

FLOW.NavigationView = Em.View.extend({
	templateName: 'navigation',
	selectedBinding: 'controller.selected',

	onLanguageChange:function(){
		this.rerender();
	}.observes('FLOW.languageControl.dashboardLanguage'),

	NavItemView: Ember.View.extend({
		tagName: 'li',
		classNameBindings: 'isActive:current navItem'.w(),

		navItem: function() {
			return this.get('item');
		}.property('item').cacheable(),

		isActive: function() {
			return this.get('item') === this.get('parentView.selected');
		}.property('item', 'parentView.selected').cacheable()
	})
});

// ********************************************************//
//                      standard views
// ********************************************************//

// TODO check if doing this in View is not impacting performance,
// as some pages have a lot of views (all navigation elements, for example)
// one way could be use an extended copy of view, with the didInsertElement,
// for some of the elements, and not for others.
Ember.View.reopen({
    didInsertElement: function() {
        this._super();
        tooltip();
		makePlaceholders();
	$("nav#topnav li.current").prev("nav#topnav li").css("background", "none");
	$("nav#topnav li").hover( function (){
		$(this).prev().css("background", "none");
		})
    // 	Adds needed classes to survey assets as nth-child selectors don't work in ie.
    $('li.aSurvey:nth-child(4n+1)').addClass('firstOfRow');
    $('li.aSurvey:nth-child(4n)').addClass('endOfRow');
    $('table#devicesListTable tbody tr:nth-child(2n)').addClass('even');

	$(".questionSetContent div.innerContent").hide();
	var nCount = 0;
	$(".addQuestion").click( function () {
		nCount++;
		$(".questionSetContent div.innerContent").fadeIn().css("box-shadow","0 0 3px rgba(0,0,0,0.1)");
		$(this).insertAfter("div.innerContent");
		$("#numberQuestion").text(
			function() {
				if ( nCount < 10 ) {
					$(this).text("0" + nCount);
					}
				else {
					$(this).text(nCount);
					}
				}
		);
		var nQ = parseInt($("#numberQuestion").text());
		$("h1.questionNbr span").text(
			function () {
				if (nQ < 10) {
					$(this).text("0" + nQ);
					}
				else {
					$(this).text(nQ);
					}
				}
		)
		}
	);

// Function displaying the options depending on question type
	$('.formElems').hide();
    // listener for QR type
    $("#questionType").change(function () {
        var selected = $("#questionType option:selected").val();
            $('.formElems').hide();
            $("." +selected).show();
    });

// Function displaying the survey groups.
	$("#main > section.surveysList").hide();
	$("#main > section#allSurvey").show();
	$(".menuGroup li a").click(
		function () {
			$(".menuGroup li a").removeClass("current");
			$(this).addClass("current");
			var sectionname = this.name;
			$("#main > section.surveysList").hide();
			$("#"+sectionname).show();
			}
	)
	$('#tabs > section').hide();
	$('#tabs > section:first').show();
	$('#tabs ul li:first').addClass('active');
	$('#tabs ul li a').click(function(){
		$('#tabs ul li').removeClass('active');
		$(this).parent().addClass('active');
		var currentTab = $(this).attr('href');
		$('#tabs > section').hide();
		$(currentTab).show();
		return false;
	});
	$( "#from" ).datepicker({
			defaultDate: "+1w",
			numberOfMonths: 1,
			onSelect: function( selectedDate ) {
				$( "#to" ).datepicker( "option", "minDate", selectedDate );
			}
		});
	$( "#to" ).datepicker({
			defaultDate: "+1w",
			numberOfMonths: 1,
			onSelect: function( selectedDate ) {
				$( "#from" ).datepicker( "option", "maxDate", selectedDate );
			}
		});
   }
})

// home screen view
FLOW.NavHomeView = Ember.View.extend({ templateName: 'navHome/nav-home'});

// surveys views
FLOW.NavSurveysView = Ember.View.extend({ templateName: 'navSurveys/nav-surveys'});
FLOW.NavSurveysMainView = Ember.View.extend({ templateName: 'navSurveys/nav-surveys-main'});
FLOW.NavSurveysEditView = Ember.View.extend({ templateName: 'navSurveys/nav-surveys-edit'});

// devices views
FLOW.NavDevicesView = Ember.View.extend({ templateName: 'navDevices/nav-devices'});
FLOW.CurrentDevicesView = Ember.View.extend({ templateName: 'navDevices/devices-list-tab/devices-list'});
FLOW.AssignSurveysOverviewView = Ember.View.extend({ templateName: 'navDevices/assignment-list-tab/assignment-list'});
FLOW.EditSurveyAssignmentView = Ember.View.extend({ templateName: 'navDevices/assignment-edit-tab/assignment-edit'});

// data views
FLOW.NavDataView = Ember.View.extend({ templateName: 'navData/nav-data'});
FLOW.InspectDataView = Ember.View.extend({ templateName: 'navData/inspect-data'});
FLOW.ImportSurveyView = Ember.View.extend({ templateName: 'navData/import-survey'});
FLOW.ExcelImportView = Ember.View.extend({ templateName: 'navData/excel-import'});
FLOW.ExcelExportView = Ember.View.extend({ templateName: 'navData/excel-export'});

// reports views
FLOW.NavReportsView = Ember.View.extend({ templateName: 'navReports/nav-reports'});

// users views
FLOW.NavUsersView = Ember.View.extend({	templateName: 'navUsers/nav-users'});

// admin views
FLOW.NavAdminView = Ember.View.extend({	templateName: 'navAdmin/nav-admin'});

// ********************************************************//
//             Subnavigation for the Data tabs
// ********************************************************//
FLOW.DatasubnavView = Em.View.extend({
	templateName: 'navData/data-subnav',
	selectedBinding: 'controller.selected',
	NavItemView: Ember.View.extend({
		tagName: 'li',
		classNameBindings: 'isActive:active'.w(),

		isActive: function() {
			return this.get('item') === this.get('parentView.selected');
		}.property('item', 'parentView.selected').cacheable()
	})
});

// ********************************************************//
//             Subnavigation for the Device tabs
// ********************************************************//
FLOW.DevicesSubnavView = Em.View.extend({
	templateName: 'navDevices/devices-subnav',
	selectedBinding: 'controller.selected',
	NavItemView: Ember.View.extend({
		tagName: 'li',
		classNameBindings: 'isActive:active'.w(),

		isActive: function() {
			return this.get('item') === this.get('parentView.selected');
		}.property('item', 'parentView.selected').cacheable()
	})
});

FLOW.ColumnView = Ember.View.extend({
	tagName: 'th',
	item:null,
	type:null,

	classNameBindings: ['isActiveAsc:sorting_asc','isActiveDesc:sorting_desc'],

	isActiveAsc: function() {
		return (this.get('item') === FLOW.tableColumnControl.get('selected')) && (FLOW.tableColumnControl.get('sortAscending')===true);
	}.property('item', 'FLOW.tableColumnControl.selected','FLOW.tableColumnControl.sortAscending').cacheable(),

	isActiveDesc: function() {
		return (this.get('item') === FLOW.tableColumnControl.get('selected'))&&(FLOW.tableColumnControl.get('sortAscending')===false);
	}.property('item', 'FLOW.tableColumnControl.selected','FLOW.tableColumnControl.sortAscending').cacheable(),

	sort:function(){
		if ((this.get('isActiveAsc'))||(this.get('isActiveDesc'))) {
			FLOW.tableColumnControl.toggleProperty('sortAscending');
		} else {
			FLOW.tableColumnControl.set('sortProperties',[this.get('item')]);
			FLOW.tableColumnControl.set('selected',this.get('item'));
		}

		if (this.get('type') === 'device') {
			FLOW.deviceControl.getSortInfo();
		} else if (this.get('type') === 'assignment'){
			FLOW.surveyAssignmentControl.getSortInfo();
		}

	}
})
<commit_msg>removed survey group javascript<commit_after>// ***********************************************//
//                      Navigation views
// ***********************************************//

require('akvo-flow/core');
require('akvo-flow/views/survey-group-views');
require('akvo-flow/views/survey-details-views');
require('akvo-flow/views/question-view');
require('akvo-flow/views/map-views');
require('akvo-flow/views/devices-views');

FLOW.ApplicationView = Ember.View.extend({
	templateName: 'application'
});

// ***********************************************//
//                      Handlebar helpers
// ***********************************************//

// localisation helper
Ember.Handlebars.registerHelper('t', function(i18nKey, options) {
  return Ember.String.loc(i18nKey);
});

// date format helper
Ember.Handlebars.registerHelper("date", function(property) {
  var d = new Date(parseInt(Ember.get(this, property),10));
  var m_names = new Array("Jan", "Feb", "Mar", "Apr", "May", "Jun", "Jul", "Aug", "Sep", "Oct", "Nov", "Dec");

  var curr_date = d.getDate();
  var curr_month = d.getMonth();
  var curr_year = d.getFullYear();
  return (curr_date + " " + m_names[curr_month] + " " + curr_year);
});

// format used in devices table
Ember.Handlebars.registerHelper("date1", function(property) {
  var d, curr_date,curr_month,curr_year,curr_hour,curr_min,monthString,dateString,hourString,minString;
  if (Ember.get(this, property)!==null){
    d = new Date(parseInt(Ember.get(this, property),10));
    curr_date = d.getDate();
    curr_month = d.getMonth()+1;
    curr_year = d.getFullYear();
    curr_hour =d.getHours();
    curr_min =d.getMinutes();

    if (curr_month<10){monthString="0"+curr_month.toString();}
    else { monthString=curr_month.toString();}

    if (curr_date<10){dateString="0"+curr_date.toString();}
    else {dateString=curr_date.toString();}

    if (curr_hour<10) {hourString="0"+curr_hour.toString();}
    else { hourString=curr_hour.toString();}

    if (curr_min<10) {minString="0"+curr_min.toString();}
    else { minString=curr_min.toString();}

    return (curr_year + "-" + monthString + "-" + dateString + "  " + hourString + ":" + minString);
  } else {return "";}
});

// ********************************************************//
//                      main navigation
// ********************************************************//

FLOW.NavigationView = Em.View.extend({
	templateName: 'navigation',
	selectedBinding: 'controller.selected',

	onLanguageChange:function(){
		this.rerender();
	}.observes('FLOW.languageControl.dashboardLanguage'),

	NavItemView: Ember.View.extend({
		tagName: 'li',
		classNameBindings: 'isActive:current navItem'.w(),

		navItem: function() {
			return this.get('item');
		}.property('item').cacheable(),

		isActive: function() {
			return this.get('item') === this.get('parentView.selected');
		}.property('item', 'parentView.selected').cacheable()
	})
});

// ********************************************************//
//                      standard views
// ********************************************************//

// TODO check if doing this in View is not impacting performance,
// as some pages have a lot of views (all navigation elements, for example)
// one way could be use an extended copy of view, with the didInsertElement,
// for some of the elements, and not for others.
Ember.View.reopen({
    didInsertElement: function() {
        this._super();
        tooltip();
		makePlaceholders();
	$("nav#topnav li.current").prev("nav#topnav li").css("background", "none");
	$("nav#topnav li").hover( function (){
		$(this).prev().css("background", "none");
		})
    // 	Adds needed classes to survey assets as nth-child selectors don't work in ie.
    $('li.aSurvey:nth-child(4n+1)').addClass('firstOfRow');
    $('li.aSurvey:nth-child(4n)').addClass('endOfRow');
    $('table#devicesListTable tbody tr:nth-child(2n)').addClass('even');

	$(".questionSetContent div.innerContent").hide();
	var nCount = 0;
	$(".addQuestion").click( function () {
		nCount++;
		$(".questionSetContent div.innerContent").fadeIn().css("box-shadow","0 0 3px rgba(0,0,0,0.1)");
		$(this).insertAfter("div.innerContent");
		$("#numberQuestion").text(
			function() {
				if ( nCount < 10 ) {
					$(this).text("0" + nCount);
					}
				else {
					$(this).text(nCount);
					}
				}
		);
		var nQ = parseInt($("#numberQuestion").text());
		$("h1.questionNbr span").text(
			function () {
				if (nQ < 10) {
					$(this).text("0" + nQ);
					}
				else {
					$(this).text(nQ);
					}
				}
		)
		}
	);

// Function displaying the options depending on question type
	$('.formElems').hide();
    // listener for QR type
    $("#questionType").change(function () {
        var selected = $("#questionType option:selected").val();
            $('.formElems').hide();
            $("." +selected).show();
    });

	$('#tabs > section').hide();
	$('#tabs > section:first').show();
	$('#tabs ul li:first').addClass('active');
	$('#tabs ul li a').click(function(){
		$('#tabs ul li').removeClass('active');
		$(this).parent().addClass('active');
		var currentTab = $(this).attr('href');
		$('#tabs > section').hide();
		$(currentTab).show();
		return false;
	});
	$( "#from" ).datepicker({
			defaultDate: "+1w",
			numberOfMonths: 1,
			onSelect: function( selectedDate ) {
				$( "#to" ).datepicker( "option", "minDate", selectedDate );
			}
		});
	$( "#to" ).datepicker({
			defaultDate: "+1w",
			numberOfMonths: 1,
			onSelect: function( selectedDate ) {
				$( "#from" ).datepicker( "option", "maxDate", selectedDate );
			}
		});
   }
})

// home screen view
FLOW.NavHomeView = Ember.View.extend({ templateName: 'navHome/nav-home'});

// surveys views
FLOW.NavSurveysView = Ember.View.extend({ templateName: 'navSurveys/nav-surveys'});
FLOW.NavSurveysMainView = Ember.View.extend({ templateName: 'navSurveys/nav-surveys-main'});
FLOW.NavSurveysEditView = Ember.View.extend({ templateName: 'navSurveys/nav-surveys-edit'});

// devices views
FLOW.NavDevicesView = Ember.View.extend({ templateName: 'navDevices/nav-devices'});
FLOW.CurrentDevicesView = Ember.View.extend({ templateName: 'navDevices/devices-list-tab/devices-list'});
FLOW.AssignSurveysOverviewView = Ember.View.extend({ templateName: 'navDevices/assignment-list-tab/assignment-list'});
FLOW.EditSurveyAssignmentView = Ember.View.extend({ templateName: 'navDevices/assignment-edit-tab/assignment-edit'});

// data views
FLOW.NavDataView = Ember.View.extend({ templateName: 'navData/nav-data'});
FLOW.InspectDataView = Ember.View.extend({ templateName: 'navData/inspect-data'});
FLOW.ImportSurveyView = Ember.View.extend({ templateName: 'navData/import-survey'});
FLOW.ExcelImportView = Ember.View.extend({ templateName: 'navData/excel-import'});
FLOW.ExcelExportView = Ember.View.extend({ templateName: 'navData/excel-export'});

// reports views
FLOW.NavReportsView = Ember.View.extend({ templateName: 'navReports/nav-reports'});

// users views
FLOW.NavUsersView = Ember.View.extend({	templateName: 'navUsers/nav-users'});

// admin views
FLOW.NavAdminView = Ember.View.extend({	templateName: 'navAdmin/nav-admin'});

// ********************************************************//
//             Subnavigation for the Data tabs
// ********************************************************//
FLOW.DatasubnavView = Em.View.extend({
	templateName: 'navData/data-subnav',
	selectedBinding: 'controller.selected',
	NavItemView: Ember.View.extend({
		tagName: 'li',
		classNameBindings: 'isActive:active'.w(),

		isActive: function() {
			return this.get('item') === this.get('parentView.selected');
		}.property('item', 'parentView.selected').cacheable()
	})
});

// ********************************************************//
//             Subnavigation for the Device tabs
// ********************************************************//
FLOW.DevicesSubnavView = Em.View.extend({
	templateName: 'navDevices/devices-subnav',
	selectedBinding: 'controller.selected',
	NavItemView: Ember.View.extend({
		tagName: 'li',
		classNameBindings: 'isActive:active'.w(),

		isActive: function() {
			return this.get('item') === this.get('parentView.selected');
		}.property('item', 'parentView.selected').cacheable()
	})
});

FLOW.ColumnView = Ember.View.extend({
	tagName: 'th',
	item:null,
	type:null,

	classNameBindings: ['isActiveAsc:sorting_asc','isActiveDesc:sorting_desc'],

	isActiveAsc: function() {
		return (this.get('item') === FLOW.tableColumnControl.get('selected')) && (FLOW.tableColumnControl.get('sortAscending')===true);
	}.property('item', 'FLOW.tableColumnControl.selected','FLOW.tableColumnControl.sortAscending').cacheable(),

	isActiveDesc: function() {
		return (this.get('item') === FLOW.tableColumnControl.get('selected'))&&(FLOW.tableColumnControl.get('sortAscending')===false);
	}.property('item', 'FLOW.tableColumnControl.selected','FLOW.tableColumnControl.sortAscending').cacheable(),

	sort:function(){
		if ((this.get('isActiveAsc'))||(this.get('isActiveDesc'))) {
			FLOW.tableColumnControl.toggleProperty('sortAscending');
		} else {
			FLOW.tableColumnControl.set('sortProperties',[this.get('item')]);
			FLOW.tableColumnControl.set('selected',this.get('item'));
		}

		if (this.get('type') === 'device') {
			FLOW.deviceControl.getSortInfo();
		} else if (this.get('type') === 'assignment'){
			FLOW.surveyAssignmentControl.getSortInfo();
		}

	}
})
<|endoftext|>