<commit_before>define([
    'service/serviceBase'
], function(ServiceBase) {
    'use strict';

    // Override in configuration.properties with `web.ui` prefix
    var DEFAULTS = {

        // Load related vertices thresholds
        'vertex.loadRelatedMaxBeforePrompt': 50,
        'vertex.loadRelatedMaxForceSearch': 250,

        // Hide multivalue properties after this count
        'properties.multivalue.defaultVisibleCount': 2,

        // Property Metadata shown in info popover
        'properties.metadata.propertyNames': 'http://lumify.io#sourceTimezone,' +
                                             'http://lumify.io#modifiedDate,' +
                                             'http://lumify.io#modifiedBy,' +
                                             'sandboxStatus,' +
                                             'http://lumify.io#confidence',
        'properties.metadata.propertyNamesDisplay': 'properties.metadata.label.source_timezone,' +
                                                    'properties.metadata.label.modified_date,' +
                                                    'properties.metadata.label.modified_by,' +
                                                    'properties.metadata.label.status,' +
                                                    'properties.metadata.label.confidence',
        'properties.metadata.propertyNamesType': 'timezone,' +
                                                 'datetime,' +
                                                 'user,' +
                                                 'sandboxStatus,' +
                                                 'percent',
        'map.provider': 'google',
        'map.provider.osm.url': 'https://a.tile.openstreetmap.org/${z}/${x}/${y}.png,' +
                                'https://b.tile.openstreetmap.org/${z}/${x}/${y}.png,' +
                                'https://c.tile.openstreetmap.org/${z}/${x}/${y}.png'
    };

    // Coerce all values to strings since that's what they will be from
    // server
    _.keys(DEFAULTS).forEach(function(key) {
        DEFAULTS[key] = '' + DEFAULTS[key];
    });

    function ConfigService() {
        ServiceBase.call(this);
        this.memoizeFunctions('config', [
            'getConfiguration'
        ]);
        return this;
    }

    ConfigService.prototype = Object.create(ServiceBase.prototype);

    ConfigService.prototype.getConfiguration = function() {
        var data = {};
        try {
            var language = localStorage.getItem('language');
            if (language) {
                data.localeLanguage = language;
            }
            var country = localStorage.getItem('country');
            if (country) {
                data.localeCountry = country;
            }
            var variant = localStorage.getItem('variant')
            if (variant) {
                data.localeVariant = variant;
            }
        } catch(e) { }
        return this._ajaxGet({ url: 'configuration', data: data });
    };

    ConfigService.prototype.getProperties = function() {
        return this.getConfiguration().then(this.applyDefaults);
    };

    ConfigService.prototype.getMessages = function() {
        return this.getConfiguration().then(function(config) {
            return config.messages;
        });
    };

    ConfigService.prototype.applyDefaults = function(config) {
        return _.extend({}, DEFAULTS, config.properties);
    };

    return ConfigService;
});
<commit_msg>missing semicolon<commit_after>define([
    'service/serviceBase'
], function(ServiceBase) {
    'use strict';

    // Override in configuration.properties with `web.ui` prefix
    var DEFAULTS = {

        // Load related vertices thresholds
        'vertex.loadRelatedMaxBeforePrompt': 50,
        'vertex.loadRelatedMaxForceSearch': 250,

        // Hide multivalue properties after this count
        'properties.multivalue.defaultVisibleCount': 2,

        // Property Metadata shown in info popover
        'properties.metadata.propertyNames': 'http://lumify.io#sourceTimezone,' +
                                             'http://lumify.io#modifiedDate,' +
                                             'http://lumify.io#modifiedBy,' +
                                             'sandboxStatus,' +
                                             'http://lumify.io#confidence',
        'properties.metadata.propertyNamesDisplay': 'properties.metadata.label.source_timezone,' +
                                                    'properties.metadata.label.modified_date,' +
                                                    'properties.metadata.label.modified_by,' +
                                                    'properties.metadata.label.status,' +
                                                    'properties.metadata.label.confidence',
        'properties.metadata.propertyNamesType': 'timezone,' +
                                                 'datetime,' +
                                                 'user,' +
                                                 'sandboxStatus,' +
                                                 'percent',
        'map.provider': 'google',
        'map.provider.osm.url': 'https://a.tile.openstreetmap.org/${z}/${x}/${y}.png,' +
                                'https://b.tile.openstreetmap.org/${z}/${x}/${y}.png,' +
                                'https://c.tile.openstreetmap.org/${z}/${x}/${y}.png'
    };

    // Coerce all values to strings since that's what they will be from
    // server
    _.keys(DEFAULTS).forEach(function(key) {
        DEFAULTS[key] = '' + DEFAULTS[key];
    });

    function ConfigService() {
        ServiceBase.call(this);
        this.memoizeFunctions('config', [
            'getConfiguration'
        ]);
        return this;
    }

    ConfigService.prototype = Object.create(ServiceBase.prototype);

    ConfigService.prototype.getConfiguration = function() {
        var data = {};
        try {
            var language = localStorage.getItem('language');
            if (language) {
                data.localeLanguage = language;
            }
            var country = localStorage.getItem('country');
            if (country) {
                data.localeCountry = country;
            }
            var variant = localStorage.getItem('variant');
            if (variant) {
                data.localeVariant = variant;
            }
        } catch(e) { }
        return this._ajaxGet({ url: 'configuration', data: data });
    };

    ConfigService.prototype.getProperties = function() {
        return this.getConfiguration().then(this.applyDefaults);
    };

    ConfigService.prototype.getMessages = function() {
        return this.getConfiguration().then(function(config) {
            return config.messages;
        });
    };

    ConfigService.prototype.applyDefaults = function(config) {
        return _.extend({}, DEFAULTS, config.properties);
    };

    return ConfigService;
});
<|endoftext|>


<commit_before>/* Router: maps hash navigation */

$.ajaxSetup({
  headers: {
    "Authorization": "Token " + window.access_token,
    "Content-Type": "application/json"
  }
});

Atmo.Router = Backbone.Router.extend({
  routes: {
    "": "instances",
    "instances": "instances",
    "instances/:instance_id": "select_instance",
    "volumes": "volumes",
    "volumes/:volume_id": "select_volume",
    "new_instance": "new_instance",
    "new_instance/:image_query": "select_image",
    "settings": "settings"
  },
  initialize: function () {
    Atmo.profile = new Atmo.Models.Profile();
    Atmo.profile.fetch({
      async: false,
      success: function (profile, foo, bar) {
        $("#username").html(profile.get('id'));
      },
      error: function () {
        //TODO: Jason's awesome replacement screen goes here
        //TODO: Find a gnome.
        //window.location.replace(site_root + "/login");
      }
    });
    Atmo.Utils.update_weather();
    Atmo.providers = new Atmo.Collections.Providers();
    Atmo.providers.fetch({
      async: false,
      success: function (providers, foo, bar) {
      }
    });
    Atmo.identities = new Atmo.Collections.Identities();
    Atmo.identities.fetch({
      async: false
    });

    var identity = Atmo.profile.get('selected_identity');
    var identity_provider_id = identity.get("provider_id");

    Atmo.maintenances = new Atmo.Collections.Maintenances();
    Atmo.maintenances.fetch({
      async: false
    });
    Atmo.instances = new Atmo.Collections.Instances();
    Atmo.volumes = new Atmo.Collections.Volumes();
    Atmo.images = new Atmo.Collections.Machines();
    if (Atmo.profile.get('is_staff') === true) {
      Atmo.instance_hypervisors = new Atmo.Collections.Hypervisors();
      Atmo.instance_hypervisors.fetch({async: false});
    }
    Atmo.instance_types = new Atmo.Collections.Sizes();

    Atmo.notifications = new Atmo.Collections.Notifications();

    this.main = new Atmo.Views.Main({el: $('#main')[0]}).render();
    new Atmo.Views.Sidebar({el: $('#menu_wrapper')}).render();

    setInterval(function () {
      $('#refresh_instances_button').click();
    }, 5 * 60 * 1000);

    new Atmo.Views.FeedbackLink({el: $('#feedback_link')[0]});
    Atmo.request_resources_modal = new Atmo.Views.RequestResourcesModal();
    $('body').append(Atmo.request_resources_modal.render().el);

    Atmo.alert_modal = new Atmo.Views.AlertModal();
    $('body').append(Atmo.alert_modal.render().el);

    // Populate the top menu with a provider switcher
    for (var i = 0; i < Atmo.identities.length; i++) {
      var identity = Atmo.identities.models[i];
      var identity_provider_id = identity.get('provider_id');
      var in_maintenance = Atmo.maintenances.in_maintenance(identity_provider_id);
      var result = '';
      var name = Atmo.identities.models[i].get('provider').get('location');
      $('#providers_menu').append($('
', {
        html: function () {
          if (identity.get('selected')) {
            result = ' ' + name;
          } else {
            result = '' + name;
          }
          if (in_maintenance) {
            result += ' ';
          }
          result += '';
          return result;
        },
        click: function (e) {
          e.preventDefault();
          var identity = $(this).data();
          if (in_maintenance) {
            Atmo.Utils.notify('Error', identity.get('provider').get('type') + ' is currently in maintenance.');
            return false;
          }
          if (identity.get('selected')) {
            Atmo.Utils.notify('Error', 'You are already using ' + identity.get('provider').get('type') + ' as your provider.');
            return false;
          }
          else {
            Atmo.profile.save({'selected_identity': identity.get('id')},
              {'async': false,
                'patch': true,
                success: location.reload()});
          }
        }
      }).data(identity));
    }

    $('#contact_support').click(function (e) {
      e.preventDefault();
      $('#feedback_link').trigger('click');
    });
    $.ajax({
      type: 'GET',
      url: site_root + '/api/v1/version',
      statusCode: {
        200: function (response) {
          $('#version').html(''
            + new Date(response['date']).toString("F") + ' '
            + '(' + response['git_sha_abbrev'] + ')');
        }
      }
    });
    $('#total_cpu_time a').click(function () {
      $('#cpu_modal').modal('show');
    });
    new Atmo.Views.NotificationHolder({el: $('#alert_holder')[0]});
  },
  instances: function () {
    var identity = Atmo.profile.get('selected_identity');
    var identity_provider_id = identity.get("provider_id");
    if (!Atmo.maintenances.in_maintenance(identity_provider_id)) {
      this.main.show_instance_screen();
      Atmo.instances.on('reset', function (collection) {
        if (!collection.isEmpty() && !collection.selected_instance)
          collection.select_instance(collection.at(0));
      });
      // Hide all help tips so none remain after navigating away from it
      Atmo.Utils.hide_all_help();
    }
  },
  volumes: function () {
    var identity = Atmo.profile.get('selected_identity');
    var identity_provider_id = identity.get("provider_id");
    if (!Atmo.maintenances.in_maintenance(identity_provider_id)) {
      this.main.show_volume_screen();
      // Hide all help tips so none remain after navigating away from it
      Atmo.Utils.hide_all_help();
    }
  },
  new_instance: function (options) {
    this.main.show_new_instance_screen();
    // Hide all help tips so none remain after navigating away from it
    Atmo.Utils.hide_all_help();
  },
  settings: function () {
    this.main.show_settings_screen();
  },
  select_instance: function (instance_id) {
    this.instances();
    var instance;
    if (instance = Atmo.instances.get(instance_id))
      Atmo.instances.select_instance(instance);
  },
  select_volume: function (volume_id) {
    var volume = Atmo.volumes.get(volume_id);
    if (volume)
      Atmo.volumes.select_volume(volume);
    //console.log(volume_id);
  },
  select_image: function (image_query) {
    if (this.new_instance_screen)
      this.new_instance_screen.set_query(image_query);
    else
      this.new_instance({'query': image_query});
  }
});

