<commit_before>/*
 * ooiui/static/js/views/science/StreamDownloadFormView.js
 * View Definition for DownloadFormView
 *
 * Dependencies
 * Partials
 * - ooiui/static/js/partials/DownloadFOrm.html
 * Libs
 * - ooiui/static/lib/underscore/underscore.js
 * - ooiui/static/lib/backbone/backbone.js
 * - ooiui/static/js/ooi.js
 * Usage
 */

var StreamDownloadFormView = Backbone.View.extend({
  events: {
    'click #download-btn' : 'onDownload',
    'change #type-select select' : 'onTypeChange',
    'click #provenance-select' : 'onCheckboxSelect',
    'click #annotation-select' : 'onCheckboxSelect',
    'change #time-range select': 'timeRangeChange',
    'click #subscription-selection-select': "onSubscribeSelect",
  },
  initialize: function() {
    "use strict";
    _.bindAll(this, 'onDownload', 'onTypeChange', 'onCheckboxSelect', 'timeRangeChange', 'resetTimeRange','onSubscribeSelect');

    this.render();
  },
  onCheckboxSelect: function() {
    "use strict";
    if((this.$el.find('#provenance-select').is(':checked')) || (this.$el.find('#annotation-select').is(':checked'))){
      this.$el.find("#type-select select option[value*='csv']").prop('disabled',true);
    }else{
      this.$el.find("#type-select select option[value*='csv']").prop('disabled',false);
    }
  },
  onSubscribeSelect:function(ev){
    var self = this;
    console.log('subscribe select',this.model);
    this.$el.find('#subscription-selection-select').attr('disabled','disabled');
    try{
      var subscribeModel = new DataSubscriptionModel({});
      var stream_names = self.model.get('stream_name').split('_');
      var refParts = self.model.get('ref_des').split('-');
      if (stream_names.length == 2 && refParts.length == 4){
        subscribeModel.set('stream',stream_names[1].replace(/-/g,"_"));
        subscribeModel.set('method',stream_names[0]);
        subscribeModel.set('email',self.model.get('email'))

        subscribeModel.attributes.referenceDesignator.node = refParts[0];
        subscribeModel.attributes.referenceDesignator.subsite = refParts[1];
        subscribeModel.attributes.referenceDesignator.sensor = refParts[2] +"-"+ refParts[3];

        subscribeModel.save(null, {
          success: function() {
            ooi.trigger('StreamDownloadFormView:resetSubscriptionCollection', null);
            self.$el.find('#subscription-selection-icon').removeClass('fa-heart-o');
            self.$el.find('#subscription-selection-icon').addClass('fa-heart');
            //SAVED!
          },
          error: function(model, response) {
            console.error('ERROR:',response);
            self.$el.find('#subscription-selection-select').attr('disabled',null);
          }
        });
      }else{
        console.error("ERROR:", "setting model");
        self.$el.find('#subscription-selection-select').attr('disabled',null);
      }
    }catch(e){
      console.error("ERROR:", e);
      self.$el.find('#subscription-selection-select').attr('disabled',null);
    }
  },
  timeRangeChange: function() {
    var timeRangeDelta, timeChangedTo, startDate, endDate;

    // get the time in days to subtract from the end date.
    timeRangeDelta = this.$el.find('#time-range select').val();

    // reset the start and end date.
    endDate = moment.utc(this.model.get('end')).toJSON();
    startDate = moment.utc(this.model.get('start')).toJSON();

    // set the start date to be the time range delta from the selection.
    if (timeRangeDelta === "all") {
        startDate = moment.utc(this.model.get('start')).toJSON();
    } else {
        startDate = moment.utc(this.model.get('end')).subtract(timeRangeDelta,'hours').toJSON();
    }

    // set the fields.
    this.$end_date_picker.setDate(endDate);
    this.$start_date_picker.setDate(startDate);

    // dance.
  },
  resetTimeRange: function() {
    "use strict";
    $("#time-range > select").val("Reset").change();
  },
  onTypeChange: function() {
    "use strict";
    var type = this.$el.find('#type-select select').val();
    if(type == 'csv') {
      this.$el.find('#provenance-select').attr("disabled", true);
      this.$el.find('#provenance-select').attr('checked', false);
      this.$el.find('#annotation-select').attr("disabled", true);
      this.$el.find('#annotation-select').attr('checked', false);
    } else {
      this.$el.find('#provenance-select').removeAttr("disabled");
      this.$el.find('#annotation-select').removeAttr("disabled");
    }

    if(type == 'json') {
      this.$el.find('#download-param-select').attr("disabled", false);
    } else{
      this.$el.find('#download-param-select').attr("disabled", true);
    }
  },
  onDownload: function() {
    "use strict";
    /*
     * Make a copy of the stream model and then set the start and end dates to
     * the form fields, then grab the URL and send the user to it.
     */
    var selection = this.$type_select.val();
    var localModel = this.model.clone();
    var startDate = moment.utc(this.$start_date.data('date')).toJSON();
    var endDate = moment.utc(this.$end_date.data('date')).toJSON();
    localModel.set('start', startDate);
    localModel.set('end', endDate);

    var email = this.$el.find('#dlEmail').val();
    var user_name = this.model.get('user_name');
    localModel.set('email', email);
    /* 10/08/2015 @ 9:37am
     * M@Campbell
     *
     * Recipient was trying to create a directory of the user name,
     * which sometimes could be the user's email address.
     *
     * Lets remove the special characters; replace the @ with a - and
     * completely remove the .
     */
    if (user_name.indexOf('.') > -1) { user_name = user_name.replace('.', '-'); }
    if (user_name.indexOf('@') > -1) { user_name = user_name.replace('@', '-'); }

    if (user_name.indexOf('.') > -1) {
        var splitUserName = user_name.split('.');
        user_name = splitUserName[0];
    }
    localModel.set('user_name', user_name);

    // Check for provenance and set the model
    if(this.$el.find('#provenance-select').is(':checked')){
      localModel.set('provenance', 'true');
    }else{
      localModel.set('provenance', 'false');
    }
    // Check for annotations and set the model
    if(this.$el.find('#annotation-select').is(':checked')){
      localModel.set('annotations', 'true');
    }else{
      localModel.set('annotations', 'false');
    }
    var url = localModel.getURL(selection);
    $.ajax({
      url: url,
      type: "GET",
      dataType: "json",
      user_email: email,
      user_name: user_name,
      success: function(resp){
        ooi.trigger('DownloadModal:onSuccess', this.user_email);
      },
      error: function(msg){
        ooi.trigger('DownloadModalFail:onFail', msg);
      }
    });
    // window.open(url, '_blank');
//    window.location.href = url;
    this.hide();
  },
  failure: function() {
    "use strict";
    console.log("this failure");
  },
  show: function(options) {
    "use strict";
    var model = options.model;
    // console.log("SHOW", options.model.attributes);
    this.model = model;

    var startDate = moment.utc(model.get('start')).toJSON();
    var endDate = moment.utc(model.get('end')).toJSON();

    this.$start_date_picker.setDate(startDate);
    this.$end_date_picker.setDate(endDate);

    if(model.get('long_display_name') != null) {
      this.$el.find('#streamName').text(model.get('long_display_name'));
    }else{
      this.$el.find('#streamName').text(model.get('stream_name'));
    }

    var email = model.get('email');
    this.$el.find('#dlEmail').val(email);

    if (!(this.model.get('stream_name').split('_')[0] == 'telemetered')){
      this.$el.find('#subscription-selection-select').css('visibility','hidden');
    }else{
      this.$el.find('#subscription-selection-select').css('visibility','visible');
    }
    //reset it first incase
    this.$el.find('#subscription-selection-icon').attr('class','fa fa-heart-o');
    this.$el.find('#subscription-selection-select').attr('disabled',null);
    if (model.get('subscriptionEnabled')){
      this.$el.find('#subscription-selection-icon').removeClass('fa-heart-o');
      this.$el.find('#subscription-selection-icon').addClass('fa-heart');
      this.$el.find('#subscription-selection-select').attr('disabled','disabled');
    }

    this.$el.find('#download-modal').modal('show');

    // Update parameters dropdown
    // $("#download-param-select").html($("#yvar0-select-default").html())
    // $('.selectpicker').selectpicker('refresh');

    this.onTypeChange();
    this.timeRangeChange();

    return this;
  },
  hide: function() {
    "use strict";
    this.$el.find('#download-modal').modal('hide');
    return this;
  },
  template: JST["ooiui/static/js/partials/StreamDownloadForm.html"],
  render: function() {
    "use strict";
    this.$el.html(this.template({}));

    this.$el.find('#start-date').datetimepicker({format: "YYYY-MM-DD HH:mm:ss",
                                                 sideBySide: true
                                                 });
    this.$el.find('#end-date').datetimepicker({format: "YYYY-MM-DD HH:mm:ss",
                                               sideBySide: true
                                               });
    this.$start_date = this.$el.find('#start-date');
    this.$end_date = this.$el.find('#end-date');
    this.$type_select = this.$el.find('#type-select select');
    this.$start_date_picker = this.$start_date.data('DateTimePicker');
    this.$end_date_picker = this.$end_date.data('DateTimePicker');

  }
});
<commit_msg>remove console log<commit_after>/*
 * ooiui/static/js/views/science/StreamDownloadFormView.js
 * View Definition for DownloadFormView
 *
 * Dependencies
 * Partials
 * - ooiui/static/js/partials/DownloadFOrm.html
 * Libs
 * - ooiui/static/lib/underscore/underscore.js
 * - ooiui/static/lib/backbone/backbone.js
 * - ooiui/static/js/ooi.js
 * Usage
 */

