<commit_before>// default new form
Util.Objects["defaultNew"] = new function() {
	this.init = function(form) {

		u.f.init(form);

		form.actions["cancel"].clicked = function(event) {
			location.href = this.url;
		}

		form.submitted = function(iN) {

			this.response = function(response) {
				if(response.cms_status == "success" && response.cms_object) {

//					alert(response);
					location.href = this.actions["cancel"].url.replace("\/list", "/edit/"+response.cms_object.item_id);
				}
				else if(response.cms_message) {
					page.notify(response);
				}
			}
//			u.bug("params:"+u.f.getParams(this))
			u.request(this, this.action, {"method":"post", "params" : u.f.getParams(this, {"send_as":"formdata"})});

		}

	}
}<commit_msg>Fixed login display on create new item<commit_after>// default new form
Util.Objects["defaultNew"] = new function() {
	this.init = function(form) {

		u.f.init(form);

		form.actions["cancel"].clicked = function(event) {
			location.href = this.url;
		}

		form.submitted = function(iN) {

			this.response = function(response) {
				if(response.cms_status == "success" && response.cms_object) {

//					alert(response);
					location.href = this.actions["cancel"].url.replace("\/list", "/edit/"+response.cms_object.item_id);
				}
				else {
					page.notify(response);
				}
			}
//			u.bug("params:"+u.f.getParams(this))
			u.request(this, this.action, {"method":"post", "params" : u.f.getParams(this, {"send_as":"formdata"})});

		}

	}
}<|endoftext|>


<commit_before>/* jshint -W097 */
/* jshint strict:false */
/* jslint node: true */
/* jshint expr: true */
var expect = require('chai').expect;
var fs        = require('fs');

describe('Test package.json and io-package.json', function() {
    it('Test package files', function (done) {
        console.log();

        var fileContentIOPackage = fs.readFileSync(__dirname + '/../io-package.json', 'utf8');
        var ioPackage = JSON.parse(fileContentIOPackage);

        var fileContentNPMPackage = fs.readFileSync(__dirname + '/../package.json', 'utf8');
        var npmPackage = JSON.parse(fileContentNPMPackage);

        expect(ioPackage).to.be.an('object');
        expect(npmPackage).to.be.an('object');

        expect(ioPackage.common.version, 'ERROR: Version number in io-package.json needs to exist').to.exist;
        expect(npmPackage.version, 'ERROR: Version number in package.json needs to exist').to.exist;

        expect(ioPackage.common.version, 'ERROR: Version numbers in package.json and io-package.json needs to match').to.be.equal(npmPackage.version);

        if (!ioPackage.common.news || !ioPackage.common.news[ioPackage.common.version]) {
            console.log('WARNING: No news entry for current version exists in io-package.json, no rollback in Admin possible!');
            console.log();
        }

        expect(npmPackage.author, 'ERROR: Author in package.json needs to exist').to.exist;
        expect(ioPackage.common.authors, 'ERROR: Authors in io-package.json needs to exist').to.exist;

        if (ioPackage.common.name.indexOf('template') !== 0) {
            if (Array.isArray(ioPackage.common.authors)) {
                expect(ioPackage.common.authors.length, 'ERROR: Author in io-package.json needs to be set').to.not.be.equal(0);
                if (ioPackage.common.authors.length === 1) {
                    expect(ioPackage.common.authors[0], 'ERROR: Author in io-package.json needs to be a real name').to.not.be.equal('my Name <my@email.com>');
                }
            }
            else {
                expect(ioPackage.common.authors, 'ERROR: Author in io-package.json needs to be a real name').to.not.be.equal('my Name <my@email.com>');
            }
        }
        else {
            console.log('WARNING: Testing for set authors field in io-package skipped because template adapter');
            console.log();
        }
        expect(fs.existsSync(__dirname + '/../README.md'), 'ERROR: README.md needs to exist! Please create one with description, detail information and changelog. English is mandatory.').to.be.true;
        expect(fs.existsSync(__dirname + '/../LICENSE'), 'ERROR: LICENSE needs to exist! Please create one.').to.be.true;
        if (!ioPackage.common.titleLang || typeof ioPackage.common.titleLang !== 'object') {
            console.log('WARNING: titleLang is not existing in io-package.json. Please add');
            console.log();
        }
        if (
            ioPackage.common.title.indexOf('iobroker') !== -1 ||
            ioPackage.common.title.indexOf('ioBroker') !== -1 ||
            ioPackage.common.title.indexOf('adapter') !== -1 ||
            ioPackage.common.title.indexOf('Adapter') !== -1
        ) {
            console.log('WARNING: title contains Adapter or ioBroker. It is clear anyway, that it is adapter for ioBroker.');
            console.log();
        }

        if (ioPackage.common.name.indexOf('vis-') !== 0) {
            if (!ioPackage.common.materialize || !fs.existsSync(__dirname + '/../admin/index_m.html') || !fs.existsSync(__dirname + '/../gulpfile.js')) {
                console.log('WARNING: Admin3 support is missing! Please add it');
                console.log();
            }
            if (ioPackage.common.materialize) {
                expect(fs.existsSync(__dirname + '/../admin/index_m.html'), 'Admin3 support is enabled in io-package.json, but index_m.html is missing!').to.be.true;
            }
        }

        expect(fs.existsSync(__dirname + '/../LICENSE'), 'A LICENSE must exist');
        var fileContentReadme = fs.readFileSync(__dirname + '/../README.md', 'utf8');
        expect(fileContentReadme.indexOf('## License'), 'The README.md needs to have a section ## License').not.equal(-1);
        expect(fileContentReadme.indexOf('## Changelog'), 'The README.md needs to have a section ## Changelog').not.equal(-1);
        expect(fileContentReadme.indexOf('## Changelog'), 'The README.md needs to have a section ## License').to.be.below(fileContentReadme.indexOf('## License'));
        done();
    });
});
<commit_msg>update basic package-file testing<commit_after>/* jshint -W097 */
/* jshint strict:false */
/* jslint node: true */
/* jshint expr: true */
var expect = require('chai').expect;
var fs        = require('fs');

describe('Test package.json and io-package.json', function() {
    it('Test package files', function (done) {
        console.log();

        var fileContentIOPackage = fs.readFileSync(__dirname + '/../io-package.json', 'utf8');
        var ioPackage = JSON.parse(fileContentIOPackage);

        var fileContentNPMPackage = fs.readFileSync(__dirname + '/../package.json', 'utf8');
        var npmPackage = JSON.parse(fileContentNPMPackage);

        expect(ioPackage).to.be.an('object');
        expect(npmPackage).to.be.an('object');

        expect(ioPackage.common.version, 'ERROR: Version number in io-package.json needs to exist').to.exist;
        expect(npmPackage.version, 'ERROR: Version number in package.json needs to exist').to.exist;

        expect(ioPackage.common.version, 'ERROR: Version numbers in package.json and io-package.json needs to match').to.be.equal(npmPackage.version);

        if (!ioPackage.common.news || !ioPackage.common.news[ioPackage.common.version]) {
            console.log('WARNING: No news entry for current version exists in io-package.json, no rollback in Admin possible!');
            console.log();
        }

        expect(npmPackage.author, 'ERROR: Author in package.json needs to exist').to.exist;
        expect(ioPackage.common.authors, 'ERROR: Authors in io-package.json needs to exist').to.exist;

        if (ioPackage.common.name.indexOf('template') !== 0) {
            if (Array.isArray(ioPackage.common.authors)) {
                expect(ioPackage.common.authors.length, 'ERROR: Author in io-package.json needs to be set').to.not.be.equal(0);
                if (ioPackage.common.authors.length === 1) {
                    expect(ioPackage.common.authors[0], 'ERROR: Author in io-package.json needs to be a real name').to.not.be.equal('my Name <my@email.com>');
                }
            }
            else {
                expect(ioPackage.common.authors, 'ERROR: Author in io-package.json needs to be a real name').to.not.be.equal('my Name <my@email.com>');
            }
        }
        else {
            console.log('WARNING: Testing for set authors field in io-package skipped because template adapter');
            console.log();
        }
        expect(fs.existsSync(__dirname + '/../README.md'), 'ERROR: README.md needs to exist! Please create one with description, detail information and changelog. English is mandatory.').to.be.true;
        expect(fs.existsSync(__dirname + '/../LICENSE'), 'ERROR: LICENSE needs to exist! Please create one.').to.be.true;
        if (!ioPackage.common.titleLang || typeof ioPackage.common.titleLang !== 'object') {
            console.log('WARNING: titleLang is not existing in io-package.json. Please add');
            console.log();
        }
        if (
            ioPackage.common.title.indexOf('iobroker') !== -1 ||
            ioPackage.common.title.indexOf('ioBroker') !== -1 ||
            ioPackage.common.title.indexOf('adapter') !== -1 ||
            ioPackage.common.title.indexOf('Adapter') !== -1
        ) {
            console.log('WARNING: title contains Adapter or ioBroker. It is clear anyway, that it is adapter for ioBroker.');
            console.log();
        }

        if (ioPackage.common.name.indexOf('vis-') !== 0) {
            if (!ioPackage.common.materialize || !fs.existsSync(__dirname + '/../admin/index_m.html') || !fs.existsSync(__dirname + '/../gulpfile.js')) {
                console.log('WARNING: Admin3 support is missing! Please add it');
                console.log();
            }
            if (ioPackage.common.materialize) {
                expect(fs.existsSync(__dirname + '/../admin/index_m.html'), 'Admin3 support is enabled in io-package.json, but index_m.html is missing!').to.be.true;
            }
        }

        expect(fs.existsSync(__dirname + '/../LICENSE'), 'A LICENSE must exist');
        var fileContentReadme = fs.readFileSync(__dirname + '/../README.md', 'utf8');
        if (fileContentReadme.indexOf('## License') === -1) {
            console.log('Warning: The README.md should have a section ## License');
            console.log();
        }
        if (fileContentReadme.indexOf('## Changelog') === -1) {
            console.log('Warning: The README.md should have a section ## Changelog');
            console.log();
        }
        done();
    });
});
<|endoftext|>


<commit_before>/* jshint -W097 */
/* jshint strict:false */
/* jslint node: true */
/* jshint expr: true */
var expect = require('chai').expect;
var fs        = require('fs');