$(document).ready(function () {
  window.app = new Atmo.Router();
  Backbone.history.start();

  var identity = Atmo.profile.get('selected_identity');
  var identity_provider_id = identity.get("provider_id");
  if (!Atmo.maintenances.in_maintenance(identity_provider_id)) {
    Atmo.instance_types.fetch({async: false});
    Atmo.instances.fetch();
    Atmo.volumes.fetch();
    Atmo.images.fetch();
  }
});
<commit_msg>fix version display issue on airport<commit_after>/* Router: maps hash navigation */

$.ajaxSetup({
  headers: {
    "Authorization": "Token " + window.access_token,
    "Content-Type": "application/json"
  }
});

Atmo.Router = Backbone.Router.extend({
  routes: {
    "": "instances",
    "instances": "instances",
    "instances/:instance_id": "select_instance",
    "volumes": "volumes",
    "volumes/:volume_id": "select_volume",
    "new_instance": "new_instance",
    "new_instance/:image_query": "select_image",
    "settings": "settings"
  },
  initialize: function () {
    Atmo.profile = new Atmo.Models.Profile();
    Atmo.profile.fetch({
      async: false,
      success: function (profile, foo, bar) {
        $("#username").html(profile.get('id'));
      },
      error: function () {
        //TODO: Jason's awesome replacement screen goes here
        //TODO: Find a gnome.
        //window.location.replace(site_root + "/login");
      }
    });
    Atmo.Utils.update_weather();
    Atmo.providers = new Atmo.Collections.Providers();
    Atmo.providers.fetch({
      async: false,
      success: function (providers, foo, bar) {
      }
    });
    Atmo.identities = new Atmo.Collections.Identities();
    Atmo.identities.fetch({
      async: false
    });

    var identity = Atmo.profile.get('selected_identity');
    var identity_provider_id = identity.get("provider_id");

    Atmo.maintenances = new Atmo.Collections.Maintenances();
    Atmo.maintenances.fetch({
      async: false
    });
    Atmo.instances = new Atmo.Collections.Instances();
    Atmo.volumes = new Atmo.Collections.Volumes();
    Atmo.images = new Atmo.Collections.Machines();
    if (Atmo.profile.get('is_staff') === true) {
      Atmo.instance_hypervisors = new Atmo.Collections.Hypervisors();
      Atmo.instance_hypervisors.fetch({async: false});
    }
    Atmo.instance_types = new Atmo.Collections.Sizes();

    Atmo.notifications = new Atmo.Collections.Notifications();

    this.main = new Atmo.Views.Main({el: $('#main')[0]}).render();
    new Atmo.Views.Sidebar({el: $('#menu_wrapper')}).render();

    setInterval(function () {
      $('#refresh_instances_button').click();
    }, 5 * 60 * 1000);

    new Atmo.Views.FeedbackLink({el: $('#feedback_link')[0]});
    Atmo.request_resources_modal = new Atmo.Views.RequestResourcesModal();
    $('body').append(Atmo.request_resources_modal.render().el);

    Atmo.alert_modal = new Atmo.Views.AlertModal();
    $('body').append(Atmo.alert_modal.render().el);

    // Populate the top menu with a provider switcher
    for (var i = 0; i < Atmo.identities.length; i++) {
      var identity = Atmo.identities.models[i];
      var identity_provider_id = identity.get('provider_id');
      var in_maintenance = Atmo.maintenances.in_maintenance(identity_provider_id);
      var result = '';
      var name = Atmo.identities.models[i].get('provider').get('location');
      $('#providers_menu').append($('
', {
        html: function () {
          if (identity.get('selected')) {
            result = ' ' + name;
          } else {
            result = '' + name;
          }
          if (in_maintenance) {
            result += ' ';
          }
          result += '';
          return result;
        },
        click: function (e) {
          e.preventDefault();
          var identity = $(this).data();
          if (in_maintenance) {
            Atmo.Utils.notify('Error', identity.get('provider').get('type') + ' is currently in maintenance.');
            return false;
          }
          if (identity.get('selected')) {
            Atmo.Utils.notify('Error', 'You are already using ' + identity.get('provider').get('type') + ' as your provider.');
            return false;
          }
          else {
            Atmo.profile.save({'selected_identity': identity.get('id')},
              {'async': false,
                'patch': true,
                success: location.reload()});
          }
        }
      }).data(identity));
    }

    $('#contact_support').click(function (e) {
      e.preventDefault();
      $('#feedback_link').trigger('click');
    });
    $.ajax({
      type: 'GET',
      url: site_root + '/api/v1/version',
      statusCode: {
        200: function (response) {
          $('#version').html(''
            + new Date(response['commit_date']).toString("F") + ' '
            + '(' + response['git_sha_abbrev'] + ')');
        }
      }
    });
    $('#total_cpu_time a').click(function () {
      $('#cpu_modal').modal('show');
    });
    new Atmo.Views.NotificationHolder({el: $('#alert_holder')[0]});
  },
  instances: function () {
    var identity = Atmo.profile.get('selected_identity');
    var identity_provider_id = identity.get("provider_id");
    if (!Atmo.maintenances.in_maintenance(identity_provider_id)) {
      this.main.show_instance_screen();
      Atmo.instances.on('reset', function (collection) {
        if (!collection.isEmpty() && !collection.selected_instance)
          collection.select_instance(collection.at(0));
      });
      // Hide all help tips so none remain after navigating away from it
      Atmo.Utils.hide_all_help();
    }
  },
  volumes: function () {
    var identity = Atmo.profile.get('selected_identity');
    var identity_provider_id = identity.get("provider_id");
    if (!Atmo.maintenances.in_maintenance(identity_provider_id)) {
      this.main.show_volume_screen();
      // Hide all help tips so none remain after navigating away from it
      Atmo.Utils.hide_all_help();
    }
  },
  new_instance: function (options) {
    this.main.show_new_instance_screen();
    // Hide all help tips so none remain after navigating away from it
    Atmo.Utils.hide_all_help();
  },
  settings: function () {
    this.main.show_settings_screen();
  },
  select_instance: function (instance_id) {
    this.instances();
    var instance;
    if (instance = Atmo.instances.get(instance_id))
      Atmo.instances.select_instance(instance);
  },
  select_volume: function (volume_id) {
    var volume = Atmo.volumes.get(volume_id);
    if (volume)
      Atmo.volumes.select_volume(volume);
    //console.log(volume_id);
  },
  select_image: function (image_query) {
    if (this.new_instance_screen)
      this.new_instance_screen.set_query(image_query);
    else
      this.new_instance({'query': image_query});
  }
});

$(document).ready(function () {
  window.app = new Atmo.Router();
  Backbone.history.start();

  var identity = Atmo.profile.get('selected_identity');
  var identity_provider_id = identity.get("provider_id");
  if (!Atmo.maintenances.in_maintenance(identity_provider_id)) {
    Atmo.instance_types.fetch({async: false});
    Atmo.instances.fetch();
    Atmo.volumes.fetch();
    Atmo.images.fetch();
  }
});
<|endoftext|>


<commit_before>var RestoreViewMixin = {
    restoreView: function () {
        var storage = window.localStorage || {};
        if (!this.__initRestore) {
            this.on('moveend', function (e) {
                if (!this._loaded)
                    return;  // Never access map bounds if view is not set.

                var view = {
                    lat: this.getCenter().lat,
                    lng: this.getCenter().lng,
                    zoom: this.getZoom()
                };
                storage['mapView'] = JSON.stringify(view);
            }, this);
            this.__initRestore = true;
        }

        var view = storage['mapView'];
        try {
            view = JSON.parse(view || '');
            this.setView(L.latLng(view.lat, view.lng), view.zoom, true);
            return true;
        }
        catch (err) {
            return false;
        }
    },
};

L.Map.include(RestoreViewMixin);
<commit_msg>Remove trailing commas for IE<commit_after>var RestoreViewMixin = {
    restoreView: function () {
        var storage = window.localStorage || {};
        if (!this.__initRestore) {
            this.on('moveend', function (e) {
                if (!this._loaded)
                    return;  // Never access map bounds if view is not set.

                var view = {
                    lat: this.getCenter().lat,
                    lng: this.getCenter().lng,
                    zoom: this.getZoom()
                };
                storage['mapView'] = JSON.stringify(view);
            }, this);
            this.__initRestore = true;
        }

        var view = storage['mapView'];
        try {
            view = JSON.parse(view || '');
            this.setView(L.latLng(view.lat, view.lng), view.zoom, true);
            return true;
        }
        catch (err) {
            return false;
        }
    }
};

L.Map.include(RestoreViewMixin);
<|endoftext|>