var StreamDownloadFormView = Backbone.View.extend({
  events: {
    'click #download-btn' : 'onDownload',
    'change #type-select select' : 'onTypeChange',
    'click #provenance-select' : 'onCheckboxSelect',
    'click #annotation-select' : 'onCheckboxSelect',
    'change #time-range select': 'timeRangeChange',
    'click #subscription-selection-select': "onSubscribeSelect",
  },
  initialize: function() {
    "use strict";
    _.bindAll(this, 'onDownload', 'onTypeChange', 'onCheckboxSelect', 'timeRangeChange', 'resetTimeRange','onSubscribeSelect');

    this.render();
  },
  onCheckboxSelect: function() {
    "use strict";
    if((this.$el.find('#provenance-select').is(':checked')) || (this.$el.find('#annotation-select').is(':checked'))){
      this.$el.find("#type-select select option[value*='csv']").prop('disabled',true);
    }else{
      this.$el.find("#type-select select option[value*='csv']").prop('disabled',false);
    }
  },
  onSubscribeSelect:function(ev){
    var self = this;
    this.$el.find('#subscription-selection-select').attr('disabled','disabled');
    try{
      var subscribeModel = new DataSubscriptionModel({});
      var stream_names = self.model.get('stream_name').split('_');
      var refParts = self.model.get('ref_des').split('-');
      if (stream_names.length == 2 && refParts.length == 4){
        subscribeModel.set('stream',stream_names[1].replace(/-/g,"_"));
        subscribeModel.set('method',stream_names[0]);
        subscribeModel.set('email',self.model.get('email'))

        subscribeModel.attributes.referenceDesignator.node = refParts[0];
        subscribeModel.attributes.referenceDesignator.subsite = refParts[1];
        subscribeModel.attributes.referenceDesignator.sensor = refParts[2] +"-"+ refParts[3];

        subscribeModel.save(null, {
          success: function() {
            self.$el.find('#subscription-selection-icon').removeClass('fa-heart-o');
            self.$el.find('#subscription-selection-icon').addClass('fa-heart');
            ooi.trigger('StreamDownloadFormView:resetSubscriptionCollection', null);
            //SAVED!
          },
          error: function(model, response) {
            console.error('ERROR:',response);
            self.$el.find('#subscription-selection-select').attr('disabled',null);
          }
        });
      }else{
        console.error("ERROR:", "setting model");
        self.$el.find('#subscription-selection-select').attr('disabled',null);
      }
    }catch(e){
      console.error("ERROR:", e);
      self.$el.find('#subscription-selection-select').attr('disabled',null);
    }
  },
  timeRangeChange: function() {
    var timeRangeDelta, timeChangedTo, startDate, endDate;

    // get the time in days to subtract from the end date.
    timeRangeDelta = this.$el.find('#time-range select').val();

    // reset the start and end date.
    endDate = moment.utc(this.model.get('end')).toJSON();
    startDate = moment.utc(this.model.get('start')).toJSON();

    // set the start date to be the time range delta from the selection.
    if (timeRangeDelta === "all") {
        startDate = moment.utc(this.model.get('start')).toJSON();
    } else {
        startDate = moment.utc(this.model.get('end')).subtract(timeRangeDelta,'hours').toJSON();
    }

    // set the fields.
    this.$end_date_picker.setDate(endDate);
    this.$start_date_picker.setDate(startDate);

    // dance.
  },
  resetTimeRange: function() {
    "use strict";
    $("#time-range > select").val("Reset").change();
  },
  onTypeChange: function() {
    "use strict";
    var type = this.$el.find('#type-select select').val();
    if(type == 'csv') {
      this.$el.find('#provenance-select').attr("disabled", true);
      this.$el.find('#provenance-select').attr('checked', false);
      this.$el.find('#annotation-select').attr("disabled", true);
      this.$el.find('#annotation-select').attr('checked', false);
    } else {
      this.$el.find('#provenance-select').removeAttr("disabled");
      this.$el.find('#annotation-select').removeAttr("disabled");
    }

    if(type == 'json') {
      this.$el.find('#download-param-select').attr("disabled", false);
    } else{
      this.$el.find('#download-param-select').attr("disabled", true);
    }
  },
  onDownload: function() {
    "use strict";
    /*
     * Make a copy of the stream model and then set the start and end dates to
     * the form fields, then grab the URL and send the user to it.
     */
    var selection = this.$type_select.val();
    var localModel = this.model.clone();
    var startDate = moment.utc(this.$start_date.data('date')).toJSON();
    var endDate = moment.utc(this.$end_date.data('date')).toJSON();
    localModel.set('start', startDate);
    localModel.set('end', endDate);

    var email = this.$el.find('#dlEmail').val();
    var user_name = this.model.get('user_name');
    localModel.set('email', email);
    /* 10/08/2015 @ 9:37am
     * M@Campbell
     *
     * Recipient was trying to create a directory of the user name,
     * which sometimes could be the user's email address.
     *
     * Lets remove the special characters; replace the @ with a - and
     * completely remove the .
     */
    if (user_name.indexOf('.') > -1) { user_name = user_name.replace('.', '-'); }
    if (user_name.indexOf('@') > -1) { user_name = user_name.replace('@', '-'); }

    if (user_name.indexOf('.') > -1) {
        var splitUserName = user_name.split('.');
        user_name = splitUserName[0];
    }
    localModel.set('user_name', user_name);

    // Check for provenance and set the model
    if(this.$el.find('#provenance-select').is(':checked')){
      localModel.set('provenance', 'true');
    }else{
      localModel.set('provenance', 'false');
    }
    // Check for annotations and set the model
    if(this.$el.find('#annotation-select').is(':checked')){
      localModel.set('annotations', 'true');
    }else{
      localModel.set('annotations', 'false');
    }
    var url = localModel.getURL(selection);
    $.ajax({
      url: url,
      type: "GET",
      dataType: "json",
      user_email: email,
      user_name: user_name,
      success: function(resp){
        ooi.trigger('DownloadModal:onSuccess', this.user_email);
      },
      error: function(msg){
        ooi.trigger('DownloadModalFail:onFail', msg);
      }
    });
    // window.open(url, '_blank');
//    window.location.href = url;
    this.hide();
  },
  failure: function() {
    "use strict";
    console.log("this failure");
  },
  show: function(options) {
    "use strict";
    var model = options.model;
    // console.log("SHOW", options.model.attributes);
    this.model = model;

    var startDate = moment.utc(model.get('start')).toJSON();
    var endDate = moment.utc(model.get('end')).toJSON();

    this.$start_date_picker.setDate(startDate);
    this.$end_date_picker.setDate(endDate);

    if(model.get('long_display_name') != null) {
      this.$el.find('#streamName').text(model.get('long_display_name'));
    }else{
      this.$el.find('#streamName').text(model.get('stream_name'));
    }

    var email = model.get('email');
    this.$el.find('#dlEmail').val(email);

    if (!(this.model.get('stream_name').split('_')[0] == 'telemetered')){
      this.$el.find('#subscription-selection-select').css('visibility','hidden');
    }else{
      this.$el.find('#subscription-selection-select').css('visibility','visible');
    }
    //reset it first incase
    this.$el.find('#subscription-selection-icon').attr('class','fa fa-heart-o');
    this.$el.find('#subscription-selection-select').attr('disabled',null);
    if (model.get('subscriptionEnabled')){
      this.$el.find('#subscription-selection-icon').removeClass('fa-heart-o');
      this.$el.find('#subscription-selection-icon').addClass('fa-heart');
      this.$el.find('#subscription-selection-select').attr('disabled','disabled');
    }

    this.$el.find('#download-modal').modal('show');

    // Update parameters dropdown
    // $("#download-param-select").html($("#yvar0-select-default").html())
    // $('.selectpicker').selectpicker('refresh');

    this.onTypeChange();
    this.timeRangeChange();

    return this;
  },
  hide: function() {
    "use strict";
    this.$el.find('#download-modal').modal('hide');
    return this;
  },
  template: JST["ooiui/static/js/partials/StreamDownloadForm.html"],
  render: function() {
    "use strict";
    this.$el.html(this.template({}));

    this.$el.find('#start-date').datetimepicker({format: "YYYY-MM-DD HH:mm:ss",
                                                 sideBySide: true
                                                 });
    this.$el.find('#end-date').datetimepicker({format: "YYYY-MM-DD HH:mm:ss",
                                               sideBySide: true
                                               });
    this.$start_date = this.$el.find('#start-date');
    this.$end_date = this.$el.find('#end-date');
    this.$type_select = this.$el.find('#type-select select');
    this.$start_date_picker = this.$start_date.data('DateTimePicker');
    this.$end_date_picker = this.$end_date.data('DateTimePicker');

  }
});
<|endoftext|>


<commit_before>var evtSrc = {};

angular.module('auction').controller('AuctionController', [
  '$scope', 'AuctionConfig', 'AuctionUtils',
  '$timeout', '$http', '$log', '$cookies', '$window',
  '$rootScope', '$location', '$translate', '$filter', 'growl', 'growlMessages', 'aside',
  function (
    $scope, AuctionConfig, AuctionUtils,
    $timeout, $http, $log, $cookies, $window,
    $rootScope, $location, $translate, $filter, growl, growlMessages, $aside
  ) {
    // init variables
    $scope.growlMessages = growlMessages;
    growlMessages.initDirective(0, 10);
    $scope.allow_bidding = true;
    $scope.bid = null;
    $rootScope.form = {};
    $rootScope.alerts = [];
    $scope.db = new PouchDB(AuctionConfig.remote_db);
    if ($translate.storage().get($translate.storageKey())){
      $scope.lang = $translate.storage().get($translate.storageKey());
    } else {
      $translate.use(AuctionConfig.default_lang);
      $scope.lang = AuctionConfig.default_lang;
    }
    $scope.format_date = AuctionUtils.format_date;
    $scope.bidder_id = null;
    $scope.$on('kick_client', function(event, client_id, msg) {
      $log.debug('Kick client connection', client_id, msg);
      $scope.growlMessages.deleteMessage(msg);
      $http.post('./kickclient', {'client_id': client_id}).success(
        function (data) {
          $log.debug('disable connection', client_id, msg);
      })
    });
    $scope.start_subscribe = function (argument) {
      evtSrc = new EventSource(window.location.href.replace(window.location.search, '') + '/event_source');
      $scope.restart_retries_events = 5;
      evtSrc.addEventListener('ClientsList', function (e) {
        var data = angular.fromJson(e.data);
        $log.debug("New ClientsList: ", data);
        $scope.$apply(function () {
          var i;
          if (angular.isObject($scope.clients)) {
            for (i in data) {
              if (!(i in $scope.clients)) {
                growl.warning($filter('translate')('In the room came a new user') + ' (IP:' + data[i].ip + ')' +'<button type="button" ng-click="$emit(\'kick_client\', + \''+i+'\', message )" class="btn btn-link">' + $filter('translate')('prohibit connection') + '</button>', {
                  ttl: 30000,
                  disableCountDown: true
                });
              }
            }
          }
          $scope.clients = data;
        });
      }, false);
      evtSrc.addEventListener('Tick', function (e) {
        $scope.restart_retries_events = 5;
        var data = angular.fromJson(e.data);
        $log.debug("Tick: ", data);
      }, false);
      evtSrc.addEventListener('Identification', function (e) {
        var data = angular.fromJson(e.data);
        $log.debug("Identification: ", data);
        $scope.$apply(function () {
          $scope.bidder_id = data.bidder_id;
          $scope.client_id = data.client_id;
        })
      }, false);

      evtSrc.addEventListener('KickClient', function (e) {
        var data = angular.fromJson(e.data);
        $log.debug("You are must logout: ", data);
        window.location.replace(window.location.href + '/logout');
      }, false);
      evtSrc.addEventListener('Close', function (e) {
        $log.debug("You are must logout ");
        evtSrc.close();
      }, false);
      evtSrc.onerror = function (e) {
        $scope.restart_retries_events = $scope.restart_retries_events - 1;
        $log.debug("EventSource failed.", e);
        if($scope.restart_retries_events == 0){
          evtSrc.close();
          $log.debug("EventSource Stoped.", e);
        }
      };
    };
    $scope.changeLanguage = function (langKey) {
      $translate.use(langKey);
      $scope.lang = langKey;
    };
    // Bidding form msgs
    $scope.closeAlert = function (msg_id) {
      for (var i = 0; i < $rootScope.alerts.length; i++) {
        if ($rootScope.alerts[i].msg_id == msg_id) {
          $rootScope.alerts.splice(i, 1);
          return true;
        }
      }
    };
    $scope.auto_close_alert = function (msg_id) {
      $timeout(function () {
        $scope.closeAlert(msg_id);
      }, 4000);
    };
    $scope.get_round_number = function (pause_index) {
      return AuctionUtils.get_round_data(pause_index, $scope.auction_doc, $scope.Rounds);
    };
    $scope.show_bids_form = function (argument) {
      if ((angular.isNumber($scope.auction_doc.current_stage)) && ($scope.auction_doc.current_stage >= 0)) {
        if (($scope.auction_doc.stages[$scope.auction_doc.current_stage].type == 'bids') && ($scope.auction_doc.stages[$scope.auction_doc.current_stage].bidder_id == $scope.bidder_id)) {
          return true;
        }
      }
      return false;
    };
    $scope.sync_times_with_server = function (start) {
      $http.get('/get_current_server_time').success(function (data) {
        $scope.last_sync = new Date(data);
        $rootScope.info_timer = AuctionUtils.prepare_info_timer_data($scope.last_sync, $scope.auction_doc, $scope.bidder_id, $scope.Rounds);
        $log.debug("Info timer data:", $rootScope.info_timer);
        $rootScope.progres_timer = AuctionUtils.prepare_progress_timer_data($scope.last_sync, $scope.auction_doc);
        $log.debug("Progres timer data:", $rootScope.progres_timer);

      });
    };
    $scope.post_bid = function () {
      if ($rootScope.form.BidsForm.$valid) {
        $http.post('./postbid', {
          'bid': $rootScope.form.bid,
          'bidder_id': $scope.bidder_id || bidder_id || "0"
        }).success(function (data) {
          var msg_id = '';
          if (data.status == 'failed') {
            for (var error_id in data.errors) {
              for (var i in data.errors[error_id]) {
                msg_id = Math.random();
                $rootScope.alerts.push({
                  msg_id: msg_id,
                  type: 'danger',
                  msg: data.errors[error_id][i]
                });
                $scope.auto_close_alert(msg_id);
              }
            }
          } else {
            msg_id = Math.random();
            $rootScope.alerts.push({
              msg_id: msg_id,
              type: 'success',
              msg: 'Bid placed'
            });
            $scope.auto_close_alert(msg_id);
            $scope.allow_bidding = false;
          }

        });
      }
    };
    $scope.edit_bid = function () {
      $scope.allow_bidding = true;
    };

    $scope.max_bid_amount = function () {
      if ((angular.isString($scope.bidder_id)) && (angular.isObject($scope.auction_doc)) && (angular.isObject($scope.auction_doc.stages[$scope.auction_doc.current_stage]))) {
        return $scope.auction_doc.stages[$scope.auction_doc.current_stage].amount - $scope.auction_doc.minimalStep.amount;
      }
      return 0;
    };
    $scope.calculate_minimal_bid_amount = function () {
      if ((angular.isObject($scope.auction_doc)) && (angular.isArray($scope.auction_doc.stages)) && (angular.isArray($scope.auction_doc.initial_bids))) {
        var bids = [];
        filter_func = function (item, index) {
          if (!angular.isUndefined(item.amount)) {
            bids.push(item.amount);
          }
        };
        $scope.auction_doc.stages.forEach(filter_func);
        $scope.auction_doc.initial_bids.forEach(filter_func);
        $scope.minimal_bid = bids.sort()[0];
      }
    };
    $scope.start_sync = function () {
      $scope.changes = $scope.db.changes({
        live: true,
        style: 'main_only',
        continuous: true,
        include_docs: true,
        doc_ids: [AuctionConfig.auction_doc_id],
        since: 0
      }).on('change', function (resp) {
        $log.debug('Change: ', resp);
        $scope.restart_retries = AuctionConfig.restart_retries;
        if (resp.id == AuctionConfig.auction_doc_id) {
          $scope.replace_document(resp.doc);
          if ($scope.auction_doc.current_stage == ($scope.auction_doc.stages.length - 1)) {
            $scope.changes.cancel();
          }
        }
      }).on('error', function (err) {
        $log.error('Changes error: ', err);
        $timeout(function () {
          growl.warning('Internet connection is lost. Attempt to restart after 1 sec', {
            ttl: 1000
          });
          $scope.restart_retries -= 1;
          if ($scope.restart_retries) {
            $log.debug('Start restart feed pooling...');
            $scope.restart_changes();
          } else {
            growl.error('Synchronization failed');
            $log.error('Restart synchronization not allowed.', AuctionConfig.restart_retries);
          }
        }, 1000);
      });
    };
    $scope.db.get(AuctionConfig.auction_doc_id, function (err, doc) {
      if (err) {
        $log.error('Error:', err);
        return 0;
      }
      $scope.start_subscribe();
      $scope.replace_document(doc);
      $scope.document_exists = true;
      $scope.scroll_to_stage();
      if ($scope.auction_doc.current_stage != ($scope.auction_doc.stages.length - 1)) {
        $scope.restart_retries = AuctionConfig.restart_retries;
        $scope.sync = $scope.start_sync();
      }
    });
    $scope.restart_changes = function () {
      $scope.changes.cancel();
      $timeout(function () {
        $scope.start_sync();
      }, 1000);
    };
    $scope.replace_document = function (new_doc) {
      $rootScope.$apply(function (argument) {
        if ((angular.isUndefined($scope.auction_doc)) || (new_doc.current_stage - $scope.auction_doc.current_stage === 0) || (new_doc.current_stage === -1)) {
          $scope.auction_doc = new_doc;
        } else {
          $rootScope.form.bid = null;
          $scope.allow_bidding = true;
          $scope.auction_doc = new_doc;
        }
        $scope.sync_times_with_server();
        $scope.calculate_rounds();
        $scope.calculate_minimal_bid_amount();
        $scope.scroll_to_stage();
      });
    };
    $scope.calculate_rounds = function (argument) {
      $scope.Rounds = [];
      $scope.auction_doc.stages.forEach(function (item, index) {
        if (item.type == 'pause') {
          $scope.Rounds.push(index);
        }
      });

    };
    $scope.scroll_to_stage = function (argument) {
      AuctionUtils.scroll_to_stage($scope.auction_doc.current_stage);
    };
    $scope.array = function (int) {
      return new Array(int);
    };
    $scope.open_menu = function () {
      var modalInstance = $aside.open({
        templateUrl: 'templates/menu.html',
        controller: 'OffCanvasController',
        scope: $scope,
        size: 'lg'
      });
    };
  }
]);