describe('Test package.json and io-package.json', function() {
    it('Test package files', function (done) {
        console.log();

        var fileContentIOPackage = fs.readFileSync(__dirname + '/../io-package.json', 'utf8');
        var ioPackage = JSON.parse(fileContentIOPackage);

        var fileContentNPMPackage = fs.readFileSync(__dirname + '/../package.json', 'utf8');
        var npmPackage = JSON.parse(fileContentNPMPackage);

        expect(ioPackage).to.be.an('object');
        expect(npmPackage).to.be.an('object');

        expect(ioPackage.common.version, 'ERROR: Version number in io-package.json needs to exist').to.exist;
        expect(npmPackage.version, 'ERROR: Version number in package.json needs to exist').to.exist;

        expect(ioPackage.common.version, 'ERROR: Version numbers in package.json and io-package.json needs to match').to.be.equal(npmPackage.version);

        if (!ioPackage.common.news || !ioPackage.common.news[ioPackage.common.version]) {
            console.log('WARNING: No news entry for current version exists in io-package.json, no rollback in Admin possible!');
            console.log();
        }

        expect(npmPackage.author, 'ERROR: Author in package.json needs to exist').to.exist;
        expect(ioPackage.common.authors, 'ERROR: Authors in io-package.json needs to exist').to.exist;

        if (ioPackage.common.name.indexOf('template') !== 0) {
            if (Array.isArray(ioPackage.common.authors)) {
                expect(ioPackage.common.authors.length, 'ERROR: Author in io-package.json needs to be set').to.not.be.equal(0);
                if (ioPackage.common.authors.length === 1) {
                    expect(ioPackage.common.authors[0], 'ERROR: Author in io-package.json needs to be a real name').to.not.be.equal('my Name <my@email.com>');
                }
            }
            else {
                expect(ioPackage.common.authors, 'ERROR: Author in io-package.json needs to be a real name').to.not.be.equal('my Name <my@email.com>');
            }
        }
        else {
            console.log('WARNING: Testing for set authors field in io-package skipped because template adapter');
            console.log();
        }
        expect(fs.existsSync(__dirname + '/../README.md'), 'ERROR: README.md needs to exist! Please create one with description, detail information and changelog. English is mandatory.').to.be.true;
        if (!ioPackage.common.titleLang || typeof ioPackage.common.titleLang !== 'object') {
            console.log('WARNING: titleLang is not existing in io-package.json. Please add');
            console.log();
        }
        if (
            ioPackage.common.title.indexOf('iobroker') !== -1 ||
            ioPackage.common.title.indexOf('ioBroker') !== -1 ||
            ioPackage.common.title.indexOf('adapter') !== -1 ||
            ioPackage.common.title.indexOf('Adapter') !== -1
        ) {
            console.log('WARNING: title contains Adapter or ioBroker. It is clear anyway, that it is adapter for ioBroker.');
            console.log();
        }

        if (ioPackage.common.name.indexOf('vis-') !== 0) {
            if (!ioPackage.common.materialize || !fs.existsSync(__dirname + '/../admin/index_m.html') || !fs.existsSync(__dirname + '/../gulpfile.js')) {
                console.log('WARNING: Admin3 support is missing! Please add it');
                console.log();
            }
            if (ioPackage.common.materialize) {
                expect(fs.existsSync(__dirname + '/../admin/index_m.html'), 'Admin3 support is enabled in io-package.json, but index_m.html is missing!').to.be.true;
            }
        }

        var licenseFileExists = fs.existsSync(__dirname + '/../LICENSE');
        var fileContentReadme = fs.readFileSync(__dirname + '/../README.md', 'utf8');
        if (fileContentReadme.indexOf('## Changelog') === -1) {
            console.log('Warning: The README.md should have a section ## Changelog');
            console.log();
        }
        expect((licenseFileExists || fileContentReadme.indexOf('## License') !== -1), 'A LICENSE must exist as LICENSE file or as part of the README.md').to.be.true;
        if (!licenseFileExists) {
            console.log('Warning: The License should also exist as LICENSE file');
            console.log();
        }
        if (fileContentReadme.indexOf('## License') === -1) {
            console.log('Warning: The README.md should also have a section ## License to be shown in Admin3');
            console.log();
        }
        done();
    });
});
<commit_msg>update basic package-file testing<commit_after>/* jshint -W097 */
/* jshint strict:false */
/* jslint node: true */
/* jshint expr: true */
'use strict';

const expect = require('chai').expect;
const fs     = require('fs');

describe('Test package.json and io-package.json', () => {
    it('Test package files', done => {
        console.log();

        const fileContentIOPackage = fs.readFileSync(__dirname + '/../io-package.json', 'utf8');
        const ioPackage = JSON.parse(fileContentIOPackage);

        const fileContentNPMPackage = fs.readFileSync(__dirname + '/../package.json', 'utf8');
        const npmPackage = JSON.parse(fileContentNPMPackage);

        expect(ioPackage).to.be.an('object');
        expect(npmPackage).to.be.an('object');

        expect(ioPackage.common.version, 'ERROR: Version number in io-package.json needs to exist').to.exist;
        expect(npmPackage.version, 'ERROR: Version number in package.json needs to exist').to.exist;

        expect(ioPackage.common.version, 'ERROR: Version numbers in package.json and io-package.json needs to match').to.be.equal(npmPackage.version);

        if (!ioPackage.common.news || !ioPackage.common.news[ioPackage.common.version]) {
            console.log('WARNING: No news entry for current version exists in io-package.json, no rollback in Admin possible!');
            console.log();
        }

        expect(npmPackage.author, 'ERROR: Author in package.json needs to exist').to.exist;
        expect(ioPackage.common.authors, 'ERROR: Authors in io-package.json needs to exist').to.exist;

        expect(ioPackage.common.license, 'ERROR: License missing in io-package in common.license').to.exist;

        if (ioPackage.common.name.indexOf('template') !== 0) {
            if (Array.isArray(ioPackage.common.authors)) {
                expect(ioPackage.common.authors.length, 'ERROR: Author in io-package.json needs to be set').to.not.be.equal(0);
                if (ioPackage.common.authors.length === 1) {
                    expect(ioPackage.common.authors[0], 'ERROR: Author in io-package.json needs to be a real name').to.not.be.equal('my Name <my@email.com>');
                }
            }
            else {
                expect(ioPackage.common.authors, 'ERROR: Author in io-package.json needs to be a real name').to.not.be.equal('my Name <my@email.com>');
            }
        }
        else {
            console.log('WARNING: Testing for set authors field in io-package skipped because template adapter');
            console.log();
        }
        expect(fs.existsSync(__dirname + '/../README.md'), 'ERROR: README.md needs to exist! Please create one with description, detail information and changelog. English is mandatory.').to.be.true;
        if (!ioPackage.common.titleLang || typeof ioPackage.common.titleLang !== 'object') {
            console.log('WARNING: titleLang is not existing in io-package.json. Please add');
            console.log();
        }
        if (
            ioPackage.common.title.indexOf('iobroker') !== -1 ||
            ioPackage.common.title.indexOf('ioBroker') !== -1 ||
            ioPackage.common.title.indexOf('adapter') !== -1 ||
            ioPackage.common.title.indexOf('Adapter') !== -1
        ) {
            console.log('WARNING: title contains Adapter or ioBroker. It is clear anyway, that it is adapter for ioBroker.');
            console.log();
        }

        if (!ioPackage.common.controller && !ioPackage.common.onlyWWW && !ioPackage.common.noConfig) {
            if (!ioPackage.common.materialize || !fs.existsSync(__dirname + '/../admin/index_m.html') || !fs.existsSync(__dirname + '/../gulpfile.js')) {
                console.log('WARNING: Admin3 support is missing! Please add it');
                console.log();
            }
            if (ioPackage.common.materialize) {
                expect(fs.existsSync(__dirname + '/../admin/index_m.html'), 'Admin3 support is enabled in io-package.json, but index_m.html is missing!').to.be.true;
            }
        }

        const licenseFileExists = fs.existsSync(__dirname + '/../LICENSE');
        const fileContentReadme = fs.readFileSync(__dirname + '/../README.md', 'utf8');
        if (fileContentReadme.indexOf('## Changelog') === -1) {
            console.log('Warning: The README.md should have a section ## Changelog');
            console.log();
        }
        expect((licenseFileExists || fileContentReadme.indexOf('## License') !== -1), 'A LICENSE must exist as LICENSE file or as part of the README.md').to.be.true;
        if (!licenseFileExists) {
            console.log('Warning: The License should also exist as LICENSE file');
            console.log();
        }
        if (fileContentReadme.indexOf('## License') === -1) {
            console.log('Warning: The README.md should also have a section ## License to be shown in Admin3');
            console.log();
        }
        done();
    });
});
<|endoftext|>


<commit_before>/* jshint -W097 */// jshint strict:false
/*jslint node: true */
var expect = require('chai').expect;
var fs        = require('fs');

describe('Test package.json and io-package.json', function() {
    it('Test package files', function (done) {
        var fileContentIOPackage = fs.readFileSync(__dirname + '/../io-package.json');
        var ioPackage = JSON.parse(fileContentIOPackage);

        var fileContentNPMPackage = fs.readFileSync(__dirname + '/../package.json');
        var npmPackage = JSON.parse(fileContentNPMPackage);

        expect(ioPackage).to.be.an('object');
        expect(npmPackage).to.be.an('object');

        expect(ioPackage.common.version).to.exist;
        expect(npmPackage.version).to.exist;

        if (!expect(ioPackage.common.version).to.be.equal(npmPackage.version)) {
            console.log('ERROR: Version numbers in package.json and io-package.json differ!!');
        }

        if (!ioPackage.common.news || !ioPackage.common.news[ioPackage.common.version]) {
            console.log('WARNING: No news entry for current version exists in io-package.json, no rollback in Admin possible!');
        }

        done();
    });
});
<commit_msg>update basic package-file testing<commit_after>/* jshint -W097 */
/* jshint strict:false */
/* jslint node: true */
/* jshint expr: true */
var expect = require('chai').expect;
var fs        = require('fs');