<commit_before>this.GobiertoAdmin.DynamicContentComponent = (function() {
  function DynamicContentComponent() {}

  DynamicContentComponent.prototype.handle = function(wrapper, namespace) {
    initializeRecordFields(wrapper);
    handleAddChild(wrapper, namespace);
    handleAddRecord();
    handleCancelRecord();
    handleEditRecord();
    handleDeleteRecord();
  };

  function initializeRecordFields(wrapper) {
    var componentWrapper = $(wrapper || ".dynamic-content-wrapper");
    var componentLocale = componentWrapper.data("locale");

    _handleGeocompleteBehavior(componentWrapper.find("input[data-behavior=geocomplete]"));
    _handleDateType(componentWrapper.find("input[data-type=date]"), componentLocale);
    _handleCurrencyType(componentWrapper.find("input[data-type=currency]"));
  }

  function handleAddChild(wrapper, namespace) {
    var componentWrapper = $(wrapper || ".dynamic-content-wrapper");
    var componentLocale = componentWrapper.data("locale");

    componentWrapper.on("click", "[data-behavior=add_child]", function(e) {
      e.preventDefault();

      var eventWrapper = $(this).closest(".dynamic-content-wrapper");
      var recordTemplate = eventWrapper.find(".dynamic-content-record-wrapper:visible:last");

      var fieldNameRegExp = new RegExp("\\[" + namespace + "\\]\\[\\d+\\]", "i");
      var fieldIdRegExp = new RegExp("_" + namespace + "_\\d+", "i");
      var contentBlockRecordRegExp = new RegExp("content-block-record-\\d+", "i");
      var randomId = new Date().getTime();
      var uniqueFieldName = "[" + namespace + "][" + randomId + "]";
      var uniqueFieldId = "_" + namespace + "_" + randomId;

      var clonedField = $(recordTemplate)
        .clone()
        .addClass("cloned-dynamic-content-record-wrapper")
        .removeClass(function() {
          var contentBlockRecordClass;

          $.each($(this).attr("class").split(" "), function(_, value) {
            if (contentBlockRecordRegExp.test(value)) {
              contentBlockRecordClass = value;
              return false;
            }
          });

          return contentBlockRecordClass;
        });

      clonedField.find("input, textarea, select").each(function() {
        var fieldName = $(this).attr("name");
        var fieldId = $(this).attr("id");

        if (fieldName !== undefined) {
          $(this).attr("name", fieldName.replace(fieldNameRegExp, uniqueFieldName));
        }

        if (fieldId !== undefined) {
          $(this).attr("id", fieldId.replace(fieldIdRegExp, uniqueFieldId));
        }

        _cleanupRecordField($(this));
        _initializeRecordField($(this), componentLocale);
      });

      clonedField.find("label").each(function() {
        var labelFor = $(this).attr("for");

        $(this).attr("for", labelFor.replace(fieldIdRegExp, uniqueFieldId));
      });

      _switchToRecordForm(clonedField);

      $(recordTemplate).after(clonedField);
    });
  }

  function handleCancelRecord() {
    var componentWrapper = $(".dynamic-content-wrapper");

    componentWrapper.on("click", "[data-behavior=cancel_record]", function(e) {
      e.preventDefault();

      $(this).closest(".cloned-dynamic-content-record-wrapper").remove();

      var eventWrapper = $(this).closest(".dynamic-content-record-wrapper");

      _setRecordFormState(eventWrapper);
      _switchToRecordView(eventWrapper);
    });
  }

  function handleEditRecord() {
    var componentWrapper = $(".dynamic-content-wrapper");

    componentWrapper.on("click", "[data-behavior=edit_record]", function(e) {
      e.preventDefault();

      var eventWrapper = $(this).closest(".dynamic-content-record-wrapper");

      _switchToRecordForm(eventWrapper);
    });
  }

  function handleDeleteRecord() {
    var componentWrapper = $(".dynamic-content-wrapper");

    componentWrapper.on("click", "[data-behavior=delete_record]", function(e) {
      e.preventDefault();

      var eventWrapper = $(this).closest(".dynamic-content-record-wrapper");
      var deleteFlag = eventWrapper.find("input.destroy-content-block-record");

      deleteFlag.prop("checked", true);
      eventWrapper.hide();
    });
  }

  function handleAddRecord() {
    var componentWrapper = $(".dynamic-content-wrapper");

    componentWrapper.on("click", "[data-behavior=add_record]", function(e) {
      e.preventDefault();

      var eventWrapper = $(this).closest(".dynamic-content-record-wrapper");

      _setRecordViewState(eventWrapper);
      _switchToRecordView(eventWrapper);
    });
  }

  function _cleanupRecordField(selector) {
    if (selector.attr("type") === "text") {
      selector.val("");
    } else if (selector.attr("type") === "select") {
      selector.find("option:selected").prop("selected", false);
    }
  }

  function _initializeRecordField(selector, locale) {
    if (selector.data("behavior") === "geocomplete") {
      _handleGeocompleteBehavior(selector);
    }

    if (selector.data("type") === "date") {
      _handleDateType(selector, locale);
    }

    if (selector.data("type") === "currency") {
      _handleCurrencyType(selector);
    }
  }

  function _handleGeocompleteBehavior(selector) {
    selector.geocomplete({
      details: ".content-block-field",
      detailsAttribute: "data-geo",
      componentRestrictions: { country: "es" }
    });
  }

  function _handleDateType(selector, locale) {
    selector.datepicker({
      language: locale,
      autoClose: true
    });
  }

  function _handleCurrencyType(selector) {
    selector.attr("type", "number");
  }

  function _switchToRecordForm(wrapper) {
    wrapper.find(".dynamic-content-record-view").hide();
    wrapper.find(".dynamic-content-record-form").show();
  }

  function _switchToRecordView(wrapper) {
    wrapper.find(".dynamic-content-record-form").hide();
    wrapper.find(".dynamic-content-record-view").show();
  }

  function _setRecordViewState(wrapper) {
    var formState = wrapper.find(".content-block-field input, select option:selected").map(function() {
      return $(this).text() || $(this).val();
    });

    wrapper.find(".dynamic-content-record-view .content-block-record-value").each(function(index) {
      $(this).html(formState[index]);
    });
  }

  function _setRecordFormState(wrapper) {
    var viewState = wrapper.find(".dynamic-content-record-view .content-block-record-value").map(function() {
      return $(this).html();
    });

    wrapper.find(".content-block-field input").each(function(index) {
      $(this).val(viewState[index]);
    });
  }

  return DynamicContentComponent;
})();

this.GobiertoAdmin.dynamic_content_component = new GobiertoAdmin.DynamicContentComponent;
<commit_msg>Set focus on first input when adding or editing a content block record<commit_after>this.GobiertoAdmin.DynamicContentComponent = (function() {
  function DynamicContentComponent() {}

  DynamicContentComponent.prototype.handle = function(wrapper, namespace) {
    initializeRecordFields(wrapper);
    handleAddChild(wrapper, namespace);
    handleAddRecord();
    handleCancelRecord();
    handleEditRecord();
    handleDeleteRecord();
  };

  function initializeRecordFields(wrapper) {
    var componentWrapper = $(wrapper || ".dynamic-content-wrapper");
    var componentLocale = componentWrapper.data("locale");

    _handleGeocompleteBehavior(componentWrapper.find("input[data-behavior=geocomplete]"));
    _handleDateType(componentWrapper.find("input[data-type=date]"), componentLocale);
    _handleCurrencyType(componentWrapper.find("input[data-type=currency]"));
  }

  function handleAddChild(wrapper, namespace) {
    var componentWrapper = $(wrapper || ".dynamic-content-wrapper");
    var componentLocale = componentWrapper.data("locale");

    componentWrapper.on("click", "[data-behavior=add_child]", function(e) {
      e.preventDefault();

      var eventWrapper = $(this).closest(".dynamic-content-wrapper");
      var recordTemplate = eventWrapper.find(".dynamic-content-record-wrapper:visible:last");

      var fieldNameRegExp = new RegExp("\\[" + namespace + "\\]\\[\\d+\\]", "i");
      var fieldIdRegExp = new RegExp("_" + namespace + "_\\d+", "i");
      var contentBlockRecordRegExp = new RegExp("content-block-record-\\d+", "i");
      var randomId = new Date().getTime();
      var uniqueFieldName = "[" + namespace + "][" + randomId + "]";
      var uniqueFieldId = "_" + namespace + "_" + randomId;

      var clonedField = $(recordTemplate)
        .clone()
        .addClass("cloned-dynamic-content-record-wrapper")
        .removeClass(function() {
          var contentBlockRecordClass;

          $.each($(this).attr("class").split(" "), function(_, value) {
            if (contentBlockRecordRegExp.test(value)) {
              contentBlockRecordClass = value;
              return false;
            }
          });

          return contentBlockRecordClass;
        });

      clonedField.find("input, textarea, select").each(function() {
        var fieldName = $(this).attr("name");
        var fieldId = $(this).attr("id");

        if (fieldName !== undefined) {
          $(this).attr("name", fieldName.replace(fieldNameRegExp, uniqueFieldName));
        }

        if (fieldId !== undefined) {
          $(this).attr("id", fieldId.replace(fieldIdRegExp, uniqueFieldId));
        }

        _cleanupRecordField($(this));
        _initializeRecordField($(this), componentLocale);
      });

      clonedField.find("label").each(function() {
        var labelFor = $(this).attr("for");

        $(this).attr("for", labelFor.replace(fieldIdRegExp, uniqueFieldId));
      });

      _switchToRecordForm(clonedField);

      $(recordTemplate).after(clonedField);

      clonedField.find("input:visible:first").focus();
    });
  }

  function handleCancelRecord() {
    var componentWrapper = $(".dynamic-content-wrapper");

    componentWrapper.on("click", "[data-behavior=cancel_record]", function(e) {
      e.preventDefault();

      $(this).closest(".cloned-dynamic-content-record-wrapper").remove();

      var eventWrapper = $(this).closest(".dynamic-content-record-wrapper");

      _setRecordFormState(eventWrapper);
      _switchToRecordView(eventWrapper);
    });
  }

  function handleEditRecord() {
    var componentWrapper = $(".dynamic-content-wrapper");

    componentWrapper.on("click", "[data-behavior=edit_record]", function(e) {
      e.preventDefault();

      var eventWrapper = $(this).closest(".dynamic-content-record-wrapper");

      _switchToRecordForm(eventWrapper);
    });
  }

  function handleDeleteRecord() {
    var componentWrapper = $(".dynamic-content-wrapper");

    componentWrapper.on("click", "[data-behavior=delete_record]", function(e) {
      e.preventDefault();

      var eventWrapper = $(this).closest(".dynamic-content-record-wrapper");
      var deleteFlag = eventWrapper.find("input.destroy-content-block-record");

      deleteFlag.prop("checked", true);
      eventWrapper.hide();
    });
  }

  function handleAddRecord() {
    var componentWrapper = $(".dynamic-content-wrapper");

    componentWrapper.on("click", "[data-behavior=add_record]", function(e) {
      e.preventDefault();

      var eventWrapper = $(this).closest(".dynamic-content-record-wrapper");

      _setRecordViewState(eventWrapper);
      _switchToRecordView(eventWrapper);
    });
  }

  function _cleanupRecordField(selector) {
    if (selector.attr("type") === "text") {
      selector.val("");
    } else if (selector.attr("type") === "select") {
      selector.find("option:selected").prop("selected", false);
    }
  }

  function _initializeRecordField(selector, locale) {
    if (selector.data("behavior") === "geocomplete") {
      _handleGeocompleteBehavior(selector);
    }

    if (selector.data("type") === "date") {
      _handleDateType(selector, locale);
    }

    if (selector.data("type") === "currency") {
      _handleCurrencyType(selector);
    }
  }

  function _handleGeocompleteBehavior(selector) {
    selector.geocomplete({
      details: ".content-block-field",
      detailsAttribute: "data-geo",
      componentRestrictions: { country: "es" }
    });
  }

  function _handleDateType(selector, locale) {
    selector.datepicker({
      language: locale,
      autoClose: true
    });
  }

  function _handleCurrencyType(selector) {
    selector.attr("type", "number");
  }

  function _switchToRecordForm(wrapper) {
    wrapper.find(".dynamic-content-record-view").hide();
    wrapper.find(".dynamic-content-record-form").show();
    wrapper.find(".dynamic-content-record-form input:visible:first").focus();
  }

  function _switchToRecordView(wrapper) {
    wrapper.find(".dynamic-content-record-form").hide();
    wrapper.find(".dynamic-content-record-view").show();
  }

  function _setRecordViewState(wrapper) {
    var formState = wrapper.find(".content-block-field input, select option:selected").map(function() {
      return $(this).text() || $(this).val();
    });

    wrapper.find(".dynamic-content-record-view .content-block-record-value").each(function(index) {
      $(this).html(formState[index]);
    });
  }

  function _setRecordFormState(wrapper) {
    var viewState = wrapper.find(".dynamic-content-record-view .content-block-record-value").map(function() {
      return $(this).html();
    });

    wrapper.find(".content-block-field input").each(function(index) {
      $(this).val(viewState[index]);
    });
  }

  return DynamicContentComponent;
})();

this.GobiertoAdmin.dynamic_content_component = new GobiertoAdmin.DynamicContentComponent;
<|endoftext|>


<commit_before>
/*
 * == BSD2 LICENSE ==
 * Copyright (c) 2014, Tidepool Project
 *
 * This program is free software; you can redistribute it and/or modify it under
 * the terms of the associated License, which is identical to the BSD 2-Clause
 * License as published by the Open Source Initiative at opensource.org.
 *
 * This program is distributed in the hope that it will be useful, but WITHOUT
 * ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS
 * FOR A PARTICULAR PURPOSE. See the License for more details.
 *
 * You should have received a copy of the License along with this program; if
 * not, you can obtain one from Tidepool Project at tidepool.org.
 * == BSD2 LICENSE ==
 */

var _ = require('lodash');
var moment = require('moment-timezone');