angular.module('auction').controller('OffCanvasController', ['$scope', '$modalInstance',
  function($scope, $modalInstance){
    $scope.allert = function () {
      console.log($scope);
      // body...
    }
    $scope.ok = function () {
      $modalInstance.close($scope.selected.item);
    };
    $scope.cancel = function () {
      $modalInstance.dismiss('cancel');
    };
  }
]);

angular.module('auction').directive('nghReplace', function($compile, $parse, $rootScope) {
    return {
      replace: true,
      link: function(scope, element, attr) {
        scope.$watch(attr.content, function() {
          element.html($parse(attr.content)(scope));
          $compile(element.contents())(scope);
        }, true);
      }
    }
  })

<commit_msg>Fixed minimal bids calculations<commit_after>var evtSrc = {};

angular.module('auction').controller('AuctionController', [
  '$scope', 'AuctionConfig', 'AuctionUtils',
  '$timeout', '$http', '$log', '$cookies', '$window',
  '$rootScope', '$location', '$translate', '$filter', 'growl', 'growlMessages', 'aside',
  function (
    $scope, AuctionConfig, AuctionUtils,
    $timeout, $http, $log, $cookies, $window,
    $rootScope, $location, $translate, $filter, growl, growlMessages, $aside
  ) {
    // init variables
    $scope.growlMessages = growlMessages;
    growlMessages.initDirective(0, 10);
    $scope.allow_bidding = true;
    $scope.bid = null;
    $rootScope.form = {};
    $rootScope.alerts = [];
    $scope.db = new PouchDB(AuctionConfig.remote_db);
    if ($translate.storage().get($translate.storageKey())){
      $scope.lang = $translate.storage().get($translate.storageKey());
    } else {
      $translate.use(AuctionConfig.default_lang);
      $scope.lang = AuctionConfig.default_lang;
    }
    $scope.format_date = AuctionUtils.format_date;
    $scope.bidder_id = null;
    $scope.$on('kick_client', function(event, client_id, msg) {
      $log.debug('Kick client connection', client_id, msg);
      $scope.growlMessages.deleteMessage(msg);
      $http.post('./kickclient', {'client_id': client_id}).success(
        function (data) {
          $log.debug('disable connection', client_id, msg);
      })
    });
    $scope.start_subscribe = function (argument) {
      evtSrc = new EventSource(window.location.href.replace(window.location.search, '') + '/event_source');
      $scope.restart_retries_events = 5;
      evtSrc.addEventListener('ClientsList', function (e) {
        var data = angular.fromJson(e.data);
        $log.debug("New ClientsList: ", data);
        $scope.$apply(function () {
          var i;
          if (angular.isObject($scope.clients)) {
            for (i in data) {
              if (!(i in $scope.clients)) {
                growl.warning($filter('translate')('In the room came a new user') + ' (IP:' + data[i].ip + ')' +'<button type="button" ng-click="$emit(\'kick_client\', + \''+i+'\', message )" class="btn btn-link">' + $filter('translate')('prohibit connection') + '</button>', {
                  ttl: 30000,
                  disableCountDown: true
                });
              }
            }
          }
          $scope.clients = data;
        });
      }, false);
      evtSrc.addEventListener('Tick', function (e) {
        $scope.restart_retries_events = 5;
        var data = angular.fromJson(e.data);
        $log.debug("Tick: ", data);
      }, false);
      evtSrc.addEventListener('Identification', function (e) {
        var data = angular.fromJson(e.data);
        $log.debug("Identification: ", data);
        $scope.$apply(function () {
          $scope.bidder_id = data.bidder_id;
          $scope.client_id = data.client_id;
        })
      }, false);

      evtSrc.addEventListener('KickClient', function (e) {
        var data = angular.fromJson(e.data);
        $log.debug("You are must logout: ", data);
        window.location.replace(window.location.href + '/logout');
      }, false);
      evtSrc.addEventListener('Close', function (e) {
        $log.debug("You are must logout ");
        evtSrc.close();
      }, false);
      evtSrc.onerror = function (e) {
        $scope.restart_retries_events = $scope.restart_retries_events - 1;
        $log.debug("EventSource failed.", e);
        if($scope.restart_retries_events == 0){
          evtSrc.close();
          $log.debug("EventSource Stoped.", e);
        }
      };
    };
    $scope.changeLanguage = function (langKey) {
      $translate.use(langKey);
      $scope.lang = langKey;
    };
    // Bidding form msgs
    $scope.closeAlert = function (msg_id) {
      for (var i = 0; i < $rootScope.alerts.length; i++) {
        if ($rootScope.alerts[i].msg_id == msg_id) {
          $rootScope.alerts.splice(i, 1);
          return true;
        }
      }
    };
    $scope.auto_close_alert = function (msg_id) {
      $timeout(function () {
        $scope.closeAlert(msg_id);
      }, 4000);
    };
    $scope.get_round_number = function (pause_index) {
      return AuctionUtils.get_round_data(pause_index, $scope.auction_doc, $scope.Rounds);
    };
    $scope.show_bids_form = function (argument) {
      if ((angular.isNumber($scope.auction_doc.current_stage)) && ($scope.auction_doc.current_stage >= 0)) {
        if (($scope.auction_doc.stages[$scope.auction_doc.current_stage].type == 'bids') && ($scope.auction_doc.stages[$scope.auction_doc.current_stage].bidder_id == $scope.bidder_id)) {
          return true;
        }
      }
      return false;
    };
    $scope.sync_times_with_server = function (start) {
      $http.get('/get_current_server_time').success(function (data) {
        $scope.last_sync = new Date(data);
        $rootScope.info_timer = AuctionUtils.prepare_info_timer_data($scope.last_sync, $scope.auction_doc, $scope.bidder_id, $scope.Rounds);
        $log.debug("Info timer data:", $rootScope.info_timer);
        $rootScope.progres_timer = AuctionUtils.prepare_progress_timer_data($scope.last_sync, $scope.auction_doc);
        $log.debug("Progres timer data:", $rootScope.progres_timer);

      });
    };
    $scope.post_bid = function () {
      if ($rootScope.form.BidsForm.$valid) {
        $http.post('./postbid', {
          'bid': $rootScope.form.bid,
          'bidder_id': $scope.bidder_id || bidder_id || "0"
        }).success(function (data) {
          var msg_id = '';
          if (data.status == 'failed') {
            for (var error_id in data.errors) {
              for (var i in data.errors[error_id]) {
                msg_id = Math.random();
                $rootScope.alerts.push({
                  msg_id: msg_id,
                  type: 'danger',
                  msg: data.errors[error_id][i]
                });
                $scope.auto_close_alert(msg_id);
              }
            }
          } else {
            msg_id = Math.random();
            $rootScope.alerts.push({
              msg_id: msg_id,
              type: 'success',
              msg: 'Bid placed'
            });
            $scope.auto_close_alert(msg_id);
            $scope.allow_bidding = false;
          }

        });
      }
    };
    $scope.edit_bid = function () {
      $scope.allow_bidding = true;
    };

    $scope.max_bid_amount = function () {
      var amount = 0;
      if ((angular.isString($scope.bidder_id)) && (angular.isObject($scope.auction_doc)) && (angular.isObject($scope.auction_doc.stages[$scope.auction_doc.current_stage]))) {
        amount = $scope.auction_doc.stages[$scope.auction_doc.current_stage].amount - $scope.auction_doc.minimalStep.amount;
      }
      if (amount < 0){
        return 0;
      };
      return amount
    };
    $scope.calculate_minimal_bid_amount = function () {
      if ((angular.isObject($scope.auction_doc)) && (angular.isArray($scope.auction_doc.stages)) && (angular.isArray($scope.auction_doc.initial_bids))) {
        var bids = [];
        filter_func = function (item, index) {
          if (!angular.isUndefined(item.amount)) {
            bids.push(item.amount);
          }
        };
        $scope.auction_doc.stages.forEach(filter_func);
        $scope.auction_doc.initial_bids.forEach(filter_func);
        $scope.minimal_bid = bids.sort()[0];
      }
    };
    $scope.start_sync = function () {
      $scope.changes = $scope.db.changes({
        live: true,
        style: 'main_only',
        continuous: true,
        include_docs: true,
        doc_ids: [AuctionConfig.auction_doc_id],
        since: 0
      }).on('change', function (resp) {
        $log.debug('Change: ', resp);
        $scope.restart_retries = AuctionConfig.restart_retries;
        if (resp.id == AuctionConfig.auction_doc_id) {
          $scope.replace_document(resp.doc);
          if ($scope.auction_doc.current_stage == ($scope.auction_doc.stages.length - 1)) {
            $scope.changes.cancel();
          }
        }
      }).on('error', function (err) {
        $log.error('Changes error: ', err);
        $timeout(function () {
          growl.warning('Internet connection is lost. Attempt to restart after 1 sec', {
            ttl: 1000
          });
          $scope.restart_retries -= 1;
          if ($scope.restart_retries) {
            $log.debug('Start restart feed pooling...');
            $scope.restart_changes();
          } else {
            growl.error('Synchronization failed');
            $log.error('Restart synchronization not allowed.', AuctionConfig.restart_retries);
          }
        }, 1000);
      });
    };
    $scope.db.get(AuctionConfig.auction_doc_id, function (err, doc) {
      if (err) {
        $log.error('Error:', err);
        return 0;
      }
      $scope.start_subscribe();
      $scope.replace_document(doc);
      $scope.document_exists = true;
      $scope.scroll_to_stage();
      if ($scope.auction_doc.current_stage != ($scope.auction_doc.stages.length - 1)) {
        $scope.restart_retries = AuctionConfig.restart_retries;
        $scope.sync = $scope.start_sync();
      }
    });
    $scope.restart_changes = function () {
      $scope.changes.cancel();
      $timeout(function () {
        $scope.start_sync();
      }, 1000);
    };
    $scope.replace_document = function (new_doc) {
      $rootScope.$apply(function (argument) {
        if ((angular.isUndefined($scope.auction_doc)) || (new_doc.current_stage - $scope.auction_doc.current_stage === 0) || (new_doc.current_stage === -1)) {
          $scope.auction_doc = new_doc;
        } else {
          $rootScope.form.bid = null;
          $scope.allow_bidding = true;
          $scope.auction_doc = new_doc;
        }
        $scope.sync_times_with_server();
        $scope.calculate_rounds();
        $scope.calculate_minimal_bid_amount();
        $scope.scroll_to_stage();
      });
    };
    $scope.calculate_rounds = function (argument) {
      $scope.Rounds = [];
      $scope.auction_doc.stages.forEach(function (item, index) {
        if (item.type == 'pause') {
          $scope.Rounds.push(index);
        }
      });

    };
    $scope.scroll_to_stage = function (argument) {
      AuctionUtils.scroll_to_stage($scope.auction_doc.current_stage);
    };
    $scope.array = function (int) {
      return new Array(int);
    };
    $scope.open_menu = function () {
      var modalInstance = $aside.open({
        templateUrl: 'templates/menu.html',
        controller: 'OffCanvasController',
        scope: $scope,
        size: 'lg'
      });
    };
  }
]);