describe('Test package.json and io-package.json', function() {
    it('Test package files', function (done) {
        var fileContentIOPackage = fs.readFileSync(__dirname + '/../io-package.json');
        var ioPackage = JSON.parse(fileContentIOPackage);

        var fileContentNPMPackage = fs.readFileSync(__dirname + '/../package.json');
        var npmPackage = JSON.parse(fileContentNPMPackage);

        expect(ioPackage).to.be.an('object');
        expect(npmPackage).to.be.an('object');

        expect(ioPackage.common.version).to.exist;
        expect(npmPackage.version).to.exist;

        if (!expect(ioPackage.common.version).to.be.equal(npmPackage.version)) {
            console.log('ERROR: Version numbers in package.json and io-package.json differ!!');
        }

        if (!ioPackage.common.news || !ioPackage.common.news[ioPackage.common.version]) {
            console.log('WARNING: No news entry for current version exists in io-package.json, no rollback in Admin possible!');
        }

        expect(ioPackage.common.authors).to.exist;
        if (ioPackage.common.name.indexOf('template') !== 0) {
            if (Array.isArray(ioPackage.common.authors)) {
                expect(ioPackage.common.authors.length).to.not.be.equal(0);
                if (ioPackage.common.authors.length === 1) {
                    expect(ioPackage.common.authors[0]).to.not.be.equal('my Name <my@email.com>');
                }
            }
            else {
                expect(ioPackage.common.authors).to.not.be.equal('my Name <my@email.com>');
            }
        }
        else {
            console.log('Testing for set authors field in io-package skipped because template adapter');
        }
        done();
    });
});
<|endoftext|>


<commit_before>/**
 * @fileoverview Provides a directive used to insert a user-defined OpenLayers
 * map in the DOM. The directive does not create an isolate scope.
 *
 * Example:
 *
 *

 */
goog.provide('ngeo.mapDirective');

goog.require('goog.asserts');
goog.require('ngeo');

/**
 * @return {angular.Directive} Directive Definition Object.
 * @ngInject
 */
ngeo.mapDirective = function() {
  return {
    restrict: 'A',
    link:
        /**
         * @param {angular.Scope} scope Scope.
         * @param {angular.JQLite} element Element.
         * @param {angular.Attributes} attrs Attributes.
         */
        function(scope, element, attrs) {
          var attr = 'ngeoMap';
          var prop = attrs[attr];

          var map = /** @type {ol.Map} */ (scope.$eval(prop));
          goog.asserts.assertInstanceof(map, ol.Map);

          map.setTarget(element[0]);
        }
  };
};

ngeoModule.directive('ngeoMap', ngeo.mapDirective);
<commit_msg>Add missing require<commit_after>/**
 * @fileoverview Provides a directive used to insert a user-defined OpenLayers
 * map in the DOM. The directive does not create an isolate scope.
 *
 * Example:
 *
 *

 */
goog.provide('ngeo.mapDirective');

goog.require('goog.asserts');
goog.require('ngeo');
goog.require('ol.Map');

/**
 * @return {angular.Directive} Directive Definition Object.
 * @ngInject
 */
ngeo.mapDirective = function() {
  return {
    restrict: 'A',
    link:
        /**
         * @param {angular.Scope} scope Scope.
         * @param {angular.JQLite} element Element.
         * @param {angular.Attributes} attrs Attributes.
         */
        function(scope, element, attrs) {
          var attr = 'ngeoMap';
          var prop = attrs[attr];

          var map = /** @type {ol.Map} */ (scope.$eval(prop));
          goog.asserts.assertInstanceof(map, ol.Map);

          map.setTarget(element[0]);
        }
  };
};

ngeoModule.directive('ngeoMap', ngeo.mapDirective);
<|endoftext|>