var datetime = {

  APPEND: 'T00:00:00.000Z',

  MS_IN_24: 86400000,

  addDays: function(s, n) {
    var d = moment(s);
    d.add(n, 'days');
    return d.toISOString();
  },

  addDuration: function(datetime, duration) {
    datetime = new Date(datetime);

    return new Date(datetime.valueOf() + duration).toISOString();
  },

  adjustToInnerEndpoints: function(s, e, endpoints) {
    if (!endpoints) {
      return null;
    }
    var start = new Date(s).valueOf(), end = new Date(e).valueOf();
    var thisTypeStart = new Date(endpoints[0]).valueOf(), thisTypeEnd = new Date(endpoints[1]).valueOf();
    if (start < thisTypeStart) {
      return [thisTypeStart, end];
    }
    else if (end > thisTypeEnd) {
      return [start, thisTypeEnd];
    }
    else {
      return [start, end];
    }
  },

  applyOffset: function(d, offset) {
    var date = new Date(d);
    date.setUTCMinutes(date.getUTCMinutes() + offset);
    return new Date(date).toISOString();
  },

  checkIfDateInRange: function(s, endpoints) {
    var d = new Date(s);
    var start = new Date(endpoints[0]);
    var end = new Date(endpoints[1]);
    if ((d.valueOf() >= start.valueOf()) && (d.valueOf() <= end.valueOf())) {
      return true;
    }
    else {
      return false;
    }
  },

  checkIfUTCDate: function(s) {
    var d = new Date(s);
    if (typeof s === 'number') {
      if (d.getUTCFullYear() < 2008) {
        return false;
      }
      else {
        return true;
      }
    }
    else if (s.slice(s.length - 1, s.length) !== 'Z') {
      return false;
    }
    else {
      if (s === d.toISOString()) {
        return true;
      }
      else {
        return false;
      }
    }
  },

  composeMsAndDateString: function(ms, d) {
    return new Date(ms + new Date(this.toISODateString(d) + this.APPEND).valueOf()).toISOString();
  },

  difference: function(d2, d1) {
    return new Date(d2) - new Date(d1);
  },

  findBasicsDays: function(range, timezone) {
    timezone = timezone || 'UTC';
    var days = [];
    var currentDate = moment.utc(range[0]).tz(timezone).toDate();
    var dateOfUpload = moment.utc(range[1]).tz(timezone).format('YYYY-MM-DD');
    while (currentDate < moment.utc(range[1]).tz(timezone).endOf('isoWeek')) {
      var date = moment.utc(currentDate).tz(timezone).format('YYYY-MM-DD');
      var dateObj = {date: date};
      if (date < dateOfUpload) {
        dateObj.type = 'past';
      }
      else if (date === dateOfUpload) {
        dateObj.type = 'mostRecent';
      }
      else {
        dateObj.type = 'future';
      }
      days.push(dateObj);
      currentDate = moment.utc(currentDate).tz(timezone).add(1, 'days').toDate();
    }
    return days;
  },

  findBasicsStart: function(timestamp, timezone) {
    timezone = timezone || 'UTC';
    return moment(Date.parse(timestamp)).tz(timezone)
      .startOf('isoWeek')
      .subtract(14, 'days')
      .toDate().toISOString();
  },

  getBrowserTimezone: function() {
    return new Intl.DateTimeFormat().resolvedOptions().timeZone;
  },

  getDuration: function(d1, d2) {
    return new Date(d2).valueOf() - new Date(d1).valueOf();
  },

  getLocalDate: function(d, timezoneName) {
    timezoneName = timezoneName || 'UTC';
    return moment.utc(d).tz(timezoneName).format('YYYY-MM-DD');
  },

  getLocalDayOfWeek: function(d, timezoneName) {
    timezoneName = timezoneName || 'UTC';
    return this.weekdayLookup(moment.utc(d).tz(timezoneName).day());
  },

  getMidnight: function(d, next) {
    if (next) {
      return this.getMidnight(this.addDays(d, 1));
    }
    else {
      return this.toISODateString(d) + this.APPEND;
    }
  },

  getMsFromMidnight: function(d) {
    var midnight = new Date(this.getMidnight(d)).valueOf();
    return new Date(d).valueOf() - midnight;
  },

  // this does basically the same as above method
  // but I don't want to take the time right now to consolidate them
  // and make sure all uses of former are covered by latter
  getMsPer24: function(d, timezoneName) {
    timezoneName = timezoneName || 'UTC';
    var localized = moment.utc(d).tz(timezoneName);
    var total;
    var hrsToMs = localized.hours() * 1000 * 60 * 60;
    var minToMs = localized.minutes() * 1000 * 60;
    var secToMs = localized.seconds() * 1000;
    var ms = localized.milliseconds();
    return hrsToMs + minToMs + secToMs + ms;
  },

  getLocalizedCeiling: function(utc, timezone) {
    if (utc instanceof Date) {
      throw new Error('`utc` must be a ISO-formatted String timestamp or integer hammertime!');
    }

    var startOfDay = moment.utc(utc)
      .tz(timezone)
      .startOf('day');

    var utcHammertime = (typeof utc === 'string') ? Date.parse(utc) : utc;
    if (startOfDay.valueOf() === utcHammertime) {
      return startOfDay.toDate();
    }
    return startOfDay.add(1, 'day').valueOf();
  },

  getOffset: function(d, timezoneName) {
    return moment.tz.zone(timezoneName).utcOffset(Date.parse(d));
  },

  getNumDays: function(s, e) {
    var start = new Date(s).valueOf(), end = new Date(e).valueOf();
    return Math.ceil((end - start)/this.MS_IN_24);
  },

  getUTCOfLocalPriorMidnight: function(d, timezoneName) {
    timezoneName = timezoneName || 'UTC';
    var local = moment.utc(d).tz(timezoneName);
    return local.startOf('day').toDate().toISOString();
  },

  getUTCOfLocalNextMidnight: function(d, timezoneName) {
    timezoneName = timezoneName || 'UTC';
    var local = moment.utc(d).tz(timezoneName);
    return new Date(local.endOf('day').valueOf() + 1).toISOString();
  },

  isATimestamp: function(s) {
    if (isNaN(Date.parse(s))) {
      return false;
    }
    else {
      return true;
    }
  },

  isLessThanTwentyFourHours: function(s, e) {
    var start = new Date(s).valueOf(), end = new Date(e).valueOf();
    if (end - start < this.MS_IN_24) {
      return true;
    }
    else { return false; }
  },

  isNearRightEdge: function(d, edge) {
    // check if d.normalTime is within six hours before edge
    var t = new Date(d.normalTime);
    if (edge.valueOf() - t.valueOf() < this.MS_IN_24/4) {
      return true;
    }
    return false;
  },

  isSegmentAcrossMidnight: function(s, e) {
    var start = new Date(s), end = new Date(e);
    var startDate = this.toISODateString(s), endDate = this.toISODateString(e);
    if (startDate === endDate) {
      return false;
    }
    else {
      if (end.getUTCDate() === start.getUTCDate() + 1) {
        if (this.getMidnight(e) === e) {
          return false;
        }
        return true;
      }
      else {
        return false;
      }
    }
  },

  isTwentyFourHours: function(s, e) {
    var start = new Date(s).valueOf(), end = new Date(e).valueOf();
    if (end - start === this.MS_IN_24) {
      return true;
    }
    else { return false; }
  },

  roundToNearestMinutes: function(d, resolution) {
    var date = new Date(d);
    var min = date.getUTCMinutes();
    var values = _.range(0, 60, resolution);
    for (var i = 0; i < values.length; ++i) {
      if (min - values[i] < resolution/2) {
        date.setUTCMinutes(values[i]);
        return date.toISOString();
      }
      else if (i === values.length - 1) {
        date.setUTCMinutes(0);
        date.setUTCHours(date.getUTCHours() + 1);
        return date.toISOString();
      }
    }
  },

  toISODateString: function(d) {
    var date = new Date(d);
    return date.toISOString().slice(0,10);
  },

  smbgEdge: function(d, offset) {
    var date = offset ? new Date(this.applyOffset(d, offset)) : new Date(d);
    if (date.getUTCHours() <= 2) {
      return 'left';
    }
    else if (date.getUTCHours() >= 21) {
      return 'right';
    }
    else {
      return null;
    }
  },

  verifyEndpoints: function(s, e, endpoints) {
    if (!endpoints) {
      return null;
    }
    if (this.checkIfUTCDate(s) && this.checkIfUTCDate(e)) {
      endpoints = this.adjustToInnerEndpoints(s, e, endpoints);
      s = endpoints[0];
      e = endpoints[1];
      if (this.checkIfDateInRange(s, endpoints) && this.checkIfDateInRange(e, endpoints)) {
        return true;
      }
      else {
        return false;
      }
    }
    else {
      return false;
    }
  },

  weekdayLookup: function(n) {
    if (n < 0 || n > 6) {
      return null;
    }
    var weekdays = {
      0: 'sunday',
      1: 'monday',
      2: 'tuesday',
      3: 'wednesday',
      4: 'thursday',
      5: 'friday',
      6: 'saturday'
    };
    return weekdays[n];
  }
};

module.exports = datetime;
<commit_msg>Fix most recent basics day calc<commit_after>
/*
 * == BSD2 LICENSE ==
 * Copyright (c) 2014, Tidepool Project
 *
 * This program is free software; you can redistribute it and/or modify it under
 * the terms of the associated License, which is identical to the BSD 2-Clause
 * License as published by the Open Source Initiative at opensource.org.
 *
 * This program is distributed in the hope that it will be useful, but WITHOUT
 * ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS
 * FOR A PARTICULAR PURPOSE. See the License for more details.
 *
 * You should have received a copy of the License along with this program; if
 * not, you can obtain one from Tidepool Project at tidepool.org.
 * == BSD2 LICENSE ==
 */

var _ = require('lodash');
var moment = require('moment-timezone');