angular.module('auction').controller('OffCanvasController', ['$scope', '$modalInstance',
  function($scope, $modalInstance){
    $scope.allert = function () {
      console.log($scope);
      // body...
    }
    $scope.ok = function () {
      $modalInstance.close($scope.selected.item);
    };
    $scope.cancel = function () {
      $modalInstance.dismiss('cancel');
    };
  }
]);

angular.module('auction').directive('nghReplace', function($compile, $parse, $rootScope) {
    return {
      replace: true,
      link: function(scope, element, attr) {
        scope.$watch(attr.content, function() {
          element.html($parse(attr.content)(scope));
          $compile(element.contents())(scope);
        }, true);
      }
    }
  })

<|endoftext|>


<commit_before>var parser = PEG.buildParser(grammar);

var td = undefined;

function getTd () { return td; }

function translateTerm () {
    try {
	var processingInstance = Processing.getInstanceById("canvas");
	var newTd =
	    processingInstance.interpret(
		collectFreeVars(
		    eliminateTermSum(
			parser.parse(
			    document.getElementById("term").value))));
	td = newTd;
	goReady();
    } catch (err) {
	switch (err.name) {
	case "SyntaxError":
	    addConsole("****************\n"
		       + err.name
		       + " at (" + err.line + "," + err.column + "): "
		       + err.message
		       + "\nInput is ignored."
		       + "\n****************");
	    break;
	case "Error":
	    addConsole("****************\n"
		       + err.name + ": " + err.message
		       + "\nInput is ignored."
		       + "\n****************");
	    break;
	default:
	    console.log(err);
	    break;
	}
	switch (getState()) {
	case STATE_IDLE: case STATE_READY: goIdle(); break;
	case STATE_RUN: case STATE_PAUSE: goPause(); break;
	}
    }
}

var count = 0;

function eliminateTermSum (parsedTerm) {
    if (parsedTerm.tag == "+") {
	if (isEqual(parsedTerm.bodies[0], parsedTerm.bodies[1])) {
	    var newVar = "C" + count;
	    count++;
	    var varSumFunc =
		new Term("lambda", [newVar],
			 [new Term("+1", [newVar], [])]);
	    parsedTerm =
		new Term("app", [],
			 [varSumFunc,
			  eliminateTermSum(parsedTerm.bodies[0])]);
	} else {
	    var newVarLeft = "L" + count;
	    count++;
	    var newVarRight = "R" + count;
	    count++;
	    var varSumFunc =
		new Term("lambda", [newVarLeft],
			 [new Term("lambda", [newVarRight],
				   [new Term("+2",
					     [newVarLeft,
					      newVarRight], [])])]);
	    parsedTerm =
		new Term("app", [],
			 [new Term("app", [],
				   [varSumFunc,
				    eliminateTermSum
				    (parsedTerm.bodies[0])]),
			  eliminateTermSum(parsedTerm.bodies[1])]);
	}
    } else {
	for (var i = 0; i < parsedTerm.bodies.length; i++) {
	    parsedTerm.bodies[i] =
		eliminateTermSum(parsedTerm.bodies[i]);
	}
    }
    return parsedTerm;
}

function collectFreeVars (parsedTerm) {
    switch (parsedTerm.tag) {
    case "var":
	var varIt = parsedTerm.parameters[0];
	var index = -1;
	for (var i = 0; i < parsedTerm.freeVars.length; i++) {
	    if (parsedTerm.freeVars[i] == varIt)
		index = i;	// take the last one
	}
	if (index < 0)
	    throw new Error("unknown variable \"" + varIt + "\"");
	else parsedTerm.parameters[0] = index;
	break;
    case "lambda": case "rec":
	parsedTerm.bodies[0].freeVars =
	    parsedTerm.freeVars.concat(parsedTerm.parameters);
	parsedTerm.bodies[0] = collectFreeVars(parsedTerm.bodies[0]);
	break;
    case "match":
	parsedTerm.bodies[0].freeVars = parsedTerm.freeVars;
	parsedTerm.bodies[0] = collectFreeVars(parsedTerm.bodies[0]);
	for (var i = 0; i <= 1; i++) {
	    parsedTerm.bodies[i + 1].freeVars =
		parsedTerm.freeVars.concat(parsedTerm.parameters[i]);
	    parsedTerm.bodies[i + 1] =
		collectFreeVars(parsedTerm.bodies[i + 1]);
	}
	break;
    default:
	for (var i = 0; i < parsedTerm.bodies.length; i++) {
	    parsedTerm.bodies[i].freeVars = parsedTerm.freeVars;
	    parsedTerm.bodies[i] =
		collectFreeVars(parsedTerm.bodies[i]);
	}
	break;
    }
    return parsedTerm;
}
<commit_msg>fix a bug in translation of sum<commit_after>var parser = PEG.buildParser(grammar);

var td = undefined;

function getTd () { return td; }

function translateTerm () {
    try {
	var processingInstance = Processing.getInstanceById("canvas");
	var newTd =
	    processingInstance.interpret(
		collectFreeVars(
		    eliminateTermSum(
			parser.parse(
			    document.getElementById("term").value))));
	td = newTd;
	goReady();
    } catch (err) {
	switch (err.name) {
	case "SyntaxError":
	    addConsole("****************\n"
		       + err.name
		       + " at (" + err.line + "," + err.column + "): "
		       + err.message
		       + "\nInput is ignored."
		       + "\n****************");
	    break;
	case "Error":
	    addConsole("****************\n"
		       + err.name + ": " + err.message
		       + "\nInput is ignored."
		       + "\n****************");
	    break;
	default:
	    console.log(err);
	    break;
	}
	switch (getState()) {
	case STATE_IDLE: case STATE_READY: goIdle(); break;
	case STATE_RUN: case STATE_PAUSE: goPause(); break;
	}
    }
}

var count = 0;

function eliminateTermSum (parsedTerm) {
    if (parsedTerm.tag == "+") {
	if (isEqual(parsedTerm.bodies[0], parsedTerm.bodies[1])) {
	    if (parsedTerm.bodies[0].tag == "var") {
		parsedTerm =
		    new Term("+1",
			     [parsedTerm.bodies[0].parameters[0]],
			     []);
	    } else {
		var newVar = "C" + count;
		count++;
		var varSumFunc =
		    new Term("lambda", [newVar],
			     [new Term("+1", [newVar], [])]);
		parsedTerm =
		    new Term("app", [],
			     [varSumFunc,
			      eliminateTermSum(parsedTerm.bodies[0])]);
	    }
	} else {
	    if (parsedTerm.bodies[0].tag == "var"
		&& parsedTerm.bodies[1].tag == "var") {
		parsedTerm =
		    new Term("+2",
			     [parsedTerm.bodies[0].parameters[0],
			      parsedTerm.bodies[1].parameters[0]],
			     []);
	    } else {
		var newVarLeft = "L" + count;
		count++;
		var newVarRight = "R" + count;
		count++;
		var varSumFunc =
		    new Term("lambda", [newVarLeft],
			     [new Term("lambda", [newVarRight],
				       [new Term("+2",
						 [newVarLeft,
						  newVarRight],
						 [])])]);
		parsedTerm =
		    new Term("app", [],
			     [new Term("app", [],
				       [varSumFunc,
					eliminateTermSum
					(parsedTerm.bodies[0])]),
			      eliminateTermSum(parsedTerm.bodies[1])]);
	    }
	}
    } else {
	for (var i = 0; i < parsedTerm.bodies.length; i++) {
	    parsedTerm.bodies[i] =
		eliminateTermSum(parsedTerm.bodies[i]);
	}
    }
    return parsedTerm;
}