<commit_before>ZBase.registerView((function() {
  var widget_list = null;
  var edit_view = null;
  var docsync = null;

  // REMOVEME
  var goToURL = function(path) {
    var kPathPrefix = "/a/reports/";
    var report_id = path.substr(kPathPrefix.length);
    loadReport(report_id);
  }
  // REMOVEME END

  var loadReport = function(report_id) {
    if (widget_list) {
      widget_list.destroy();
      widget_list = null;
    }

    $.showLoader();
    $.httpGet("/api/v1/documents/" + report_id, function(r) {
      if (r.status == 200) {
        var doc = JSON.parse(r.response);
        if (doc.content.length == 0) {
          doc.content = null;
        } else {
          doc.content = JSON.parse(doc.content);
        }

        // load required widgets
        var required_widgets = findRequiredWidgets(doc);
        ReportWidgetFactory.loadWidgets(required_widgets, function() {
          render(doc);
          $.hideLoader();
        });
      } else {
        $.fatalError();
      }
    });
  };

  var destroy = function() {
    if (docsync) {
      docsync.close();
    }

    if (widget_list) {
      widget_list.destroy();
    }

    if (edit_view) {
      edit_view.destroy();
    }
  };

  var render = function(doc) {
    var readonly = !doc.is_writable;
    var page = $.getTemplate(
        "views/report",
        "zbase_report_main_tpl");

    //doc settings
    var settings_widget = DocumentSettingsWidget(
        $(".document_settings", page),
        doc.uuid);
    settings_widget.render();

    $.handleLinks(page);
    $.replaceViewport(page);

    setReportName(doc.name);

    var description = "";
    if (doc.content != null && doc.content.hasOwnProperty("description")) {
      description = doc.content.description;
    }
    setReportDescription(description);

    var widgets = [];
    if (doc.content != null && doc.content.hasOwnProperty("widgets")) {
      widgets = doc.content.widgets;
    }
    widget_list = WidgetList(widgets);
    widget_list.onWidgetEdit(function(widget_id) {
      showWidgetEditor(widget_id);
    });

    //setup docsync
    docsync = DocSync(
        getDocument,
        "/api/v1/documents/" + doc.uuid,
        $(".zbase_report_infobar"));

    if (readonly) {
      $(".zbase_report_pane").classList.add("readonly");
    } else {
      initNameEditing();
      initDescriptionEditing();
      initShareDocModal(doc.uuid);
      $.onClick($(".zbase_report_pane .link.edit_source"), showRawJSONEditor);

      //add widget flow
      var add_widget_flow = AddReportWidgetFlow(
          $(".zbase_report_pane"));
      add_widget_flow.onWidgetAdded(function(widget_type) {
        if (!widget_list || !docsync) {
          $.fatalError();
          return;
        }
        widget_list.addNewEmptyWidget(widget_type);
        docsync.saveDocument();
        showReportView();
        $.hideLoader();
      });
      $.onClick($(".zbase_report_pane .link.add_widget"), function() {
        add_widget_flow.render();
      });

      // handle display mode
      $(".zbase_report_pane z-dropdown.mode").addEventListener("change", setEditable);
    }

    showReportView();
  };

  var showReportView = function(doc) {
    //showLoader?
    if (edit_view) {
      edit_view.destroy();
    }
    var viewport = $(".zbase_report_viewport");
    viewport.innerHTML = "";
    viewport.classList.remove("editor");

    if (widget_list) {
      widget_list.render(viewport);
      widget_list.setEditable(true);
    } else {
      $.fatalError();
    }
  };

  var showWidgetEditor = function(widget_id) {
    if (!widget_list) {
      $.fatalError();
      return;
    }

    var conf = widget_list.getWidgetConfig(widget_id);
    var editor = ReportWidgetFactory.getWidgetEditor(conf);

    editor.onSave(function(config) {
      if (!docsync) {
        $.fatalError();
        return;
      }
      widget_list.updateWidgetConfig(widget_id, config);
      docsync.saveDocument();
      showReportView();
    });

    editor.onCancel(function() {
      showReportView();
    });

    showEditView(editor);
  };

  var showRawJSONEditor = function() {
    var editor = ReportJSONEditor(getContentJSON());
    showEditView(editor);

    editor.onSave(function(json) {
      if (!widget_list) {
        $.fatalError();
        return;
      }
      var content = JSON.parse(json);
      setReportDescription(content.description);
      $.showLoader();
      widget_list.setJSON(content.widgets, function() {
        if (!docsync) {
          $.fatalError();
          return;
        }
        docsync.saveDocument();
        showReportView();
        $.hideLoader();
      });
    });

    editor.onCancel(showReportView);
  };

  var showEditView = function(editor) {
    edit_view = editor;
    var viewport = $(".zbase_report_viewport");
    viewport.innerHTML = "";
    viewport.classList.add("editor");
    edit_view.render(viewport);
  };

  var setEditable = function() {
    if (!widget_list) {
      $.fatalError();
      return;
    }

    if (this.getValue() == "editing") {
      $(".zbase_report_pane").classList.add("editable");
      widget_list.setEditable(true);
    } else {
      $(".zbase_report_pane").classList.remove("editable");
      widget_list.setEditable(false);
    }
  };

  var initShareDocModal = function(doc_id) {
    var modal = ShareDocModal(
        $(".zbase_report_pane"),
        doc_id,
        "http://zbase.io/a/reports/" + doc_id);

    $.onClick($(".zbase_report_pane .link.share"), function() {
      modal.show();
    });
  };

  var initNameEditing = function() {
    var report_pane = $(".zbase_report_pane");
    var modal = $("z-modal.rename_report", report_pane);
    var name_input = $("input.report_name", modal);

    $.onClick($(".report_name.editable", report_pane), function() {
      if (report_pane.classList.contains("editable")) {
        modal.show();
        name_input.focus();
      }
    });

    $.onClick($("button.submit", modal), function() {
      if (!docsync) {
        $.fatalError();
        return;
      }
      setReportName($.escapeHTML(name_input.value));
      docsync.saveDocument();
      modal.close();
    });
  };

  var initDescriptionEditing = function() {
    var report_pane = $(".zbase_report_pane");
    var modal = $("z-modal.edit_description", report_pane);
    var textarea = $("textarea.report_description", modal);

    var showModal = function() {
      if (report_pane.classList.contains("editable")) {
        modal.show();
        textarea.focus();
      }
    };

    $.onClick($(".report_description.editable", report_pane), showModal);
    $.onClick($(".link.add_description", report_pane), showModal);

    $.onClick($("button.submit", modal), function() {
      if (!docsync) {
        $.fatalError();
        return;
      }
      setReportDescription($.escapeHTML(textarea.value));
      docsync.saveDocument();
      modal.close();
    });
  };

  var setReportName = function(name) {
    var escaped_name = $.escapeHTML(name);
    $("zbase-breadcrumbs-section.report_name").innerHTML = escaped_name;
    $(".zbase_report_pane .report_name").innerHTML = escaped_name;
    $(".zbase_report_pane z-modal input.report_name").value = escaped_name;
  };

  var setReportDescription = function(description) {
    var escaped_description = $.nl2p($.escapeHTML(description));

    if (description.length == 0) {
      // display edit link
      $(".zbase_report_pane .link.add_description").classList.remove("hidden");
    } else {
      $(".zbase_report_pane .link.add_description").classList.add("hidden");
    }

    $(".zbase_report_pane .report_description").innerHTML = escaped_description;
    $(".zbase_report_pane z-modal textarea.report_description").innerHTML =
      description;
  };

  var getContentJSON = function() {
    var widgets = [];
    if (widget_list) {
      widgets = widget_list.getJSON();
    }

    return JSON.stringify({
        description: $(".zbase_report_pane textarea.report_description").innerHTML,
        widgets: widgets});
  };

  var getDocument = function() {
    return {
      content: getContentJSON(),
      name: $(".zbase_report_pane input.report_name").value
    };
  };

  var findRequiredWidgets = function(doc) {
    var widgets = [];

    if (doc.content != null && doc.content.hasOwnProperty("widgets")) {
      for (var i = 0; i < doc.content.widgets.length; i++) {
        if (widgets.indexOf(doc.content.widgets[i].type) == -1) {
          widgets.push(doc.content.widgets[i].type);
        }
      }
    }

    return widgets;
  };

  return {
    name: "report",
    loadView: function(params) { goToURL(params.path); },
    unloadView: destroy,
    handleNavigationChange: goToURL
  };

})());
<commit_msg>show widget editor after adding a new widget<commit_after>ZBase.registerView((function() {
  var widget_list = null;
  var edit_view = null;
  var docsync = null;

  // REMOVEME
  var goToURL = function(path) {
    var kPathPrefix = "/a/reports/";
    var report_id = path.substr(kPathPrefix.length);
    loadReport(report_id);
  }
  // REMOVEME END

  var loadReport = function(report_id) {
    if (widget_list) {
      widget_list.destroy();
      widget_list = null;
    }

    $.showLoader();
    $.httpGet("/api/v1/documents/" + report_id, function(r) {
      if (r.status == 200) {
        var doc = JSON.parse(r.response);
        if (doc.content.length == 0) {
          doc.content = null;
        } else {
          doc.content = JSON.parse(doc.content);
        }

        // load required widgets
        var required_widgets = findRequiredWidgets(doc);
        ReportWidgetFactory.loadWidgets(required_widgets, function() {
          render(doc);
          $.hideLoader();
        });
      } else {
        $.fatalError();
      }
    });
  };

  var destroy = function() {
    if (docsync) {
      docsync.close();
    }

    if (widget_list) {
      widget_list.destroy();
    }

    if (edit_view) {
      edit_view.destroy();
    }
  };

  var render = function(doc) {
    var readonly = !doc.is_writable;
    var page = $.getTemplate(
        "views/report",
        "zbase_report_main_tpl");

    //doc settings
    var settings_widget = DocumentSettingsWidget(
        $(".document_settings", page),
        doc.uuid);
    settings_widget.render();

    $.handleLinks(page);
    $.replaceViewport(page);

    setReportName(doc.name);

    var description = "";
    if (doc.content != null && doc.content.hasOwnProperty("description")) {
      description = doc.content.description;
    }
    setReportDescription(description);

    var widgets = [];
    if (doc.content != null && doc.content.hasOwnProperty("widgets")) {
      widgets = doc.content.widgets;
    }
    widget_list = WidgetList(widgets);
    widget_list.onWidgetEdit(function(widget_id) {
      showWidgetEditor(widget_id);
    });

    //setup docsync
    docsync = DocSync(
        getDocument,
        "/api/v1/documents/" + doc.uuid,
        $(".zbase_report_infobar"));

    if (readonly) {
      $(".zbase_report_pane").classList.add("readonly");
    } else {
      initNameEditing();
      initDescriptionEditing();
      initShareDocModal(doc.uuid);
      $.onClick($(".zbase_report_pane .link.edit_source"), showRawJSONEditor);

      //add widget flow
      var add_widget_flow = AddReportWidgetFlow(
          $(".zbase_report_pane"));
      add_widget_flow.onWidgetAdded(function(widget_type) {
        if (!widget_list || !docsync) {
          $.fatalError();
          return;
        }
        var widget_id = widget_list.addNewEmptyWidget(widget_type);
        docsync.saveDocument();
        showWidgetEditor(widget_id);
        $.hideLoader();
      });
      $.onClick($(".zbase_report_pane .link.add_widget"), function() {
        add_widget_flow.render();
      });

      // handle display mode
      $(".zbase_report_pane z-dropdown.mode").addEventListener("change", setEditable);
    }

    showReportView();
  };

  var showReportView = function(doc) {
    //showLoader?
    if (edit_view) {
      edit_view.destroy();
    }
    var viewport = $(".zbase_report_viewport");
    viewport.innerHTML = "";
    viewport.classList.remove("editor");

    if (widget_list) {
      widget_list.render(viewport);
      widget_list.setEditable(true);
    } else {
      $.fatalError();
    }
  };

  var showWidgetEditor = function(widget_id) {
    if (!widget_list) {
      $.fatalError();
      return;
    }

    var conf = widget_list.getWidgetConfig(widget_id);
    var editor = ReportWidgetFactory.getWidgetEditor(conf);

    editor.onSave(function(config) {
      if (!docsync) {
        $.fatalError();
        return;
      }
      widget_list.updateWidgetConfig(widget_id, config);
      docsync.saveDocument();
      showReportView();
    });

    editor.onCancel(function() {
      showReportView();
    });

    showEditView(editor);
  };

  var showRawJSONEditor = function() {
    var editor = ReportJSONEditor(getContentJSON());
    showEditView(editor);

    editor.onSave(function(json) {
      if (!widget_list) {
        $.fatalError();
        return;
      }
      var content = JSON.parse(json);
      setReportDescription(content.description);
      $.showLoader();
      widget_list.setJSON(content.widgets, function() {
        if (!docsync) {
          $.fatalError();
          return;
        }
        docsync.saveDocument();
        showReportView();
        $.hideLoader();
      });
    });

    editor.onCancel(showReportView);
  };

  var showEditView = function(editor) {
    edit_view = editor;
    var viewport = $(".zbase_report_viewport");
    viewport.innerHTML = "";
    viewport.classList.add("editor");
    edit_view.render(viewport);
  };

  var setEditable = function() {
    if (!widget_list) {
      $.fatalError();
      return;
    }

    if (this.getValue() == "editing") {
      $(".zbase_report_pane").classList.add("editable");
      widget_list.setEditable(true);
    } else {
      $(".zbase_report_pane").classList.remove("editable");
      widget_list.setEditable(false);
    }
  };

  var initShareDocModal = function(doc_id) {
    var modal = ShareDocModal(
        $(".zbase_report_pane"),
        doc_id,
        "http://zbase.io/a/reports/" + doc_id);

    $.onClick($(".zbase_report_pane .link.share"), function() {
      modal.show();
    });
  };

  var initNameEditing = function() {
    var report_pane = $(".zbase_report_pane");
    var modal = $("z-modal.rename_report", report_pane);
    var name_input = $("input.report_name", modal);

    $.onClick($(".report_name.editable", report_pane), function() {
      if (report_pane.classList.contains("editable")) {
        modal.show();
        name_input.focus();
      }
    });

    $.onClick($("button.submit", modal), function() {
      if (!docsync) {
        $.fatalError();
        return;
      }
      setReportName($.escapeHTML(name_input.value));
      docsync.saveDocument();
      modal.close();
    });
  };

  var initDescriptionEditing = function() {
    var report_pane = $(".zbase_report_pane");
    var modal = $("z-modal.edit_description", report_pane);
    var textarea = $("textarea.report_description", modal);

    var showModal = function() {
      if (report_pane.classList.contains("editable")) {
        modal.show();
        textarea.focus();
      }
    };

    $.onClick($(".report_description.editable", report_pane), showModal);
    $.onClick($(".link.add_description", report_pane), showModal);

    $.onClick($("button.submit", modal), function() {
      if (!docsync) {
        $.fatalError();
        return;
      }
      setReportDescription($.escapeHTML(textarea.value));
      docsync.saveDocument();
      modal.close();
    });
  };

  var setReportName = function(name) {
    var escaped_name = $.escapeHTML(name);
    $("zbase-breadcrumbs-section.report_name").innerHTML = escaped_name;
    $(".zbase_report_pane .report_name").innerHTML = escaped_name;
    $(".zbase_report_pane z-modal input.report_name").value = escaped_name;
  };

  var setReportDescription = function(description) {
    var escaped_description = $.nl2p($.escapeHTML(description));

    if (description.length == 0) {
      // display edit link
      $(".zbase_report_pane .link.add_description").classList.remove("hidden");
    } else {
      $(".zbase_report_pane .link.add_description").classList.add("hidden");
    }

    $(".zbase_report_pane .report_description").innerHTML = escaped_description;
    $(".zbase_report_pane z-modal textarea.report_description").innerHTML =
      description;
  };

  var getContentJSON = function() {
    var widgets = [];
    if (widget_list) {
      widgets = widget_list.getJSON();
    }

    return JSON.stringify({
        description: $(".zbase_report_pane textarea.report_description").innerHTML,
        widgets: widgets});
  };

  var getDocument = function() {
    return {
      content: getContentJSON(),
      name: $(".zbase_report_pane input.report_name").value
    };
  };

  var findRequiredWidgets = function(doc) {
    var widgets = [];

    if (doc.content != null && doc.content.hasOwnProperty("widgets")) {
      for (var i = 0; i < doc.content.widgets.length; i++) {
        if (widgets.indexOf(doc.content.widgets[i].type) == -1) {
          widgets.push(doc.content.widgets[i].type);
        }
      }
    }

    return widgets;
  };

  return {
    name: "report",
    loadView: function(params) { goToURL(params.path); },
    unloadView: destroy,
    handleNavigationChange: goToURL
  };

})());
<|endoftext|>


<commit_before>module.exports = {
  "env": {
    "browser": true,
    "es6": true
  },
  "extends": "standard",
  "parserOptions": {
    "ecmaFeatures": {
      "experimentalObjectRestSpread": true,
      "jsx": true
    },
    "sourceType": "module"
  },
  "plugins": [
    "react"
  ],
  "rules": {
    "quotes": [
      "error",
      "single"
    ],
    "semi": [
      "error",
      "never"
    ],
    "react/jsx-uses-react": "error",
    "react/jsx-uses-vars": "error",
    'no-debugger': process.env.NODE_ENV === 'production' ? 2 : 0
  }
};
<commit_msg>Update .eslintrc.js<commit_after>module.exports = {
  "env": {
    "browser": true,
    "es6": true
  },
  "extends": "standard",
  "parserOptions": {
    "ecmaFeatures": {
      "experimentalObjectRestSpread": true,
      "jsx": true
    },
    "sourceType": "module"
  },
  "plugins": [
    "react"
  ],
  "rules": {
    "quotes": [
      "error",
      "single"
    ],
    "semi": [
      "error",
      "never"
    ],
    "react/jsx-uses-react": "error",
    "react/jsx-uses-vars": "error",
    'no-debugger': 0
  }
};
<|endoftext|>