var datetime = {

  APPEND: 'T00:00:00.000Z',

  MS_IN_24: 86400000,

  addDays: function(s, n) {
    var d = moment(s);
    d.add(n, 'days');
    return d.toISOString();
  },

  addDuration: function(datetime, duration) {
    datetime = new Date(datetime);

    return new Date(datetime.valueOf() + duration).toISOString();
  },

  adjustToInnerEndpoints: function(s, e, endpoints) {
    if (!endpoints) {
      return null;
    }
    var start = new Date(s).valueOf(), end = new Date(e).valueOf();
    var thisTypeStart = new Date(endpoints[0]).valueOf(), thisTypeEnd = new Date(endpoints[1]).valueOf();
    if (start < thisTypeStart) {
      return [thisTypeStart, end];
    }
    else if (end > thisTypeEnd) {
      return [start, thisTypeEnd];
    }
    else {
      return [start, end];
    }
  },

  applyOffset: function(d, offset) {
    var date = new Date(d);
    date.setUTCMinutes(date.getUTCMinutes() + offset);
    return new Date(date).toISOString();
  },

  checkIfDateInRange: function(s, endpoints) {
    var d = new Date(s);
    var start = new Date(endpoints[0]);
    var end = new Date(endpoints[1]);
    if ((d.valueOf() >= start.valueOf()) && (d.valueOf() <= end.valueOf())) {
      return true;
    }
    else {
      return false;
    }
  },

  checkIfUTCDate: function(s) {
    var d = new Date(s);
    if (typeof s === 'number') {
      if (d.getUTCFullYear() < 2008) {
        return false;
      }
      else {
        return true;
      }
    }
    else if (s.slice(s.length - 1, s.length) !== 'Z') {
      return false;
    }
    else {
      if (s === d.toISOString()) {
        return true;
      }
      else {
        return false;
      }
    }
  },

  composeMsAndDateString: function(ms, d) {
    return new Date(ms + new Date(this.toISODateString(d) + this.APPEND).valueOf()).toISOString();
  },

  difference: function(d2, d1) {
    return new Date(d2) - new Date(d1);
  },

  findBasicsDays: function(range, timezone) {
    timezone = timezone || 'UTC';
    var days = [];
    var currentDate = moment.utc(range[0]).tz(timezone).toDate();
    var dateOfUpload = moment.utc(range[1]).subtract(1, 'ms').tz(timezone).format('YYYY-MM-DD');
    while (currentDate < moment.utc(range[1]).subtract(1, 'ms').tz(timezone).endOf('isoWeek')) {
      var date = moment.utc(currentDate).tz(timezone).format('YYYY-MM-DD');
      var dateObj = {date: date};
      if (date < dateOfUpload) {
        dateObj.type = 'past';
      }
      else if (date === dateOfUpload) {
        dateObj.type = 'mostRecent';
      }
      else {
        dateObj.type = 'future';
      }
      days.push(dateObj);
      currentDate = moment.utc(currentDate).tz(timezone).add(1, 'days').toDate();
    }
    return days;
  },

  findBasicsStart: function(timestamp, timezone) {
    timezone = timezone || 'UTC';
    return moment(Date.parse(timestamp)).tz(timezone)
      .startOf('isoWeek')
      .subtract(14, 'days')
      .toDate().toISOString();
  },

  getBrowserTimezone: function() {
    return new Intl.DateTimeFormat().resolvedOptions().timeZone;
  },

  getDuration: function(d1, d2) {
    return new Date(d2).valueOf() - new Date(d1).valueOf();
  },

  getLocalDate: function(d, timezoneName) {
    timezoneName = timezoneName || 'UTC';
    return moment.utc(d).tz(timezoneName).format('YYYY-MM-DD');
  },

  getLocalDayOfWeek: function(d, timezoneName) {
    timezoneName = timezoneName || 'UTC';
    return this.weekdayLookup(moment.utc(d).tz(timezoneName).day());
  },

  getMidnight: function(d, next) {
    if (next) {
      return this.getMidnight(this.addDays(d, 1));
    }
    else {
      return this.toISODateString(d) + this.APPEND;
    }
  },

  getMsFromMidnight: function(d) {
    var midnight = new Date(this.getMidnight(d)).valueOf();
    return new Date(d).valueOf() - midnight;
  },

  // this does basically the same as above method
  // but I don't want to take the time right now to consolidate them
  // and make sure all uses of former are covered by latter
  getMsPer24: function(d, timezoneName) {
    timezoneName = timezoneName || 'UTC';
    var localized = moment.utc(d).tz(timezoneName);
    var total;
    var hrsToMs = localized.hours() * 1000 * 60 * 60;
    var minToMs = localized.minutes() * 1000 * 60;
    var secToMs = localized.seconds() * 1000;
    var ms = localized.milliseconds();
    return hrsToMs + minToMs + secToMs + ms;
  },

  getLocalizedCeiling: function(utc, timezone) {
    if (utc instanceof Date) {
      throw new Error('`utc` must be a ISO-formatted String timestamp or integer hammertime!');
    }

    var startOfDay = moment.utc(utc)
      .tz(timezone)
      .startOf('day');

    var utcHammertime = (typeof utc === 'string') ? Date.parse(utc) : utc;
    if (startOfDay.valueOf() === utcHammertime) {
      return startOfDay.toDate();
    }
    return startOfDay.add(1, 'day').valueOf();
  },

  getOffset: function(d, timezoneName) {
    return moment.tz.zone(timezoneName).utcOffset(Date.parse(d));
  },

  getNumDays: function(s, e) {
    var start = new Date(s).valueOf(), end = new Date(e).valueOf();
    return Math.ceil((end - start)/this.MS_IN_24);
  },

  getUTCOfLocalPriorMidnight: function(d, timezoneName) {
    timezoneName = timezoneName || 'UTC';
    var local = moment.utc(d).tz(timezoneName);
    return local.startOf('day').toDate().toISOString();
  },

  getUTCOfLocalNextMidnight: function(d, timezoneName) {
    timezoneName = timezoneName || 'UTC';
    var local = moment.utc(d).tz(timezoneName);
    return new Date(local.endOf('day').valueOf() + 1).toISOString();
  },

  isATimestamp: function(s) {
    if (isNaN(Date.parse(s))) {
      return false;
    }
    else {
      return true;
    }
  },

  isLessThanTwentyFourHours: function(s, e) {
    var start = new Date(s).valueOf(), end = new Date(e).valueOf();
    if (end - start < this.MS_IN_24) {
      return true;
    }
    else { return false; }
  },

  isNearRightEdge: function(d, edge) {
    // check if d.normalTime is within six hours before edge
    var t = new Date(d.normalTime);
    if (edge.valueOf() - t.valueOf() < this.MS_IN_24/4) {
      return true;
    }
    return false;
  },

  isSegmentAcrossMidnight: function(s, e) {
    var start = new Date(s), end = new Date(e);
    var startDate = this.toISODateString(s), endDate = this.toISODateString(e);
    if (startDate === endDate) {
      return false;
    }
    else {
      if (end.getUTCDate() === start.getUTCDate() + 1) {
        if (this.getMidnight(e) === e) {
          return false;
        }
        return true;
      }
      else {
        return false;
      }
    }
  },

  isTwentyFourHours: function(s, e) {
    var start = new Date(s).valueOf(), end = new Date(e).valueOf();
    if (end - start === this.MS_IN_24) {
      return true;
    }
    else { return false; }
  },

  roundToNearestMinutes: function(d, resolution) {
    var date = new Date(d);
    var min = date.getUTCMinutes();
    var values = _.range(0, 60, resolution);
    for (var i = 0; i < values.length; ++i) {
      if (min - values[i] < resolution/2) {
        date.setUTCMinutes(values[i]);
        return date.toISOString();
      }
      else if (i === values.length - 1) {
        date.setUTCMinutes(0);
        date.setUTCHours(date.getUTCHours() + 1);
        return date.toISOString();
      }
    }
  },

  toISODateString: function(d) {
    var date = new Date(d);
    return date.toISOString().slice(0,10);
  },

  smbgEdge: function(d, offset) {
    var date = offset ? new Date(this.applyOffset(d, offset)) : new Date(d);
    if (date.getUTCHours() <= 2) {
      return 'left';
    }
    else if (date.getUTCHours() >= 21) {
      return 'right';
    }
    else {
      return null;
    }
  },

  verifyEndpoints: function(s, e, endpoints) {
    if (!endpoints) {
      return null;
    }
    if (this.checkIfUTCDate(s) && this.checkIfUTCDate(e)) {
      endpoints = this.adjustToInnerEndpoints(s, e, endpoints);
      s = endpoints[0];
      e = endpoints[1];
      if (this.checkIfDateInRange(s, endpoints) && this.checkIfDateInRange(e, endpoints)) {
        return true;
      }
      else {
        return false;
      }
    }
    else {
      return false;
    }
  },

  weekdayLookup: function(n) {
    if (n < 0 || n > 6) {
      return null;
    }
    var weekdays = {
      0: 'sunday',
      1: 'monday',
      2: 'tuesday',
      3: 'wednesday',
      4: 'thursday',
      5: 'friday',
      6: 'saturday'
    };
    return weekdays[n];
  }
};

module.exports = datetime;
<|endoftext|>


<commit_before>'use strict';

var Bundle = /** @type Bundle */ require('./bundle/Bundle');
var Class = /** @type Class */ require('fist.lang.class/Class');
var Emitter = /** @type EventEmitter */ require('events').EventEmitter;
var Next = /** @type Next */ require('fist.util.next/Next');

var toArray = require('fist.lang.toarray');
var _ = /** @type _ */ require('lodash');

/**
 * @abstract
 * @class Tracker
 * @extends EventEmitter
 * @extends Class
 * */
var Tracker = Class.extend.call(Emitter, /** @lends Tracker.prototype */ {

    /**
     * @protected
     * @memberOf {Tracker}
     * @method
     *
     * @constructs
     * */
    constructor: function () {
        Class.apply(this, arguments);
        Tracker.Parent.apply(this, arguments);

        /**
         * @public
         * @memberOf {Tracker}
         * @property {Object}
         * */
        this.decls = Object.create(null);
    },

    /**
     * Декларирует узел
     *
     * @public
     * @memberOf {Tracker}
     * @method
     *
     * @param {String} path
     * @param {*} [deps]
     * @param {Function} [body]
     *
     * @returns {Tracker}
     * */
    decl: function (path, deps, body) {

        if ( 3 > arguments.length ) {
            body = deps;
            deps = [];
        }

        return this.unit(path, {
            deps: deps,
            body: body
        });
    },

    /**
     * Запускает операцию разрешения узла
     *
     * @public
     * @memberOf {Tracker}
     * @method
     *
     * @param {Track} track
     * @param {String} path
     * @param {*} done
     * */
    resolve: function (track, path, done) {

        var next;

        if ( path in track.tasks ) {
            track.tasks[path].done(done, this);

            return;
        }

        next = track.tasks[path] = new Next();
        next.done(done, this);

        done = this._createResolver(path, next);

        if ( path in this.decls ) {
            this._pend(track, this.decls[path], done);

            return;
        }

        done.reject();
    },

    /**
     * @public
     * @memberOf {Tracker}
     * @method
     *
     * @param {String} path
     * @param {Object} unit
     *
     * @returns {Tracker}
     * */
    unit: function (path, unit) {
        unit = Object(unit);

        if ( this._checkDeps(path, unit) ) {
            this.decls[path] = unit;

            return this;
        }

        throw new ReferenceError(path);
    },

    /**
     * @protected
     * @memberOf {Tracker}
     * @method
     *
     * @param {Track} track
     * @param {Array<String>} deps
     * @param {Function} done done(bundle)
     * */
    _bundle: function (track, deps, done) {

        var bundle;
        var length;

        deps = toArray(deps);
        bundle = this._createBundle();
        length = deps.length;

        if ( 0 === length ) {
            done.call(this, bundle);

            return;
        }

        //  Здесь for-each а не просто цикл
        // потому что нужно замыкание `path`
        _.forEach(deps, function (path) {
            this.resolve(track, path, function () {
                bundle.bundlify(path, arguments);
                length -= 1;

                if ( 0 === length ) {
                    done.call(this, bundle);
                }
            });
        }, this);
    },

    /**
     * @protected
     * @memberOf {Tracker}
     * @method
     *
     * @param {Function} body
     * @param {Track} track
     * @param {Bundle} bundle
     * @param {Function} done
     * */
    _call: function (body, track, bundle, done) {
        body.call(this, track, bundle.errors, bundle.result, done);
    },

    /**
     * @protected
     * @memberOf {Tracker}
     * @method
     *
     * @param {String} path
     * @param {Object} unit
     *
     * @returns {Boolean}
     * */
    _checkDeps: function (path, unit) {

        var deps = /** @type {Array} */ toArray(unit.deps);
        var l = deps.length;

        while ( l ) {
            l -= 1;

            if ( path === deps[l] ) {

                return false;
            }

            unit = this.decls[deps[l]];

            if ( void 0 === unit || this._checkDeps(path, unit) ) {

                continue;
            }

            return false;
        }

        return true;
    },

    /**
     * @protected
     * @memberOf {Tracker}
     * @method
     *
     * @returns {Bundle}
     * */
    _createBundle: function () {

        return new Bundle();
    },

    /**
     * @protected
     * @memberOf {Tracker}
     * @method
     *
     * @param {String} path
     * @param {Next} next
     *
     * @returns {Function}
     * */
    _createResolver: function (path, next) {

        var date = new Date();
        var self = this;

        function trigger (name, data) {
            self.emit(name, {
                path: path,
                time: new Date() - date,
                data: data
            });
        }

        function done (err, res) {

            if ( 2 > arguments.length ) {
                done.reject(err);

                return;
            }

            done.accept(res);
        }

        done.accept = function (data) {
            trigger('sys:accept', data);
            next.resolve(null, data);
        };

        done.notify = function (data) {
            trigger('sys:notify', data);
        };

        done.reject = function (data) {
            trigger('sys:reject', data);
            next.resolve(data);
        };

        return done;
    },

    /**
     * @protected
     * @memberOf {Tracker}
     * @method
     *
     * @param {Track} track
     * @param {Object} decl
     * @param {Function} done
     * */
    _pend: function (track, decl, done) {
        this._bundle(track, decl.deps, function (bundle) {
            this._call(decl.body, track, bundle, done);
        });
    }

});