function collectFreeVars (parsedTerm) {
    switch (parsedTerm.tag) {
    case "var":
	var varIt = parsedTerm.parameters[0];
	var index = -1;
	for (var i = 0; i < parsedTerm.freeVars.length; i++) {
	    if (parsedTerm.freeVars[i] == varIt)
		index = i;	// take the last one
	}
	if (index < 0)
	    throw new Error("unknown variable \"" + varIt + "\"");
	else parsedTerm.parameters[0] = index;
	break;
    case "lambda": case "rec":
	parsedTerm.bodies[0].freeVars =
	    parsedTerm.freeVars.concat(parsedTerm.parameters);
	parsedTerm.bodies[0] = collectFreeVars(parsedTerm.bodies[0]);
	break;
    case "match":
	parsedTerm.bodies[0].freeVars = parsedTerm.freeVars;
	parsedTerm.bodies[0] = collectFreeVars(parsedTerm.bodies[0]);
	for (var i = 0; i <= 1; i++) {
	    parsedTerm.bodies[i + 1].freeVars =
		parsedTerm.freeVars.concat(parsedTerm.parameters[i]);
	    parsedTerm.bodies[i + 1] =
		collectFreeVars(parsedTerm.bodies[i + 1]);
	}
	break;
    default:
	for (var i = 0; i < parsedTerm.bodies.length; i++) {
	    parsedTerm.bodies[i].freeVars = parsedTerm.freeVars;
	    parsedTerm.bodies[i] =
		collectFreeVars(parsedTerm.bodies[i]);
	}
	break;
    }
    return parsedTerm;
}
<|endoftext|>


<commit_before>(function () {

    app(function (api) {

        api.on("load:detail", function (path) {

            var result = path.split("/")[1] && api.searchResults[path.split("/")[1]],
                tmpl = $("#tmpl-detail").innerHTML.trim();

            $("#detail section").innerHTML = riot.render(tmpl, {
                name: result.fileinfo.name,
                path: result.fileinfo.path,
                size: result.file.size ? Math.round(result.file.size / 1000) + " KB" : "Unknown",
                modified: result.file.lastModifiedDate ? result.file.lastModifiedDate.toDateString() : "Unknown",
                icontype: api.iconclass(result.file.type),
                i: path.split("/")[1],
                shareorpickid: api.activityRequest ? "pick" : "share",
                shareorpickclass: api.activityRequest ? "ok-circled" : "share"
            });

            // Preview button handler
            $("#previewbtn").addEventListener("click", function (e) {
                e.preventDefault();

                var activityname = "open",
                    result = api.searchResults[e.target.dataset.index];
                if (result.file.type === "application/pdf") {
                    activityname = "view";
                }

                var activity = new MozActivity({
                    name: activityname,
                    data: {
                        type: result.file.type,
                        blob: result.file
                    }
                });

                activity.onerror = function () {
                    alert("Cannot preview this file.");
                };

            }, false);

            // Share button handler
            $("#sharebtn").addEventListener("click", function (e) {
                e.preventDefault();

                var result = api.searchResults[e.target.dataset.index];

                var data = { blobs: [result.file], number: 1 };

                if (result.file.type.indexOf("image") === 0) {
                    data.type = "image/*";
                }

                var activity = new MozActivity({
                    name: "share",
                    data: data
                });

            }, false);

            // Memory cleanup
            result = tmpl = null;

        });

    });

})();
<commit_msg>Make preview and share button handlers check for their existence<commit_after>(function () {

    app(function (api) {

        api.on("load:detail", function (path) {

            var result = path.split("/")[1] && api.searchResults[path.split("/")[1]],
                tmpl = $("#tmpl-detail").innerHTML.trim();

            $("#detail section").innerHTML = riot.render(tmpl, {
                name: result.fileinfo.name,
                path: result.fileinfo.path,
                size: result.file.size ? Math.round(result.file.size / 1000) + " KB" : "Unknown",
                modified: result.file.lastModifiedDate ? result.file.lastModifiedDate.toDateString() : "Unknown",
                icontype: api.iconclass(result.file.type),
                i: path.split("/")[1],
                shareorpickid: api.activityRequest ? "pick" : "share",
                shareorpickclass: api.activityRequest ? "ok-circled" : "share"
            });

            // Preview button handler
            $("#previewbtn") && $("#previewbtn").addEventListener("click", function (e) {
                e.preventDefault();

                var activityname = "open",
                    result = api.searchResults[e.target.dataset.index];
                if (result.file.type === "application/pdf") {
                    activityname = "view";
                }

                var activity = new MozActivity({
                    name: activityname,
                    data: {
                        type: result.file.type,
                        blob: result.file
                    }
                });

                activity.onerror = function () {
                    alert("Cannot preview this file.");
                };

            }, false);

            // Share button handler
            $("#sharebtn") && $("#sharebtn").addEventListener("click", function (e) {
                e.preventDefault();

                var result = api.searchResults[e.target.dataset.index];

                var data = { blobs: [result.file], number: 1 };

                if (result.file.type.indexOf("image") === 0) {
                    data.type = "image/*";
                }

                var activity = new MozActivity({
                    name: "share",
                    data: data
                });

            }, false);

            // Memory cleanup
            result = tmpl = null;

        });

    });

})();
<|endoftext|>


<commit_before>/* Namespace for core functionality related to DataTables. */
horizon.datatables = {

};

horizon.datatables.add_no_results_row = function (table) {
  /*// Add a "no results" row if there are no results.
  template = horizon.templates.compiled_templates["#empty_row_template"];
  if (!table.find("div.list-group-item:visible").length
      && typeof(template) !== "undefined") {
    table.append(template.render());
  }*/
  table.find("p.empty").show();
};

horizon.datatables.remove_no_results_row = function (table) {
  table.find("p.empty").hide();
};