<commit_before>function updateFriendList(friends)
{
    var friendlist = $('#friendlist ul');

    //Empty out the friendlist
    friendlist.empty();

    //Fill in the new friendlist with new friends
    for( var i = 0; i < friends.length; i++)
    {
        //friendlist.append("
" + friends[i].firstName + " "+ friends[i].lastName + "
");
        console.log("
" + friends[i].firstName + " " + friends[i].lastName +"
");
        friendlist.append("
" + friends[i].firstName + " " + friends[i].lastName +"
");
    }
}

function filterFriends(e)
{
    var filterTerm = $('#friendSearch').val();

    if( e.keyCode == 13 )
    {
        $.ajax({
            type: 'POST',
            url: '/app_dev.php/FriendSearch',
            data: { searchTerm: filterTerm },
            success: function(data, textStatus, jqXHR) {
                updateFriendList(jQuery.parseJSON(data));
            }
        });
    }
}

$(document).ready(function(){

    $('#friendlist ul li').click(function(){
       window.location = $(this).find("a").attr("href");
    });

    $('#friendSearch').keyup(filterFriends);
});<commit_msg>Friend search results now links to the friend pages.<commit_after>function updateFriendList(friends)
{
    var friendlist = $('#friendlist ul');

    //Empty out the friendlist
    friendlist.empty();

    //Fill in the new friendlist with new friends
    for( var i = 0; i < friends.length; i++)
    {
        //friendlist.append("
" + friends[i].firstName + " "+ friends[i].lastName + "
");
        console.log("
" + friends[i].firstName + " " + friends[i].lastName +"
");
        friendlist.append("
" + friends[i].firstName + " " + friends[i].lastName +"
");
    }
}

function filterFriends(e)
{
    var filterTerm = $('#friendSearch').val();

    if( e.keyCode == 13 )
    {
        $.ajax({
            type: 'POST',
            url: '/app_dev.php/FriendSearch',
            data: { searchTerm: filterTerm },
            success: function(data, textStatus, jqXHR) {
                updateFriendList(jQuery.parseJSON(data));
            }
        });
    }
}

$(document).ready(function(){

    $('#friendlist ul li').click(function(){
       window.location = $(this).find("a").attr("href");
    });

    $('#friendSearch').keyup(filterFriends);
});<|endoftext|>


<commit_before>//
// charts_update.js
// Will De Freitas
//
// Draws irrigation charts
//
//

//-------------------------------------------------------------------------------
// Draws irrigation data
//-------------------------------------------------------------------------------
function displayIrrigation() {

	// Highlights correct navbar location
	$('li').removeClass('active');
	$('#irrig').parent().addClass('active');

	// Clear chart area
	$('#graph-container').empty();

    // Set up chart screen sections
    $('

').appendTo('#graph-container');
    $('

').appendTo('#graph-container');

    getIrrigData(garden-input-bar-sectiondrawIrrigChart, []);

}

//-------------------------------------------------------------------------------
// Grab irrigation data
//-------------------------------------------------------------------------------
function getIrrigData(functionCall, args) {

    var error_data = {"9999": {"time":10, "msg": "Loading data failure"}};

    $.ajax({
        cache: false,
        url: 'weather_data/config.json',
        dataType: "json",
        success: function(config_data) {
            $.ajax({
                cache: false,
                url: 'weather_data/irrigation.json',
                dataType: "json",
                success: function(chart_data) {
                    args.push(config_data);
                    args.push(chart_data);
                    functionCall.apply(this, args);
                },
                error: function () {
                    displayErrorMessage(error_data, false, false);
                },
                onFailure: function () {
                    displayErrorMessage(error_data, false, false);
                }
            })
        }
    });

}

//-------------------------------------------------------------------------------
// Draw charts
//-------------------------------------------------------------------------------
function drawIrrigChart(config_data, chart_data) {

	// Clear chart area
	$('#chart-section').empty();

    // Override the reset function, we don't need to hide the tooltips and crosshairs.
    Highcharts.Pointer.prototype.reset = function () {
        return undefined;
    };

    // Synchronize zooming through the setExtremes event handler.
    function syncExtremes(e) {
        var thisChart = this.chart;

        if (e.trigger !== 'syncExtremes') { // Prevent feedback loop
            Highcharts.each(Highcharts.charts, function (chart) {
                if (chart !== thisChart) {
                    if (chart.xAxis[0].setExtremes) { // It is null while updating
                        chart.xAxis[0].setExtremes(e.min, e.max, undefined, false, { trigger: 'syncExtremes' });
                    }
                }
            });
        }
    }

    dates = [];

    // Set up chart
	highchartOptions = {
        chart: {
            marginLeft: 60,
            spacingTop: 10,
            spacingBottom: 10,
            zoomType: 'x'
        },
        title: {
            text: null,
            align: 'left',
            margin: 0,
            x: 30
        },
        yAxis: [{ // Primary yAxis
            title: {
                text: 'Depth',
                style: {
                    color: Highcharts.getOptions().colors[0]
                }
            },
            min: 0,
            labels: {
                format: '{value} mm',
                style: {
                    color: Highcharts.getOptions().colors[0]
                }
            }
        }, { // Secondary yAxis
            title: {
                text: 'Temperature',
                style: {
                    color: Highcharts.getOptions().colors[1]
                }
            },
            min: 0,
            labels: {
                format: '{value}°C',
                style: {
                    color: Highcharts.getOptions().colors[1]
                }
            },
            opposite: true
        }],
        xAxis: {
            events: {
                setExtremes: syncExtremes
            },
        	type: 'datetime',
            maxZoom: 48 * 3600 * 1000,
            crosshair: false
        },
        credits: {
            enabled: false
        },
        legend: {
            enabled: false
        },
        tooltip: {
            shared: false,
            useHTML: true,
            valueDecimals: 2,
            crosshairs: true
        },
        plotOptions: {
            area: {
                fillColor: {
                    linearGradient: {
                        x1: 0,
                        y1: 0,
                        x2: 0,
                        y2: 1
                    },
                    stops: [
                        [0, Highcharts.getOptions().colors[0]],
                        [1, Highcharts.Color(Highcharts.getOptions().colors[0]).setOpacity(0).get('rgba')]
                    ]
                },
                marker: {
                    radius: 2
                },
                lineWidth: 1,
                states: {
                    hover: {
                        lineWidth: 1
                    }
                },
                threshold: null
            },
            column: {
                stacking: 'normal'
            }
        },
        series: [
	        {
	            name: 'Predicted Rainfall',
	            type: 'column',
	            data: chart_data.precip,
                pointStart: Date.UTC(chart_data.date[0], chart_data.date[1]-1, chart_data.date[2]),
                pointInterval: 24 * 3600 * 1000, // one day
	            color: COLOR_L_BLUE,
	            fillOpacity: 0.3,
	            tooltip: {
	                valueSuffix: 'mm'
	        	},
                stack: 'irrig'
	        },{
                name: 'Irrigation Amount',
                type: 'column',
                data: chart_data.irrig_amount,
                pointStart: Date.UTC(chart_data.date[0], chart_data.date[1]-1, chart_data.date[2]),
                pointInterval: 24 * 3600 * 1000, // one day
                color: COLOR_L_GREEN,
                fillOpacity: 0.3,
                tooltip: {
                    valueSuffix: 'mm'
                },
                stack: 'irrig'
            },{
                name: 'Depth',
                type: 'area',
                data: chart_data.depth,
                pointStart: Date.UTC(chart_data.date[0], chart_data.date[1]-1, chart_data.date[2]),
                pointInterval: 24 * 3600 * 1000, // one day
                fillOpacity: 0.3,
                lineWidth: 4,
                color: COLOR_BLUE,
                tooltip: {
                    valueSuffix: 'mm'
                }
            },{
          //       name: 'Depth Linear',
          //       type: 'spline',
          //       data: chart_data.linear,
          //       //fillOpacity: 0.3,
          //       marker: {
          //           enabled: false
          //       },
          //       color: COLOR_L_GREY,
             //    dashstyle: 'dash',
             //    tooltip: {
             //        valueSuffix: 'mm'
                // }

            },{
	            name: 'Alarm Level',
	            type: 'line',
	            data: chart_data.alarm_level,
                pointStart: Date.UTC(chart_data.date[0], chart_data.date[1]-1, chart_data.date[2]),
                pointInterval: 24 * 3600 * 1000, // one day
	            color: COLOR_RED,
                dashstyle: 'dash',
	            fillOpacity: 0.3,
                marker: {
                    enabled: false
                },
	            tooltip: {
	                valueSuffix: 'mm'
	        	}
            },{
                name: 'Predicted Temp',
                type: 'spline',
                data: chart_data.temp,
                pointStart: Date.UTC(chart_data.date[0], chart_data.date[1]-1, chart_data.date[2]),
                pointInterval: 24 * 3600 * 1000, // one day
                fillOpacity: 0.3,
                color: COLOR_YELLOW,
                yAxis: 1,
                tooltip: {
                    valueSuffix: '°C'
                }
	        }
        ]
    }

	// // Draw chart
    $('
').appendTo('#chart-section').highcharts(highchartOptions);

    drawIrrigBar(chart_data.irrig_amount[0], config_data.irrigation.IRRIG_FULL, false);

}

//-------------------------------------------------------------------------------
// Add irrigation amount
//-------------------------------------------------------------------------------
function addIrrigationAmount(amount, irrig_amount, irrig_full) {

    // increment in 25% steps
    irrig_amount = irrig_amount + amount * (irrig_full/4);

    if (irrig_amount < 0) {
        irrig_amount = 0;
    } else if (irrig_amount > irrig_full) {
        irrig_amount = irrig_full;
    }

    drawIrrigBar(irrig_amount, irrig_full, true);

}

//-------------------------------------------------------------------------------
// Draws irrigation bar
//-------------------------------------------------------------------------------
function drawIrrigBar(irrig_amount, irrig_full, unsaved) {

    // Clear chart area
    $('#irrig-input-bar-section').empty();

    if(unsaved == true) {
        HTMLirrigButton_formatted = HTMLirrigButton.replace(/%disk_icon%/gi, 'glyphicon glyphicon-floppy-disk')
    } else {
        HTMLirrigButton_formatted = HTMLirrigButton.replace(/%disk_icon%/gi, 'glyphicon glyphicon-ok')
    }

    var HTMLirrigBar_formatted   = HTMLirrigBar.replace(/%barvalue%/gi, (irrig_amount/irrig_full)*100);
    HTMLirrigBar_formatted       = HTMLirrigBar_formatted.replace(/%irrig_amount%/gi, irrig_amount);
    HTMLirrigBar_formatted       = HTMLirrigBar_formatted.replace(/%irrig_depth_full%/gi, irrig_full);
    var HTMLirrig_formatted      = HTMLirrig.replace('%col1%', HTMLirrigButton_formatted);
    HTMLirrig_formatted          = HTMLirrig_formatted.replace('%col2%', HTMLirrigBar_formatted);
    $(HTMLirrig_formatted).appendTo('#irrig-input-bar-section');

    $('#irrig-minus-btn').click(function() {
        addIrrigationAmount(-1, irrig_amount, irrig_full);
    });

    $('#irrig-plus-btn').click(function() {
        addIrrigationAmount(1, irrig_amount, irrig_full);
    });

    $('#irrig-save-btn').click(function() {
         getIrrigData(saveIrrigation, [irrig_amount]);
    });

}

//-------------------------------------------------------------------------------
// If user has irrigated, save it to json file
//-------------------------------------------------------------------------------
function saveIrrigation(irrig_amount, config_data, chart_data) {

    var error_data = {"9999": {"time":10, "msg": "Unable to save data!"}};

    chart_data.irrig_amount[0] = irrig_amount;

    var json = JSON.stringify(chart_data);
    var encoded = btoa(json);

    $.ajax({
        url: 'php/save_irrig_data.php',
        type: "post",
        data: 'json=' + encoded,
        success: function(rxData) {
            alert(rxData);
            getIrrigData(drawIrrigChart, []);
        },
        error: function () {
            displayErrorMessage(error_data, false, false);
        },
        onFailure: function () {
            displayErrorMessage(error_data, false, false);
        }
    });

}

<commit_msg>Bug fix<commit_after>//
// charts_update.js
// Will De Freitas
//
// Draws irrigation charts
//
//

//-------------------------------------------------------------------------------
// Draws irrigation data
//-------------------------------------------------------------------------------
function displayIrrigation() {

	// Highlights correct navbar location
	$('li').removeClass('active');
	$('#irrig').parent().addClass('active');

	// Clear chart area
	$('#graph-container').empty();

    // Set up chart screen sections
    $('

').appendTo('#graph-container');
    $('

').appendTo('#graph-container');

    getIrrigData(IrrigChart, []);

}

//-------------------------------------------------------------------------------
// Grab irrigation data
//-------------------------------------------------------------------------------
function getIrrigData(functionCall, args) {

    var error_data = {"9999": {"time":10, "msg": "Loading data failure"}};

    $.ajax({
        cache: false,
        url: 'weather_data/config.json',
        dataType: "json",
        success: function(config_data) {
            $.ajax({
                cache: false,
                url: 'weather_data/irrigation.json',
                dataType: "json",
                success: function(chart_data) {
                    args.push(config_data);
                    args.push(chart_data);
                    functionCall.apply(this, args);
                },
                error: function () {
                    displayErrorMessage(error_data, false, false);
                },
                onFailure: function () {
                    displayErrorMessage(error_data, false, false);
                }
            })
        }
    });

}

//-------------------------------------------------------------------------------
// Draw charts
//-------------------------------------------------------------------------------
function drawIrrigChart(config_data, chart_data) {

	// Clear chart area
	$('#chart-section').empty();

    // Override the reset function, we don't need to hide the tooltips and crosshairs.
    Highcharts.Pointer.prototype.reset = function () {
        return undefined;
    };

    // Synchronize zooming through the setExtremes event handler.
    function syncExtremes(e) {
        var thisChart = this.chart;

        if (e.trigger !== 'syncExtremes') { // Prevent feedback loop
            Highcharts.each(Highcharts.charts, function (chart) {
                if (chart !== thisChart) {
                    if (chart.xAxis[0].setExtremes) { // It is null while updating
                        chart.xAxis[0].setExtremes(e.min, e.max, undefined, false, { trigger: 'syncExtremes' });
                    }
                }
            });
        }
    }

    dates = [];

    // Set up chart
	highchartOptions = {
        chart: {
            marginLeft: 60,
            spacingTop: 10,
            spacingBottom: 10,
            zoomType: 'x'
        },
        title: {
            text: null,
            align: 'left',
            margin: 0,
            x: 30
        },
        yAxis: [{ // Primary yAxis
            title: {
                text: 'Depth',
                style: {
                    color: Highcharts.getOptions().colors[0]
                }
            },
            min: 0,
            labels: {
                format: '{value} mm',
                style: {
                    color: Highcharts.getOptions().colors[0]
                }
            }
        }, { // Secondary yAxis
            title: {
                text: 'Temperature',
                style: {
                    color: Highcharts.getOptions().colors[1]
                }
            },
            min: 0,
            labels: {
                format: '{value}°C',
                style: {
                    color: Highcharts.getOptions().colors[1]
                }
            },
            opposite: true
        }],
        xAxis: {
            events: {
                setExtremes: syncExtremes
            },
        	type: 'datetime',
            maxZoom: 48 * 3600 * 1000,
            crosshair: false
        },
        credits: {
            enabled: false
        },
        legend: {
            enabled: false
        },
        tooltip: {
            shared: false,
            useHTML: true,
            valueDecimals: 2,
            crosshairs: true
        },
        plotOptions: {
            area: {
                fillColor: {
                    linearGradient: {
                        x1: 0,
                        y1: 0,
                        x2: 0,
                        y2: 1
                    },
                    stops: [
                        [0, Highcharts.getOptions().colors[0]],
                        [1, Highcharts.Color(Highcharts.getOptions().colors[0]).setOpacity(0).get('rgba')]
                    ]
                },
                marker: {
                    radius: 2
                },
                lineWidth: 1,
                states: {
                    hover: {
                        lineWidth: 1
                    }
                },
                threshold: null
            },
            column: {
                stacking: 'normal'
            }
        },
        series: [
	        {
	            name: 'Predicted Rainfall',
	            type: 'column',
	            data: chart_data.precip,
                pointStart: Date.UTC(chart_data.date[0], chart_data.date[1]-1, chart_data.date[2]),
                pointInterval: 24 * 3600 * 1000, // one day
	            color: COLOR_L_BLUE,
	            fillOpacity: 0.3,
	            tooltip: {
	                valueSuffix: 'mm'
	        	},
                stack: 'irrig'
	        },{
                name: 'Irrigation Amount',
                type: 'column',
                data: chart_data.irrig_amount,
                pointStart: Date.UTC(chart_data.date[0], chart_data.date[1]-1, chart_data.date[2]),
                pointInterval: 24 * 3600 * 1000, // one day
                color: COLOR_L_GREEN,
                fillOpacity: 0.3,
                tooltip: {
                    valueSuffix: 'mm'
                },
                stack: 'irrig'
            },{
                name: 'Depth',
                type: 'area',
                data: chart_data.depth,
                pointStart: Date.UTC(chart_data.date[0], chart_data.date[1]-1, chart_data.date[2]),
                pointInterval: 24 * 3600 * 1000, // one day
                fillOpacity: 0.3,
                lineWidth: 4,
                color: COLOR_BLUE,
                tooltip: {
                    valueSuffix: 'mm'
                }
            },{
          //       name: 'Depth Linear',
          //       type: 'spline',
          //       data: chart_data.linear,
          //       //fillOpacity: 0.3,
          //       marker: {
          //           enabled: false
          //       },
          //       color: COLOR_L_GREY,
             //    dashstyle: 'dash',
             //    tooltip: {
             //        valueSuffix: 'mm'
                // }

            },{
	            name: 'Alarm Level',
	            type: 'line',
	            data: chart_data.alarm_level,
                pointStart: Date.UTC(chart_data.date[0], chart_data.date[1]-1, chart_data.date[2]),
                pointInterval: 24 * 3600 * 1000, // one day
	            color: COLOR_RED,
                dashstyle: 'dash',
	            fillOpacity: 0.3,
                marker: {
                    enabled: false
                },
	            tooltip: {
	                valueSuffix: 'mm'
	        	}
            },{
                name: 'Predicted Temp',
                type: 'spline',
                data: chart_data.temp,
                pointStart: Date.UTC(chart_data.date[0], chart_data.date[1]-1, chart_data.date[2]),
                pointInterval: 24 * 3600 * 1000, // one day
                fillOpacity: 0.3,
                color: COLOR_YELLOW,
                yAxis: 1,
                tooltip: {
                    valueSuffix: '°C'
                }
	        }
        ]
    }

	// // Draw chart
    $('
').appendTo('#chart-section').highcharts(highchartOptions);

    drawIrrigBar(chart_data.irrig_amount[0], config_data.irrigation.IRRIG_FULL, false);

}

//-------------------------------------------------------------------------------
// Add irrigation amount
//-------------------------------------------------------------------------------
function addIrrigationAmount(amount, irrig_amount, irrig_full) {

    // increment in 25% steps
    irrig_amount = irrig_amount + amount * (irrig_full/4);

    if (irrig_amount < 0) {
        irrig_amount = 0;
    } else if (irrig_amount > irrig_full) {
        irrig_amount = irrig_full;
    }

    drawIrrigBar(irrig_amount, irrig_full, true);

}

//-------------------------------------------------------------------------------
// Draws irrigation bar
//-------------------------------------------------------------------------------
function drawIrrigBar(irrig_amount, irrig_full, unsaved) {

    // Clear chart area
    $('#irrig-input-bar-section').empty();

    if(unsaved == true) {
        HTMLirrigButton_formatted = HTMLirrigButton.replace(/%disk_icon%/gi, 'glyphicon glyphicon-floppy-disk')
    } else {
        HTMLirrigButton_formatted = HTMLirrigButton.replace(/%disk_icon%/gi, 'glyphicon glyphicon-ok')
    }

    var HTMLirrigBar_formatted   = HTMLirrigBar.replace(/%barvalue%/gi, (irrig_amount/irrig_full)*100);
    HTMLirrigBar_formatted       = HTMLirrigBar_formatted.replace(/%irrig_amount%/gi, irrig_amount);
    HTMLirrigBar_formatted       = HTMLirrigBar_formatted.replace(/%irrig_depth_full%/gi, irrig_full);
    var HTMLirrig_formatted      = HTMLirrig.replace('%col1%', HTMLirrigButton_formatted);
    HTMLirrig_formatted          = HTMLirrig_formatted.replace('%col2%', HTMLirrigBar_formatted);
    $(HTMLirrig_formatted).appendTo('#irrig-input-bar-section');

    $('#irrig-minus-btn').click(function() {
        addIrrigationAmount(-1, irrig_amount, irrig_full);
    });

    $('#irrig-plus-btn').click(function() {
        addIrrigationAmount(1, irrig_amount, irrig_full);
    });

    $('#irrig-save-btn').click(function() {
         getIrrigData(saveIrrigation, [irrig_amount]);
    });

}

//-------------------------------------------------------------------------------
// If user has irrigated, save it to json file
//-------------------------------------------------------------------------------
function saveIrrigation(irrig_amount, config_data, chart_data) {

    var error_data = {"9999": {"time":10, "msg": "Unable to save data!"}};

    chart_data.irrig_amount[0] = irrig_amount;

    var json = JSON.stringify(chart_data);
    var encoded = btoa(json);

    $.ajax({
        url: 'php/save_irrig_data.php',
        type: "post",
        data: 'json=' + encoded,
        success: function(rxData) {
            alert(rxData);
            getIrrigData(drawIrrigChart, []);
        },
        error: function () {
            displayErrorMessage(error_data, false, false);
        },
        onFailure: function () {
            displayErrorMessage(error_data, false, false);
        }
    });

}

<|endoftext|>


<commit_before>/**
 * @file Unit tests for the competitions background module
 * @author Daniil Filippov <filippovdaniil@gmail.com>
 */

require('../background.js');
var sinon = require('sinon');
var assertStyles = require('../../assert-styles.js');
var expect = assertStyles.expect;
var fixtures = require('../../fixtures.js');

describe('competitions module', function () {
  describe('Competitions class', function () {
    // Reference to the sinon sandbox:
    var sandbox;
    // Reference to the Competitions class instance:
    var competitions;

    beforeEach(function () {
      sandbox = sinon.sandbox.create();
      sandbox.useFakeTimers();
      // Setting up stubs and spies for the kango mock object:
      sandbox.stub(kango.storage, 'getItem');
      sandbox.stub(kango.xhr, 'send');
      sandbox.spy(kango.storage, 'setItem');

      sandbox.stub(KlavoTools.tabs, 'createOrNavigateExisting');
      sandbox.spy(Competitions.prototype, '_updateNotifications');
      sandbox.spy(Competitions.prototype, '_createNotification');
      // Setting up a spy for the DeferredNotification class constructor:
      sandbox.spy(global, 'DeferredNotification');
      sandbox.stub(DeferredNotification.prototype, 'revoke');
      sandbox.stub(DeferredNotification.prototype, 'show');
      competitions = new Competitions;
      // Set the default server time delta to 1000 milliseconds:
      competitions._timeCorrection = 1000;
    });

    afterEach(function () {
      // Unwraping all stubs and spies:
      sandbox.restore();
    });

    /**
     * Tests for the Competitions class constructor
     */
    it('should set the correct default settings', function () {
      expect(competitions.rates).to.be.deep.equal([3, 5]);
      expect(competitions.delay).to.be.equal(60);
      expect(competitions.displayTime).to.be.equal(0);
      expect(competitions.audio).to.be.equal(false);
    });

    /**
     * Test for the Competitions.prototype.getParams method
     */
    it('should return the correct settings with the getParams() method', function () {
      kango.storage.getItem.withArgs('competition_rates').returns([1, 2, 3, 5]);
      kango.storage.getItem.withArgs('competition_delay').returns(15);
      kango.storage.getItem.withArgs('competition_displayTime').returns(5);
      kango.storage.getItem.withArgs('competition_audio').returns(false);
      competitions = new Competitions;
      expect(competitions.getParams()).to.be.deep.equal({
        rates: [1, 2, 3, 5],
        delay: 15,
        displayTime: 5,
        audio: false,
        onlyWithPlayers: false,
        minimalPlayersNumber: 2,
      });
    });

    /**
     * Tests for the Competitions.prototype.setParams method
     */
    it('should save the correct settings to storage with the setParams() method', function () {
      // Checking the invalid parameters:
      competitions.setParams({
        delay: null,
        rates: null,
        displayTime: null,
        audio: null
      });
      // sinon-chai doesn't support neverCalledWithMatch :(
      sinon
        .assert
        .neverCalledWithMatch(kango.storage.setItem, sinon.match.string, null);
      // Checking the valid parameters:
      competitions.setParams({
        delay: 15,
        rates: [1, 2, 3, 5],
        displayTime: 5,
        audio: false
      });
      expect(kango.storage.setItem)
        .to.have.been.calledWithExactly('competition_delay', 15)
        .to.have.been.calledWithExactly('competition_rates', [1, 2, 3, 5])
        .to.have.been.calledWithExactly('competition_displayTime', 5)
        .to.have.been.calledWithExactly('competition_audio', false);
    });

    it('should call the _updateNotifications() method within ' +
        'the setParams() method', function () {
      var competitions = new Competitions;
      competitions.setParams({ delay: 15 });
      competitions.setParams({ displayTime: 5 });
      expect(Competitions.prototype._updateNotifications).to.have.been.calledTwice;
    });

    it('should recreate deferred notifications instances with the for ' +
        'active competitions', function () {
      var spy1 = new DeferredNotification('test1');
      var spy2 = new DeferredNotification('test2');
      sandbox.stub(Competitions.prototype, 'getRemainingTime').returns(1000);
      competitions._hash = {
        1337: {
          id: 1337,
          beginTime: null,
          ratingValue: 1,
        },
        1338: {
          id: 1338,
          // For this test doesn't matter:
          beginTime: 0,
          ratingValue: 3,
          notification: spy1,
        },
        1339: {
          id: 1339,
          beginTime: 0,
          ratingValue: 5,
          notification: spy2,
        },
      }
      competitions._updateNotifications();
      expect(spy1.revoke).to.have.been.called;
      expect(spy2.revoke).to.have.been.called;
      expect(Competitions.prototype._createNotification).to.have.been.calledTwice;
      expect(competitions._hash[1338].notification)
        .to.be.an.instanceOf(DeferredNotification)
        .to.be.not.deep.equal(spy1);
      expect(competitions._hash[1339].notification)
        .to.be.an.instanceOf(DeferredNotification)
        .to.be.not.deep.equal(spy2);
    });

    it('should create the "deferred" notification with correct parameters', function () {
      var competitionData = {
        id: 1337,
        ratingValue: 5,
        // For this test doesn't matter:
        beginTime: 0,
      };
      var notification = competitions._createNotification(competitionData, 400);
      expect(DeferredNotification)
        .to.have.been.calledWithExactly('Соревнование', {
          body: 'Соревнование x5 начинается',
          // TODO: set the stub for the kango.io.getResourceUrl
          icon: undefined,
          displayTime: undefined,
          audio: false,
        });
      // Default delay is set to 1 minute:
      expect(DeferredNotification.prototype.show)
        .to.have.been.calledWithExactly(340);
      // Check the notification's click handler:
      notification.onclick();
      expect(KlavoTools.tabs.createOrNavigateExisting)
        .to.have.been.calledWithExactly('http://klavogonki.ru/g/?gmid=1337');
      // Check the case with a huge displayTime:
      kango.storage.getItem.withArgs('competition_displayTime').returns(500);
      competitions = new Competitions;
      var notification = competitions._createNotification(competitionData, 400);
      expect(DeferredNotification)
        .to.have.been.calledWithExactly('Соревнование', {
          body: 'Соревнование x5 начинается',
          icon: undefined,
          // displayTime == delay:
          displayTime: 60,
          audio: false,
        });
      // Check the case with a huge delay:
      kango.storage.getItem.withArgs('competition_delay').returns(500);
      competitions = new Competitions;
      var notification = competitions._createNotification(competitionData, 400);
      expect(DeferredNotification.prototype.show)
        .to.have.been.calledWithExactly(0);
    });

    it('should revoke the notification with the click on it', function () {
      var competitionData = {
        id: 1337,
        ratingValue: 5,
        // For this test doesn't matter:
        beginTime: 0,
      };
      var notification = competitions._createNotification(competitionData, 400);
      notification.onclick();
      expect(DeferredNotification.prototype.revoke).to.have.been.called;
    });

    it('should correctly calculate the remaining time before the ' +
        'competition start', function () {
      sandbox.clock.tick(1470230514177);
      // The default server time delta is set to 1000 milliseconds:
      expect(competitions.getRemainingTime(1470230614)).to.be.equal(99);
      expect(competitions.getRemainingTime('2016-08-03T13:23:34.000Z')).to.be.equal(99);
    });

    it('should throw an error for invalid competition begin time or ' +
        'server time delta', function () {
      sandbox.clock.tick(1470230514177);
      expect(competitions.getRemainingTime.bind(competitions, null)).to.throw(TypeError);
      competitions._timeCorrection = null;
      expect(competitions.getRemainingTime.bind(competitions, 1470230614))
        .to.throw(Error);
    });

    it('should delete already started competitions with _clearStarted() ' +
        'method', function () {
      sandbox.clock.tick(2 * 1e3);
      competitions._hash = {
        1337: {
          id: 1337,
          beginTime: null,
          ratingValue: 1,
        },
        1338: {
          id: 1338,
          beginTime: 0,
          ratingValue: 3,
        },
        1339: {
          id: 1339,
          beginTime: 5,
          ratingValue: 5,
        },
      };
      competitions._clearStarted();
      expect(competitions._hash[1337]).to.be.an('object');
      expect(competitions._hash[1338]).to.be.undefined;
      expect(competitions._hash[1339]).to.be.an('object');
    });

    it('should show the notifications only for selected rates', function () {
      sandbox.stub(Competitions.prototype, 'getRemainingTime').returns(1000);
      kango.storage.getItem.withArgs('competition_rates').returns([2, 3, 5]);
      competitions = new Competitions;
      competitions._hash = {
        1337: {
          id: 1337,
          beginTime: 0,
          ratingValue: 1,
        },
        1338: {
          id: 1338,
          beginTime: 0,
          ratingValue: 2,
        },
        1339: {
          id: 1339,
          beginTime: 0,
          ratingValue: 3,
        },
        1340: {
          id: 1340,
          beginTime: 0,
          ratingValue: 5,
        },
      };
      competitions._notify(1337);
      competitions._notify(1338);
      competitions._notify(1339);
      competitions._notify(1340);
      expect(Competitions.prototype._createNotification).to.have.been.calledThrice;
    });

    it('should not show notifications if the delay is set to zero', function () {
      sandbox.stub(Competitions.prototype, 'getRemainingTime').returns(1000);
      kango.storage.getItem.withArgs('competition_delay').returns(0);
      competitions = new Competitions;
      competitions._hash = {
        1337: {
          id: 1338,
          beginTime: 0,
          ratingValue: 3,
        },
        1338: {
          id: 1339,
          beginTime: 5,
          ratingValue: 5,
        },
      };
      competitions._notify(1337);
      competitions._notify(1338);
      expect(Competitions.prototype._createNotification).to.not.been.called;
    });

    it('should revoke all notifications on teardown');
  });
});
<commit_msg>Apply tests to commit 00df3cca<commit_after>/**
 * @file Unit tests for the competitions background module
 * @author Daniil Filippov <filippovdaniil@gmail.com>
 */

require('../background.js');
var sinon = require('sinon');
var assertStyles = require('../../assert-styles.js');
var expect = assertStyles.expect;
var fixtures = require('../../fixtures.js');

describe('competitions module', function () {
  describe('Competitions class', function () {
    // Reference to the sinon sandbox:
    var sandbox;
    // Reference to the Competitions class instance:
    var competitions;

    beforeEach(function () {
      sandbox = sinon.sandbox.create();
      sandbox.useFakeTimers();
      // Setting up stubs and spies for the kango mock object:
      sandbox.stub(kango.storage, 'getItem');
      sandbox.stub(kango.xhr, 'send');
      sandbox.spy(kango.storage, 'setItem');

      sandbox.stub(KlavoTools.tabs, 'createOrNavigateExisting');
      sandbox.spy(Competitions.prototype, '_updateNotifications');
      sandbox.spy(Competitions.prototype, '_createNotification');
      // Setting up a spy for the DeferredNotification class constructor:
      sandbox.spy(global, 'DeferredNotification');
      sandbox.stub(DeferredNotification.prototype, 'revoke');
      sandbox.stub(DeferredNotification.prototype, 'show');
      competitions = new Competitions;
      // Set the default server time delta to 1000 milliseconds:
      competitions._timeCorrection = 1000;
    });

    afterEach(function () {
      // Unwraping all stubs and spies:
      sandbox.restore();
    });

    /**
     * Tests for the Competitions class constructor
     */
    it('should set the correct default settings', function () {
      expect(competitions.rates).to.be.deep.equal([3, 5]);
      expect(competitions.delay).to.be.equal(60);
      expect(competitions.audio).to.be.equal(false);
    });

    /**
     * Test for the Competitions.prototype.getParams method
     */
    it('should return the correct settings with the getParams() method', function () {
      kango.storage.getItem.withArgs('competition_rates').returns([1, 2, 3, 5]);
      kango.storage.getItem.withArgs('competition_delay').returns(15);
      kango.storage.getItem.withArgs('competition_audio').returns(false);
      competitions = new Competitions;
      expect(competitions.getParams()).to.be.deep.equal({
        rates: [1, 2, 3, 5],
        delay: 15,
        audio: false,
        onlyWithPlayers: false,
        minimalPlayersNumber: 2,
      });
    });

    /**
     * Tests for the Competitions.prototype.setParams method
     */
    it('should save the correct settings to storage with the setParams() method', function () {
      // Checking the invalid parameters:
      competitions.setParams({
        delay: null,
        rates: null,
        audio: null
      });
      // sinon-chai doesn't support neverCalledWithMatch :(
      sinon
        .assert
        .neverCalledWithMatch(kango.storage.setItem, sinon.match.string, null);
      // Checking the valid parameters:
      competitions.setParams({
        delay: 15,
        rates: [1, 2, 3, 5],
        audio: false
      });
      expect(kango.storage.setItem)
        .to.have.been.calledWithExactly('competition_delay', 15)
        .to.have.been.calledWithExactly('competition_rates', [1, 2, 3, 5])
        .to.have.been.calledWithExactly('competition_audio', false);
    });

    it('should recreate deferred notifications instances with the for ' +
        'active competitions', function () {
      var spy1 = new DeferredNotification('test1');
      var spy2 = new DeferredNotification('test2');
      sandbox.stub(Competitions.prototype, 'getRemainingTime').returns(1000);
      competitions._hash = {
        1337: {
          id: 1337,
          beginTime: null,
          ratingValue: 1,
        },
        1338: {
          id: 1338,
          // For this test doesn't matter:
          beginTime: 0,
          ratingValue: 3,
          notification: spy1,
        },
        1339: {
          id: 1339,
          beginTime: 0,
          ratingValue: 5,
          notification: spy2,
        },
      }
      competitions._updateNotifications();
      expect(spy1.revoke).to.have.been.called;
      expect(spy2.revoke).to.have.been.called;
      expect(Competitions.prototype._createNotification).to.have.been.calledTwice;
      expect(competitions._hash[1338].notification)
        .to.be.an.instanceOf(DeferredNotification)
        .to.be.not.deep.equal(spy1);
      expect(competitions._hash[1339].notification)
        .to.be.an.instanceOf(DeferredNotification)
        .to.be.not.deep.equal(spy2);
    });

    it('should create the "deferred" notification with correct parameters', function () {
      var competitionData = {
        id: 1337,
        ratingValue: 5,
        // For this test doesn't matter:
        beginTime: 0,
      };
      var notification = competitions._createNotification(competitionData, 400);
      expect(DeferredNotification)
        .to.have.been.calledWithExactly('Соревнование', {
          body: 'Соревнование x5 начинается',
          // TODO: set the stub for the kango.io.getResourceUrl
          icon: undefined,
          audio: false,
        });
      // Default delay is set to 1 minute:
      expect(DeferredNotification.prototype.show)
        .to.have.been.calledWithExactly(340);
      // Check the notification's click handler:
      notification.onclick();
      expect(KlavoTools.tabs.createOrNavigateExisting)
        .to.have.been.calledWithExactly('http://klavogonki.ru/g/?gmid=1337');
      // Check the case with a huge displayTime:
      kango.storage.getItem.withArgs('competition_displayTime').returns(500);
      competitions = new Competitions;
      var notification = competitions._createNotification(competitionData, 400);
      expect(DeferredNotification)
        .to.have.been.calledWithExactly('Соревнование', {
          body: 'Соревнование x5 начинается',
          icon: undefined,
          audio: false
        });
      // Check the case with a huge delay:
      kango.storage.getItem.withArgs('competition_delay').returns(500);
      competitions = new Competitions;
      var notification = competitions._createNotification(competitionData, 400);
      expect(DeferredNotification.prototype.show)
        .to.have.been.calledWithExactly(0);
    });

    it('should revoke the notification with the click on it', function () {
      var competitionData = {
        id: 1337,
        ratingValue: 5,
        // For this test doesn't matter:
        beginTime: 0,
      };
      var notification = competitions._createNotification(competitionData, 400);
      notification.onclick();
      expect(DeferredNotification.prototype.revoke).to.have.been.called;
    });

    it('should correctly calculate the remaining time before the ' +
        'competition start', function () {
      sandbox.clock.tick(1470230514177);
      // The default server time delta is set to 1000 milliseconds:
      expect(competitions.getRemainingTime(1470230614)).to.be.equal(99);
      expect(competitions.getRemainingTime('2016-08-03T13:23:34.000Z')).to.be.equal(99);
    });

    it('should throw an error for invalid competition begin time or ' +
        'server time delta', function () {
      sandbox.clock.tick(1470230514177);
      expect(competitions.getRemainingTime.bind(competitions, null)).to.throw(TypeError);
      competitions._timeCorrection = null;
      expect(competitions.getRemainingTime.bind(competitions, 1470230614))
        .to.throw(Error);
    });

    it('should delete already started competitions with _clearStarted() ' +
        'method', function () {
      sandbox.clock.tick(2 * 1e3);
      competitions._hash = {
        1337: {
          id: 1337,
          beginTime: null,
          ratingValue: 1,
        },
        1338: {
          id: 1338,
          beginTime: 0,
          ratingValue: 3,
        },
        1339: {
          id: 1339,
          beginTime: 5,
          ratingValue: 5,
        },
      };
      competitions._clearStarted();
      expect(competitions._hash[1337]).to.be.an('object');
      expect(competitions._hash[1338]).to.be.undefined;
      expect(competitions._hash[1339]).to.be.an('object');
    });

    it('should show the notifications only for selected rates', function () {
      sandbox.stub(Competitions.prototype, 'getRemainingTime').returns(1000);
      kango.storage.getItem.withArgs('competition_rates').returns([2, 3, 5]);
      competitions = new Competitions;
      competitions._hash = {
        1337: {
          id: 1337,
          beginTime: 0,
          ratingValue: 1,
        },
        1338: {
          id: 1338,
          beginTime: 0,
          ratingValue: 2,
        },
        1339: {
          id: 1339,
          beginTime: 0,
          ratingValue: 3,
        },
        1340: {
          id: 1340,
          beginTime: 0,
          ratingValue: 5,
        },
      };
      competitions._notify(1337);
      competitions._notify(1338);
      competitions._notify(1339);
      competitions._notify(1340);
      expect(Competitions.prototype._createNotification).to.have.been.calledThrice;
    });

    it('should not show notifications if the delay is set to zero', function () {
      sandbox.stub(Competitions.prototype, 'getRemainingTime').returns(1000);
      kango.storage.getItem.withArgs('competition_delay').returns(0);
      competitions = new Competitions;
      competitions._hash = {
        1337: {
          id: 1338,
          beginTime: 0,
          ratingValue: 3,
        },
        1338: {
          id: 1339,
          beginTime: 5,
          ratingValue: 5,
        },
      };
      competitions._notify(1337);
      competitions._notify(1338);
      expect(Competitions.prototype._createNotification).to.not.been.called;
    });

    it('should revoke all notifications on teardown');
  });
});
<|endoftext|>