module.exports = Tracker;
<commit_msg>unit: объединил методы _pend и _bundle в _resolveUnit<commit_after>'use strict';

var Bundle = /** @type Bundle */ require('./bundle/Bundle');
var Class = /** @type Class */ require('fist.lang.class/Class');
var Emitter = /** @type EventEmitter */ require('events').EventEmitter;
var Next = /** @type Next */ require('fist.util.next/Next');

var toArray = require('fist.lang.toarray');
var _ = /** @type _ */ require('lodash');

/**
 * @abstract
 * @class Tracker
 * @extends EventEmitter
 * @extends Class
 * */
var Tracker = Class.extend.call(Emitter, /** @lends Tracker.prototype */ {

    /**
     * @protected
     * @memberOf {Tracker}
     * @method
     *
     * @constructs
     * */
    constructor: function () {
        Class.apply(this, arguments);
        Tracker.Parent.apply(this, arguments);

        /**
         * @public
         * @memberOf {Tracker}
         * @property {Object}
         * */
        this.decls = Object.create(null);
    },

    /**
     * Декларирует узел
     *
     * @public
     * @memberOf {Tracker}
     * @method
     *
     * @param {String} path
     * @param {*} [deps]
     * @param {Function} [body]
     *
     * @returns {Tracker}
     * */
    decl: function (path, deps, body) {

        if ( 3 > arguments.length ) {
            body = deps;
            deps = [];
        }

        return this.unit(path, {
            deps: deps,
            body: body
        });
    },

    /**
     * Запускает операцию разрешения узла
     *
     * @public
     * @memberOf {Tracker}
     * @method
     *
     * @param {Track} track
     * @param {String} path
     * @param {*} done
     * */
    resolve: function (track, path, done) {

        var next;

        if ( path in track.tasks ) {
            track.tasks[path].done(done, this);

            return;
        }

        next = track.tasks[path] = new Next();
        next.done(done, this);

        done = this._createResolver(path, next);

        if ( path in this.decls ) {
            this._resolveUnit(track, this.decls[path], done);

            return;
        }

        done.reject();
    },

    /**
     * @public
     * @memberOf {Tracker}
     * @method
     *
     * @param {String} path
     * @param {Object} unit
     *
     * @returns {Tracker}
     * */
    unit: function (path, unit) {
        unit = Object(unit);

        if ( this._checkDeps(path, unit) ) {
            this.decls[path] = unit;

            return this;
        }

        throw new ReferenceError(path);
    },

    /**
     * @protected
     * @memberOf {Tracker}
     * @method
     *
     * @param {Function} body
     * @param {Track} track
     * @param {Bundle} bundle
     * @param {Function} done
     * */
    _call: function (body, track, bundle, done) {
        body.call(this, track, bundle.errors, bundle.result, done);
    },

    /**
     * @protected
     * @memberOf {Tracker}
     * @method
     *
     * @param {String} path
     * @param {Object} unit
     *
     * @returns {Boolean}
     * */
    _checkDeps: function (path, unit) {

        var deps = toArray(unit.deps);
        var l = deps.length;

        while ( l ) {
            l -= 1;

            if ( path === deps[l] ) {

                return false;
            }

            unit = this.decls[deps[l]];

            if ( void 0 === unit || this._checkDeps(path, unit) ) {

                continue;
            }

            return false;
        }

        return true;
    },

    /**
     * @protected
     * @memberOf {Tracker}
     * @method
     *
     * @returns {Bundle}
     * */
    _createBundle: function () {

        return new Bundle();
    },

    /**
     * @protected
     * @memberOf {Tracker}
     * @method
     *
     * @param {String} path
     * @param {Next} next
     *
     * @returns {Function}
     * */
    _createResolver: function (path, next) {

        var date = new Date();
        var self = this;

        function trigger (name, data) {
            self.emit(name, {
                path: path,
                time: new Date() - date,
                data: data
            });
        }

        function done (err, res) {

            if ( 2 > arguments.length ) {
                done.reject(err);

                return;
            }

            done.accept(res);
        }

        done.accept = function (data) {
            trigger('sys:accept', data);
            next.resolve(null, data);
        };

        done.notify = function (data) {
            trigger('sys:notify', data);
        };

        done.reject = function (data) {
            trigger('sys:reject', data);
            next.resolve(data);
        };

        return done;
    },

    /**
     * @private
     * @memberOf {Tracker}
     * @method
     *
     * @param {Track} track
     * @param {Object} unit
     * @param {Function} done
     * */
    _resolveUnit: function (track, unit, done) {

        var bundle;
        var deps = toArray(unit.deps);
        var length;

        deps = toArray(deps);
        bundle = this._createBundle();
        length = deps.length;

        if ( 0 === length ) {
            this._call(unit.body, track, bundle, done);

            return;
        }

        _.forEach(deps, function (path) {
            this.resolve(track, path, function () {
                bundle.bundlify(path, arguments);
                length -= 1;

                if ( 0 === length ) {
                    this._call(unit.body, track, bundle, done);
                }
            });
        }, this);
    }

});

module.exports = Tracker;
<|endoftext|>


<commit_before>#!/usr/bin/env node
//
// lib/app.js
//
// Copyright (c) 2012 Lee Olayvar <leeolayvar@gmail.com>
// MIT Licensed
//
/*jshint asi: true, laxcomma: true*/
var methods = require('./methods')
  , utils = require('./utils')
// The nodejs url module. This may not compile to the user, we'll see.
var url = require('url')

// () -> function
//
// Returns:
//  A function which hands off the given request object to `app.handle(req)`
//
// Desc:
//  Create a tork instance.
exports.create = function () {
  /* I'm disabling this functionality until `app.use()` gets implemented.
  function app(req) {
    this.handle(req)
  }
  */
  var app = {}

  utils.merge(app, proto)
  app.init()
  return app
}

// The 'prototype' for our app object.
var proto = exports.proto = {}

// () -> undefined
//
// Desc:
//  Initialize the data for this object instance.
proto.init = function () {
  var self = this

  // The stack is a collection of objects containing routes to match to
  // in the following format..
  //{
  //    'method': 'get'
  //  , 'route': \foo\
  //  , 'handler': function
  //}
  this.stack = []

  // Add additional methods to this object for each 'method' supported.
  for (var i = 0; i < methods.length; i++) {
    var method = methods[i]
    self[method] = function (route, fn) {
      self._add_route(method, route, fn)
    }
  }
}

// (method, route, fn) -> undefined
//
// Params:
//  method: The method to match to. undefined is matches all.
//  route: The route to match to. undefined is matches all.
//  handler: The handler to callback if the method & route matches.
//
// Desc:
//  Used internally by all the add route functions, such as `self.get()`,
//  `self.all()` and `self.use()`
proto._add_route = function (method, route, handler) {
  this.stack.push({
      'method': method
    , 'route': route
    , 'handler': handler
  })
}

// (index, req) -> undefined
//
// Params:
//  index: The index of the stack currently being iterated over.
//  req: The request object given to `self.handle(req)`
//
// Desc:
//  Iterate over the stack, calling any handlers found in the stack that
//  match the req objects information.
proto._iterate_stack = function (index, req) {
  var self = this
    , stack_item = this.stack[index]

  // If stackitem is undefined, there are no more routes to try and match.
  if (stack_item === undefined)
    return undefined

  if (stack_item.method) {
    // If the item method and req method don't match, proceed
    // to the next stack item, and end this one.
    if (stack_item.method !== req.method)
      return this._iterate_stack(++index, req)
  }

  if (stack_item.route) {
    // If the item route and req href don't match, proceed
    // to the next stack item, and end this one.
    if (!stack_item.route.test(req.href))
      return this._iterate_stack(++index, req)
  }
  // If we've made it this far, method and route are acceptable matches (or
  //  match alls)

  // Our handler callback. Aptly named, `handler_callback`!
  var handler_callback = function () {
    // Here we would process additional arguments and add them to future
    // stack matches, allowing middleware to inject objects in the stack.
    // For now this feature is being left out.
    self._iterate_stack(++index, req)
  }

  // Now that we're all done, call the handler!
  stack_item.handler(req, handler_callback)
}

// (handler) -> undefined
//
// Params:
//  handler: The handler to callback on all events.
//
// Desc:
//  Match all events given to this app.
proto.all = function (handler) {
  this._add_route(undefined, undefined, handler)
}

// (req) -> undefined
//
// Params:
//  req: A request object, currently consisting of the following minimum data..
//    {
//        'method': 'get'
//      , 'url': '/'
//    }
//    Note that the app will parse the url and add to the request object.
//    So, things like hostname, port, etc, will be taken care of.
//
// Desc:
//  Create an event for this app to handle. This basically just starts the
//  `self._iterate_stack()` function.
proto.handle = function (req) {
  var stack_index = 0
  req = utils.merge(url.parse(req.url), req)
  this._iterate_stack(stack_index, req)
}

// (route, fn) -> undefined
//
// Params:
//  route: The route to match to. Undefined matches all.
//  fn: The function to call if the route is matched
//
// Desc:
//  Add middleware to this app. Currently this feature just adds a route
//  handler, but we're calling that middleware.
proto.use = function (route, handler) {
  this._add_route(undefined, route, handler)
}<commit_msg>Added some param handling to proto._add_route, along with a pattern format call.<commit_after>#!/usr/bin/env node
//
// lib/app.js
//
// Copyright (c) 2012 Lee Olayvar <leeolayvar@gmail.com>
// MIT Licensed
//
/*jshint asi: true, laxcomma: true*/
var methods = require('./methods')
  , utils = require('./utils')
// The nodejs url module. This may not compile to the user, we'll see.
var url = require('url')

// () -> function
//
// Returns:
//  A function which hands off the given request object to `app.handle(req)`
//
// Desc:
//  Create a tork instance.
exports.create = function () {
  /* I'm disabling this functionality until `app.use()` gets implemented.
  function app(req) {
    this.handle(req)
  }
  */
  var app = {}

  utils.merge(app, proto)
  app.init()
  return app
}

// The 'prototype' for our app object.
var proto = exports.proto = {}

// () -> undefined
//
// Desc:
//  Initialize the data for this object instance.
proto.init = function () {
  var self = this

  // The stack is a collection of objects containing routes to match to
  // in the following format..
  //{
  //    'method': 'get'
  //  , 'route': \foo\
  //  , 'handler': function
  //}
  this.stack = []

  // Add additional methods to this object for each 'method' supported.
  for (var i = 0; i < methods.length; i++) {
    var method = methods[i]
    self[method] = function (route, fn) {
      self._add_route(method, route, fn)
    }
  }
}

// (method, route, fn) -> undefined
//
// Params:
//  method: The method to match to. undefined is matches all.
//  route: The route to match to. undefined is matches all.
//  handler: The handler to callback if the method & route matches.
//
// Desc:
//  Used internally by all the add route functions, such as `self.get()`,
//  `self.all()` and `self.use()`
proto._add_route = function (method, route, handler) {
  // Check if handler is the 1st/2nd params
  if (typeof method == 'function') {
    handler = method
    method = route = undefined
  } else if (typeof route == 'function') {
    handler = route
    route = method
    method = undefined
  }

  if (route) {
    route = utils.format_route_pattern(route)
  }

  this.stack.push({
      'method': method
    , 'route': route
    , 'handler': handler
  })
}