horizon.datatables.ajax_paginate = function(table, table_selector, page_num) {
  horizon.ajax.queue({
    type: 'GET',
    url: table.attr('data-pagination-url'),
    data: {
      page: page_num,
      application_id: table.attr('data-application_id'),
      organization_id: table.attr('data-organization_id'),
    },
    beforeSend: function () {
      // add a spinner to show progress
      var list_group = $('#'+table_selector).find('div.list-group');
      list_group.html('');
    },
    complete: function () {
    },
    error: function(jqXHR, status, errorThrown) {
    },
    success: function (data, textStatus, jqXHR) {
      var list_group = $('#'+table_selector).find('div.list-group');
      list_group.empty();

      // process data
      var items = data['items'];
      if (items.length) {
        horizon.datatables.remove_no_results_row(table);
      } else {
        horizon.datatables.add_no_results_row(table);
      }

      for (var i in items) {
        var display_name = items[i]['username'];
        if (display_name === undefined) {
          display_name = items[i]['name'];
        }
        var avatar = items[i]['img_small'];
        var data_id = items[i]['id'];
        var description = items[i]['description'];

        list_group.append('
' +
          '' +
          '

'+
          '
'+ display_name +'
' +
          '
'+ description +'

');
      }

      // reinitialize pagination
      horizon.datatables.init_pagination(table, table_selector, data['pages']);
    }
  });
}
horizon.datatables.init_pagination = function (table, table_selector, total_pages) {
  // init bootpag
  $('#'+table_selector+'_pagination_container').bootpag({
      total: total_pages,
      first: 'First',
      last:'Last',
      maxVisible: 10,
      wrapClass: 'pagination',
      firstLastUse: true
  }).on("page", function(event, page_num){
    horizon.datatables.ajax_paginate(table, table_selector, page_num);
  });
};

horizon.datatables.set_table_query_filter = function (parent) {
  horizon.datatables.qs = {};
  $(parent).find('div.panel').each(function (index, elm) {
    var input = $($(elm).find('div.table_search.client input')),
        table_selector;
    if (input.length > 0) {
      // Disable server-side searching if we have client-side searching since
      // (for now) the client-side is actually superior. Server-side filtering
      // remains as a noscript fallback.
      // TODO(gabriel): figure out an overall strategy for making server-side
      // filtering the preferred functional method.
      input.on('keypress', function (evt) {
        if (evt.keyCode === 13) {
          return false;
        }
      });
      input.next('button.btn span.fa-search').on('click keypress', function (evt) {
        return false;
      });

      // Enable the client-side searching.
      table_selector = '#' + $(elm).find('div.list-group').attr('id');

      var qs = input.quicksearch(table_selector + ' div.list-group-item', {
        'delay': 300,
        'loader': 'span.loading',
        'bind': 'keyup click',
        'show': this.show,
        'hide': this.hide,
        onBefore: function () {
          var table = $(table_selector);
          horizon.datatables.remove_no_results_row(table);
        },
        onAfter: function () {
          var template, table, colspan, params;
          table = $(table_selector);
          horizon.datatables.add_no_results_row(table);
        },
        prepareQuery: function (val) {
          return new RegExp(val, "i");
        },
        testQuery: function (query, txt, _row) {
          return query.test($(_row).find('div.filter_field:not(.hidden):not(.actions_column)').text());
        }
      });
    }
  });
};

horizon.addInitFunction(function() {
  $('div.datatable').each(function (idx, el) {
    var table_selector = $(el).attr('id');
    // load intial elements
    horizon.datatables.ajax_paginate($(el), table_selector, 1);
  });

  // Trigger run-once setup scripts for tables.
  horizon.datatables.set_table_query_filter($('body'));

  // Also apply on tables in modal views.
  horizon.modals.addModalInitFunction(horizon.datatables.set_table_query_filter);

  // Also apply on tables in tabs views for lazy-loaded data.
  horizon.tabs.addTabLoadFunction(horizon.datatables.set_table_query_filter);

});
<commit_msg>added filter by name through API<commit_after>/* Namespace for core functionality related to DataTables. */
horizon.datatables = {
  timestamp_query: performance.now(),
  pending_request: undefined,
};

horizon.datatables.add_no_results_row = function (table) {
  /*// Add a "no results" row if there are no results.
  template = horizon.templates.compiled_templates["#empty_row_template"];
  if (!table.find("div.list-group-item:visible").length
      && typeof(template) !== "undefined") {
    table.append(template.render());
  }*/
  table.find("p.empty").show();
};

horizon.datatables.remove_no_results_row = function (table) {
  table.find("p.empty").hide();
};

horizon.datatables.ajax_paginate = function(table, table_selector, page_num) {
  horizon.ajax.queue({
    type: 'GET',
    url: table.attr('data-pagination-url'),
    data: {
      page: page_num,
      application_id: table.attr('data-application_id'),
      organization_id: table.attr('data-organization_id'),
      name__startswith: table.find('div.table_search.client input').val() || undefined,
    },
    beforeSend: function () {
      // add a spinner to show progress
      var list_group = $('#'+table_selector).find('div.list-group');
      list_group.html('');
    },
    complete: function () {
    },
    error: function(jqXHR, status, errorThrown) {
    },
    success: function (data, textStatus, jqXHR) {
      var list_group = $('#'+table_selector).find('div.list-group');
      list_group.empty();

      // process data
      var items = data['items'];
      if (items.length) {
        horizon.datatables.remove_no_results_row(table);
      } else {
        horizon.datatables.add_no_results_row(table);
      }

      for (var i in items) {
        var display_name = items[i]['username'];
        if (display_name === undefined) {
          display_name = items[i]['name'];
        }
        var avatar = items[i]['img_small'];
        var data_id = items[i]['id'];
        var description = items[i]['description'];

        list_group.append('
' +
          '' +
          '

'+
          '
'+ display_name +'
' +
          '
'+ description +'

');
      }

      // reinitialize pagination
      horizon.datatables.init_pagination(table, table_selector, data['pages']);
    }
  });
}
horizon.datatables.init_pagination = function (table, table_selector, total_pages) {
  // init bootpag
  $('#'+table_selector+'_pagination_container').bootpag({
      total: total_pages,
      first: 'First',
      last:'Last',
      maxVisible: 10,
      wrapClass: 'pagination',
      firstLastUse: true
  }).on("page", function(event, page_num){
    horizon.datatables.ajax_paginate(table, table_selector, page_num);
  });
};

horizon.datatables.set_pagination_filter = function(table, table_selector) {
  var MIN_TIME_BETWEEN_QUERIES = 600; // ms
  var MIN_LETTERS_TO_QUERY = -1;

  table.find('div.table_search.client input').on('input', function() {
    var $input = $(this);
    var filter_data = $input.attr('value');
    if (filter_data.length < MIN_LETTERS_TO_QUERY){
      return;
    }

    var dif =  performance.now() - horizon.datatables.timestamp_query;
    if(dif < MIN_TIME_BETWEEN_QUERIES){
      if (horizon.datatables.pending_request !== undefined) {
        // kill previous request
        window.clearTimeout(horizon.datatables.pending_request);
      }
    }

    //store query time
    horizon.datatables.timestamp_query = performance.now();

    horizon.datatables.pending_request = window.setTimeout(function() {
        horizon.datatables.ajax_paginate(table, table_selector, 1);
      }, MIN_TIME_BETWEEN_QUERIES);
  });

};

horizon.datatables.set_table_query_filter = function (parent) {
  horizon.datatables.qs = {};
  $(parent).find('div.panel').each(function (index, elm) {
    var input = $($(elm).find('div.table_search.client input')),
        table_selector;
    if (input.length > 0) {
      // Disable server-side searching if we have client-side searching since
      // (for now) the client-side is actually superior. Server-side filtering
      // remains as a noscript fallback.
      // TODO(gabriel): figure out an overall strategy for making server-side
      // filtering the preferred functional method.
      input.on('keypress', function (evt) {
        if (evt.keyCode === 13) {
          return false;
        }
      });
      input.next('button.btn span.fa-search').on('click keypress', function (evt) {
        return false;
      });

      // Enable the client-side searching.
      table_selector = '#' + $(elm).find('div.list-group').attr('id');

      var qs = input.quicksearch(table_selector + ' div.list-group-item', {
        'delay': 300,
        'loader': 'span.loading',
        'bind': 'keyup click',
        'show': this.show,
        'hide': this.hide,
        onBefore: function () {
          var table = $(table_selector);
          horizon.datatables.remove_no_results_row(table);
        },
        onAfter: function () {
          var template, table, colspan, params;
          table = $(table_selector);
          horizon.datatables.add_no_results_row(table);
        },
        prepareQuery: function (val) {
          return new RegExp(val, "i");
        },
        testQuery: function (query, txt, _row) {
          return query.test($(_row).find('div.filter_field:not(.hidden):not(.actions_column)').text());
        }
      });
    }
  });
};

horizon.addInitFunction(function() {
  $('div.datatable').each(function (idx, el) {
    var table_selector = $(el).attr('id');

    // load intial elements
    horizon.datatables.ajax_paginate($(el), table_selector, 1);

    // set up filter
    horizon.datatables.set_pagination_filter($(el), table_selector)
  });

  // Trigger run-once setup scripts for tables.
  //horizon.datatables.set_table_query_filter($('body'));

  // Also apply on tables in modal views.
  horizon.modals.addModalInitFunction(horizon.datatables.set_table_query_filter);

  // Also apply on tables in tabs views for lazy-loaded data.
  horizon.tabs.addTabLoadFunction(horizon.datatables.set_table_query_filter);

});
<|endoftext|>


<commit_before>$(document).ready(function() {
	//=========Calcula los montos totales de la Factura o Tikect=========//
	//=========INICI0=========//
	$('#DetalleFac').on('change', 'input[type="text"]', function(i,e) {
		if($('input[class=FilaMarcada]:checkbox:checked').length == 0){
			var cells = $(this).closest('tr').children('td');
			var vCantidad = cells.eq(13).find('input').val();
			var vPrecionConIva = parseFloat(cells.eq(14).html());
			cells.eq(15).text(vCantidad * vPrecionConIva);
			sumaFila();
		}
	});
	function sumaFila(){
		var vIva = 0;
		var vTotal = 0;
		var vtGravada = 0;
		$('table tr:not(:first)').each(function()  {
			var cells = $(this).closest('tr').children('td');
			vtGravada  += parseFloat(cells.eq(15).html());
		});
			$("input:text#txt_VentaGravada").val(vtGravada);
			vIva = vtGravada*0.13;
			$("input:text#txt_Iva").val(vIva.toFixed(2));
			vTotal = vtGravada*1.13;
			$("input:text#txt_Total").val(vTotal.toFixed(2));
	}
	//=========FIN=========//
	//=========Traduce el DataTable=========//
	//=========INICI0=========//
	$('#DetalleFac').DataTable( {
		"language": {
			"sProcessing":     "Procesando...",
			"sLengthMenu":     "Mostrar _MENU_ registros",
			"sZeroRecords":    "No se encontraron resultados",
			"sEmptyTable":     "Ningún dato disponible en esta tabla",
			"sInfo":           "Registros del _START_ al _END_ de un total de _TOTAL_",
			"sInfoEmpty":      "Mostrando registros del 0 al 0 de un total de 0 registros",
			"sInfoFiltered":   "(filtrado de un total de _MAX_ registros)",
			"sInfoPostFix":    "",
			"sSearch":         "Buscar:",
			"sUrl":            "",
			"sInfoThousands":  ",",
			"sLoadingRecords": "Cargando...",
			"oPaginate": {
				"sFirst":    "Primero",
				"sLast":     "Último",
				"sNext":     "Siguiente",
				"sPrevious": "Anterior"
			},
			"oAria": {
				"sSortAscending":  ": Activar para ordenar la columna de manera ascendente",
				"sSortDescending": ": Activar para ordenar la columna de manera descendente"
			}
		}
	} );
	//=========FIN=========//
	//=========Marca todas los checkbok de la tabla=========//
	//=========INICI0=========//
	$('#DetalleFac').on('change', 'input[class=check_Todas]', function() {
		$('input[class=FilaMarcada]:checkbox').each(function(){
			if($('input[class=check_Todas]:checkbox:checked').length == 0){
				$(this).prop("checked", false);
			} else {
				$(this).prop("checked", true);
			}
		});
	});
    //=========FIN=========//
    //=========Borra las filas marcadas en la tabla=========//
	//=========INICI0=========//
	$("#Remover").on('click', function() {
		$('.FilaMarcada:checkbox:checked').parents("tr").remove();
		$('.check_Todas').prop("checked", false);
		check();
	});
    //=========FIN=========//
    //=========Genera el numero de fila=========//
	//=========INICI0=========//
	function check(){
		obj=$('table tr:not(:first)').find('span');
		$.each( obj, function( key, value ) {
			id=value.id;
			$('#'+id).html(key+1);
		});
	}
   //=========FIN=========//
   //=========Genera una fila y la coloca al final=========//
   //=========INICI0=========//
   $("#Agregar").on('click',function(){
   	var vNumFilaAgregada=$('table tr').length;
   	var vFilaAgregada="
								"+vNumFilaAgregada+"	<input type='checkbox' class='FilaMarcada'>	";
   	vFilaAgregada +="<input class='form-control' id='txt_CodProducto' name='txt_CodProducto' placeholder='Producto' type='text' value=''/>			<input class='form-control' id='txt_Cantidad' name='txt_Cantidad' placeholder='Cantidad' type='text' value=''/>		<input class='form-control' id='txt_Afecta' name='txt_Afecta' placeholder='Total' type='text' value='' readonly/>
";
   	$('table').append(vFilaAgregada);
   });
   //=========FIN=========//
});<commit_msg>v_Factura-V5,19/05/2017<commit_after>$(document).ready(function() {
	//=========Calcula los montos totales de la Factura o Tikect=========//
	//=========INICI0=========//
	$('#DetalleFac').on('change', 'input[type="text"]', function(i,e) {
		if($('input[class=FilaMarcada]:checkbox:checked').length == 0){
			var cells = $(this).closest('tr').children('td');
			var vCantidad = cells.eq(13).find('input').val();
			var vPrecionConIva = parseFloat(cells.eq(14).html());
			cells.eq(15).text(vCantidad * vPrecionConIva);
			sumaFila();
		}
	});
	function sumaFila(){
		var vIva = 0;
		var vTotal = 0;
		var vtGravada = 0;
		$('table tr:not(:first)').each(function()  {
			var cells = $(this).closest('tr').children('td');
			if(!isNaN(parseFloat(cells.eq(15).html()))){
			   vtGravada  += parseFloat(cells.eq(15).html());
			}else{
				vtGravada  +=0;
			}

		});
			$("input:text#txt_VentaGravada").val(vtGravada);
			vIva = vtGravada*0.13;
			$("input:text#txt_Iva").val(vIva.toFixed(2));
			vTotal = vtGravada*1.13;
			$("input:text#txt_Total").val(vTotal.toFixed(2));
	}
	//=========FIN=========//
	//=========Traduce el DataTable=========//
	//=========INICI0=========//
	$('#DetalleFac').DataTable( {
		"language": {
			"sProcessing":     "Procesando...",
			"sLengthMenu":     "Mostrar _MENU_ registros",
			"sZeroRecords":    "No se encontraron resultados",
			"sEmptyTable":     "Ningún dato disponible en esta tabla",
			"sInfo":           "Registros del _START_ al _END_ de un total de _TOTAL_",
			"sInfoEmpty":      "Mostrando registros del 0 al 0 de un total de 0 registros",
			"sInfoFiltered":   "(filtrado de un total de _MAX_ registros)",
			"sInfoPostFix":    "",
			"sSearch":         "Buscar:",
			"sUrl":            "",
			"sInfoThousands":  ",",
			"sLoadingRecords": "Cargando...",
			"oPaginate": {
				"sFirst":    "Primero",
				"sLast":     "Último",
				"sNext":     "Siguiente",
				"sPrevious": "Anterior"
			},
			"oAria": {
				"sSortAscending":  ": Activar para ordenar la columna de manera ascendente",
				"sSortDescending": ": Activar para ordenar la columna de manera descendente"
			}
		}
	} );
	//=========FIN=========//
	//=========Marca todas los checkbok de la tabla=========//
	//=========INICI0=========//
	$('#DetalleFac').on('change', 'input[class=check_Todas]', function() {
		$('input[class=FilaMarcada]:checkbox').each(function(){
			if($('input[class=check_Todas]:checkbox:checked').length == 0){
				$(this).prop("checked", false);
			} else {
				$(this).prop("checked", true);
			}
		});
	});
    //=========FIN=========//
    //=========Borra las filas marcadas en la tabla=========//
	//=========INICI0=========//
	$("#Remover").on('click', function() {
		$('.FilaMarcada:checkbox:checked').parents("tr").remove();
		$('.check_Todas').prop("checked", false);
		check();
	});
    //=========FIN=========//
    //=========Genera el numero de fila=========//
	//=========INICI0=========//
	function check(){
		obj=$('table tr:not(:first)').find('span');
		$.each( obj, function( key, value ) {
			id=value.id;
			$('#'+id).html(key+1);
		});
	}
   //=========FIN=========//
   //=========Genera una fila y la coloca al final=========//
   //=========INICI0=========//
   $("#Agregar").on('click',function(){
   	var vNumFilaAgregada=$('table tr').length;
   	var vFilaAgregada="
								"+vNumFilaAgregada+"	<input type='checkbox' class='FilaMarcada'>	";
   	vFilaAgregada +="<input class='form-control' id='txt_CodProducto' name='txt_CodProducto' placeholder='Producto' type='text' value=''/>			<input class='form-control' id='txt_Cantidad' name='txt_Cantidad' placeholder='Cantidad' type='text' value=''/>		<input class='form-control' id='txt_Afecta' name='txt_Afecta' placeholder='Total' type='text' value='' readonly/>
";
   	$('table').append(vFilaAgregada);
   });
   //=========FIN=========//
});<|endoftext|>


<commit_before>var DeveloperPlayground = DeveloperPlayground || {};

DeveloperPlayground.MapView = Backbone.View.extend({
    el: '#map-view',

    events: {
        'click #map-view' : 'getBounds'
    },

    setCollection: function(options){
        this.collection = options.collection;
        this.listenTo(this.collection, 'add', this.addFeature);
        this.listenTo(this.collection, 'sync', this.addFeatureGroup);
        this.emptydata = true;
        this.collection.each(this.addFeature, this);
        if (this.collection.length > 0) {
            this.addFeatureGroup();
        }
    },

    clearCollection: function() {
        this.stopListening();
    },

    render: function() {
        this.markerclustergroup = new L.MarkerClusterGroup({showCoverageOnHover: false});

        this.map = L.map('map-view',{
            scrollWheelZoom: false
        }).setView([37.749, -122.443], 15);
        L.tileLayer('https://{s}.tiles.mapbox.com/v3/randyme.li1lhlf0/{z}/{x}/{y}.png', {
            maxZoom: 18,
            attribution: '© OpenStreetMap contributors'
        })
        .addTo(this.map);
        L.control.locations({ position: 'topright', keepCurrentZoomLevel: true }).addTo(this.map);
        return this;
    },

    getBounds: function() {
        this.bounds=this.map.getBounds();
        this.bBoxString=this.bounds.toBBoxString();
        return this.bBoxString;

    },

    addFeature: function(feature) {
        this.collection = feature.collection;
        if (feature.get('display') !== false) {
            var s = {};

            if (feature.attributes.name == feature.attributes.tags.route_long_name || feature.attributes.tags.route_long_name === undefined){
                s = {
                'type': 'Feature',
                'name': feature.attributes.name,
                'longName': "",
                'geometry':feature.attributes.geometry,
                };
            } else {
                s = {
                    'type': 'Feature',
                    'name': feature.attributes.name,
                    'longName': feature.attributes.tags.route_long_name,
                    'geometry':feature.attributes.geometry,
                };
            }
            L.geoJson(s, {
                onEachFeature: this.onEachFeature,
                style: this.styleEachFeature
            })
            .addTo(this.markerclustergroup);
        }
        this.emptydata = false;
        return this;
    },

    styleEachFeature: function(feature) {
        var color;
        var r = Math.floor(Math.random() * 255);
        var g = Math.floor(Math.random() * 255);
        var b = Math.floor(Math.random() * 255);
        color= "rgb("+r+" ,"+g+","+ b+")";

        var operatorStyle = {
            color: color,
            fillColor: color,
            weight: 3,
            opacity: .6,
            fillOpacity: .3
            // className: 'blah'
        };

        var routeStyle = {
            color: color,
            // color: "#"+feature.attributes.tags.route_color,
            weight: 4,
            opacity: .3
            // className: 'blah'
        };

        var geom_type = feature.geometry.type.toLowerCase();

        if ( geom_type === 'polygon') {
            return operatorStyle;
        } else if (geom_type == 'point') {
            return {};
        } else if (geom_type.indexOf('line') !== -1) {
            return routeStyle;
        }
        return {};
    },

    onEachFeature: function(feature, layer) {

        function highlightFeature(e) {
            var layer = e.target;
            layer.setStyle({
                opacity: 1,
            });
            layer.bringToFront();
        }
        function resetFeatureStyle(e) {
            var layer = e.target;
            layer.setStyle({
                opacity: .3
            });
        }

        var stopIcon = L.icon({
            iconUrl: "/images/dot2a.png",
            iconSize:     [15, 15], // size of the icon
            iconAnchor:   [5, 5], // point of the icon which will correspond to marker's location
            popupAnchor:  [5, 5] // point from which the popup should open relative to the iconAnchor
        });

        var geom_type = feature.geometry.type.toLowerCase();
        if (geom_type == 'point') {
            layer.setIcon(stopIcon);
        }

        layer.on({
            popupopen: highlightFeature,
            popupclose: resetFeatureStyle
        });
        layer.bindPopup(feature.name + " " + feature.longName);
    },

    addFeatureGroup: function(feature) {
        var $entitySelect = $('select.form-control#entity');
        var $parameterSelect = $('select.form-control#parameter');
        if (!this.map.hasLayer(this.markerclustergroup)) {
            this.markerclustergroup.addTo(this.map);
        }
        if(!this.emptydata){
            if ($entitySelect.val() == "routes") {
                if ($parameterSelect.val() !== "map view"){
                    this.map.fitBounds(this.markerclustergroup.getBounds());
                }
            }else{
                   this.map.fitBounds(this.markerclustergroup.getBounds());
            }
        }else{
            if($(".no-result").hasClass("hide")){
                $(".no-result").removeClass("hide");
            }
        }
    }

});

<commit_msg>update map attribution<commit_after>var DeveloperPlayground = DeveloperPlayground || {};

DeveloperPlayground.MapView = Backbone.View.extend({
    el: '#map-view',

    events: {
        'click #map-view' : 'getBounds'
    },

    setCollection: function(options){
        this.collection = options.collection;
        this.listenTo(this.collection, 'add', this.addFeature);
        this.listenTo(this.collection, 'sync', this.addFeatureGroup);
        this.emptydata = true;
        this.collection.each(this.addFeature, this);
        if (this.collection.length > 0) {
            this.addFeatureGroup();
        }
    },

    clearCollection: function() {
        this.stopListening();
    },

    render: function() {
        this.markerclustergroup = new L.MarkerClusterGroup({showCoverageOnHover: false});

        this.map = L.map('map-view',{
            scrollWheelZoom: false
        }).setView([37.749, -122.443], 15);
        L.tileLayer('https://{s}.tiles.mapbox.com/v3/randyme.li1lhlf0/{z}/{x}/{y}.png', {
            maxZoom: 18,
            attribution: 'Map data © OpenStreetMap contributors, CC-BY-SA, Imagery © Mapbox',
        })
        .addTo(this.map);
        L.control.locations({ position: 'topright', keepCurrentZoomLevel: true }).addTo(this.map);
        return this;
    },

    getBounds: function() {
        this.bounds=this.map.getBounds();
        this.bBoxString=this.bounds.toBBoxString();
        return this.bBoxString;

    },

    addFeature: function(feature) {
        this.collection = feature.collection;
        if (feature.get('display') !== false) {
            var s = {};

            if (feature.attributes.name == feature.attributes.tags.route_long_name || feature.attributes.tags.route_long_name === undefined){
                s = {
                'type': 'Feature',
                'name': feature.attributes.name,
                'longName': "",
                'geometry':feature.attributes.geometry,
                };
            } else {
                s = {
                    'type': 'Feature',
                    'name': feature.attributes.name,
                    'longName': feature.attributes.tags.route_long_name,
                    'geometry':feature.attributes.geometry,
                };
            }
            L.geoJson(s, {
                onEachFeature: this.onEachFeature,
                style: this.styleEachFeature
            })
            .addTo(this.markerclustergroup);
        }
        this.emptydata = false;
        return this;
    },

    styleEachFeature: function(feature) {
        var color;
        var r = Math.floor(Math.random() * 255);
        var g = Math.floor(Math.random() * 255);
        var b = Math.floor(Math.random() * 255);
        color= "rgb("+r+" ,"+g+","+ b+")";

        var operatorStyle = {
            color: color,
            fillColor: color,
            weight: 3,
            opacity: .6,
            fillOpacity: .3
            // className: 'blah'
        };

        var routeStyle = {
            color: color,
            // color: "#"+feature.attributes.tags.route_color,
            weight: 4,
            opacity: .3
            // className: 'blah'
        };

        var geom_type = feature.geometry.type.toLowerCase();

        if ( geom_type === 'polygon') {
            return operatorStyle;
        } else if (geom_type == 'point') {
            return {};
        } else if (geom_type.indexOf('line') !== -1) {
            return routeStyle;
        }
        return {};
    },

    onEachFeature: function(feature, layer) {

        function highlightFeature(e) {
            var layer = e.target;
            layer.setStyle({
                opacity: 1,
            });
            layer.bringToFront();
        }
        function resetFeatureStyle(e) {
            var layer = e.target;
            layer.setStyle({
                opacity: .3
            });
        }

        var stopIcon = L.icon({
            iconUrl: "/images/dot2a.png",
            iconSize:     [15, 15], // size of the icon
            iconAnchor:   [5, 5], // point of the icon which will correspond to marker's location
            popupAnchor:  [5, 5] // point from which the popup should open relative to the iconAnchor
        });

        var geom_type = feature.geometry.type.toLowerCase();
        if (geom_type == 'point') {
            layer.setIcon(stopIcon);
        }

        layer.on({
            popupopen: highlightFeature,
            popupclose: resetFeatureStyle
        });
        layer.bindPopup(feature.name + " " + feature.longName);
    },

    addFeatureGroup: function(feature) {
        var $entitySelect = $('select.form-control#entity');
        var $parameterSelect = $('select.form-control#parameter');
        if (!this.map.hasLayer(this.markerclustergroup)) {
            this.markerclustergroup.addTo(this.map);
        }
        if(!this.emptydata){
            if ($entitySelect.val() == "routes") {
                if ($parameterSelect.val() !== "map view"){
                    this.map.fitBounds(this.markerclustergroup.getBounds());
                }
            }else{
                   this.map.fitBounds(this.markerclustergroup.getBounds());
            }
        }else{
            if($(".no-result").hasClass("hide")){
                $(".no-result").removeClass("hide");
            }
        }
    }

});

<|endoftext|>


<commit_before>/* jshint asi:true */
//先等图片都加载完成
//再执行布局函数

/**
 * 执行主函数
 * @param  {[type]} function( [description]
 * @return {[type]}           [description]
 */
(function() {

    /**
     * 内容JSON
     */
    var demoContent = [{
        demo_link: 'https://summerboys.github.io/mask/'
        img_link: 'https://summerboys.github.io/mask/1.png'
        code_link: 'https://summerboys.github/mask/'
        title: '鼠标移入产生遮罩'
        core_tech: 'jQuery javascript'
        description: '根据鼠标移入的方向不同，产生的遮罩方向也就不相同'
    }];

    contentInit(demoContent) //内容初始化
    waitImgsLoad() //等待图片加载，并执行布局初始化
}());

/**
 * 内容初始化
 * @return {[type]} [description]
 */
function contentInit(content) {
    // var htmlArr = [];
    // for (var i = 0; i < content.length; i++) {
    //     htmlArr.push('
')
    //     htmlArr.push('')
    //     htmlArr.push('')
    //     htmlArr.push('')
    //     htmlArr.push('
')
    //     htmlArr.push(''+content[i].title+'')
    //     htmlArr.push('
')
    //     htmlArr.push('
主要技术：'+content[i].core_tech+'
')
    //     htmlArr.push('
'+content[i].description)
    //     htmlArr.push('源代码 ')
    //     htmlArr.push('
')
    //     htmlArr.push('
')
    // }
    // var htmlStr = htmlArr.join('')
    var htmlStr = ''
    for (var i = 0; i < content.length; i++) {
        htmlStr +=
            '
' +
            '   ' +
            '       ' +
            '   ' +
            '
' +
            '       ' + content[i].title + '' +
            '
' +
            '
主要技术：' + content[i].core_tech + '
' +
            '
' + content[i].description +
            '       源代码 ' +
            '
' +
            '
'
    }
    var grid = document.querySelector('.grid')
    grid.insertAdjacentHTML('afterbegin', htmlStr)
}

/**
 * 等待图片加载
 * @return {[type]} [description]
 */
function waitImgsLoad() {
    var imgs = document.querySelectorAll('.grid img')
    var totalImgs = imgs.length
    var count = 0
        //console.log(imgs)
    for (var i = 0; i < totalImgs; i++) {
        if (imgs[i].complete) {
            //console.log('complete');
            count++
        } else {
            imgs[i].onload = function() {
                // alert('onload')
                count++
                //console.log('onload' + count)
                if (count == totalImgs) {
                    //console.log('onload---bbbbbbbb')
                    initGrid()
                }
            }
        }
    }
    if (count == totalImgs) {
        //console.log('---bbbbbbbb')
        initGrid()
    }
}

/**
 * 初始化栅格布局
 * @return {[type]} [description]
 */
function initGrid() {
    var msnry = new Masonry('.grid', {
        // options
        itemSelector: '.grid-item',
        columnWidth: 250,
        isFitWidth: true,
        gutter: 20,
    })
}
<commit_msg>demo 2<commit_after>/* jshint asi:true */
//先等图片都加载完成
//再执行布局函数

/**
 * 执行主函数
 * @param  {[type]} function( [description]
 * @return {[type]}           [description]
 */
(function() {

    /**
     * 内容JSON
     */
    var demoContent = [{
        demo_link: 'https://summerboys.github.io/mask/'
        img_link: 'https://github.com/summerboys/mask/blob/master/1.jpg'
        code_link: 'https://github.com/summerboys/mask'
        title: '鼠标移入产生遮罩'
        core_tech: 'jQuery javascript'
        description: '根据鼠标移入的方向不同，产生的遮罩方向也就不相同'
    }];

    contentInit(demoContent) //内容初始化
    waitImgsLoad() //等待图片加载，并执行布局初始化
}());

/**
 * 内容初始化
 * @return {[type]} [description]
 */
function contentInit(content) {
    // var htmlArr = [];
    // for (var i = 0; i < content.length; i++) {
    //     htmlArr.push('
')
    //     htmlArr.push('')
    //     htmlArr.push('')
    //     htmlArr.push('')
    //     htmlArr.push('
')
    //     htmlArr.push(''+content[i].title+'')
    //     htmlArr.push('
')
    //     htmlArr.push('
主要技术：'+content[i].core_tech+'
')
    //     htmlArr.push('
'+content[i].description)
    //     htmlArr.push('源代码 ')
    //     htmlArr.push('
')
    //     htmlArr.push('
')
    // }
    // var htmlStr = htmlArr.join('')
    var htmlStr = ''
    for (var i = 0; i < content.length; i++) {
        htmlStr +=
            '
' +
            '   ' +
            '       ' +
            '   ' +
            '
' +
            '       ' + content[i].title + '' +
            '
' +
            '
主要技术：' + content[i].core_tech + '
' +
            '
' + content[i].description +
            '       源代码 ' +
            '
' +
            '
'
    }
    var grid = document.querySelector('.grid')
    grid.insertAdjacentHTML('afterbegin', htmlStr)
}

/**
 * 等待图片加载
 * @return {[type]} [description]
 */
function waitImgsLoad() {
    var imgs = document.querySelectorAll('.grid img')
    var totalImgs = imgs.length
    var count = 0
        //console.log(imgs)
    for (var i = 0; i < totalImgs; i++) {
        if (imgs[i].complete) {
            //console.log('complete');
            count++
        } else {
            imgs[i].onload = function() {
                // alert('onload')
                count++
                //console.log('onload' + count)
                if (count == totalImgs) {
                    //console.log('onload---bbbbbbbb')
                    initGrid()
                }
            }
        }
    }
    if (count == totalImgs) {
        //console.log('---bbbbbbbb')
        initGrid()
    }
}

/**
 * 初始化栅格布局
 * @return {[type]} [description]
 */
function initGrid() {
    var msnry = new Masonry('.grid', {
        // options
        itemSelector: '.grid-item',
        columnWidth: 250,
        isFitWidth: true,
        gutter: 20,
    })
}
<|endoftext|>


<commit_before>import extend_core from '../js/extend_core.js'
import id_core from '../js/id_core.js'
import event_bus from '../js/event_bus.js'

var
  ping_time = 40000,
  ping_message = { type: 'ping' },
  Websocket = function() {
  this.bindContexts();
  this.responseCallbacks = [];
  this.protocol = window.location.origin.indexOf('https') >= 0 ? 'wss://' : 'ws://';
};

Websocket.prototype = {

  port: ':8000',

  bindContexts: function() {
    var self = this;
    self.bindedOnOpen = self.onOpen.bind(self);
    self.bindedOnClose = self.onClose.bind(self);
    self.bindedOnMessage = self.onMessage.bind(self);
    self.bindedOnError = self.onError.bind(self);
  },

  createAndListen: function() {
    this.create();
    this.addSocketListeners();
    if (!this.connectionPing) {
      this.connectionPing = setInterval(() => {
        if (this.socket && this.socket.readyState === this.socket.OPEN) {
          this.sendMessage(ping_message);
        }
      }, ping_time);
    }
  },

  create: function() {
    var url;
    if (window.location.hostname.indexOf('localhost') >= 0 ||
      window.location.hostname.indexOf('192.168.') >= 0) {
      url = this.protocol + window.location.host;
    } else {
      url = this.protocol + window.location.hostname + this.port;
    }
    this.socket = new WebSocket(url);
  },

  dispose: function() {
    this.removeSocketListeners();
    if (this.socket) {
      this.socket.close();
      this.socket = null;
    }
  },

  addSocketListeners: function() {
    if (!this.socket) {
      return;
    }
    var self = this;
    self.removeSocketListeners();
    self.socket.onopen = self.bindedOnOpen;
    self.socket.onclose = self.bindedOnClose;
    self.socket.onmessage = self.bindedOnMessage;
    self.socket.onerror = self.bindedOnError;
  },

  removeSocketListeners: function() {
    if (!this.socket) {
      return;
    }
    var sels = this;
    sels.socket.onopen = null;
    sels.socket.onclose = null;
    sels.socket.onmessage = null;
    sels.socket.onerror = null;
  },

  onOpen: function(event) {
    console.log('WebSocket connection established');
  },

  onClose: function(event) {
    var newState;
    if (event.wasClean) {
      console.warn('WebSocket connection closed');
    } else {
      event_bus.trigger("websocket_abortConnection", 103);
    }
    console.warn('Code: ' + event.code + ' reason: ' + event.reason);
  },

  onMessage: function(event) {
    if (event.data) {
      try {
        var parsedMessageData = JSON.parse(event.data);
      } catch (e) {
        console.error(e);
        return;
      }
    }
    console.info('WebSocket received message data', parsedMessageData);
    if (parsedMessageData.response_id) {
      var depleted = [], nowDatetime = Date.now();
      this.responseCallbacks.forEach(function(callbDescr) {
        if (callbDescr.request_id === parsedMessageData.response_id) {
          callbDescr.responseCallback(null, parsedMessageData);
          depleted.push(callbDescr);
        } else if (nowDatetime - callbDescr.datetime > 50000) {
          callbDescr.responseCallback(new Error('Timeout fro request'));
          depleted.push(callbDescr);
        }
      });
      while (depleted.length) {
        var toRemoveCallbDescr = depleted.shift();
        var removeIndex = this.responseCallbacks.indexOf(toRemoveCallbDescr);
        if (removeIndex !== -1) {
          this.responseCallbacks.splice(removeIndex, 1);
        }
      }
    } else {
      event_bus.trigger('web_socket_message', parsedMessageData);
    }
  },

  onError: function(error) {
    console.error(error);
  },

  sendMessage: function(data) {
    var senddata = data;
    if (typeof data !== "string") {
      try {
        senddata = JSON.stringify(data);
      } catch (e) {
        console.error(e);
        return;
      }
    }
    this.socket.send(senddata);
  },

  wsRequest: function(requestData, responseCallback) {
    requestData.request_id = this.generateId();
    this.responseCallbacks.push({
      datetime: Date.now(),
      request_id: requestData.request_id,
      responseCallback: responseCallback
    });
    this.sendMessage(requestData);
  }
};
extend_core.prototype.inherit(Websocket, id_core);

export default new Websocket();
<commit_msg>Default port for heroku<commit_after>import extend_core from '../js/extend_core.js'
import id_core from '../js/id_core.js'
import event_bus from '../js/event_bus.js'

var
  ping_time = 40000,
  ping_message = { type: 'ping' },
  Websocket = function() {
  this.bindContexts();
  this.responseCallbacks = [];
  this.protocol = window.location.origin.indexOf('https') >= 0 ? 'wss://' : 'ws://';
};

Websocket.prototype = {

  bindContexts: function() {
    var self = this;
    self.bindedOnOpen = self.onOpen.bind(self);
    self.bindedOnClose = self.onClose.bind(self);
    self.bindedOnMessage = self.onMessage.bind(self);
    self.bindedOnError = self.onError.bind(self);
  },

  createAndListen: function() {
    this.create();
    this.addSocketListeners();
    if (!this.connectionPing) {
      this.connectionPing = setInterval(() => {
        if (this.socket && this.socket.readyState === this.socket.OPEN) {
          this.sendMessage(ping_message);
        }
      }, ping_time);
    }
  },

  create: function() {
    var url;
    if (window.location.hostname.indexOf('localhost') >= 0 ||
      window.location.hostname.indexOf('192.168.') >= 0) {
      url = this.protocol + window.location.host;
    } else {
      url = this.protocol + window.location.hostname;
    }
    this.socket = new WebSocket(url);
  },

  dispose: function() {
    this.removeSocketListeners();
    if (this.socket) {
      this.socket.close();
      this.socket = null;
    }
  },

  addSocketListeners: function() {
    if (!this.socket) {
      return;
    }
    var self = this;
    self.removeSocketListeners();
    self.socket.onopen = self.bindedOnOpen;
    self.socket.onclose = self.bindedOnClose;
    self.socket.onmessage = self.bindedOnMessage;
    self.socket.onerror = self.bindedOnError;
  },

  removeSocketListeners: function() {
    if (!this.socket) {
      return;
    }
    var sels = this;
    sels.socket.onopen = null;
    sels.socket.onclose = null;
    sels.socket.onmessage = null;
    sels.socket.onerror = null;
  },

  onOpen: function(event) {
    console.log('WebSocket connection established');
  },

  onClose: function(event) {
    var newState;
    if (event.wasClean) {
      console.warn('WebSocket connection closed');
    } else {
      event_bus.trigger("websocket_abortConnection", 103);
    }
    console.warn('Code: ' + event.code + ' reason: ' + event.reason);
  },

  onMessage: function(event) {
    if (event.data) {
      try {
        var parsedMessageData = JSON.parse(event.data);
      } catch (e) {
        console.error(e);
        return;
      }
    }
    console.info('WebSocket received message data', parsedMessageData);
    if (parsedMessageData.response_id) {
      var depleted = [], nowDatetime = Date.now();
      this.responseCallbacks.forEach(function(callbDescr) {
        if (callbDescr.request_id === parsedMessageData.response_id) {
          callbDescr.responseCallback(null, parsedMessageData);
          depleted.push(callbDescr);
        } else if (nowDatetime - callbDescr.datetime > 50000) {
          callbDescr.responseCallback(new Error('Timeout fro request'));
          depleted.push(callbDescr);
        }
      });
      while (depleted.length) {
        var toRemoveCallbDescr = depleted.shift();
        var removeIndex = this.responseCallbacks.indexOf(toRemoveCallbDescr);
        if (removeIndex !== -1) {
          this.responseCallbacks.splice(removeIndex, 1);
        }
      }
    } else {
      event_bus.trigger('web_socket_message', parsedMessageData);
    }
  },

  onError: function(error) {
    console.error(error);
  },

  sendMessage: function(data) {
    var senddata = data;
    if (typeof data !== "string") {
      try {
        senddata = JSON.stringify(data);
      } catch (e) {
        console.error(e);
        return;
      }
    }
    this.socket.send(senddata);
  },

  wsRequest: function(requestData, responseCallback) {
    requestData.request_id = this.generateId();
    this.responseCallbacks.push({
      datetime: Date.now(),
      request_id: requestData.request_id,
      responseCallback: responseCallback
    });
    this.sendMessage(requestData);
  }
};
extend_core.prototype.inherit(Websocket, id_core);

export default new Websocket();
<|endoftext|>