<commit_before>/* SpinSubmit */
var SpinSubmit = function(submit) {
  this.submit = submit;
  this.originalText = this.submit.text();

  this.submit.html('' + this.originalText + '');

  this.original = this.submit.children('.original');

  //this.submit.prepend('⟲');
  this.submit.prepend('');
}

SpinSubmit.prototype.start = function (text) {
  this.original.text((text ? text : this.originalText));
  this.submit.addClass('submit-spinner--spinning');
}

SpinSubmit.prototype.stop = function (text) {
  this.original.text((text ? text : this.originalText));
  this.submit.removeClass('submit-spinner--spinning');
}

$(document).ready(function() {
  /* Functions */

  // Reset progress bar
  function resetProgress(){
    $('.progress-bar').css({ 'width': '0%', 'transition': 'none' });
    $('.progress-bar span').html('');
  }

  function updateProgress(current, max){
    // Calculate percent
    var percent = 100 / max * current;
    // Adjust width
    $('.progress-bar').css('width', Math.round(percent) + '%');
    $('.progress-bar span').html('RBL check ' + current + ' / ' + max);
  }

  function countTableRows(){
    // Return the current amount of rows in our result table
    return $('.results tbody tr').length;
  }

  function updateListingBadge(){
    /* jshint ignore:start */

    // Count listings and errors
    var listings = $(".results tbody tr:contains('Listed')").length
    , errors = $(".results tbody tr:contains('Error')").length;

    // If no listing, add success class, otherwise remove it
    if (listings == 0) {
      $('.label-listings').removeClass('label-danger');
      $('.label-listings').addClass('label-success');
    } else {
      $('.label-listings').removeClass('label-success');
      $('.label-listings').addClass('label-danger');
    }

    // Show possible error label
    if (errors > 0) {
      $('.label-errors').show();
      $('.label-errors').html(errors + ' errors');
    } else {
      $('.label-errors').hide();
      $('.label-errors').html('');
    }

    // Update listings label
    $('.label-listings').html(listings + ' listings');

    /* jshint ignore:end */
  }

  // Enable general inputs
  function enableInputs(){
    $('.results').hide();
    $('.btn-cancel-check').hide();
    $('input#inputMailserverHost').prop('disabled', false);
    $('.btn-submit-check').prop('disabled', false);
  }

  // Disable general inputs
  function disableInputs(){
    $('.results').show();
    $('.btn-cancel-check').show();
    $('input#inputMailserverHost').prop('disabled', true);
    $('.btn-submit-check').prop('disabled', true);
  }

  /*init*/
  var spinnerInput = $('#spinner')
  , Spinner = new SpinSubmit(spinnerInput);

  // Enable inputs on page load
  enableInputs();

  // Hide progress bar
  $('.progress').hide();

  // Initialize table sorter
  $('.results table').tablesorter();

  // Function to start the blacklist probes
  var startBlacklistProbes = function (hostToCheck, obj) {
    $('.results tbody').html('');
    resetProgress();
    $('.progress').show();
    $('.results').show();

    var requests = [];
    $.each(obj.blacklists, function(key, value) {
      var rowId = parseFloat(key) + parseFloat(1)
      , promise = $.get('api/?dnsbl=' + value + '&host=' + hostToCheck, function(data, status) {
        if (status === 'success') {
          var jsonProbe = $.parseJSON(data);
          if (jsonProbe.success === true) {
            if (jsonProbe.payload.result === 200) {
              console.log(hostToCheck + ': not listed on "' + jsonProbe.payload.dnsbl + '"');
              $('.results table > tbody').append('
' + rowId + '	' + jsonProbe.payload.dnsbl + '	OK
');
            } else if (jsonProbe.payload.result === 300) {
              console.log(hostToCheck + ': listed on "' + jsonProbe.payload.dnsbl + '"');
              $('.results table > tbody').append('
' + rowId + '	' + jsonProbe.payload.dnsbl + '	Listed
');
            }
          } else {
            console.log('Error: ' + jsonProbe.error);
            $('.results table > tbody').append('
' + rowId + '	' + value + '	Error: ' + jsonProbe.error + '
');
          }
          updateProgress(countTableRows(), obj.blacklists.length);
          updateListingBadge();
        }
      });

      $('.btn-cancel-check').on('click', function(e) {
        e.preventDefault();
        promise.abort();
        /* jshint ignore:start */
        delete requests;
        /* jshint ignore:end */
        resetProgress();
        enableInputs();
        Spinner.stop('Check another');
      });

      requests.push(promise);
    });

    // Enable stuff again, when all API calls are finished
    $.when.apply($, requests).done(function() {
      enableInputs();
      $('.results').show();
      $('.progress').fadeOut();
      $('.results table').trigger('update')
        .trigger('appendCache')
        .trigger('sorton',[ [ [ 2,0 ], [ 0,0 ] ] ]); // Sort table
      Spinner.stop('Check another');
    });
  }

  // Show RBL count in jumbotron
  $.getJSON('dnsbl.json', function(json) {
    var jsonObj = json;
    $('.a-tooltip').attr('data-original-title', 'Currently testing agaist ' + jsonObj.blacklists.length + ' RBLs.').tooltip();

    // Validate input form
    $('form.form-input').formValidation({
      framework: 'bootstrap'
      , icon: {
        valid: 'glyphicon glyphicon-ok'
        , invalid: 'glyphicon glyphicon-remove'
        , validating: 'glyphicon glyphicon-refresh'
      }
      , fields: {
        inputMailserverHost: {
          validators: {
            notEmpty: {
              message: 'The full name is required'
            }
          }
        }
      }
    }).on('success.form.fv', function(e) {
      // Prevent form submission
      e.preventDefault();

      Spinner.start('Checking...');

      // // instances, we can use at a later point
      // var $form = $(e.target) // The form instance
      // , fv    = $(e.target).data('formValidation'); // FormValidation instance

      // Disable inputs during the check
      disableInputs();
      // As well as prepare some other elements
      $('.alert-hint').hide();
      startBlacklistProbes($('input#inputMailserverHost').val(), jsonObj);
    });
  });
});
<commit_msg>Get rid of redundant SpinSubmit function<commit_after>/* global SpinSubmit */

$(document).ready(function() {
  /* Functions */

  // Reset progress bar
  function resetProgress(){
    $('.progress-bar').css({ 'width': '0%', 'transition': 'none' });
    $('.progress-bar span').html('');
  }

  function updateProgress(current, max){
    // Calculate percent
    var percent = 100 / max * current;
    // Adjust width
    $('.progress-bar').css('width', Math.round(percent) + '%');
    $('.progress-bar span').html('RBL check ' + current + ' / ' + max);
  }

  function countTableRows(){
    // Return the current amount of rows in our result table
    return $('.results tbody tr').length;
  }

  function updateListingBadge(){
    /* jshint ignore:start */

    // Count listings and errors
    var listings = $(".results tbody tr:contains('Listed')").length
    , errors = $(".results tbody tr:contains('Error')").length;

    // If no listing, add success class, otherwise remove it
    if (listings == 0) {
      $('.label-listings').removeClass('label-danger');
      $('.label-listings').addClass('label-success');
    } else {
      $('.label-listings').removeClass('label-success');
      $('.label-listings').addClass('label-danger');
    }

    // Show possible error label
    if (errors > 0) {
      $('.label-errors').show();
      $('.label-errors').html(errors + ' errors');
    } else {
      $('.label-errors').hide();
      $('.label-errors').html('');
    }

    // Update listings label
    $('.label-listings').html(listings + ' listings');

    /* jshint ignore:end */
  }

  // Enable general inputs
  function enableInputs(){
    $('.results').hide();
    $('.btn-cancel-check').hide();
    $('input#inputMailserverHost').prop('disabled', false);
    $('.btn-submit-check').prop('disabled', false);
  }

  // Disable general inputs
  function disableInputs(){
    $('.results').show();
    $('.btn-cancel-check').show();
    $('input#inputMailserverHost').prop('disabled', true);
    $('.btn-submit-check').prop('disabled', true);
  }

  /*init*/
  var spinnerInput = $('#spinner')
  , Spinner = new SpinSubmit(spinnerInput);

  // Enable inputs on page load
  enableInputs();

  // Hide progress bar
  $('.progress').hide();

  // Initialize table sorter
  $('.results table').tablesorter();

  // Function to start the blacklist probes
  var startBlacklistProbes = function (hostToCheck, obj) {
    $('.results tbody').html('');
    resetProgress();
    $('.progress').show();
    $('.results').show();

    var requests = [];
    $.each(obj.blacklists, function(key, value) {
      var rowId = parseFloat(key) + parseFloat(1)
      , promise = $.get('api/?dnsbl=' + value + '&host=' + hostToCheck, function(data, status) {
        if (status === 'success') {
          var jsonProbe = $.parseJSON(data);
          if (jsonProbe.success === true) {
            if (jsonProbe.payload.result === 200) {
              console.log(hostToCheck + ': not listed on "' + jsonProbe.payload.dnsbl + '"');
              $('.results table > tbody').append('
' + rowId + '	' + jsonProbe.payload.dnsbl + '	OK
');
            } else if (jsonProbe.payload.result === 300) {
              console.log(hostToCheck + ': listed on "' + jsonProbe.payload.dnsbl + '"');
              $('.results table > tbody').append('
' + rowId + '	' + jsonProbe.payload.dnsbl + '	Listed
');
            }
          } else {
            console.log('Error: ' + jsonProbe.error);
            $('.results table > tbody').append('
' + rowId + '	' + value + '	Error: ' + jsonProbe.error + '
');
          }
          updateProgress(countTableRows(), obj.blacklists.length);
          updateListingBadge();
        }
      });

      $('.btn-cancel-check').on('click', function(e) {
        e.preventDefault();
        promise.abort();
        /* jshint ignore:start */
        delete requests;
        /* jshint ignore:end */
        resetProgress();
        enableInputs();
        Spinner.stop('Check another');
      });

      requests.push(promise);
    });

    // Enable stuff again, when all API calls are finished
    $.when.apply($, requests).done(function() {
      enableInputs();
      $('.results').show();
      $('.progress').fadeOut();
      $('.results table').trigger('update')
        .trigger('appendCache')
        .trigger('sorton',[ [ [ 2,0 ], [ 0,0 ] ] ]); // Sort table
      Spinner.stop('Check another');
    });
  }

  // Show RBL count in jumbotron
  $.getJSON('dnsbl.json', function(json) {
    var jsonObj = json;
    $('.a-tooltip').attr('data-original-title', 'Currently testing agaist ' + jsonObj.blacklists.length + ' RBLs.').tooltip();

    // Validate input form
    $('form.form-input').formValidation({
      framework: 'bootstrap'
      , icon: {
        valid: 'glyphicon glyphicon-ok'
        , invalid: 'glyphicon glyphicon-remove'
        , validating: 'glyphicon glyphicon-refresh'
      }
      , fields: {
        inputMailserverHost: {
          validators: {
            notEmpty: {
              message: 'The full name is required'
            }
          }
        }
      }
    }).on('success.form.fv', function(e) {
      // Prevent form submission
      e.preventDefault();

      Spinner.start('Checking...');

      // // instances, we can use at a later point
      // var $form = $(e.target) // The form instance
      // , fv    = $(e.target).data('formValidation'); // FormValidation instance

      // Disable inputs during the check
      disableInputs();
      // As well as prepare some other elements
      $('.alert-hint').hide();
      startBlacklistProbes($('input#inputMailserverHost').val(), jsonObj);
    });
  });
});
<|endoftext|>


<commit_before>/**
 * @class
 * @constructor
 * @description A drawable vector layer
 */
Ext.define("viewer.viewercontroller.openlayers.OpenLayersVectorLayer",{
    extend: "viewer.viewercontroller.controller.VectorLayer",
    point:null,
    line:null,
    polygon:null,
    circle:null,
    modifyFeature:null,
    enabledEvents: new Object(),
    mixins: {
        openLayersLayer: "viewer.viewercontroller.openlayers.OpenLayersLayer"
    },
    constructor : function (config){
        delete config.style;
        viewer.viewercontroller.openlayers.OpenLayersVectorLayer.superclass.constructor.call(this, config);
        this.frameworkLayer = new OpenLayers.Layer.Vector(config.id, config);
        var me = this;
        this.frameworkLayer.events.register("afterfeaturemodified", this, this.featureModified);
        this.frameworkLayer.events.register("sketchstarted", this, this.featureModified);
        this.frameworkLayer.events.register("featureadded", this, function (args){
            me.onFeatureInsert(args.feature);
            return true;
        });

        this.frameworkLayer.onFeatureInsert = function(feature){
            me.onFeatureInsert(feature);
        };
        this.point =  new OpenLayers.Control.DrawFeature(this.frameworkLayer, OpenLayers.Handler.Point, {
            displayClass: 'olControlDrawFeaturePoint',
            handlerOptions: {
                citeCompliant: false
            }
        });
        this.line = new OpenLayers.Control.DrawFeature(this.frameworkLayer, OpenLayers.Handler.Path, {
            displayClass: 'olControlDrawFeaturePath',
            handlerOptions: {
                citeCompliant: false
            }
        });
        this.polygon =  new OpenLayers.Control.DrawFeature(this.frameworkLayer, OpenLayers.Handler.Polygon, {
            displayClass: 'olControlDrawFeaturePolygon',
            handlerOptions: {
                citeCompliant: false
            }
        });

        var map = this.viewerController.mapComponent.getMap().getFrameworkMap();
        map.addControl(this.point);
        map.addControl(this.line);
        map.addControl(this.polygon);

        this.modifyFeature = new OpenLayers.Control.ModifyFeature(this.frameworkLayer);
        map.addControl(this.modifyFeature);
        this.modifyFeature.activate();
    },
    adjustStyle : function(){
        this.viewerController.logger.error("OpenLayersVectorLayer.adjustStyle() not yet implemented!");
    },
    removeAllFeatures : function(){
        this.getFrameworkLayer().removeAllFeatures();
    },

    getActiveFeature : function(){
        var index = this.getFrameworkLayer().features.length - 1;
        var olFeature = this.getFrameworkLayer().features[index];
        var featureObj = new Feature();
        var feature = featureObj.fromOpenLayersFeature(olFeature);

        return feature;
    },

    getFeature : function(id){
        return this.getFrameworkLayer().features[id];
    },

    getAllFeatures : function(){
        var olFeatures = this.getFrameworkLayer().features;
        var features = new Array();
        var featureObj = new viewer.viewercontroller.controller.Feature();
        for(var i = 0 ; i < olFeatures.length;i++){
            var olFeature = olFeatures[i];
            var feature = featureObj.fromOpenLayersFeature(olFeature);

            features.push(feature);
        }
        return features;
    },

    addFeature : function(feature){
        var features = new Array();
        features.push(feature);
        this.addFeatures(features);
    },

    addFeatures : function(features){
        var olFeatures = new Array();
        for(var i = 0 ; i < features.length ; i++){
            var feature = features[i];
            var olFeature = this.toOpenLayersFeature(feature);
            olFeatures.push(olFeature);
        }
        return this.getFrameworkLayer().addFeatures(olFeatures);
    },

    drawFeature : function(type){
        if(type == "Point"){
            this.point.activate();
        }else if(type == "LineString"){
            this.line.activate();
        }else if(type == "Polygon"){
            this.polygon.activate();
        }else{
            throw ("Feature type >" + type + "< not implemented!");
        }
    },

    activeFeatureChanged : function (feature){
        this.fireEvent(viewer.viewercontroller.controller.Event.ON_ACTIVE_FEATURE_CHANGED,this,feature);
    },

    featureModified : function (evt){
        var featureObject = this.fromOpenLayersFeature(evt.feature);
        this.fireEvent(viewer.viewercontroller.controller.Event.ON_ACTIVE_FEATURE_CHANGED,this,featureObject);
    },

    onFeatureInsert : function (feature){
        this.point.deactivate();
        this.line.deactivate();
        this.polygon.deactivate();
        this.editFeature(feature);
        var featureObject = this.fromOpenLayersFeature(feature);
        this.fireEvent(viewer.viewercontroller.controller.Event.ON_FEATURE_ADDED,this,featureObject);
    },

    editFeature : function (feature){
        this.modifyFeature.selectControl.unselectAll();
        this.modifyFeature.selectControl.select(feature);
    },

    /**
     * Converts this feature to a OpenLayersFeature
     * @return The OpenLayerstype feature
     */
    toOpenLayersFeature : function(feature){
       // throw ("Not yet implemented");
        var geom = OpenLayers.Geometry.fromWKT(feature.wktgeom);
        var olFeature = new OpenLayers.Feature.Vector(geom);
        return olFeature;
    },

    /**
     * Helper function: Converts the given OpenLayers Feature to the generic feature.
     * @param openLayersFeature The OpenLayersFeature to be converted
     * @return The generic feature
     */
    fromOpenLayersFeature : function(openLayersFeature){
        var feature = new viewer.viewercontroller.controller.Feature({id:openLayersFeature.id,wktgeom: openLayersFeature.geometry.toString()});
        return feature;
    },

    addListener : function (event, handler, scope){
        var olSpecificEvent = this.viewerController.mapComponent.getSpecificEventName(event);
         if(olSpecificEvent){
            if(!scope){
                scope = this;
            }
            this.registerToLayer(olSpecificEvent);
            viewer.viewercontroller.openlayers.OpenLayersVectorLayer.superclass.addListener.call(this,event,handler,scope);
         }else{
            this.viewerController.logger.warning("Event not listed in OpenLayersVectorLayer >"+ event + "<. The application  might not work correctly.");
        }
    },

    registerToLayer : function (specificEvent){
          if(this.enabledEvents[specificEvent] == null ||this.enabledEvents[specificEvent] == undefined){
            this.enabledEvents[specificEvent] = true;

            this.frameworkLayer.events.register(specificEvent, this, this.handleEvent);
        }
    },

    handleEvent : function (event){
        var options = new Object();
        options.layer = this.map.getLayerByOpenLayersId(event.element.id);
        options.feature = this.fromOpenLayersFeature(event.feature);
        var eventName = this.viewerController.mapComponent.getGenericEventName(event.type);
        this.fireEvent(eventName,options);
    }
});
<commit_msg>Fixed the OpenLayersVectorLayer TODO: Make a circlecontrol TODO: fix the selecting of a newly added point (after adding another geometry first)<commit_after>/**
 * @class
 * @constructor
 * @description A drawable vector layer
 */
Ext.define("viewer.viewercontroller.openlayers.OpenLayersVectorLayer",{
    extend: "viewer.viewercontroller.controller.VectorLayer",
    point:null,
    line:null,
    polygon:null,
    drawFeatureControls:null,
    modifyFeature:null,
    enabledEvents: new Object(),
    mixins: {
        openLayersLayer: "viewer.viewercontroller.openlayers.OpenLayersLayer"
    },
    constructor : function (config){
        delete config.style;
        viewer.viewercontroller.openlayers.OpenLayersVectorLayer.superclass.constructor.call(this, config);
        this.frameworkLayer = new OpenLayers.Layer.Vector(config.id, config);

        // Make all drawFeature controls: the controls to draw features on the vectorlayer
        this.point =  new OpenLayers.Control.DrawFeature(this.frameworkLayer, OpenLayers.Handler.Point, {
            displayClass: 'olControlDrawFeaturePoint'
        });
        this.line = new OpenLayers.Control.DrawFeature(this.frameworkLayer, OpenLayers.Handler.Path, {
            displayClass: 'olControlDrawFeaturePath'
        });
        this.polygon =  new OpenLayers.Control.DrawFeature(this.frameworkLayer, OpenLayers.Handler.Polygon, {
            displayClass: 'olControlDrawFeaturePolygon'
        });
        this.drawFeatureControls = new Array();
        this.drawFeatureControls.push(this.polygon);
        this.drawFeatureControls.push(this.line);
        this.drawFeatureControls.push(this.point);

        // The modifyfeature control allows us to edit and select features.
        this.modifyFeature = new OpenLayers.Control.ModifyFeature(this.frameworkLayer);

        var map = this.viewerController.mapComponent.getMap().getFrameworkMap();
        map.addControl(this.point);
        map.addControl(this.line);
        map.addControl(this.polygon);
        map.addControl(this.modifyFeature);

        this.modifyFeature.selectControl.events.register("featurehighlighted", this, this.activeFeatureChanged);
        this.frameworkLayer.events.register("afterfeaturemodified", this, this.featureModified);
        this.frameworkLayer.events.register("featuremodified", this, this.featureModified);
        this.frameworkLayer.events.register("featureadded", this, this.featureAdded);

        this.modifyFeature.activate();
    },

    adjustStyle : function(){
        this.viewerController.logger.error("OpenLayersVectorLayer.adjustStyle() not yet implemented!");
    },

    removeAllFeatures : function(){
        this.getFrameworkLayer().removeAllFeatures();
    },

    getActiveFeature : function(){
        var index = this.getFrameworkLayer().features.length - 1;
        var olFeature = this.getFrameworkLayer().features[index];
        var featureObj = new Feature();
        var feature = featureObj.fromOpenLayersFeature(olFeature);

        return feature;
    },

    getFeature : function(id){
        return this.getFrameworkLayer().features[id];
    },

    getAllFeatures : function(){
        var olFeatures = this.getFrameworkLayer().features;
        var features = new Array();
        var featureObj = new viewer.viewercontroller.controller.Feature();
        for(var i = 0 ; i < olFeatures.length;i++){
            var olFeature = olFeatures[i];
            var feature = featureObj.fromOpenLayersFeature(olFeature);

            features.push(feature);
        }
        return features;
    },

    addFeature : function(feature){
        var features = new Array();
        features.push(feature);
        this.addFeatures(features);
    },

    addFeatures : function(features){
        var olFeatures = new Array();
        for(var i = 0 ; i < features.length ; i++){
            var feature = features[i];
            var olFeature = this.toOpenLayersFeature(feature);
            olFeatures.push(olFeature);
        }
        return this.getFrameworkLayer().addFeatures(olFeatures);
    },

    drawFeature : function(type){
        if(type == "Point"){
            this.point.activate();
        }else if(type == "LineString"){
            this.line.activate();
        }else if(type == "Polygon"){
            this.polygon.activate();
        }else{
            throw ("Feature type >" + type + "< not implemented!");
        }
    },

    /**
     * Called when a feature is selected
     */
    activeFeatureChanged : function (object){
        var feature = this.fromOpenLayersFeature (object.feature);
        this.fireEvent(viewer.viewercontroller.controller.Event.ON_ACTIVE_FEATURE_CHANGED,this,feature);
    },

    /**
     * Called when a feature is modified.
     */
    featureModified : function (evt){
        var featureObject = this.fromOpenLayersFeature(evt.feature);
        this.fireEvent(viewer.viewercontroller.controller.Event.ON_FEATURE_ADDED,this,featureObject);
    },

    /**
     * Called when a feature is added to the vectorlayer. It deactivates all drawFeature controls, makes the added feature editable and fires @see viewer.viewercontroller.controller.Event.ON_FEATURE_ADDED
     */
    featureAdded : function (object){
        var feature = this.fromOpenLayersFeature (object.feature);
        for ( var i = 0 ; i < this.drawFeatureControls.length ; i++ ){
            var control = this.drawFeatureControls[i];
            control.deactivate();
        }
        this.editFeature(object.feature);
        this.fireEvent(viewer.viewercontroller.controller.Event.ON_FEATURE_ADDED,this,feature);
    },

    /**
     * Puts an openlayersfeature in editmode and fires an event: viewer.viewercontroller.controller.Event.ON_ACTIVE_FEATURE_CHANGED
     */
    editFeature : function (feature){
        this.modifyFeature.selectControl.unselectAll();
        this.modifyFeature.selectControl.select(feature);
        var featureObject = this.fromOpenLayersFeature (feature);
        this.fireEvent(viewer.viewercontroller.controller.Event.ON_ACTIVE_FEATURE_CHANGED,this,featureObject);
    },

    /**
     * Converts this feature to a OpenLayersFeature
     * @return The OpenLayerstype feature
     */
    toOpenLayersFeature : function(feature){
        var geom = OpenLayers.Geometry.fromWKT(feature.wktgeom);
        var olFeature = new OpenLayers.Feature.Vector(geom);
        return olFeature;
    },

    /**
     * Helper function: Converts the given OpenLayers Feature to the generic feature.
     * @param openLayersFeature The OpenLayersFeature to be converted
     * @return The generic feature
     */
    fromOpenLayersFeature : function(openLayersFeature){
        var feature = new viewer.viewercontroller.controller.Feature({id:openLayersFeature.id,wktgeom: openLayersFeature.geometry.toString()});
        return feature;
    },

    addListener : function (event, handler, scope){
        var olSpecificEvent = this.viewerController.mapComponent.getSpecificEventName(event);
         if(olSpecificEvent){
            if(!scope){
                scope = this;
            }
            if(!olSpecificEvent == "featureadded"){
                this.registerToLayer(olSpecificEvent);
            }
         }else{
            this.viewerController.logger.warning("Event not listed in OpenLayersVectorLayer >"+ event + "<. The application  might not work correctly.");
        }
        viewer.viewercontroller.openlayers.OpenLayersVectorLayer.superclass.addListener.call(this,event,handler,scope);
    },

    /**
     * Add event to OpenLayersVectorLayer only once, to prevent multiple fired events.
     * @param specificEvent The openLayers specific event.
     */
    registerToLayer : function (specificEvent){
          if(this.enabledEvents[specificEvent] == null ||this.enabledEvents[specificEvent] == undefined){
            this.enabledEvents[specificEvent] = true;

            this.frameworkLayer.events.register(specificEvent, this, this.handleEvent);
        }
    },

    /**
     * Handles the events fired by OpenLayers.VectorLayer and propagates them to the registered objects.
     *
     */
    handleEvent : function (event){
        var options = new Object();
        options.layer = this.map.getLayerByOpenLayersId(event.element.id);
        options.feature = this.fromOpenLayersFeature(event.feature);
        var eventName = this.viewerController.mapComponent.getGenericEventName(event.type);
        if(!eventName){
            eventName = event;
        }
        this.fireEvent(eventName,options);
    }
});
<|endoftext|>


<commit_before>/**
 * @class
 * @constructor
 * @description A drawable vector layer
 */
Ext.define("viewer.viewercontroller.openlayers.OpenLayersVectorLayer",{
    extend: "viewer.viewercontroller.controller.VectorLayer",
    point:null,
    line:null,
    polygon:null,
    drawFeatureControls:null,
    modifyFeature:null,
    enabledEvents: new Object(),
    mixins: {
        openLayersLayer: "viewer.viewercontroller.openlayers.OpenLayersLayer"
    },
    constructor : function (config){
        // TODO make styles work in openlayersvectorlayers
        delete config.style;
        viewer.viewercontroller.openlayers.OpenLayersVectorLayer.superclass.constructor.call(this, config);
        this.frameworkLayer = new OpenLayers.Layer.Vector(config.id, config);

        // Make all drawFeature controls: the controls to draw features on the vectorlayer
        //TODO: Make a circlecontrol
        this.point =  new OpenLayers.Control.DrawFeature(this.frameworkLayer, OpenLayers.Handler.Point, {
            displayClass: 'olControlDrawFeaturePoint'
        });
        this.line = new OpenLayers.Control.DrawFeature(this.frameworkLayer, OpenLayers.Handler.Path, {
            displayClass: 'olControlDrawFeaturePath'
        });
        this.polygon =  new OpenLayers.Control.DrawFeature(this.frameworkLayer, OpenLayers.Handler.Polygon, {
            displayClass: 'olControlDrawFeaturePolygon'
        });
        this.drawFeatureControls = new Array();
        this.drawFeatureControls.push(this.polygon);
        this.drawFeatureControls.push(this.line);
        this.drawFeatureControls.push(this.point);

        // The modifyfeature control allows us to edit and select features.
        this.modifyFeature = new OpenLayers.Control.ModifyFeature(this.frameworkLayer);

        var map = this.viewerController.mapComponent.getMap().getFrameworkMap();
        map.addControl(this.point);
        map.addControl(this.line);
        map.addControl(this.polygon);
        map.addControl(this.modifyFeature);

        this.modifyFeature.selectControl.events.register("featurehighlighted", this, this.activeFeatureChanged);
        this.frameworkLayer.events.register("afterfeaturemodified", this, this.featureModified);
        this.frameworkLayer.events.register("featuremodified", this, this.featureModified);
        this.frameworkLayer.events.register("featureadded", this, this.featureAdded);

        this.modifyFeature.activate();
    },

    adjustStyle : function(){
        this.viewerController.logger.error("OpenLayersVectorLayer.adjustStyle() not yet implemented!");
    },

    removeAllFeatures : function(){
        this.getFrameworkLayer().removeAllFeatures();
    },

    getActiveFeature : function(){
        var index = this.getFrameworkLayer().features.length - 1;
        var olFeature = this.getFrameworkLayer().features[index];
        var featureObj = new Feature();
        var feature = featureObj.fromOpenLayersFeature(olFeature);

        return feature;
    },

    getFeature : function(id){
        return this.getFrameworkLayer().features[id];
    },

    getAllFeatures : function(){
        var olFeatures = this.getFrameworkLayer().features;
        var features = new Array();
        var featureObj = new viewer.viewercontroller.controller.Feature();
        for(var i = 0 ; i < olFeatures.length;i++){
            var olFeature = olFeatures[i];
            var feature = featureObj.fromOpenLayersFeature(olFeature);

            features.push(feature);
        }
        return features;
    },

    addFeature : function(feature){
        var features = new Array();
        features.push(feature);
        this.addFeatures(features);
    },

    addFeatures : function(features){
        var olFeatures = new Array();
        for(var i = 0 ; i < features.length ; i++){
            var feature = features[i];
            var olFeature = this.toOpenLayersFeature(feature);
            olFeatures.push(olFeature);
        }
        return this.getFrameworkLayer().addFeatures(olFeatures);
    },

    drawFeature : function(type){
        if(type == "Point"){
            this.point.activate();
        }else if(type == "LineString"){
            this.line.activate();
        }else if(type == "Polygon"){
            this.polygon.activate();
        }else{
            throw ("Feature type >" + type + "< not implemented!");
        }
    },

    /**
     * Called when a feature is selected
     */
    activeFeatureChanged : function (object){
        var feature = this.fromOpenLayersFeature (object.feature);
        this.fireEvent(viewer.viewercontroller.controller.Event.ON_ACTIVE_FEATURE_CHANGED,this,feature);
    },

    /**
     * Called when a feature is modified.
     */
    featureModified : function (evt){
        var featureObject = this.fromOpenLayersFeature(evt.feature);
        this.fireEvent(viewer.viewercontroller.controller.Event.ON_FEATURE_ADDED,this,featureObject);
    },

    /**
     * Called when a feature is added to the vectorlayer. It deactivates all drawFeature controls, makes the added feature editable and fires @see viewer.viewercontroller.controller.Event.ON_FEATURE_ADDED
     */
    featureAdded : function (object){
        var feature = this.fromOpenLayersFeature (object.feature);
        for ( var i = 0 ; i < this.drawFeatureControls.length ; i++ ){
            var control = this.drawFeatureControls[i];
            control.deactivate();
        }
        this.editFeature(object.feature);
        this.fireEvent(viewer.viewercontroller.controller.Event.ON_FEATURE_ADDED,this,feature);
    },

    /**
     * Puts an openlayersfeature in editmode and fires an event: viewer.viewercontroller.controller.Event.ON_ACTIVE_FEATURE_CHANGED
     * TODO: fix the selecting of a newly added point (after adding another geometry first)
     */
    editFeature : function (feature){
        this.modifyFeature.selectControl.unselectAll();
        this.modifyFeature.selectControl.select(feature);
        var featureObject = this.fromOpenLayersFeature (feature);
        this.fireEvent(viewer.viewercontroller.controller.Event.ON_ACTIVE_FEATURE_CHANGED,this,featureObject);
    },

    /**
     * Converts this feature to a OpenLayersFeature
     * @return The OpenLayerstype feature
     */
    toOpenLayersFeature : function(feature){
        var geom = OpenLayers.Geometry.fromWKT(feature.wktgeom);
        var olFeature = new OpenLayers.Feature.Vector(geom);
        return olFeature;
    },

    /**
     * Helper function: Converts the given OpenLayers Feature to the generic feature.
     * @param openLayersFeature The OpenLayersFeature to be converted
     * @return The generic feature
     */
    fromOpenLayersFeature : function(openLayersFeature){
        var feature = new viewer.viewercontroller.controller.Feature({id:openLayersFeature.id,wktgeom: openLayersFeature.geometry.toString()});
        return feature;
    },

    // TODO: implement this
    setLabel : function (id, label){
        this.viewerController.logger.warning("OpenLayersVectorLayer.setLabel() not yet implemented!");
    },

    /******** overwrite functions to make use of the mixin functions **********/
    /**
     * @see viewer.viewercontroller.openlayers.OpenLayersLayer#setVisible
     */
    setVisible: function(vis){
        this.mixins.openLayersLayer.setVisible.call(this,vis);
    },
    /**
     * @see viewer.viewercontroller.OpenLayers.OpenLayersLayer#setAlpha
     */
    setAlpha: function (alpha){
        this.mixins.openLayersLayer.setAlpha.call(this,alpha);
    },
    /**
     * @see viewer.viewercontroller.OpenLayers.OpenLayersLayer#addListener
     */
    addListener: function (event,handler,scope){
        this.mixins.openLayersLayer.addListener.call(this,event,handler,scope);
    },
    /**
     * @see viewer.viewercontroller.OpenLayers.OpenLayersLayer#removeListener
     */
    removeListener: function (event,handler,scope){
        this.mixins.openLayersLayer.removeListener.call(this,event,handler,scope);
    }
});
<commit_msg>Warning instead of throws<commit_after>/**
 * @class
 * @constructor
 * @description A drawable vector layer
 */
Ext.define("viewer.viewercontroller.openlayers.OpenLayersVectorLayer",{
    extend: "viewer.viewercontroller.controller.VectorLayer",
    point:null,
    line:null,
    polygon:null,
    drawFeatureControls:null,
    modifyFeature:null,
    enabledEvents: new Object(),
    mixins: {
        openLayersLayer: "viewer.viewercontroller.openlayers.OpenLayersLayer"
    },
    constructor : function (config){
        // TODO make styles work in openlayersvectorlayers
        delete config.style;
        viewer.viewercontroller.openlayers.OpenLayersVectorLayer.superclass.constructor.call(this, config);
        this.frameworkLayer = new OpenLayers.Layer.Vector(config.id, config);

        // Make all drawFeature controls: the controls to draw features on the vectorlayer
        //TODO: Make a circlecontrol
        this.point =  new OpenLayers.Control.DrawFeature(this.frameworkLayer, OpenLayers.Handler.Point, {
            displayClass: 'olControlDrawFeaturePoint'
        });
        this.line = new OpenLayers.Control.DrawFeature(this.frameworkLayer, OpenLayers.Handler.Path, {
            displayClass: 'olControlDrawFeaturePath'
        });
        this.polygon =  new OpenLayers.Control.DrawFeature(this.frameworkLayer, OpenLayers.Handler.Polygon, {
            displayClass: 'olControlDrawFeaturePolygon'
        });
        this.drawFeatureControls = new Array();
        this.drawFeatureControls.push(this.polygon);
        this.drawFeatureControls.push(this.line);
        this.drawFeatureControls.push(this.point);

        // The modifyfeature control allows us to edit and select features.
        this.modifyFeature = new OpenLayers.Control.ModifyFeature(this.frameworkLayer);

        var map = this.viewerController.mapComponent.getMap().getFrameworkMap();
        map.addControl(this.point);
        map.addControl(this.line);
        map.addControl(this.polygon);
        map.addControl(this.modifyFeature);

        this.modifyFeature.selectControl.events.register("featurehighlighted", this, this.activeFeatureChanged);
        this.frameworkLayer.events.register("afterfeaturemodified", this, this.featureModified);
        this.frameworkLayer.events.register("featuremodified", this, this.featureModified);
        this.frameworkLayer.events.register("featureadded", this, this.featureAdded);

        this.modifyFeature.activate();
    },

    adjustStyle : function(){
        this.viewerController.logger.error("OpenLayersVectorLayer.adjustStyle() not yet implemented!");
    },

    removeAllFeatures : function(){
        this.getFrameworkLayer().removeAllFeatures();
    },

    getActiveFeature : function(){
        var index = this.getFrameworkLayer().features.length - 1;
        var olFeature = this.getFrameworkLayer().features[index];
        var featureObj = new Feature();
        var feature = featureObj.fromOpenLayersFeature(olFeature);

        return feature;
    },

    getFeature : function(id){
        return this.getFrameworkLayer().features[id];
    },

    getAllFeatures : function(){
        var olFeatures = this.getFrameworkLayer().features;
        var features = new Array();
        var featureObj = new viewer.viewercontroller.controller.Feature();
        for(var i = 0 ; i < olFeatures.length;i++){
            var olFeature = olFeatures[i];
            var feature = featureObj.fromOpenLayersFeature(olFeature);

            features.push(feature);
        }
        return features;
    },

    addFeature : function(feature){
        var features = new Array();
        features.push(feature);
        this.addFeatures(features);
    },

    addFeatures : function(features){
        var olFeatures = new Array();
        for(var i = 0 ; i < features.length ; i++){
            var feature = features[i];
            var olFeature = this.toOpenLayersFeature(feature);
            olFeatures.push(olFeature);
        }
        return this.getFrameworkLayer().addFeatures(olFeatures);
    },

    drawFeature : function(type){
        if(type == "Point"){
            this.point.activate();
        }else if(type == "LineString"){
            this.line.activate();
        }else if(type == "Polygon"){
            this.polygon.activate();
        }else{
           this.viewerController.logger.warning("Feature type >" + type + "< not implemented!");
        }
    },

    /**
     * Called when a feature is selected
     */
    activeFeatureChanged : function (object){
        var feature = this.fromOpenLayersFeature (object.feature);
        this.fireEvent(viewer.viewercontroller.controller.Event.ON_ACTIVE_FEATURE_CHANGED,this,feature);
    },

    /**
     * Called when a feature is modified.
     */
    featureModified : function (evt){
        var featureObject = this.fromOpenLayersFeature(evt.feature);
        this.fireEvent(viewer.viewercontroller.controller.Event.ON_FEATURE_ADDED,this,featureObject);
    },

    /**
     * Called when a feature is added to the vectorlayer. It deactivates all drawFeature controls, makes the added feature editable and fires @see viewer.viewercontroller.controller.Event.ON_FEATURE_ADDED
     */
    featureAdded : function (object){
        var feature = this.fromOpenLayersFeature (object.feature);
        for ( var i = 0 ; i < this.drawFeatureControls.length ; i++ ){
            var control = this.drawFeatureControls[i];
            control.deactivate();
        }
        this.editFeature(object.feature);
        this.fireEvent(viewer.viewercontroller.controller.Event.ON_FEATURE_ADDED,this,feature);
    },

    /**
     * Puts an openlayersfeature in editmode and fires an event: viewer.viewercontroller.controller.Event.ON_ACTIVE_FEATURE_CHANGED
     * TODO: fix the selecting of a newly added point (after adding another geometry first)
     */
    editFeature : function (feature){
        this.modifyFeature.selectControl.unselectAll();
        this.modifyFeature.selectControl.select(feature);
        var featureObject = this.fromOpenLayersFeature (feature);
        this.fireEvent(viewer.viewercontroller.controller.Event.ON_ACTIVE_FEATURE_CHANGED,this,featureObject);
    },

    /**
     * Converts this feature to a OpenLayersFeature
     * @return The OpenLayerstype feature
     */
    toOpenLayersFeature : function(feature){
        var geom = OpenLayers.Geometry.fromWKT(feature.wktgeom);
        var olFeature = new OpenLayers.Feature.Vector(geom);
        return olFeature;
    },

    /**
     * Helper function: Converts the given OpenLayers Feature to the generic feature.
     * @param openLayersFeature The OpenLayersFeature to be converted
     * @return The generic feature
     */
    fromOpenLayersFeature : function(openLayersFeature){
        var feature = new viewer.viewercontroller.controller.Feature({id:openLayersFeature.id,wktgeom: openLayersFeature.geometry.toString()});
        return feature;
    },

    // TODO: implement this
    setLabel : function (id, label){
        this.viewerController.logger.warning("OpenLayersVectorLayer.setLabel() not yet implemented!");
    },

    /******** overwrite functions to make use of the mixin functions **********/
    /**
     * @see viewer.viewercontroller.openlayers.OpenLayersLayer#setVisible
     */
    setVisible: function(vis){
        this.mixins.openLayersLayer.setVisible.call(this,vis);
    },
    /**
     * @see viewer.viewercontroller.OpenLayers.OpenLayersLayer#setAlpha
     */
    setAlpha: function (alpha){
        this.mixins.openLayersLayer.setAlpha.call(this,alpha);
    },
    /**
     * @see viewer.viewercontroller.OpenLayers.OpenLayersLayer#addListener
     */
    addListener: function (event,handler,scope){
        this.mixins.openLayersLayer.addListener.call(this,event,handler,scope);
    },
    /**
     * @see viewer.viewercontroller.OpenLayers.OpenLayersLayer#removeListener
     */
    removeListener: function (event,handler,scope){
        this.mixins.openLayersLayer.removeListener.call(this,event,handler,scope);
    }
});
<|endoftext|>


<commit_before>var _ = require('underscore');
var WidgetModel = require('../widget_model');

module.exports = WidgetModel.extend({

  // TODO: The response format has probably changed
  parse: function(r) {
    return {
      data: r[this.get('operation')],
      nulls: r.nulls
    };
  },

  toJSON: function(d) {
      return {
          type: "formula",
          options: {
              column: this.get('column'),
              operation: this.get('operation')
          }
      };
  }
});
<commit_msg>Use result key from formula response<commit_after>var _ = require('underscore');
var WidgetModel = require('../widget_model');

module.exports = WidgetModel.extend({

  // TODO: The response format has probably changed
  parse: function(r) {
    return {
      data: r.result,
      nulls: r.nulls
    };
  },

  toJSON: function(d) {
      return {
          type: "formula",
          options: {
              column: this.get('column'),
              operation: this.get('operation')
          }
      };
  }
});
<|endoftext|>


<commit_before>'use strict';

(function() {
  var xhr = new XMLHttpRequest();

  xhr.open('GET', '/api/posts');
  xhr.send(null);

  xhr.onreadystatechange = function() {
    var DONE = 4; // readyState 4 means the request is done.
    var OK = 200; // status 200 is a successful return.
    var post, posts, i;

    if (xhr.readyState === DONE) {
      if (xhr.status === OK) {

        posts = JSON.parse(xhr.responseText);

        for (i = 0; i < posts.length; i++) {
          var card        = document.createElement("div");
          var cardContent = document.createElement("div");
          var cardAction  = document.createElement("div");
          var link        = document.createElement("a");
          var button      = document.createElement("button");
          var title       = document.createElement("span");
          var titleText   = document.createTextNode(posts[i].title);
          var content     = document.createElement("p");
          var contentText = document.createTextNode(posts[i].content);
          var element     = document.getElementById("posts-container");

          card.appendChild(cardContent);
          card.className += "card grey lighten-2";

          cardContent.appendChild(title)
          cardContent.className += "card-content black-text";
          cardContent.appendChild(content)
          cardContent.appendChild(cardAction);

          cardAction.className += "card-action";
          cardAction.appendChild(link);

          button.innerHTML = "Click to Read";
          button.className += "btn waves-effect blue";

          link.setAttribute("href", "#");
          link.appendChild(button)
          link.className += "";

          title.appendChild(titleText);
          title.className += "card-title";

          content.appendChild(contentText);

          element.appendChild(card);
        }
      }
    }
  };
})();
<commit_msg>restrict amount of character in content preview<commit_after>'use strict';

(function() {
  var xhr = new XMLHttpRequest();

  xhr.open('GET', '/api/posts');
  xhr.send(null);

  xhr.onreadystatechange = function() {
    var DONE = 4; // readyState 4 means the request is done.
    var OK = 200; // status 200 is a successful return.
    var post, posts, i;

    if (xhr.readyState === DONE) {
      if (xhr.status === OK) {

        posts = JSON.parse(xhr.responseText);

        for (i = 0; i < posts.length; i++) {
          var card        = document.createElement("div");
          var cardContent = document.createElement("div");
          var cardAction  = document.createElement("div");
          var link        = document.createElement("a");
          var button      = document.createElement("button");
          var title       = document.createElement("span");
          var titleText   = document.createTextNode(posts[i].title);
          var content     = document.createElement("p");
          var contentText = document.createTextNode(posts[i].content.slice(0, 245) + "....");
          var element     = document.getElementById("posts-container");

          card.appendChild(cardContent);
          card.className += "card grey lighten-2";

          cardContent.appendChild(title)
          cardContent.className += "card-content black-text";
          cardContent.appendChild(content)
          cardContent.appendChild(cardAction);

          cardAction.className += "card-action";
          cardAction.appendChild(link);

          button.innerHTML = "Click to Read";
          button.className += "btn waves-effect blue";

          link.setAttribute("href", "#");
          link.appendChild(button)
          link.className += "";

          title.appendChild(titleText);
          title.className += "card-title";

          content.appendChild(contentText);

          element.appendChild(card);
        }
      }
    }
  };
})();
<|endoftext|>


<commit_before>/**
 * User: _Jay
 * Desciption: ajax use javascript
 * Dependent on: any mondules
 * Datetime: 31 July 2016 (Sunday) 20:15
 */

'use strict';

var Ajax = (function(stringifyFn) {
	/**
	 * Ajax对象 * @type {Object}
	 */
	var Ajax = {
		/**
		 * 获取xhr对象
		 * @return {[type]} [description]
		 */
		_getXHR: function() {
			var xhr;
			try {
				xhr = new XMLHttpRequest();
			} catch (e) {
				var IEXHRVers = ["Msxml3.XMLHTTP", "Msxml2.XMLHTTP", "Microsoft.XMLHTTP"];
				for (var i = 0, len = IEXHRVers.length; i < len; i++) {
					try {
						xhr = new ActiveXObject(IEXHRVers[i]);
					} catch (e) {
						continue;
					}
				}
			}
			return xhr;
		},
		/**
		 * 打印info日志
		 * @return {[type]} [description]
		 */
		_info: function() {
			console.log(arguments);
		},
		/**
		 * 打印error日志
		 * @return {[type]} [description]
		 */
		_error: function() {
			console.error(arguments);
		},
		_formatParams2Url: function(data) {
			var arrData = [];
			for (var key in data) {
				if (data.hasOwnProperty(key)) {
					arrData.push(key + '=' + data[key]);
				}
			}
			return arrData.join('&');
		},
		/**
		 * 发起get请求
		 * @param  {[type]} url     [description]
		 * @param  {[type]} data    [description]
		 * @param  {[type]} success [description]
		 * @param  {[type]} error   [description]
		 * @return {[type]}         [description]
		 */
		get: function(url, data, success, error) {
			var _p = this;
			var xhr = _p._getXHR();
			//监听
			xhr.onreadystatechange = function() {
				if (xhr.readyState == 4) {
					xhr.status == 200 && success && success(xhr.responseText);
					xhr.status != 200 && error && error(xhr.status, xhr.responseText);
					xhr = undefined;
				}
			}

			xhr.open('GET', url, true); //第三个参数标示使用异步
			//TODO 是否需要设置头
			if (data instanceof Function) {
				success && (error = success);
				success = data;
				xhr.send(null);
			} else {
				xhr.send(_p._formatParams2Url(data));
			}
		},
		/**
		 * post method
		 * post json data by default
		 * @param  {[type]}  url           [description]
		 * @param  {[type]}  data          [description]
		 * @param  {[type]}  success       [description]
		 * @param  {[type]}  error         [description]
		 * @param  {Boolean} isLikeOneForm [description]
		 * @return {[type]}                [description]
		 */
		post: function(url, data, success, error, isLikeOneForm) {
			var _p = this;
			var xhr = _p._getXHR();
			var lastArg = arguments[arguments.length - 1];

			xhr.onreadystatechange = function() {
				if (xhr.readyState == 4) {
					xhr.status == 200 && success && success(xhr.responseText);
					xhr.status != 200 && error && error(xhr.status, xhr.responseText);
					xhr = undefined;
				}
			}

			xhr.open('POST', url, true); //第三个参数标示使用异步
			//TODO 是否需要设置头
			if (data instanceof Function) {
				success && (error = success);
				success = data;
			}
			//判断是否是json格式
			if (typeof lastArg == 'boolean') {
				if (!lastArg) {
					xhr.setRequestHeader('Content-Type', 'application/json;charset=utf-8');
					xhr.send(stringifyFn(data));
				} else {
					xhr.setRequestHeader("Content-Type", "application/x-www-form-urlencoded")
					xhr.send(_p._formatParams2Url(data))
				}
			}
		},

		delete: function(){},
		put: function(){}
	};

	return Ajax;
})(JSON.stringify);<commit_msg>[modify] parse ajax responseText to son<commit_after>/**
 * User: _Jay
 * Desciption: ajax use javascript
 * Dependent on: any mondules
 * Datetime: 31 July 2016 (Sunday) 20:15
 */

'use strict';

var Ajax = (function(stringifyFn, parseFn) {
	/**
	 * Ajax对象 * @type {Object}
	 */
	var Ajax = {
		/**
		 * 获取xhr对象
		 * @return {[type]} [description]
		 */
		_getXHR: function() {
			var xhr;
			try {
				xhr = new XMLHttpRequest();
			} catch (e) {
				var IEXHRVers = ["Msxml3.XMLHTTP", "Msxml2.XMLHTTP", "Microsoft.XMLHTTP"];
				for (var i = 0, len = IEXHRVers.length; i < len; i++) {
					try {
						xhr = new ActiveXObject(IEXHRVers[i]);
					} catch (e) {
						continue;
					}
				}
			}
			return xhr;
		},
		/**
		 * 打印info日志
		 * @return {[type]} [description]
		 */
		_info: function() {
			console.log(arguments);
		},
		/**
		 * 打印error日志
		 * @return {[type]} [description]
		 */
		_error: function() {
			console.error(arguments);
		},
		_formatParams2Url: function(data) {
			var arrData = [];
			for (var key in data) {
				if (data.hasOwnProperty(key)) {
					arrData.push(key + '=' + data[key]);
				}
			}
			return arrData.join('&');
		},
		/**
		 * 发起get请求
		 * @param  {[type]} url     [description]
		 * @param  {[type]} data    [description]
		 * @param  {[type]} success [description]
		 * @param  {[type]} error   [description]
		 * @return {[type]}         [description]
		 */
		get: function(url, data, success, error) {
			var _p = this;
			var xhr = _p._getXHR();
			//监听
			xhr.onreadystatechange = function() {
				if (xhr.readyState == 4) {
					xhr.status == 200 && success && success(parseFn(xhr.responseText));
					xhr.status != 200 && error && error(xhr.status, xhr.responseText);
					xhr = undefined;
				}
			}

			xhr.open('GET', url, true); //第三个参数标示使用异步
			//TODO 是否需要设置头
			if (data instanceof Function) {
				success && (error = success);
				success = data;
				xhr.send(null);
			} else {
				xhr.send(_p._formatParams2Url(data));
			}
		},
		/**
		 * post method
		 * post json data by default
		 * @param  {[type]}  url           [description]
		 * @param  {[type]}  data          [description]
		 * @param  {[type]}  success       [description]
		 * @param  {[type]}  error         [description]
		 * @param  {Boolean} isLikeOneForm [description]
		 * @return {[type]}                [description]
		 */
		post: function(url, data, success, error, isLikeOneForm) {
			var _p = this;
			var xhr = _p._getXHR();
			var lastArg = arguments[arguments.length - 1];

			xhr.onreadystatechange = function() {
				if (xhr.readyState == 4) {
					xhr.status == 200 && success && success(parseFn(xhr.responseText));
					xhr.status != 200 && error && error(xhr.status, xhr.responseText);
					xhr = undefined;
				}
			}

			xhr.open('POST', url, true); //第三个参数标示使用异步
			//TODO 是否需要设置头
			if (data instanceof Function) {
				success && (error = success);
				success = data;
			}
			//判断是否是json格式
			if (typeof lastArg == 'boolean') {
				if (!lastArg) {
					xhr.setRequestHeader('Content-Type', 'application/json;charset=utf-8');
					xhr.send(stringifyFn(data));
				} else {
					xhr.setRequestHeader("Content-Type", "application/x-www-form-urlencoded")
					xhr.send(_p._formatParams2Url(data))
				}
			}
		},

		delete: function(){},
		put: function(){}
	};

	return Ajax;
})(JSON.stringify, JSON.parse);<|endoftext|>


<commit_before>var Auth = {

  $form: $('#js-auth'),
  $name: $('#js-nombre'),
  $tel: $('#js-tel'),

  $keyboards: $('.keyboard'),

  init: function init () {
    this.listen();
    return this;
  },

  listen: function listen () {

    this.$name.focus(this.showKeyboard.bind(this));
    this.$tel.focus(this.showKeyboard.bind(this));

    this.$form.submit(this.onSubmit.bind(this));
    this.$keyboards.click(this.onType.bind(this));

    $.ripple('.key', { duration: .4 });

    return this;
  },

  onSubmit: function onSubmit (event) {
    event.preventDefault();
    PubSub.publish('user:register', this.serializeForm());
    return this;
  },

  serializeForm: function serializeForm () {
    return _.chain(this.$form.serializeArray())
      .map(_.values)
      .object()
      .value();
  },

  onType: function onType (event) {
    var $target = $(event.target).closest('.key'),
        $container = $target.closest('.authForm__input'),
        $input = $container.find('input'),
        key = $target.data('key');

    event.stopPropagation();

    switch (key) {
      case 8:
        $input.val($input.val().slice(0, -1)).focus();
        break;
      case 13:
        this.hideKeyboards();
        break;
      default:
        $input.val($input.val() + String.fromCharCode(key)).focus();
    }

    return this;
  },

  showKeyboard: function showKeyboard (event) {
    this.hideKeyboards();

    $(event.target)
      .closest('.authForm__input')
      .find('.keyboard')
      .removeClass('hide');

    return this;
  },

  hideKeyboards: function hideKeyboards () {
    this.$keyboards.addClass('hide');
    return this;
  }
};

Auth.init();
<commit_msg>Prevent multiple form submissions<commit_after>var Auth = {

  $form: $('#js-auth'),
  $name: $('#js-nombre'),
  $tel: $('#js-tel'),

  $keyboards: $('.keyboard'),

  init: function init () {
    this.listen();
    return this;
  },

  listen: function listen () {

    this.$name.focus(this.showKeyboard.bind(this));
    this.$tel.focus(this.showKeyboard.bind(this));

    this.$form.submit(this.onSubmit.bind(this));
    this.$keyboards.click(this.onType.bind(this));

    $.ripple('.key', { duration: .4 });

    return this;
  },

  onSubmit: function onSubmit (event) {
    event.preventDefault();

    if (!this.isSubmitted) {
      PubSub.publish('user:register', this.serializeForm());
      this.isSubmitted = true;
    }

    return this;
  },

  serializeForm: function serializeForm () {
    return _.chain(this.$form.serializeArray())
      .map(_.values)
      .object()
      .value();
  },

  onType: function onType (event) {
    var $target = $(event.target).closest('.key'),
        $container = $target.closest('.authForm__input'),
        $input = $container.find('input'),
        key = $target.data('key');

    event.stopPropagation();

    switch (key) {
      case 8:
        $input.val($input.val().slice(0, -1)).focus();
        break;
      case 13:
        this.hideKeyboards();
        break;
      default:
        $input.val($input.val() + String.fromCharCode(key)).focus();
    }

    return this;
  },

  showKeyboard: function showKeyboard (event) {
    this.hideKeyboards();

    $(event.target)
      .closest('.authForm__input')
      .find('.keyboard')
      .removeClass('hide');

    return this;
  },

  hideKeyboards: function hideKeyboards () {
    this.$keyboards.addClass('hide');
    return this;
  }
};

Auth.init();
<|endoftext|>


<commit_before>$(document).ready(function(){
      $(window).bind('hashchange', function(e){
        //대기 표시 한다.
        //여기서 요청을 보내고
        var path = getHash().replace(/^#/, "");
        var branch = encodeURIComponent($("#selected-branch").text());

        $.ajax("code/" + branch + "/!" + path, {
          datatype : "json",
          success : function(data, textStatus, jqXHR){
              console.log(data);
            updateBreadcrumbs(path);
//            updateNav(path);
            switch(data.type){
              case "file" :
                  handleFile(data);
                break;
              case "folder" :
                  handleFolder(data);
                break;
            }
          },
          error : function(){
            $("#codeError").show();
          }
        });
        function handleFile(data){
            //파일을 표시한다.
            $("#commiter").text(data.author);
            $("#commitMessage").text(data.msg);
            $("#commitDate").text(moment(new Date(data.date)).fromNow());
            $("code").text(data.data);
            $("#rawCode").attr("href", "rawcode"+path);//TODO 현재 동작하지 않음.

            $("#folderView").hide();
            $("#codeView").show();
            $("code").highlight();
        }
        function handleFolder(data){
            //폴더내용을 리스팅 한다.
            $("#commiter").text(data.author);
            $("#commitMessage").text(data.msg);
            $("#commitDate").text(data.date);

            $(".contents").children().remove();

            for(var name in data.data){
              var info = data.data[name];
              var tablerow = makeTableRow(name, info.msg, info.date, info.author);
              $(".contents").append(tablerow);
            }

            $("#folderView").show();
            $("#codeView").hide();
        }
        function makeTableRow(name, message, date, author){
          if (message.length > 70){
            message = message.substr(0, 70) + "...";
          }
          return $("
")
              .append(
                  $("").append(
                      $("").text(name).attr("href", "#" + (path !== "/" ? path : "") + "/" +name)
                    ).addClass("filename")
                  )
              .append($("").text(message).addClass("message"))
              .append($("").text(moment(new Date(date)).fromNow()).addClass("date"))
              //.append($("").text(author).addClass("author"))
              .append($('	'));
        }
        function updateBreadcrumbs(path){
          var $breadcrumbs = $("#breadcrumbs");
          $($breadcrumbs).html('/');

          var names = path.split("/");
          var str = "#"
          for(var i = 1; i < names.length; i++){
            var name = names[i];
            str += "/" + name;
            $breadcrumbs.append(" > ");
            $("").text(name).attr("href", str).appendTo($breadcrumbs);
          }
        }
      });

      if (!$("#selected-branch").text()) $("#selected-branch").text('HEAD');
      $(window).trigger('hashchange');
  });

  function getHash(){
      //혹시 있을지도 모를 호완성을 위해.
      return location.hash;
  }
  function setHash(hash){
      return location.hash = hash;
  }
  function standizePath(path){
    return "/" + path.split("/").filter(isEmpty).join("/");
    function isEmpty(data){
      if(data == ""){
        return false;
      } else {
        return true;
      }
    }
  }

  $(".branch-item").click(function(ev){
    $("#selected-branch").text($(this).text());
    $(window).trigger('hashchange');
  });

// adaptorForDynatree adaptor function is used for existed function
// Also, it pass the below tests
//
// it("file & folder combine", function() {
//     //Given
//     var target = {
//         "attachment": {
//             "type": "folder",
//             "msg": "add folders",
//             "author": "doortts",
//             "date": "Mon Jan 28 14:21:07 KST 2013"
//         },
//         "favicon.ico": {
//             "type": "file",
//             "msg": "add folders",
//             "author": "doortts",
//             "date": "Mon Jan 28 14:21:07 KST 2013"
//         }
//     };
//     var expected = [
//         {title: "attachment", isFolder: true, isLazy: true},
//         {title: "favicon.ico"}
//     ];
//     //When
//     var result = adaptorForDynatree(target);
//     //Then
//     assert.deepEqual(result, expected);
// });

var result = [];
function adaptorForDynatree(target){
    result = [];
    _.each(target, function(value, key, list){
        if(value.type === "folder") {
            result.push({ title: key, isFolder: true, isLazy: true});
        } else {
            result.push({ title: key});
        }
    })
    return _.sortBy(result, function(elm){
        return -elm.hasOwnProperty("isFolder");
    })
}

// Traverse the path of selected tree item
function getTreePath(node){
    var path = "";
    var title = "";
    if( node.getParent() && node.getParent().data.title !== null ){
        path = getTreePath(node.getParent()) + "/" + node.data.title;
    } else {
        path = node.data.title;
    }
    return path;
}

// initial path loading
var rootPath = "";
$(function(){
    var path = getHash().replace(/^#/, "");
    var branch = encodeURIComponent($("#selected-branch").text());
    rootPath = "code/" + branch + "/!/";
    console.log("rootPath=", rootPath);
    $.ajax({
        url: rootPath,
        success: function(result, textStatus){
            treeInit(adaptorForDynatree(result.data));
        }
    });
});

// DynaTree Init function
// see: http://wwwendt.de/tech/dynatree/doc/dynatree-doc.html
function treeInit(initData){
    $("#folderNav").dynatree({
        fx: { height: "toggle", duration: 200 },
        autoFocus: false,
        isLazy: true,
        onLazyRead: function(node){

            $.ajax({
                url: rootPath + getTreePath(node),
                success: function(result, textStatus) {
                    // Called after nodes have been created and the waiting icon was removed.
                    // 'this' is the options for this Ajax request
                    if(result){
                        node.setLazyNodeStatus(DTNodeStatus_Ok);
                        node.addChild(adaptorForDynatree(result.data));
                    }else{
                        // Server returned an error condition: set node status accordingly
                        node.setLazyNodeStatus(DTNodeStatus_Error, {
                            tooltip: result.faultDetails,
                            info: result.faultString
                        });
                    }
                },
                error: function(node, XMLHttpRequest, textStatus, errorThrown) {
                    // Called on error, after error icon was created.
                    console.log(node);
                },
                cache: false // Append random '_' argument to url to prevent caching.
            });
        },
        onActivate: function(node) {
            // A DynaTreeNode object is passed to the activation handler
            // Note: we also get this event, if persistence is on, and the page is reloaded.
            window.location = "#/" + getTreePath(node);
        },
        title: "/",
        children: initData
    });
}<commit_msg>remove unused string<commit_after>$(document).ready(function(){
      $(window).bind('hashchange', function(e){
        //대기 표시 한다.
        //여기서 요청을 보내고
        var path = getHash().replace(/^#/, "");
        var branch = encodeURIComponent($("#selected-branch").text());

        $.ajax("code/" + branch + "/!" + path, {
          datatype : "json",
          success : function(data, textStatus, jqXHR){
              console.log(data);
            updateBreadcrumbs(path);
//            updateNav(path);
            switch(data.type){
              case "file" :
                  handleFile(data);
                break;
              case "folder" :
                  handleFolder(data);
                break;
            }
          },
          error : function(){
            $("#codeError").show();
          }
        });
        function handleFile(data){
            //파일을 표시한다.
            $("#commiter").text(data.author);
            $("#commitMessage").text(data.msg);
            $("#commitDate").text(moment(new Date(data.date)).fromNow());
            $("code").text(data.data);
            $("#rawCode").attr("href", "rawcode"+path);//TODO 현재 동작하지 않음.

            $("#folderView").hide();
            $("#codeView").show();
            $("code").highlight();
        }
        function handleFolder(data){
            //폴더내용을 리스팅 한다.
            $("#commiter").text(data.author);
            $("#commitMessage").text(data.msg);
            $("#commitDate").text(data.date);

            $(".contents").children().remove();

            for(var name in data.data){
              var info = data.data[name];
              var tablerow = makeTableRow(name, info.msg, info.date, info.author);
              $(".contents").append(tablerow);
            }

            $("#folderView").show();
            $("#codeView").hide();
        }
        function makeTableRow(name, message, date, author){
          if (message.length > 70){
            message = message.substr(0, 70) + "...";
          }
          return $("
")
              .append(
                  $("").append(
                      $("").text(name).attr("href", "#" + (path !== "/" ? path : "") + "/" +name)
                    ).addClass("filename")
                  )
              .append($("").text(message).addClass("message"))
              .append($("").text(moment(new Date(date)).fromNow()).addClass("date"))
              //.append($("").text(author).addClass("author"))
              .append($('	'));
        }
        function updateBreadcrumbs(path){
          var $breadcrumbs = $("#breadcrumbs");
          $($breadcrumbs).html('/');

          var names = path.split("/");
          var str = "#"
          for(var i = 1; i < names.length; i++){
            var name = names[i];
            str += "/" + name;
            $breadcrumbs.append(" > ");
            $("").text(name).attr("href", str).appendTo($breadcrumbs);
          }
        }
      });

      if (!$("#selected-branch").text()) $("#selected-branch").text('HEAD');
      $(window).trigger('hashchange');
  });

  function getHash(){
      //혹시 있을지도 모를 호완성을 위해.
      return location.hash;
  }
  function setHash(hash){
      return location.hash = hash;
  }
  function standizePath(path){
    return "/" + path.split("/").filter(isEmpty).join("/");
    function isEmpty(data){
      if(data == ""){
        return false;
      } else {
        return true;
      }
    }
  }

  $(".branch-item").click(function(ev){
    $("#selected-branch").text($(this).text());
    $(window).trigger('hashchange');
  });

// adaptorForDynatree adaptor function is used for existed function
// Also, it pass the below tests
//
// it("file & folder combine", function() {
//     //Given
//     var target = {
//         "attachment": {
//             "type": "folder",
//             "msg": "add folders",
//             "author": "doortts",
//             "date": "Mon Jan 28 14:21:07 KST 2013"
//         },
//         "favicon.ico": {
//             "type": "file",
//             "msg": "add folders",
//             "author": "doortts",
//             "date": "Mon Jan 28 14:21:07 KST 2013"
//         }
//     };
//     var expected = [
//         {title: "attachment", isFolder: true, isLazy: true},
//         {title: "favicon.ico"}
//     ];
//     //When
//     var result = adaptorForDynatree(target);
//     //Then
//     assert.deepEqual(result, expected);
// });

var result = [];
function adaptorForDynatree(target){
    result = [];
    _.each(target, function(value, key, list){
        if(value.type === "folder") {
            result.push({ title: key, isFolder: true, isLazy: true});
        } else {
            result.push({ title: key});
        }
    })
    return _.sortBy(result, function(elm){
        return -elm.hasOwnProperty("isFolder");
    })
}

// Traverse the path of selected tree item
function getTreePath(node){
    var path = "";
    if( node.getParent() && node.getParent().data.title !== null ){
        path = getTreePath(node.getParent()) + "/" + node.data.title;
    } else {
        path = node.data.title;
    }
    return path;
}

// initial path loading
var rootPath = "";
$(function(){
    var path = getHash().replace(/^#/, "");
    var branch = encodeURIComponent($("#selected-branch").text());
    rootPath = "code/" + branch + "/!/";
    console.log("rootPath=", rootPath);
    $.ajax({
        url: rootPath,
        success: function(result, textStatus){
            treeInit(adaptorForDynatree(result.data));
        }
    });
});

// DynaTree Init function
// see: http://wwwendt.de/tech/dynatree/doc/dynatree-doc.html
function treeInit(initData){
    $("#folderNav").dynatree({
        fx: { height: "toggle", duration: 200 },
        autoFocus: false,
        isLazy: true,
        onLazyRead: function(node){

            $.ajax({
                url: rootPath + getTreePath(node),
                success: function(result, textStatus) {
                    // Called after nodes have been created and the waiting icon was removed.
                    // 'this' is the options for this Ajax request
                    if(result){
                        node.setLazyNodeStatus(DTNodeStatus_Ok);
                        node.addChild(adaptorForDynatree(result.data));
                    }else{
                        // Server returned an error condition: set node status accordingly
                        node.setLazyNodeStatus(DTNodeStatus_Error, {
                            tooltip: result.faultDetails,
                            info: result.faultString
                        });
                    }
                },
                error: function(node, XMLHttpRequest, textStatus, errorThrown) {
                    // Called on error, after error icon was created.
                    console.log(node);
                },
                cache: false // Append random '_' argument to url to prevent caching.
            });
        },
        onActivate: function(node) {
            // A DynaTreeNode object is passed to the activation handler
            // Note: we also get this event, if persistence is on, and the page is reloaded.
            window.location = "#/" + getTreePath(node);
        },
        title: "/",
        children: initData
    });
}<|endoftext|>


<commit_before>'use strict';
/*globals $:false */

var numFiles = 0;
var isThread = location.href.split('/')[3] === 'thread';

function enableSubmit() {
  var title = document.getElementById('title');
  var submit = document.getElementById('submit');

  if (!isThread) {
    submit.disabled = (title.value.length === 0 || numFiles === 0);
  }
  else {
    submit.disabled = (numFiles === 0);
  }

}

// make sure at the title is filled
$('#title').on('input', function() {
  enableSubmit();
});

/*global Dropzone */
Dropzone.options.newThread = {

  // The configuration
  autoProcessQueue: false,
  uploadMultiple: true,
  parallelUploads: 10,
  maxFiles: 50,
  previewsContainer: '.dropzone-previews',
  clickable: '.dropzone-upload',

  // The setting up of the dropzone
  init: function() {
    var self = this;

    // config
    self.options.addRemoveLinks = true;
    self.options.dictRemoveFile = 'Delete';

    // First change the button to actually tell Dropzone to process the queue.
    this.element.querySelector('button[type=submit]').addEventListener('click',
     function(e) {
      // Make sure that the form isn't actually being sent.
      e.preventDefault();
      e.stopPropagation();
      self.processQueue();
    });

    // New file added
    self.on('addedfile', function(file) {
      numFiles = this.files.length;
      enableSubmit();
      console.log('new file added ', file);
    });

    // File removed
    self.on('removedfile', function(file) {
      numFiles = this.files.length;
      enableSubmit();
      console.log('new file added ', file);
    });

    // Send file starts
    self.on('sending', function(file) {
      console.log('upload started', file);
    });

    // File completed
    self.on('complete', function(file) {
      /*global dom */
      dom.addThreadDom(file.xhr.response, file);
      console.log('complete upload');
    });

  }
};
<commit_msg>Fixes #9<commit_after>'use strict';
/*globals $:false */

var numFiles = 0;
var isThread = location.href.split('/')[3] === 'thread';

function enableSubmit() {
  var title = document.getElementById('title');
  var submit = document.getElementById('submit');

  if (!isThread) {
    submit.disabled = (title.value.length === 0 || numFiles === 0);
  }
  else {
    submit.disabled = (numFiles === 0);
  }

}

// make sure at the title is filled
$('#title').on('input', function() {
  enableSubmit();
});

/*global Dropzone */
Dropzone.options.newThread = {

  // The configuration
  autoProcessQueue: false,
  uploadMultiple: true,
  parallelUploads: 10,
  maxFiles: 50,
  previewsContainer: '.dropzone-previews',
  clickable: '.dropzone-upload',

  // The setting up of the dropzone
  init: function() {
    var self = this;

    // config
    self.options.addRemoveLinks = true;
    self.options.dictRemoveFile = 'Delete';

    // First change the button to actually tell Dropzone to process the queue.
    this.element.querySelector('button[type=submit]').addEventListener('click',
     function(e) {
      // Make sure that the form isn't actually being sent.
      e.preventDefault();
      e.stopPropagation();
      self.processQueue();
    });

    // New file added
    self.on('addedfile', function(file) {
      numFiles = this.files.length;
      enableSubmit();
      console.log('new file added ', file);
    });

    // File removed
    self.on('removedfile', function(file) {
      numFiles = this.files.length;
      enableSubmit();
      console.log('new file added ', file);
    });

    // Send file starts
    self.on('sending', function(file, xhr, data) {
      console.log('upload started', file);
      console.log('upload started', xhr);
      data.append('title', document.getElementById('title').value);
      data.append('comment', document.getElementById('comment').value);

    });

    // File completed
    self.on('complete', function(file) {
      /*global dom */
      dom.addThreadDom(file.xhr.response, file);
      console.log('complete upload');
    });

  }
};
<|endoftext|>


<commit_before>/*
   Copyright 2012 Igor Laborie

   Licensed under the Apache License, Version 2.0 (the "License");
   you may not use this file except in compliance with the License.
   You may obtain a copy of the License at

       http://www.apache.org/licenses/LICENSE-2.0

   Unless required by applicable law or agreed to in writing, software
   distributed under the License is distributed on an "AS IS" BASIS,
   WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
   See the License for the specific language governing permissions and
   limitations under the License.
*/
// Define some default objets
// Utilities
if (typeof String.prototype.startsWith != "function") {
	// see below for better implementation!
	String.prototype.startsWith = function (str) {
		return this.indexOf(str) === 0;
	};
}

$.postJSON = function(url, data, callback, onError) {
	var fun = doOnError;
	if (onError && $.isFunction(onError)) {
		fun = onError;
	}
    return jQuery.ajax({
        type: "POST",
        url: url,
        contentType: "application/json",
        data: JSON.stringify(data),
        dataType: "json",
        success: callback,
        timeout: 3000,
		tryCount : 0,
		retryLimit : 3,
        onError: fun
    });
};

$.deleteJSON = function(url, data, callback, onError) {
	var fun = doOnError;
	if (onError && $.isFunction(onError)) {
		fun = onError;
	}
    return jQuery.ajax({
        type: "DELETE",
        url: url,
        contentType: "application/json",
        data: JSON.stringify(data),
        dataType: "json",
        success: callback,
        timeout: 3000,
		tryCount : 0,
		retryLimit : 3,
        onError: fun
    });
};

var doOnError = function(xhr, textStatus, errorThrown) {
	var msg = "Error: " +textStatus +"\n"+errorThrown;
	console.log(msg);
	createNotice({
		kind: "error",
		message: msg
	});
};

/**
 * Create a dynamic notice
 */
var createNotice = function(notice) {
	$(".top-right").notify({
		type: notice.kind,
		message: { html: notice.message }
	}).show();
};

/**
 * Open Modal
 */
var openModalDialog = function(title, message, buttons) {
	$("#modalDialog .modal-header h3").html(title);
	$("#modalDialog .modal-body p").empty().append(message);

	var $buttonsBar = $("#modalDialog .modal-footer");
	$buttonsBar.empty();
	if (typeof buttons === "undefined") {
		$buttonsBar.append(createButton({
			text: "Close",
			"data-dismiss" : "modal"
		}));
	} else if ($.isArray(buttons)) {
		for(var i=0; i< buttons.length; i++) {
			$buttonsBar.append(createButton(buttons[i]));
		}
	} else {
		$buttonsBar.append(createButton(buttons));
	}
	$("#modalDialog").unbind("shown").on("shown",function(){
		$("#modalDialog .modal-footer button:last-child").focus();
	}).modal("show");
};

/**
 * Create a button
 */
var createButton = function(props) {
	var text  = props.text;
	var click = props.click;
	var cssClass = "btn";
	if (props["class"]) {
		cssClass += " " +  props["class"];
	}

	var attrs = {};
	for (var p in props) {
		if ((p!== "text") && (p!== "click") && (p!== "class")) {
			attrs[p] = props[p];
		}
	}

	$btn = $("<button/>", attrs).addClass(cssClass).html(text);
	if (typeof click === "function") {
		$btn.click(click);
	}

	return $btn;
};

/**
 * Create an UUID
 */
this.createUuid = function() {
    var S4 = function() {
       return (((1+Math.random())*0x10000)|0).toString(16).substring(1);
    };
    return (S4()+S4()+"-"+S4()+"-"+S4()+"-"+S4()+"-"+S4()+S4()+S4());
};

/**
 * isInteger
 */
var isInteger = function(s) {
  return ((""+s).search(/^-?[0-9]+$/) === 0);
};

var scollToBottom = function() {
	if ($(".score-left-container").is(":visible")) {
		var h = $(document).height();
		$("body").scrollTop(h);
	}
};

// TODO Board & Darts

// Player
var players = {
	db: [],
	addPlayer: function(player) {
		players.db.push({
			uuid: player.uuid,
			name: player.name,
			surname: player.surname,
			com: player.com,
			comLevel: player.comLevel,
			comTarget: player.comTarget
		});
		// Store to DB
		localStorage.setItem("players", JSON.stringify(players.db));
	},
	update: function(player) {
		var p;
		for (var i=0; i<players.db.length; i++) {
			p = players.db[i];
			if (p.uuid === player.uuid) {
				p.name = player.name;
				p.surname = player.surname;
				p.com = player.com;
				p.comLevel = player.comLevel;
				p.comTarget = player.comTarget;
			}
		}
		// Store to DB
		localStorage.setItem("players", JSON.stringify(players.db));
	},
	getPlayer: function(playerId) {
		var pId = playerId;
		if (pId.lastIndexOf("_")!=-1) {
			var idx = pId.lastIndexOf("_");
			pId = pId.substring(0,idx);
		}
		var p;
		var player;
		for (var i=0; i<players.db.length; i++) {
			p = players.db[i];
			if (p.uuid === pId) {
				player = new Player(p.name, p.surname);
				player.uuid = p.uuid;
				player.com = p.com;
				player.comLevel = p.comLevel;
				player.comTarget = p.comTarget;
				return player;
			}
		}
		player = new Player("Mr. X", null);
		this.addPlayer(player);
		return player;
	},
	getByPrefix : function(prefix) {
		var res = [];
		var player;
		var p;
		for (var i=0; i<players.db.length; i++) {
			p = players.db[i];
			if (prefix===null || prefix==="" || p.name.startsWith(prefix)) {
				player = new Player(p.name, p.surname);
				player.uuid = p.uuid;
				player.com = p.com;
				player.comLevel = p.comLevel;
				player.comTarget = p.comTarget;
				res.push(player);
			}
		}
		return res;
	},
	getPlayerByNameSurname : function(name, surname) {
		var player;
		for (var i=0; i<players.db.length; i++) {
			p = players.db[i];
			if ((p.name === name) && (p.surname===surname)) {
				player = new Player(p.name, p.surname);
				player.uuid = p.uuid;
				player.com = p.com;
				player.comLevel = p.comLevel;
				player.comTarget = p.comTarget;
				return player;
			}
		}
		player = new Player(name, surname);
		this.addPlayer(player);
		return player;
	}
};
// Load to DB
var playersDB = localStorage.getItem("players");
if (playersDB !== null) {
	players.db = JSON.parse(playersDB);
}

function Player(name, surname) {
	this.uuid = createUuid();
	this.name = name;
	this.surname = surname;

	this.com = false;
	this.comLevel = 0;
	this.comTarget = 20;

	// Name
	this.getName = function() {
		var res;
		if (this.name) {
			res = this.name;
		} else {
			res = this.id;
		}
		return res;
	};
	this.getFullName = function() {
		var res = this.getName();
		if (this.surname) {
			res +=  " «"+this.surname+"»";
		}
		return res;
	};
	this.getDisplayName = function() {
		if (this.com) {
			return ' '+this.comLevel+' play ' + this.comTarget;
		} else {
			return ' ' + this.getFullName();

		}
	};
}
// Dialog for player selection
$("#diaPlayerSelect .input").keyup(function() {
	var prefix = $(this).val();
	updatePlayerList(prefix);
});
var updatePlayerList = function(prefix) {
	// unselect all & clear list
	$("#diaPlayerSelect .btn-primary").attr("disabled","disabled");
	$("#diaSelectedPlayer").val("");
	$("#diaPlayerSelect .playerList").empty();

	// Fill list
	var p = players.getByPrefix(prefix);
	$.each(p, function(idx, player) {
		$("#diaPlayerSelect .playerList").append(
			$("
").append(
				$("").attr("href", "#").append(player.getDisplayName()).click(function (event) {
					if ($(this).parent().hasClass("active")) {
						$("#diaSelectedPlayer").val("");
						$("#diaPlayerSelect .btn-primary").attr("disabled","disabled");
						$("#diaPlayerSelect .playerList li").removeClass("active");
					} else {
						$("#diaSelectedPlayer").val(player.uuid);
						$("#diaPlayerSelect .btn-primary").removeAttr("disabled");
						$("#diaPlayerSelect .playerList li").removeClass("active");
						$(this).parent().addClass("active");
					}
					return true;
				})
			)
		);
	});
};

$("#diaPlayerSelect").on("shown", function() {
	$("#diaPlayerSelect .input").focus();
});
var selectPlayer = function(callback) {
	updatePlayerList($("#diaPlayerSelect .input").val());

	$("#diaPlayerSelect .btn-primary").unbind("click").click(function(e) {
		var playerId = $("#diaSelectedPlayer").val();
		if (playerId!=="") {
			var player = players.getPlayer(playerId);
			$("#diaPlayerSelect").modal("hide");
			callback(player);
		}
	});
	$("#diaPlayerSelect").modal("show");
};

// Create player Dialog

$("#diaPlayerCreation").on("shown", function(event) {
	$("#playerName").focus();
});
var diaCreatePlayerLoaded = false;
var createPlayer = function(callback) {
	if (!diaCreatePlayerLoaded) {
		diaCreatePlayerLoaded = true;
		$("#isComputer").toggleButtons({
			onChange: function($el, status) {
				if (status) {
					$(".playerComputer").show();
					$(".humanPlayer").hide();
				} else {
					$(".playerComputer").hide();
					$(".humanPlayer").show();
				}
			}
		});
	}
	// initial state
	if ($("#isComputer input").is(":checked")) {
		$(".playerComputer").show();
		$(".humanPlayer").hide();
	} else {
		$(".playerComputer").hide();
		$(".humanPlayer").show();
	}

	$("#diaPlayerCreation .btn-success").unbind("click").click(function(event){
		doCreatePlayer(event, callback);
	});
	$("#diaPlayerCreation form").unbind("submit").submit(function(event){
		doCreatePlayer(event, callback);
	});
	$("#diaPlayerCreation").modal("show");
};

var doCreatePlayer = function(event, callback) {
	var name;
	var surname;

	var isComputer = $("#isComputer input").is(":checked");
	if (isComputer) {
		name = "Ishur #" + $("#playerLevel").val();
		surname = $("#diaPlayerCreation .btnTarget .active").html();
	} else {
		name = $("#playerName").val();
		surname = $("#playerSurname").val();
		if (!name) {
			name = "Mr. X";
		}
	}

	// Create player
	var player;
	// Computer field
	if (isComputer) {
		player = players.getPlayerByNameSurname(name, surname);
		player.com = true;
		player.comLevel = $("#playerLevel").val();
		player.comTarget = $("#diaPlayerCreation .btnTarget .active").html();
		players.update(player);
	} else {
		player = players.getPlayerByNameSurname(name, surname);
	}
	$("#diaPlayerCreation").modal("hide");

	// Callback
	if (callback && $.isFunction(callback)) {
		callback(player);
	}

	event.preventDefault();
	return false;
};<commit_msg>Fix player selection filtering<commit_after>/*
   Copyright 2012 Igor Laborie

   Licensed under the Apache License, Version 2.0 (the "License");
   you may not use this file except in compliance with the License.
   You may obtain a copy of the License at

       http://www.apache.org/licenses/LICENSE-2.0

   Unless required by applicable law or agreed to in writing, software
   distributed under the License is distributed on an "AS IS" BASIS,
   WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
   See the License for the specific language governing permissions and
   limitations under the License.
*/
// Define some default objets
// Utilities
if (typeof String.prototype.startsWith != "function") {
	// see below for better implementation!
	String.prototype.startsWith = function (str) {
		return this.indexOf(str) === 0;
	};
}

$.postJSON = function(url, data, callback, onError) {
	var fun = doOnError;
	if (onError && $.isFunction(onError)) {
		fun = onError;
	}
    return jQuery.ajax({
        type: "POST",
        url: url,
        contentType: "application/json",
        data: JSON.stringify(data),
        dataType: "json",
        success: callback,
        timeout: 3000,
		tryCount : 0,
		retryLimit : 3,
        onError: fun
    });
};

$.deleteJSON = function(url, data, callback, onError) {
	var fun = doOnError;
	if (onError && $.isFunction(onError)) {
		fun = onError;
	}
    return jQuery.ajax({
        type: "DELETE",
        url: url,
        contentType: "application/json",
        data: JSON.stringify(data),
        dataType: "json",
        success: callback,
        timeout: 3000,
		tryCount : 0,
		retryLimit : 3,
        onError: fun
    });
};

var doOnError = function(xhr, textStatus, errorThrown) {
	var msg = "Error: " +textStatus +"\n"+errorThrown;
	console.log(msg);
	createNotice({
		kind: "error",
		message: msg
	});
};

/**
 * Create a dynamic notice
 */
var createNotice = function(notice) {
	$(".top-right").notify({
		type: notice.kind,
		message: { html: notice.message }
	}).show();
};

/**
 * Open Modal
 */
var openModalDialog = function(title, message, buttons) {
	$("#modalDialog .modal-header h3").html(title);
	$("#modalDialog .modal-body p").empty().append(message);

	var $buttonsBar = $("#modalDialog .modal-footer");
	$buttonsBar.empty();
	if (typeof buttons === "undefined") {
		$buttonsBar.append(createButton({
			text: "Close",
			"data-dismiss" : "modal"
		}));
	} else if ($.isArray(buttons)) {
		for(var i=0; i< buttons.length; i++) {
			$buttonsBar.append(createButton(buttons[i]));
		}
	} else {
		$buttonsBar.append(createButton(buttons));
	}
	$("#modalDialog").unbind("shown").on("shown",function(){
		$("#modalDialog .modal-footer button:last-child").focus();
	}).modal("show");
};

/**
 * Create a button
 */
var createButton = function(props) {
	var text  = props.text;
	var click = props.click;
	var cssClass = "btn";
	if (props["class"]) {
		cssClass += " " +  props["class"];
	}

	var attrs = {};
	for (var p in props) {
		if ((p!== "text") && (p!== "click") && (p!== "class")) {
			attrs[p] = props[p];
		}
	}

	$btn = $("<button/>", attrs).addClass(cssClass).html(text);
	if (typeof click === "function") {
		$btn.click(click);
	}

	return $btn;
};

/**
 * Create an UUID
 */
this.createUuid = function() {
    var S4 = function() {
       return (((1+Math.random())*0x10000)|0).toString(16).substring(1);
    };
    return (S4()+S4()+"-"+S4()+"-"+S4()+"-"+S4()+"-"+S4()+S4()+S4());
};

/**
 * isInteger
 */
var isInteger = function(s) {
  return ((""+s).search(/^-?[0-9]+$/) === 0);
};

var scollToBottom = function() {
	if ($(".score-left-container").is(":visible")) {
		var h = $(document).height();
		$("body").scrollTop(h);
	}
};

// TODO Board & Darts

// Player
var players = {
	db: [],
	addPlayer: function(player) {
		players.db.push({
			uuid: player.uuid,
			name: player.name,
			surname: player.surname,
			com: player.com,
			comLevel: player.comLevel,
			comTarget: player.comTarget
		});
		// Store to DB
		localStorage.setItem("players", JSON.stringify(players.db));
	},
	update: function(player) {
		var p;
		for (var i=0; i<players.db.length; i++) {
			p = players.db[i];
			if (p.uuid === player.uuid) {
				p.name = player.name;
				p.surname = player.surname;
				p.com = player.com;
				p.comLevel = player.comLevel;
				p.comTarget = player.comTarget;
			}
		}
		// Store to DB
		localStorage.setItem("players", JSON.stringify(players.db));
	},
	getPlayer: function(playerId) {
		var pId = playerId;
		if (pId.lastIndexOf("_")!=-1) {
			var idx = pId.lastIndexOf("_");
			pId = pId.substring(0,idx);
		}
		var p;
		var player;
		for (var i=0; i<players.db.length; i++) {
			p = players.db[i];
			if (p.uuid === pId) {
				player = new Player(p.name, p.surname);
				player.uuid = p.uuid;
				player.com = p.com;
				player.comLevel = p.comLevel;
				player.comTarget = p.comTarget;
				return player;
			}
		}
		player = new Player("Mr. X", null);
		this.addPlayer(player);
		return player;
	},
	getByPrefix : function(prefix) {
		var res = [];
		var player;
		var p;
		for (var i=0; i<players.db.length; i++) {
			p = players.db[i];
			if (prefix===null || prefix==="" || p.name.startsWith(prefix)) {
				player = new Player(p.name, p.surname);
				player.uuid = p.uuid;
				player.com = p.com;
				player.comLevel = p.comLevel;
				player.comTarget = p.comTarget;
				res.push(player);
			}
		}
		return res;
	},
	getPlayerByNameSurname : function(name, surname) {
		var player;
		for (var i=0; i<players.db.length; i++) {
			p = players.db[i];
			if ((p.name === name) && (p.surname===surname)) {
				player = new Player(p.name, p.surname);
				player.uuid = p.uuid;
				player.com = p.com;
				player.comLevel = p.comLevel;
				player.comTarget = p.comTarget;
				return player;
			}
		}
		player = new Player(name, surname);
		this.addPlayer(player);
		return player;
	}
};
// Load to DB
var playersDB = localStorage.getItem("players");
if (playersDB !== null) {
	players.db = JSON.parse(playersDB);
}

function Player(name, surname) {
	this.uuid = createUuid();
	this.name = name;
	this.surname = surname;

	this.com = false;
	this.comLevel = 0;
	this.comTarget = 20;

	// Name
	this.getName = function() {
		var res;
		if (this.name) {
			res = this.name;
		} else {
			res = this.id;
		}
		return res;
	};
	this.getFullName = function() {
		var res = this.getName();
		if (this.surname) {
			res +=  " «"+this.surname+"»";
		}
		return res;
	};
	this.getDisplayName = function() {
		if (this.com) {
			return ' ' +this.name+ ' '+this.comLevel+' play ' + this.comTarget;
		} else {
			return ' ' + this.getFullName();

		}
	};
}
// Dialog for player selection
var updatePlayerList = function(prefix) {
	// unselect all & clear list
	$("#diaPlayerSelect .btn-primary").attr("disabled","disabled");
	$("#diaSelectedPlayer").val("");
	$("#diaPlayerSelect .playerList").empty();

	// Fill list
	var p = players.getByPrefix(prefix);
	$.each(p, function(idx, player) {
		$("#diaPlayerSelect .playerList").append(
			$("
").append(
				$("").attr("href", "#").append(player.getDisplayName()).click(function (event) {
					if ($(this).parent().hasClass("active")) {
						$("#diaSelectedPlayer").val("");
						$("#diaPlayerSelect .btn-primary").attr("disabled","disabled");
						$("#diaPlayerSelect .playerList li").removeClass("active");
					} else {
						$("#diaSelectedPlayer").val(player.uuid);
						$("#diaPlayerSelect .btn-primary").removeAttr("disabled");
						$("#diaPlayerSelect .playerList li").removeClass("active");
						$(this).parent().addClass("active");
					}
					return true;
				})
			)
		);
	});
};
var diaSelectPlayerLoaded = false;
var selectPlayer = function(callback) {
	if (!diaSelectPlayerLoaded) {
		diaSelectPlayerLoaded = true;

		$("#diaPlayerSelect .input").keyup(function() {
			var prefix = $(this).val();
			updatePlayerList(prefix);
		});
		$("#diaPlayerSelect").on("shown", function() {
			$("#diaPlayerSelect .input").focus();
		});
	}
	updatePlayerList($("#diaPlayerSelect .input").val());

	$("#diaPlayerSelect .btn-primary").unbind("click").click(function(e) {
		var playerId = $("#diaSelectedPlayer").val();
		if (playerId!=="") {
			var player = players.getPlayer(playerId);
			$("#diaPlayerSelect").modal("hide");
			callback(player);
		}
	});
	$("#diaPlayerSelect").modal("show");
};

// Create player Dialog

$("#diaPlayerCreation").on("shown", function(event) {
	$("#playerName").focus();
});
var diaCreatePlayerLoaded = false;
var createPlayer = function(callback) {
	if (!diaCreatePlayerLoaded) {
		diaCreatePlayerLoaded = true;
		$("#isComputer").toggleButtons({
			onChange: function($el, status) {
				if (status) {
					$(".playerComputer").show();
					$(".humanPlayer").hide();
				} else {
					$(".playerComputer").hide();
					$(".humanPlayer").show();
				}
			}
		});
	}
	// initial state
	if ($("#isComputer input").is(":checked")) {
		$(".playerComputer").show();
		$(".humanPlayer").hide();
	} else {
		$(".playerComputer").hide();
		$(".humanPlayer").show();
	}

	$("#diaPlayerCreation .btn-success").unbind("click").click(function(event){
		doCreatePlayer(event, callback);
	});
	$("#diaPlayerCreation form").unbind("submit").submit(function(event){
		doCreatePlayer(event, callback);
	});
	$("#diaPlayerCreation").modal("show");
};

var doCreatePlayer = function(event, callback) {
	var name;
	var surname;

	var isComputer = $("#isComputer input").is(":checked");
	if (isComputer) {
		name = "Ishur #" + $("#playerLevel").val();
		surname = $("#diaPlayerCreation .btnTarget .active").html();
	} else {
		name = $("#playerName").val();
		surname = $("#playerSurname").val();
		if (!name) {
			name = "Mr. X";
		}
	}

	// Create player
	var player;
	// Computer field
	if (isComputer) {
		player = players.getPlayerByNameSurname(name, surname);
		player.com = true;
		player.comLevel = $("#playerLevel").val();
		player.comTarget = $("#diaPlayerCreation .btnTarget .active").html();
		players.update(player);
	} else {
		player = players.getPlayerByNameSurname(name, surname);
	}
	$("#diaPlayerCreation").modal("hide");

	// Callback
	if (callback && $.isFunction(callback)) {
		callback(player);
	}

	event.preventDefault();
	return false;
};<|endoftext|>