// (index, req) -> undefined
//
// Params:
//  index: The index of the stack currently being iterated over.
//  req: The request object given to `self.handle(req)`
//
// Desc:
//  Iterate over the stack, calling any handlers found in the stack that
//  match the req objects information.
proto._iterate_stack = function (index, req) {
  var self = this
    , stack_item = this.stack[index]

  // If stackitem is undefined, there are no more routes to try and match.
  if (stack_item === undefined)
    return undefined

  if (stack_item.method) {
    // If the item method and req method don't match, proceed
    // to the next stack item, and end this one.
    if (stack_item.method !== req.method)
      return this._iterate_stack(++index, req)
  }

  if (stack_item.route) {
    // If the item route and req href don't match, proceed
    // to the next stack item, and end this one.
    if (!stack_item.route.test(req.href))
      return this._iterate_stack(++index, req)
  }
  // If we've made it this far, method and route are acceptable matches (or
  //  match alls)

  // Our handler callback. Aptly named, `handler_callback`!
  var handler_callback = function () {
    // Here we would process additional arguments and add them to future
    // stack matches, allowing middleware to inject objects in the stack.
    // For now this feature is being left out.
    self._iterate_stack(++index, req)
  }

  // Now that we're all done, call the handler!
  stack_item.handler(req, handler_callback)
}

// (handler) -> undefined
//
// Params:
//  handler: The handler to callback on all events.
//
// Desc:
//  Match all events given to this app.
proto.all = function (handler) {
  this._add_route(undefined, undefined, handler)
}

// (req) -> undefined
//
// Params:
//  req: A request object, currently consisting of the following minimum data..
//    {
//        'method': 'get'
//      , 'url': '/'
//    }
//    Note that the app will parse the url and add to the request object.
//    So, things like hostname, port, etc, will be taken care of.
//
// Desc:
//  Create an event for this app to handle. This basically just starts the
//  `self._iterate_stack()` function.
proto.handle = function (req) {
  var stack_index = 0
  req = utils.merge(url.parse(req.url), req)
  this._iterate_stack(stack_index, req)
}

// (route, fn) -> undefined
//
// Params:
//  route: The route to match to. Undefined matches all.
//  fn: The function to call if the route is matched
//
// Desc:
//  Add middleware to this app. Currently this feature just adds a route
//  handler, but we're calling that middleware.
proto.use = function (route, handler) {
  this._add_route(undefined, route, handler)
}<|endoftext|>


<commit_before>var Look = {

  // -- Private --------------------------------------------------------------
  _setAttributes :
  function(element, attributes) {
    for (var name in attributes) {
      element.setAttribute(name, attributes[name]);
    }
  },

  _setContent :
  function(element, content) {
    content.forEach(function(object) {
      Look.create(object,element);
    });
  },

  _for :
  function(collection, attribute, content, position) {
    if (collection.length != 0) {
      for (var i in collection) {
        if (collection[i].getAttribute(attribute) === content) return collection[i];
      }
    }
    return false;
  },

  _objectElements :
  function(object) {
    return Object.keys(object).length;
  },
  // -- Public ---------------------------------------------------------------

  create :
  function(object, container) {
    var element = this.newElement(object.tag);
    if (object.attr) this._setAttributes(element, object.attr);
    if (object.text) this.setText.to.oneElement(element, object.text);
    if (object.content) this._setContent(element, object.content);
    container ? container.appendChild(element) : document.body.appendChild(element);
    return element;
  },

  createMany :
  function(times, object, container) {
    var many = [];
    var i = 0;
    for (i; i < times; i++) {
      many.push(Look.create(object, container));
    }
    return many;
  },

  copy :
  function(from, to) {
    return this.create(from.cloneNode(true), to);
  },

  // -- document operations substitution ---------------------------------

  newElement :
  function(tag) {
    return document.createElement(tag);
  },

  getBy : {
    id :
    function(id) {
      return document.getElementById(id);
    },
    className :
    function(name, at) {
      if (at) return document.getElementsByClassName(name)[at];
      return document.getElementsByClassName(name);
    },
    tagName :
    function(name, at) {
      if (at) return document.getElementsByTagName(name)[at];
      return document.getElementsByTagName(name);
    },
    href :
    function(link, at) {
      if (at) return Look._for(document.getElementsByTagName('a'), 'href', link, at);
      return Look._for(document.getElementsByTagName('a'), 'href', link);
    },
    src :
    function(link, at) {
      if (at) return Look._for(document.getElementsByTagName('img'), 'src', link, at);
      return Look._for(document.getElementsByTagName('img'), 'src', link);
    }
  },

  setText : {
    to : {
      oneElement :
      function(element, text) {
        element.textContent = text;
      },
      manyElements :
      function(elements, texts, language) {
        var i = 0;
        for (i; i < Look._objectElements(texts); i++) {
          elements[i].textContent = texts[i][language];
        }
      },
      allElements :
      function(elements, text) {
        var i = 0;
        console.log(elements);
        for (i; i < elements.length; i++) {
          if (elements[i]) elements[i].textContent = text;
        }
      }
    }
  }
}

Look.components = {
	list: {},
	add:
	function(id, component) {
		if (!Look.components.checkId(component)) {
			Look.components.list[id] = component;
		}
		return component
	},
	checkId:
	function(id) {
		return ((id !== "")
			&& (id !== null)
			&& (Look.components.list.hasOwnProperty(id)))
	},
	get:
	function(id) {
		return Look.components.list[id];
	},
	extend:
	function(componentId, newId, newProperties) {
		var oldComponent = Look.components.get(componentId);
		var newComponent = Look.mergeJson(oldComponent, newProperties);
		return Look.components.add(newId, newComponent);
	},
	extendAttribute:
	function(componentId, newId, newProperties) {
		var oldComponent = Look.components.get(componentId);
		var newComponent = Look.extendKey(oldComponent, newProperties);
		return Look.components.add(newId, newComponent);
	},
	merge:
	function(component1, component2, newId) {
		return Look.components.add(
					newId,
					Look.extendKey(
						Look.components.get(component1),
						Look.components.get(component2))
				);
	}
}

Look.createFromComponent =
	function(id, container) {
		return Look.create(Look.components.get(id), container);
	}
function Controller(id) {

}
Look.language = {
  change :
  function(language, localizer) {
    if (localizer['id']) {
      for (var element in localizer['id']) {
        Look.setText.to.oneElement(Look.getBy.id(element), localizer['id'][element][language]);
      }
    };

    if (localizer['class']) {
      for (var element in localizer['class']) {
        Look.setText.to.manyElements(Look.getBy.className(element), localizer['class'][element], language);
      }
    };

    if (localizer['tag']) {
      for (var element in localizer['tag']) {
        Look.setText.to.manyElements(Look.getBy.tagName(element), localizer['tag'][element], language);
      }
    };

    if (localizer['allClass']) {
      for (var element in localizer['allClass']) {
        Look.setText.to.allElements(Look.getBy.className(element), localizer['allClass'][element][language]);
      }
    };

    if (localizer['allTag']) {
      for (var element in localizer['allTag']) {
        Look.setText.to.allElements(Look.getBy.className(element), localizer['allTag'][element][language]);
      }
    };
  }
}

Look.copyJson = function(object1, object2) {

}

Look.mergeJson = function(object1, object2) {
	var key;
	var newObject = object2;
	for (key in object1) {
		if (typeof object1[key] === "object") {
			newObject[key] = Look.mergeJson(object1[key], newObject[key])
		} else {
			newObject[key] = object1[key];
		}
	}
	return newObject;
}

Look.extendKey = function(object1, object2) {
	var key;
	var newObject = object2;
	for (key in object1) {
		if (typeof object1[key] === "object") {
			Look.extendKey(object1[key], newObject[key])
		} else {
			if (Look.differentKey(object1, newObject, key)) {
				newObject[key] += ' ' + object1[key];
			}
		}
	}
	return newObject;
}

Look.differentKey = function(object1, object2, key) {
	return ((object1[key]) &&  (object2[key]) &&  (object1[key] !== object2[key]));
}
Look.style = {
	setProperty:
	function(element, property, value) {
		element.style[property] = value;
	},

	setStyle:
	function(element, properties) {
		for (property in properties) {
			Look.style.setProperty(element, property, properties[property]);
		}
	}
}<commit_msg>last compilation<commit_after>var Look = {

  // -- Private --------------------------------------------------------------
  _setAttributes :
  function(element, attributes) {
    for (var name in attributes) {
      element.setAttribute(name, attributes[name]);
    }
  },

  _setContent :
  function(element, content) {
    content.forEach(function(object) {
      Look.create(object,element);
    });
  },

  _for :
  function(collection, attribute, content, position) {
    if (collection.length != 0) {
      for (var i in collection) {
        if (collection[i].getAttribute(attribute) === content) return collection[i];
      }
    }
    return false;
  },

  _objectElements :
  function(object) {
    return Object.keys(object).length;
  },
  // -- Public ---------------------------------------------------------------

  create :
  function(object, container) {
    var element = this.newElement(object.tag);
    if (object.attr) this._setAttributes(element, object.attr);
    if (object.text) this.setText.to.oneElement(element, object.text);
    if (object.content) this._setContent(element, object.content);
    container ? container.appendChild(element) : document.body.appendChild(element);
    return element;
  },

  createMany :
  function(times, object, container) {
    var many = [];
    var i = 0;
    for (i; i < times; i++) {
      many.push(Look.create(object, container));
    }
    return many;
  },

  copy :
  function(from, to) {
    return this.create(from.cloneNode(true), to);
  },

  // -- document operations substitution ---------------------------------

  newElement :
  function(tag) {
    return document.createElement(tag);
  },

  getBy : {
    id :
    function(id) {
      return document.getElementById(id);
    },
    className :
    function(name, at) {
      if (at) return document.getElementsByClassName(name)[at];
      return document.getElementsByClassName(name);
    },
    tagName :
    function(name, at) {
      if (at) return document.getElementsByTagName(name)[at];
      return document.getElementsByTagName(name);
    },
    href :
    function(link, at) {
      if (at) return Look._for(document.getElementsByTagName('a'), 'href', link, at);
      return Look._for(document.getElementsByTagName('a'), 'href', link);
    },
    src :
    function(link, at) {
      if (at) return Look._for(document.getElementsByTagName('img'), 'src', link, at);
      return Look._for(document.getElementsByTagName('img'), 'src', link);
    }
  },

  setText : {
    to : {
      oneElement :
      function(element, text) {
        element.textContent = text;
      },
      manyElements :
      function(elements, texts, language) {
        var i = 0;
        for (i; i < Look._objectElements(texts); i++) {
          elements[i].textContent = texts[i][language];
        }
      },
      allElements :
      function(elements, text) {
        var i = 0;
        console.log(elements);
        for (i; i < elements.length; i++) {
          if (elements[i]) elements[i].textContent = text;
        }
      }
    }
  }
}

Look.components = {
	list: {},
	add:
	function(id, component) {
		if (!Look.components.checkId(component)) {
			Look.components.list[id] = component;
		}
		return component
	},
	checkId:
	function(id) {
		return ((id !== "")
			&& (id !== null)
			&& (Look.components.list.hasOwnProperty(id)))
	},
	get:
	function(id) {
		return Look.components.list[id];
	},
	extend:
	function(componentId, newId, newProperties) {
		var oldComponent = Look.components.get(componentId);
		var newComponent = Look.mergeJson(oldComponent, newProperties);
		return Look.components.add(newId, newComponent);
	},
	extendAttribute:
	function(componentId, newId, newProperties) {
		var oldComponent = Look.components.get(componentId);
		var newComponent = Look.extendKey(oldComponent, newProperties);
		return Look.components.add(newId, newComponent);
	},
	merge:
	function(component1, component2, newId) {
		return Look.components.add(
					newId,
					Look.extendKey(
						Look.components.get(component1),
						Look.components.get(component2))
				);
	}
}

Look.createFromComponent =
	function(id, container) {
		return Look.create(Look.components.get(id), container);
	}
var lc = Look.controllers;

Look.controllers = {
	create:
	function(model, operations) {
		return Look.controllers.extend(model, operations);
	},
	extend:
	function(model, operations) {
		var operation;
		operations['model'] = model;
		model['operations'] = operations;
		return model;
	}
}

Look.language = {
  change :
  function(language, localizer) {
    if (localizer['id']) {
      for (var element in localizer['id']) {
        Look.setText.to.oneElement(Look.getBy.id(element), localizer['id'][element][language]);
      }
    };

    if (localizer['class']) {
      for (var element in localizer['class']) {
        Look.setText.to.manyElements(Look.getBy.className(element), localizer['class'][element], language);
      }
    };

    if (localizer['tag']) {
      for (var element in localizer['tag']) {
        Look.setText.to.manyElements(Look.getBy.tagName(element), localizer['tag'][element], language);
      }
    };

    if (localizer['allClass']) {
      for (var element in localizer['allClass']) {
        Look.setText.to.allElements(Look.getBy.className(element), localizer['allClass'][element][language]);
      }
    };

    if (localizer['allTag']) {
      for (var element in localizer['allTag']) {
        Look.setText.to.allElements(Look.getBy.className(element), localizer['allTag'][element][language]);
      }
    };
  }
}

Look.copyJson = function(object1, object2) {

}

Look.mergeJson = function(object1, object2) {
	var key;
	var newObject = object2;
	for (key in object1) {
		if (typeof object1[key] === "object") {
			newObject[key] = Look.mergeJson(object1[key], newObject[key])
		} else {
			newObject[key] = object1[key];
		}
	}
	return newObject;
}

Look.extendKey = function(object1, object2) {
	var key;
	var newObject = object2;
	for (key in object1) {
		if (typeof object1[key] === "object") {
			Look.extendKey(object1[key], newObject[key])
		} else {
			if (Look.differentKey(object1, newObject, key)) {
				newObject[key] += ' ' + object1[key];
			}
		}
	}
	return newObject;
}

Look.differentKey = function(object1, object2, key) {
	return ((object1[key]) &&  (object2[key]) &&  (object1[key] !== object2[key]));
}
Look.style = {
	setProperty:
	function(element, property, value) {
		element.style[property] = value;
	},

	setStyle:
	function(element, properties) {
		for (property in properties) {
			Look.style.setProperty(element, property, properties[property]);
		}
	}
}<|endoftext|>


<commit_before>/**
 * Licensed to the Apache Software Foundation (ASF) under one
 * or more contributor license agreements.  See the NOTICE file
 * distributed with this work for additional information
 * regarding copyright ownership.  The ASF licenses this file
 * to you 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.
 */
'use strict';

angular.module('ambariAdminConsole')
.controller('ClustersManageAccessCtrl', ['$scope', '$location', 'Cluster', '$routeParams', 'Alert', 'PermissionLoader', 'PermissionSaver', '$translate', 'RoleDetailsModal', '$timeout', function($scope, $location, Cluster, $routeParams, Alert, PermissionLoader, PermissionSaver, $translate, RoleDetailsModal, $timeout) {
  var $t = $translate.instant;
  $scope.getConstant = function (key) {
    return $t(key).toLowerCase();
  };
  $scope.identity = angular.identity;
  function reloadClusterData(){
    PermissionLoader.getClusterPermissions({
      clusterId: $routeParams.id
    }).then(function(permissions) {
      // Refresh data for rendering
      $scope.permissionsEdit = permissions;
      $scope.permissions = angular.copy(permissions);
      //"$scope.isDataLoaded" should be set to true on initial load after "$scope.permissionsEdit" watcher
      $timeout(function() {
        $scope.isDataLoaded = true;
      });
      var orderedRoles = Cluster.orderedRoles;
      var pms = [];
      for (var key in orderedRoles) {
        pms.push($scope.permissions[orderedRoles[key]]);
      }
      $scope.permissions = pms;
    })
    .catch(function(data) {
      Alert.error($t('clusters.alerts.cannotLoadClusterData'), data.data.message);
    });
  }

  $scope.isDataLoaded = false;
  reloadClusterData();
  $scope.isEditMode = false;
  $scope.permissions = {};
  $scope.clusterName = $routeParams.id;

  $scope.toggleEditMode = function() {
    $scope.isEditMode = !$scope.isEditMode;
  };

  $scope.cancel = function() {
    $scope.isEditMode = false;
    $scope.permissionsEdit = angular.copy($scope.permissions); // Reset textedit areaes
  };

  $scope.save = function() {
    PermissionSaver.saveClusterPermissions(
      $scope.permissionsEdit,
      {
        clusterId: $routeParams.id
      }
    ).then(reloadClusterData)
    .catch(function(data) {
      Alert.error($t('common.alerts.cannotSavePermissions'), data.data.message);
      reloadClusterData();
    });
    $scope.isEditMode = false;
  };

  $scope.$watch(function() {
    return $scope.permissionsEdit;
  }, function(newValue) {
    if (newValue && $scope.isDataLoaded) {
      $scope.save();
    }
  }, true);

  $scope.switchToList = function() {
    $location.url('/clusters/' + $routeParams.id + '/userAccessList');
  };

  $scope.showHelpPage = function() {
    Cluster.getRolesWithAuthorizations().then(function(roles) {
      RoleDetailsModal.show(roles);
    });
  };
}]);
<commit_msg>AMBARI-20810. Roles page in Ambari UI shows extra rows in IE browser (alexantonenko)<commit_after>/**
 * Licensed to the Apache Software Foundation (ASF) under one
 * or more contributor license agreements.  See the NOTICE file
 * distributed with this work for additional information
 * regarding copyright ownership.  The ASF licenses this file
 * to you 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.
 */
'use strict';

angular.module('ambariAdminConsole')
.controller('ClustersManageAccessCtrl', ['$scope', '$location', 'Cluster', '$routeParams', 'Alert', 'PermissionLoader', 'PermissionSaver', '$translate', 'RoleDetailsModal', '$timeout', function($scope, $location, Cluster, $routeParams, Alert, PermissionLoader, PermissionSaver, $translate, RoleDetailsModal, $timeout) {
  var $t = $translate.instant;
  $scope.getConstant = function (key) {
    return $t(key).toLowerCase();
  };
  $scope.identity = angular.identity;
  function reloadClusterData(){
    PermissionLoader.getClusterPermissions({
      clusterId: $routeParams.id
    }).then(function(permissions) {
      // Refresh data for rendering
      $scope.permissionsEdit = permissions;
      $scope.permissions = angular.copy(permissions);
      //"$scope.isDataLoaded" should be set to true on initial load after "$scope.permissionsEdit" watcher
      $timeout(function() {
        $scope.isDataLoaded = true;
      });
      var orderedRoles = Cluster.orderedRoles;
      var pms = [];
      for (var key=0;key<orderedRoles.length;key++) {
        pms.push($scope.permissions[orderedRoles[key]]);
      }
      $scope.permissions = pms;
    })
    .catch(function(data) {
      Alert.error($t('clusters.alerts.cannotLoadClusterData'), data.data.message);
    });
  }

  $scope.isDataLoaded = false;
  reloadClusterData();
  $scope.isEditMode = false;
  $scope.permissions = {};
  $scope.clusterName = $routeParams.id;

  $scope.toggleEditMode = function() {
    $scope.isEditMode = !$scope.isEditMode;
  };

  $scope.cancel = function() {
    $scope.isEditMode = false;
    $scope.permissionsEdit = angular.copy($scope.permissions); // Reset textedit areaes
  };

  $scope.save = function() {
    PermissionSaver.saveClusterPermissions(
      $scope.permissionsEdit,
      {
        clusterId: $routeParams.id
      }
    ).then(reloadClusterData)
    .catch(function(data) {
      Alert.error($t('common.alerts.cannotSavePermissions'), data.data.message);
      reloadClusterData();
    });
    $scope.isEditMode = false;
  };

  $scope.$watch(function() {
    return $scope.permissionsEdit;
  }, function(newValue) {
    if (newValue && $scope.isDataLoaded) {
      $scope.save();
    }
  }, true);

  $scope.switchToList = function() {
    $location.url('/clusters/' + $routeParams.id + '/userAccessList');
  };

  $scope.showHelpPage = function() {
    Cluster.getRolesWithAuthorizations().then(function(roles) {
      RoleDetailsModal.show(roles);
    });
  };
}]);
<|endoftext|>


<commit_before>/*

# Scoped JS Interopation Mixin for reproCSS
## version 0.0.7

Evaluate JavaScript from the context of each HTML element that matches the supplied CSS selector list.

### Syntax

    scoped(selectorList, rule)

- `selectorList` is a comma-separated string containing one or more CSS selectors
- `rule` is a semicolon-separated string containing one or more CSS declarations

### Example

    scoped('div', 'height: eval(this.offsetWidth / (16/9))px')

- https://github.com/tomhodgins/reprocss

Author: Tommy Hodgins

License: MIT

*/

function scoped(selectorList, rule) {

  var tag = document.querySelectorAll(selectorList)
  var style = ''
  var count = 0

  for (var i=0; i < tag.length; i++) {

    var attr = btoa(selectorList).replace(/=/g, '')

    tag[i].setAttribute('data-scoped-' + attr, count)

    var scopedRule = rule.replace(/eval\((.*)\)/g, function(string, match){

      var func = new Function('return ' + match)

      return (func.call(tag[i]) || '')

    })

    style += '\n/* Scope: ' + selectorList + ' */\n'
             + '[data-scoped-' + attr + '="' + count + '"] {\n'
             + '  ' + scopedRule + '\n'
             + '}\n'
    count++

  }

  return style

}<commit_msg>Update scoped-eval.js<commit_after>/*

# Scoped JS Interopation Mixin for reproCSS
## version 0.0.7

Evaluate JavaScript from the context of each HTML element that matches the supplied CSS selector list.

### Syntax

    scoped(selectorList, rule)

- `selectorList` is a comma-separated string containing one or more CSS selectors
- `rule` is a semicolon-separated string containing one or more CSS declarations

### Example

    scoped('div', 'height: eval(this.offsetWidth / (16/9))px')

- https://github.com/tomhodgins/reprocss

Author: Tommy Hodgins

License: MIT

*/

function scoped(selectorList, rule) {

  var tag = document.querySelectorAll(selectorList)
  var style = ''
  var count = 0

  for (var i=0; i < tag.length; i++) {

    var attr = btoa(selectorList).replace(/=/g, '')

    tag[i].setAttribute('data-scoped-' + attr, count)

    var scopedRule = rule.replace(/eval\((.*)\)/g, function(string, match){

      var func = new Function('return ' + match)

      return (func.call(tag[i]) || '')

    })

    style += '\n/* Scope: ' + selectorList + ' */\n'
             + '[data-scoped-' + attr + '="' + count + '"] {\n'
             + '  ' + scopedRule + '\n'
             + '}\n'

      count++

  }

  return style

}
<|endoftext|>