<commit_before>$( document ).ready(function() {

	// Search in a table and display only result who correspond to the search
  	// @author Dessauges Antoine
  	$('.search').on('input',function(e){

    	var search = $('.search').val().toLowerCase();

    	$('.searchIn tr, .searchIn .hideSearch').each( function() {

    		var teamName = $(this).find(".name").text().toLowerCase();

    		if(teamName.indexOf(search) < 0)
    			$(this).hide( "fast");
    		else
    			$(this).show( "fast");

    	});

    });

	// Init Datatable on our table -> https://datatables.net/
    // @author Dessaules Loïc
	var tableFrTranslateWithoutAllInfos = {
		"language": {
	        "decimal":        "",
		    "emptyTable":     "Aucune données disponible",
		    "info":           "_START_ à _END_ sur _TOTAL_ entrées",
		    "infoEmpty":      "0 à 0 sur 0 entrées",
		    "infoFiltered":   "(Total de _MAX_ total entrées)",
		    "infoPostFix":    "",
		    "thousands":      ",",
		    "lengthMenu":     "Voir _MENU_ entrée",
		    "loadingRecords": "Chargement...",
		    "processing":     "En traitement...",
		   	"search":         "",
		    "searchPlaceholder": "Recherche",
		    "zeroRecords":    "Aucune données trouvées",
		    "paginate": {
		        "first":      "Première",
		        "last":       "Dernière",
		        "next":       "Suivant",
		        "previous":   "Précédent"
		    }
	    },
	    "paging":   false,
        "info":     false,
        "searching":	false,
	};

	var tableFrTranslateWithoutEntries = {
		"language": {
	        "decimal":        "",
		    "emptyTable":     "Aucune données disponible",
		    "info":           "_START_ à _END_ sur _TOTAL_ entrées",
		    "infoEmpty":      "0 à 0 sur 0 entrées",
		    "infoFiltered":   "(Total de _MAX_ total entrées)",
		    "infoPostFix":    "",
		    "thousands":      ",",
		    "lengthMenu":     "Voir _MENU_ entrée",
		    "loadingRecords": "Chargement...",
		    "processing":     "En traitement...",
		    "search":         "",
		    "searchPlaceholder": "Recherche",
		    "zeroRecords":    "Aucune données trouvées",
		    "paginate": {
		        "first":      "Première",
		        "last":       "Dernière",
		        "next":       "Suivant",
		        "previous":   "Précédent"
		    }
	    },
        "bLengthChange":     false,
	};

	// Specific table without the top-left élément (nb x - y entries)
	$('#tournament-teams-table').DataTable(tableFrTranslateWithoutEntries);
	$('#teams-table').DataTable(tableFrTranslateWithoutEntries);
	$('#participants-table').DataTable(tableFrTranslateWithoutEntries);
	// All tables without all data, just the table
	$('.translate').DataTable(tableFrTranslateWithoutAllInfos);

	// datatables add a container fluid, I don't want that, so I delete the class
	$('.dataTables_wrapper').removeClass('container-fluid');

	// Redirect when click on a cell
	$('#pools-table tr td.clickable').click(function(){
		var tournament_id = $("#pools-table").data("tournament");
		var pool_id = $(this).data("id");
		window.location.href = tournament_id+"/pools/"+pool_id;
	});

	$('#teams-table tr td.clickable').click(function(){
		var team_id = $(this).data("id");
		window.location.href = "teams/"+team_id;
	});

	$('#teams-show-table tr td.clickable').click(function(){
		var participant_id = $(this).data("id");
		window.location.href = "/admin/participants/"+participant_id;
	});

	$('#participants-table tr td.clickable').click(function(){
		var participant_id = $(this).data("id");
		window.location.href = "participants/"+participant_id;
	});

	$('#participants-show-table tr td.clickable').click(function(){
		var team_id = $(this).data("id");
		window.location.href = "/admin/teams/"+team_id;
	});

	$('#tournament-teams-table tr td.clickable').click(function(){
		var team_id = $(this).data("id");
		window.location.href = "/admin/teams/"+team_id;
	});
});
<commit_msg>Fixed problem were elements on second page of tables lost the click event<commit_after>$( document ).ready(function() {

	// Search in a table and display only result who correspond to the search
  	// @author Dessauges Antoine
  	$('.search').on('input',function(e){

    	var search = $('.search').val().toLowerCase();

    	$('.searchIn tr, .searchIn .hideSearch').each( function() {

    		var teamName = $(this).find(".name").text().toLowerCase();

    		if(teamName.indexOf(search) < 0)
    			$(this).hide( "fast");
    		else
    			$(this).show( "fast");

    	});

    });

	// Init Datatable on our table -> https://datatables.net/
    // @author Dessaules Loïc
	var tableFrTranslateWithoutAllInfos = {
		"language": {
	        "decimal":        "",
		    "emptyTable":     "Aucune données disponible",
		    "info":           "_START_ à _END_ sur _TOTAL_ entrées",
		    "infoEmpty":      "0 à 0 sur 0 entrées",
		    "infoFiltered":   "(Total de _MAX_ total entrées)",
		    "infoPostFix":    "",
		    "thousands":      ",",
		    "lengthMenu":     "Voir _MENU_ entrée",
		    "loadingRecords": "Chargement...",
		    "processing":     "En traitement...",
		   	"search":         "",
		    "searchPlaceholder": "Recherche",
		    "zeroRecords":    "Aucune données trouvées",
		    "paginate": {
		        "first":      "Première",
		        "last":       "Dernière",
		        "next":       "Suivant",
		        "previous":   "Précédent"
		    }
	    },
	    "paging":   false,
        "info":     false,
        "searching":	false,
	};

	var tableFrTranslateWithoutEntries = {
		"language": {
	        "decimal":        "",
		    "emptyTable":     "Aucune données disponible",
		    "info":           "_START_ à _END_ sur _TOTAL_ entrées",
		    "infoEmpty":      "0 à 0 sur 0 entrées",
		    "infoFiltered":   "(Total de _MAX_ total entrées)",
		    "infoPostFix":    "",
		    "thousands":      ",",
		    "lengthMenu":     "Voir _MENU_ entrée",
		    "loadingRecords": "Chargement...",
		    "processing":     "En traitement...",
		    "search":         "",
		    "searchPlaceholder": "Recherche",
		    "zeroRecords":    "Aucune données trouvées",
		    "paginate": {
		        "first":      "Première",
		        "last":       "Dernière",
		        "next":       "Suivant",
		        "previous":   "Précédent"
		    }
	    },
        "bLengthChange":     false,
	};

	// Specific table without the top-left élément (nb x - y entries)
	$('#tournament-teams-table').DataTable(tableFrTranslateWithoutEntries);
	$('#teams-table').DataTable(tableFrTranslateWithoutEntries);
	$('#participants-table').DataTable(tableFrTranslateWithoutEntries);
	// All tables without all data, just the table
	$('.translate').DataTable(tableFrTranslateWithoutAllInfos);

	// datatables add a container fluid, I don't want that, so I delete the class
	$('.dataTables_wrapper').removeClass('container-fluid');

	// Redirect when click on a cell
	$('#pools-table').on('click', 'td.clickable', function(){
		var tournament_id = $("#pools-table").data("tournament");
		var pool_id = $(this).data("id");
		window.location.href = tournament_id+"/pools/"+pool_id;
	});

	$('#teams-table').on('click', 'td.clickable', function(){
		var team_id = $(this).data("id");
		window.location.href = "teams/"+team_id;
	});

	$('#teams-show-table').on('click', 'td.clickable', function(){
		var participant_id = $(this).data("id");
		window.location.href = "/admin/participants/"+participant_id;
	});

	$('#participants-table').on('click', 'td.clickable', function(){
		var participant_id = $(this).data("id");
		window.location.href = "participants/"+participant_id;
	});

	$('#participants-show-table').on('click', 'td.clickable', function(){
		var team_id = $(this).data("id");
		window.location.href = "/admin/teams/"+team_id;
	});

	$('#tournament-teams-table').on('click', 'td.clickable', function(){
		var team_id = $(this).data("id");
		window.location.href = "/admin/teams/"+team_id;
	});
});
<|endoftext|>


<commit_before>// Copyright 2017-2018, University of Colorado Boulder

/**
 * Base type for instrumented PhET-iO instances, provides support for PhET-iO features when running with PhET-iO enabled.
 *
 * @author Sam Reid (PhET Interactive Simulations)
 */
define( function( require ) {
  'use strict';

  // modules
  var inherit = require( 'PHET_CORE/inherit' );
  var tandemNamespace = require( 'TANDEM/tandemNamespace' );
  var Tandem = require( 'TANDEM/Tandem' );

  // ifphetio
  var ObjectIO = require( 'ifphetio!PHET_IO/types/ObjectIO' );
  var phetioEvents = require( 'ifphetio!PHET_IO/phetioEvents' );

  // constants
  var PHET_IO_ENABLED = !!( window.phet && window.phet.phetio );

  // Flag that indicates a high frequency message was skipped.
  var SKIPPING_HIGH_FREQUENCY_MESSAGE = -1;

  var DEFAULTS = {
    tandem: Tandem.optional,     // By default tandems are optional, but subtypes can specify this as
                                 // `Tandem.tandemRequired` to enforce its presence
    phetioType: ObjectIO,        // Supply the appropriate IO type
    phetioDocumentation: null,   // Useful notes about an instrumented instance, shown in the PhET-iO Studio Wrapper

    phetioState: true,           // When true, includes the instance in the PhET-iO state
    phetioReadOnly: false,       // When true, you can only get values from the instance; no setting allowed.
    phetioEventType: 'model',    // Default event type for this instance, can be overriden in phetioStartEvent options
    phetioHighFrequency: false,   // High frequency events such as mouse moves or stepSimulation can be omitted from data stream
    phetioInputEvent: false
  };

  var OPTIONS_KEYS = _.keys( DEFAULTS );

  /**
   * @param {Object} [options]
   * @constructor
   */
  function PhetioObject( options ) {

    // @public (read-only) {Tandem} - assigned in initializePhetioObject - the unique tandem for this instance
    this.tandem = null;

    // @public (read-only) {IOType} - assigned in initializePhetioObject - the IO type associated with this instance
    this.phetioType = null;

    // @public (read-only) {boolean} - assigned in initializePhetioObject - When true, included in the PhET-iO state
    this.phetioState = null;

    // @public (read-only) {boolean} - assigned in initializePhetioObject - When true, values can be get but not set
    this.phetioReadOnly = null;

    // @public (read-only) {string} - assigned in initializePhetioObject - Notes about an instance, shown in the PhET-iO Studio Wrapper
    this.phetioDocumentation = null;

    // @public (read-only) {Object} - assigned in initializePhetioObject - The wrapper instance for PhET-iO interoperation
    this.phetioWrapper = null;

    // @private {boolean} - track whether the object has been initialized.  This is necessary because initialization
    // can happen in the constructor or in a subsequent call to initializePhetioObject (to support scenery Node)
    this.phetioObjectInitialized = false;

    // @private {number|null} - tracks the indices of started messages so that phetioEvents can check that ends match starts
    this.phetioMessageStack = [];

    // @private {boolean} - has the instance been disposed?
    this.phetioObjectDisposed = false;

    // @private {string} - 'model' | 'user'
    this.phetioEventType = null;

    // @private {boolean} - If marked as phetioHighFrequency: true, the event will be omitted when the query parameter phetioEmitHighFrequencyEvents=false
    this.phetioHighFrequency = null;

    // @private {boolean} - TODO: rename to phetioPlaybackEvent.  This indicates a (usually high-frequency) event that is required for
    // visual playbacks, but can be otherwise overwhelming.  For instance, frameEndedEmitter emits dt's that are critical to playbacks
    // but not helpful when reading console: colorized.
    this.phetioInputEvent = null;

    if ( options ) {
      this.initializePhetioObject( {}, options );
    }
  }

  tandemNamespace.register( 'PhetioObject', PhetioObject );

  return inherit( Object, PhetioObject, {

    /**
     * @param {Object} baseOptions - only applied if options keys intersect OPTIONS_KEYS
     * @param {Object} options
     * @protected
     */
    initializePhetioObject: function( baseOptions, options ) {
      assert && assert( options, 'initializePhetioObject must be called with options' );

      // TODO: garbage-free implementation
      var intersection = _.intersection( _.keys( options ), OPTIONS_KEYS );
      if ( intersection.length === 0 ) {
        return; // no PhetioObject keys provided, perhaps they will be provided in a subsequent mutate call.
      }
      assert && assert( !this.phetioObjectInitialized, 'cannot initialize twice' );

      assert && assert( options.tandem, 'Component was missing its tandem' );
      assert && assert( options.tandem.phetioID, 'Component was missing its phetioID' );

      if ( assert && options.phetioType && PHET_IO_ENABLED ) {
        assert && assert( options.phetioType.documentation, 'There must be a documentation string for each IO Type.' );

        for ( var methodName in options.phetioType.methods ) {
          var method = options.phetioType.methods[ methodName ];

          if ( typeof method === 'function' ) {

            // This is a private function for internal phet-io mechanics, not for exporting over the API, so it doesn't
            // need to be checked.
          }
          else {
            var IOType = options.phetioType;

            // If you get one of these assertion errors, go to the IOType definition file and check its methods
            assert && assert( !!method.returnType, IOType.typeName + '.' + methodName + ' needs a returnType' );
            assert && assert( !!method.implementation, IOType.typeName + '.' + methodName + ' needs an implementation function' );
            assert && assert( !!method.parameterTypes, IOType.typeName + '.' + methodName + ' needs a parameterTypes array' );
            assert && assert( !!method.documentation, IOType.typeName + '.' + methodName + ' needs a documentation string' );
          }
        }

        assert && assert( options.phetioType !== undefined, options.tandem.phetioID + ' missing type from phetio.api' );
        assert && assert( options.phetioType.typeName, 'no type name for ' + options.tandem.phetioID + '(may be missing type parameter)' );
        assert && assert( options.phetioType.typeName, 'type must be specified and have a typeName for ' + options.tandem.phetioID );
      }

      options = _.extend( {}, DEFAULTS, baseOptions, options );

      // Unpack options to instance properties
      this.tandem = options.tandem;
      this.phetioType = options.phetioType;
      this.phetioState = options.phetioState;
      this.phetioReadOnly = options.phetioReadOnly;
      this.phetioEventType = options.phetioEventType;
      this.phetioDocumentation = options.phetioDocumentation;
      this.phetioHighFrequency = options.phetioHighFrequency;
      this.phetioInputEvent = options.phetioInputEvent;

      // Instantiate the wrapper instance which is used for PhET-iO communication
      if ( PHET_IO_ENABLED && this.tandem.supplied ) {
        // this assertion should be enabled for new phet-io sim publications
        // assert && assert( this.phetioDocumentation, 'Instance documentation is required for: ' + this.tandem.phetioID );
        this.phetioWrapper = new this.phetioType( this, this.tandem.phetioID );
      }

      // Register with the tandem registry
      this.tandem.addInstance( this );

      this.phetioObjectInitialized = true;
    },

    /**
     * Start an event for the nested PhET-iO data stream.
     *
     * @param {string} event - the name of the event
     * @param {Object|function} [args] - arguments for the event, either an object, or a function that returns an object
     * @public
     */
    phetioStartEvent: function( event, args ) {
      assert && assert( this.phetioObjectInitialized, 'phetioObject should be initialized' );
      assert && assert( typeof event === 'string' );
      assert && args && assert( typeof args === 'object' || typeof args === 'function' );
      assert && assert( arguments.length !== 3, 'Prevent usage of incorrect signature' );

      // Opt out of high-frequency events
      if ( window.phet && window.phet.phetio ) {
        var omit = !window.phet.phetio.queryParameters.phetioEmitHighFrequencyEvents && this.phetioHighFrequency;
        var omit2 = !window.phet.phetio.queryParameters.phetioEmitInputEvents && this.phetioInputEvent;
        if ( omit || omit2 ) {
          this.phetioMessageStack.push( SKIPPING_HIGH_FREQUENCY_MESSAGE );
          return;
        }
      }

      if ( this.isPhetioInstrumented() ) {

        // Only get the args if we are actually going to send the event.
        if ( typeof args === 'function' ) {
          args = args();
        }
        this.phetioMessageStack.push( phetioEvents.start( this.phetioEventType, this, event, args ) );
      }
    },

    /**
     * End an event on the nested PhET-iO data stream.
     * It this object was disposed or phetioEvents.start was not called, this is a no-op.
     * @public
     */
    phetioEndEvent: function() {

      var topMessageIndex = this.phetioMessageStack.pop();

      // The message was started as a high frequency event to be skipped, so the end is a no-op
      if ( topMessageIndex === SKIPPING_HIGH_FREQUENCY_MESSAGE ) {
        return;
      }

      if ( this.isPhetioInstrumented() ) {
        phetioEvents.end( topMessageIndex );
      }
    },

    /**
     * Just because a tandem is passed to an instance doesn't mean that it is instrumented. An instance will only be
     * instrumented if:
     * (1) Running in PhET-iO mode
     * (2) The tandem that was passed in was "supplied". See Tandem.supplied for more info
     * @returns {boolean}
     * @public
     */
    isPhetioInstrumented: function() {
      return this.tandem && this.tandem.supplied && PHET_IO_ENABLED;
    },

    /**
     * JSONifiable metadata that describes the nature of the PhetioObject.
     * @returns {Object}
     * @public
     */
    getMetadata: function() {
      return {
        phetioTypeName: this.phetioType.typeName,
        phetioState: this.phetioState,
        phetioReadOnly: this.phetioReadOnly,
        phetioDocumentation: this.phetioDocumentation,
        phetioEventType: this.phetioEventType,
        phetioHighFrequency: this.phetioHighFrequency,
        phetioInputEvent: this.phetioInputEvent
      };
    },

    /**
     * Unregisters from tandem when longer used.
     * @public
     */
    dispose: function() {
      var self = this;
      assert && assert( !this.phetioObjectDisposed, 'PhetioObject can only be disposed once' );

      // In order to support the structured data stream, PhetioObjects must end the messages in the correct
      // sequence, without being interrupted by dispose() calls.  Therefore, we do not clear out any of the state
      // related to the endEvent.  Note this means it is acceptable (and expected) for endEvent() to be called on disposed PhetioObjects.
      //
      // The phetioEvent stack should resolve by the next clock tick, so that's when we check it.
      assert && setTimeout( function() {
        assert && assert( self.phetioMessageStack.length === 0, 'phetioMessageStack should be clear' );
      }, 0 );

      // OK to dispose something that was never phetioObjectInitialized, this means it was an uninstrumented instance
      if ( this.phetioObjectInitialized ) {

        // Tandem de-registration
        this.tandem.removeInstance( this );
        this.phetioWrapper && this.phetioWrapper.dispose && this.phetioWrapper.dispose();
      }

      this.phetioObjectDisposed = true;
    }
  }, {
    DEFAULT_OPTIONS: DEFAULTS // the default options for the phet-io object
  } );
} );<commit_msg>rename phet-io input events to playback events, https://github.com/phetsims/phet-io/issues/1388<commit_after>// Copyright 2017-2018, University of Colorado Boulder

/**
 * Base type for instrumented PhET-iO instances, provides support for PhET-iO features when running with PhET-iO enabled.
 *
 * @author Sam Reid (PhET Interactive Simulations)
 */
define( function( require ) {
  'use strict';

  // modules
  var inherit = require( 'PHET_CORE/inherit' );
  var tandemNamespace = require( 'TANDEM/tandemNamespace' );
  var Tandem = require( 'TANDEM/Tandem' );

  // ifphetio
  var ObjectIO = require( 'ifphetio!PHET_IO/types/ObjectIO' );
  var phetioEvents = require( 'ifphetio!PHET_IO/phetioEvents' );

  // constants
  var PHET_IO_ENABLED = !!( window.phet && window.phet.phetio );

  // Flag that indicates a high frequency message was skipped.
  var SKIPPING_HIGH_FREQUENCY_MESSAGE = -1;

  var DEFAULTS = {
    tandem: Tandem.optional,     // By default tandems are optional, but subtypes can specify this as
                                 // `Tandem.tandemRequired` to enforce its presence
    phetioType: ObjectIO,        // Supply the appropriate IO type
    phetioDocumentation: null,   // Useful notes about an instrumented instance, shown in the PhET-iO Studio Wrapper

    phetioState: true,           // When true, includes the instance in the PhET-iO state
    phetioReadOnly: false,       // When true, you can only get values from the instance; no setting allowed.
    phetioEventType: 'model',    // Default event type for this instance, can be overriden in phetioStartEvent options
    phetioHighFrequency: false,   // High frequency events such as mouse moves or stepSimulation can be omitted from data stream
    phetioInputEvent: false
  };

  var OPTIONS_KEYS = _.keys( DEFAULTS );

  /**
   * @param {Object} [options]
   * @constructor
   */
  function PhetioObject( options ) {

    // @public (read-only) {Tandem} - assigned in initializePhetioObject - the unique tandem for this instance
    this.tandem = null;

    // @public (read-only) {IOType} - assigned in initializePhetioObject - the IO type associated with this instance
    this.phetioType = null;

    // @public (read-only) {boolean} - assigned in initializePhetioObject - When true, included in the PhET-iO state
    this.phetioState = null;

    // @public (read-only) {boolean} - assigned in initializePhetioObject - When true, values can be get but not set
    this.phetioReadOnly = null;

    // @public (read-only) {string} - assigned in initializePhetioObject - Notes about an instance, shown in the PhET-iO Studio Wrapper
    this.phetioDocumentation = null;

    // @public (read-only) {Object} - assigned in initializePhetioObject - The wrapper instance for PhET-iO interoperation
    this.phetioWrapper = null;

    // @private {boolean} - track whether the object has been initialized.  This is necessary because initialization
    // can happen in the constructor or in a subsequent call to initializePhetioObject (to support scenery Node)
    this.phetioObjectInitialized = false;

    // @private {number|null} - tracks the indices of started messages so that phetioEvents can check that ends match starts
    this.phetioMessageStack = [];

    // @private {boolean} - has the instance been disposed?
    this.phetioObjectDisposed = false;

    // @private {string} - 'model' | 'user'
    this.phetioEventType = null;

    // @private {boolean} - If marked as phetioHighFrequency: true, the event will be omitted when the query parameter phetioEmitHighFrequencyEvents=false
    this.phetioHighFrequency = null;

    // @private {boolean} - TODO: rename to phetioPlaybackEvent.  This indicates a (usually high-frequency) event that is required for
    // visual playbacks, but can be otherwise overwhelming.  For instance, frameEndedEmitter emits dt's that are critical to playbacks
    // but not helpful when reading console: colorized.
    this.phetioInputEvent = null;

    if ( options ) {
      this.initializePhetioObject( {}, options );
    }
  }

  tandemNamespace.register( 'PhetioObject', PhetioObject );

  return inherit( Object, PhetioObject, {

    /**
     * @param {Object} baseOptions - only applied if options keys intersect OPTIONS_KEYS
     * @param {Object} options
     * @protected
     */
    initializePhetioObject: function( baseOptions, options ) {
      assert && assert( options, 'initializePhetioObject must be called with options' );

      // TODO: garbage-free implementation
      var intersection = _.intersection( _.keys( options ), OPTIONS_KEYS );
      if ( intersection.length === 0 ) {
        return; // no PhetioObject keys provided, perhaps they will be provided in a subsequent mutate call.
      }
      assert && assert( !this.phetioObjectInitialized, 'cannot initialize twice' );

      assert && assert( options.tandem, 'Component was missing its tandem' );
      assert && assert( options.tandem.phetioID, 'Component was missing its phetioID' );

      if ( assert && options.phetioType && PHET_IO_ENABLED ) {
        assert && assert( options.phetioType.documentation, 'There must be a documentation string for each IO Type.' );

        for ( var methodName in options.phetioType.methods ) {
          var method = options.phetioType.methods[ methodName ];

          if ( typeof method === 'function' ) {

            // This is a private function for internal phet-io mechanics, not for exporting over the API, so it doesn't
            // need to be checked.
          }
          else {
            var IOType = options.phetioType;

            // If you get one of these assertion errors, go to the IOType definition file and check its methods
            assert && assert( !!method.returnType, IOType.typeName + '.' + methodName + ' needs a returnType' );
            assert && assert( !!method.implementation, IOType.typeName + '.' + methodName + ' needs an implementation function' );
            assert && assert( !!method.parameterTypes, IOType.typeName + '.' + methodName + ' needs a parameterTypes array' );
            assert && assert( !!method.documentation, IOType.typeName + '.' + methodName + ' needs a documentation string' );
          }
        }

        assert && assert( options.phetioType !== undefined, options.tandem.phetioID + ' missing type from phetio.api' );
        assert && assert( options.phetioType.typeName, 'no type name for ' + options.tandem.phetioID + '(may be missing type parameter)' );
        assert && assert( options.phetioType.typeName, 'type must be specified and have a typeName for ' + options.tandem.phetioID );
      }

      options = _.extend( {}, DEFAULTS, baseOptions, options );

      // Unpack options to instance properties
      this.tandem = options.tandem;
      this.phetioType = options.phetioType;
      this.phetioState = options.phetioState;
      this.phetioReadOnly = options.phetioReadOnly;
      this.phetioEventType = options.phetioEventType;
      this.phetioDocumentation = options.phetioDocumentation;
      this.phetioHighFrequency = options.phetioHighFrequency;
      this.phetioInputEvent = options.phetioInputEvent;

      // Instantiate the wrapper instance which is used for PhET-iO communication
      if ( PHET_IO_ENABLED && this.tandem.supplied ) {
        // this assertion should be enabled for new phet-io sim publications
        // assert && assert( this.phetioDocumentation, 'Instance documentation is required for: ' + this.tandem.phetioID );
        this.phetioWrapper = new this.phetioType( this, this.tandem.phetioID );
      }

      // Register with the tandem registry
      this.tandem.addInstance( this );

      this.phetioObjectInitialized = true;
    },

    /**
     * Start an event for the nested PhET-iO data stream.
     *
     * @param {string} event - the name of the event
     * @param {Object|function} [args] - arguments for the event, either an object, or a function that returns an object
     * @public
     */
    phetioStartEvent: function( event, args ) {
      assert && assert( this.phetioObjectInitialized, 'phetioObject should be initialized' );
      assert && assert( typeof event === 'string' );
      assert && args && assert( typeof args === 'object' || typeof args === 'function' );
      assert && assert( arguments.length !== 3, 'Prevent usage of incorrect signature' );

      // Opt out of certain events if queryParameter override is provided
      if ( window.phet && window.phet.phetio ) {
        var omit = !window.phet.phetio.queryParameters.phetioEmitHighFrequencyEvents && this.phetioHighFrequency;
        var omit2 = !window.phet.phetio.queryParameters.phetioEmitPlaybackEvents && this.phetioInputEvent;
        if ( omit || omit2 ) {
          this.phetioMessageStack.push( SKIPPING_HIGH_FREQUENCY_MESSAGE );
          return;
        }
      }

      if ( this.isPhetioInstrumented() ) {

        // Only get the args if we are actually going to send the event.
        if ( typeof args === 'function' ) {
          args = args();
        }
        this.phetioMessageStack.push( phetioEvents.start( this.phetioEventType, this, event, args ) );
      }
    },

    /**
     * End an event on the nested PhET-iO data stream.
     * It this object was disposed or phetioEvents.start was not called, this is a no-op.
     * @public
     */
    phetioEndEvent: function() {

      var topMessageIndex = this.phetioMessageStack.pop();

      // The message was started as a high frequency event to be skipped, so the end is a no-op
      if ( topMessageIndex === SKIPPING_HIGH_FREQUENCY_MESSAGE ) {
        return;
      }

      if ( this.isPhetioInstrumented() ) {
        phetioEvents.end( topMessageIndex );
      }
    },

    /**
     * Just because a tandem is passed to an instance doesn't mean that it is instrumented. An instance will only be
     * instrumented if:
     * (1) Running in PhET-iO mode
     * (2) The tandem that was passed in was "supplied". See Tandem.supplied for more info
     * @returns {boolean}
     * @public
     */
    isPhetioInstrumented: function() {
      return this.tandem && this.tandem.supplied && PHET_IO_ENABLED;
    },

    /**
     * JSONifiable metadata that describes the nature of the PhetioObject.
     * @returns {Object}
     * @public
     */
    getMetadata: function() {
      return {
        phetioTypeName: this.phetioType.typeName,
        phetioState: this.phetioState,
        phetioReadOnly: this.phetioReadOnly,
        phetioDocumentation: this.phetioDocumentation,
        phetioEventType: this.phetioEventType,
        phetioHighFrequency: this.phetioHighFrequency,
        phetioInputEvent: this.phetioInputEvent
      };
    },

    /**
     * Unregisters from tandem when longer used.
     * @public
     */
    dispose: function() {
      var self = this;
      assert && assert( !this.phetioObjectDisposed, 'PhetioObject can only be disposed once' );

      // In order to support the structured data stream, PhetioObjects must end the messages in the correct
      // sequence, without being interrupted by dispose() calls.  Therefore, we do not clear out any of the state
      // related to the endEvent.  Note this means it is acceptable (and expected) for endEvent() to be called on disposed PhetioObjects.
      //
      // The phetioEvent stack should resolve by the next clock tick, so that's when we check it.
      assert && setTimeout( function() {
        assert && assert( self.phetioMessageStack.length === 0, 'phetioMessageStack should be clear' );
      }, 0 );

      // OK to dispose something that was never phetioObjectInitialized, this means it was an uninstrumented instance
      if ( this.phetioObjectInitialized ) {

        // Tandem de-registration
        this.tandem.removeInstance( this );
        this.phetioWrapper && this.phetioWrapper.dispose && this.phetioWrapper.dispose();
      }

      this.phetioObjectDisposed = true;
    }
  }, {
    DEFAULT_OPTIONS: DEFAULTS // the default options for the phet-io object
  } );
} );<|endoftext|>


<commit_before>

var FormHelper = {
    messageAnimDurationMs: 200
};

FormHelper.initForm = function (form, container, onSubmitSuccess, options) {
    form = $(form);
    container = $(container);
    if (!options) {
        options = {}
    }
    options = $.extend({}, {
        isJson: true,
        clearForm: true
    }, options);
    var customInitiator = form.attr('data-initiator');
    if (customInitiator) {
        var ret = eval(customInitiator + '(form, container, onSubmitSuccess);');
        if (ret === false) {
            return;
        }
    }
    form.find('.selectpicker').selectpicker();
    form.find('input.switch[type="checkbox"]').bootstrapSwitch();

    form.ajaxForm({
        clearForm: !!options.clearForm,
        dataType: !options.isJson ? 'html' : 'json',
        beforeSubmit: function () {
            FormHelper.removeAllFormMessagesAndErrors(form);
            Utils.showPreloader(container);
        },
        error: function (xhr) {
            Utils.hidePreloader(container);
            FormHelper.handleAjaxErrors(form, xhr);
        },
        success: function (data) {
            if ($.isFunction(onSubmitSuccess)) {
                onSubmitSuccess(data, form, container);
            } else {
                Utils.hidePreloader(container);
                if (!isHtml) {
                    Utils.handleAjaxSuccess(data);
                }
            }
        }
    });
};

FormHelper.removeAllFormMessagesAndErrors = function (form) {
    return $.when(FormHelper.removeFormMessage(form), FormHelper.removeFormValidationMessages(form));
};

FormHelper.setFormMessage = function (form, message, type) {
    if (!type) {
        type = 'error';
    }
    toastr[type](message);
    /*
    var errorDiv = form.find('.form-error');
    if (!errorDiv.length) {
        errorDiv = $('

').hide();
        form.prepend(errorDiv);
    }
    return errorDiv.slideUp(100, function () {
        errorDiv.html('
' + message + '
').slideDown(100);
    });*/
};

FormHelper.removeFormMessage = function (form) {
    /*var errorDiv = form.find('.form-error');
    return errorDiv.slideUp(100, function () {
        errorDiv.html('');
    })*/
};

FormHelper.removeFormValidationMessages = function (form) {
    form.find('.has-error').removeClass('has-error');
    return form.find('.error-text').slideUp(FormHelper.messageAnimDurationMs, function () {
        $(this).html('');
    });
};

FormHelper.handleAjaxErrors = function (form, xhr) {
    FormHelper.removeAllFormMessagesAndErrors(form).done(function () {
        if (xhr.status === 400) {
            var response = Utils.convertXhrResponseToJsonIfPossible(xhr);
            if (!response) {
                Utils.handleAjaxError(xhr);
                return;
            }
            if (response._message) {
                FormHelper.setFormMessage(form, response._message);
            }
            if (response.errors && $.isPlainObject(response.errors)) {
                for (var inputName in response.errors) {
                    if (form[0][inputName]) {
                        var container = $(form[0][inputName]).closest('.form-group, .checkbox').addClass('has-error');
                        var errorEl = container.find('.error-text');
                        if (errorEl.length == 0) {
                            errorEl = $('

').hide();
                            container.append(errorEl);
                        }
                        errorEl.html(response.errors[inputName]).slideDown(FormHelper.messageAnimDurationMs);
                    }
                }
            }
            return;
        }
        Utils.handleAjaxError(xhr);
    });
};

var AdminUI = {
    $el: null,
    visible: false,
    userInfoTplSelector: '#user-panel-tpl',
    userInfoTpl: null,
    userInfoContainer: '#user-panel .info'
};

AdminUI.destroyUI = function () {
    var deferred = $.Deferred();
    var wrapper = Utils.getPageWrapper();
    wrapper.fadeOut(GlobalVars.contentChangeAnimationDurationMs, function () {
        Utils.showPreloader(wrapper);
        if (AdminUI.$el) {
            AdminUI.$el.detach();
        }
        wrapper.removeClass('with-ui').empty();
        wrapper.show();
        AdminUI.visible = false;
        deferred.resolve();
        $(document).trigger('appui:hidden');
    });
    return deferred;
};

AdminUI.showUI = function () {
    var deferred = $.Deferred();
    var wrapper = Utils.getPageWrapper();
    if (AdminUI.visible) {
        deferred.resolve();
    } else {
        Utils.showPreloader(wrapper);
        $.when(
            AdminUI.loadUI(),
            wrapper.fadeOut(GlobalVars.contentChangeAnimationDurationMs)
        ).done(function (uiEl) {
            wrapper.addClass('with-ui').empty().append(uiEl[0]);
            AdminUI.visible = true;
            AdminUI.updateUserInfo();
            wrapper.fadeIn(GlobalVars.contentChangeAnimationDurationMs);
            Utils.hidePreloader(wrapper);
            Utils.highlightLinks(window.adminApp.request.path);
            deferred.resolve();
            $(document).trigger('appui:shown');
        });
    }
    return deferred;
};

AdminUI.loadUI = function () {
    var deferred = $.Deferred();
    if (!AdminUI.$el) {
        Utils.downloadHtml(GlobalVars.uiUrl, true, false)
            .done(function (html) {
                AdminUI.$el = $('
' + html + '
');
                deferred.resolve(AdminUI.$el);
                $(document).trigger('appui:loaded');
            });
    } else {
        deferred.resolve(AdminUI.$el);
    }
    return deferred;
};

AdminUI.updateUserInfo = function (userInfo) {
    if (!AdminUI.visible) {
        return;
    }
    if (!userInfo) {
        Utils.getUser().done(function (userInfo) {
            AdminUI.updateUserInfo(userInfo);
        });
        return;
    }
    var container = $(AdminUI.userInfoContainer);
    if (!AdminUI.userInfoTpl) {
        AdminUI.userInfoTpl = html = Utils.makeTemplateFromText($(AdminUI.userInfoTplSelector).html(), 'User Info block template');
        container.addClass('fading fade-out').width();
        $(document).on('change:user', function (event, userInfo) {
            AdminUI.updateUserInfo(userInfo);
        });
    }
    container.html(AdminUI.userInfoTpl(userInfo)).removeClass('fade-out');
};<commit_msg>cmf.helpers.js - improved initForm (added 2 options)<commit_after>
var FormHelper = {
    messageAnimDurationMs: 200
};

FormHelper.initForm = function (form, container, onSubmitSuccess, options) {
    var $form = $(form);
    var $container = $(container);
    if (!options) {
        options = {}
    }
    options = $.extend({}, {
        isJson: true,
        clearForm: true,
        onValidationErrors: null,
        beforeSubmit: null
    }, options);
    var customInitiator = $form.attr('data-initiator');
    if (customInitiator) {
        var ret = eval(customInitiator + '(form, container, onSubmitSuccess);');
        if (ret === false) {
            return;
        }
    }
    $form.find('.selectpicker').selectpicker();
    $form.find('input.switch[type="checkbox"]').bootstrapSwitch();

    $form.ajaxForm({
        clearForm: !!options.clearForm,
        dataType: !options.isJson ? 'html' : 'json',
        beforeSubmit: function () {
            var defaultBeforeSubmit = function () {
                FormHelper.removeAllFormMessagesAndErrors($form);
                Utils.showPreloader($container);
            };
            if (typeof options.beforeSubmit === 'function') {
                options.beforeSubmit($form, $container, defaultBeforeSubmit);
            } else {
                defaultBeforeSubmit();
            }
        },
        error: function (xhr) {
            Utils.hidePreloader($container);
            if (xhr.status === 400 && typeof options.onValidationErrors === 'function') {
                options.onValidationErrors(xhr, $form, $container);
            } else {
                FormHelper.handleAjaxErrors($form, xhr);
            }
        },
        success: function (data) {
            if ($.isFunction(onSubmitSuccess)) {
                onSubmitSuccess(data, $form, $container);
            } else {
                Utils.hidePreloader($container);
                if (options.isJson) {
                    Utils.handleAjaxSuccess(data);
                }
            }
        }
    });
};

FormHelper.removeAllFormMessagesAndErrors = function ($form) {
    return $.when(FormHelper.removeFormMessage($form), FormHelper.removeFormValidationMessages($form));
};

FormHelper.setFormMessage = function ($form, message, type) {
    if (!type) {
        type = 'error';
    }
    toastr[type](message);
    /*
    var errorDiv = $form.find('.form-error');
    if (!errorDiv.length) {
        errorDiv = $('

').hide();
        $form.prepend(errorDiv);
    }
    return errorDiv.slideUp(100, function () {
        errorDiv.html('
' + message + '
').slideDown(100);
    });*/
};

FormHelper.removeFormMessage = function ($form) {
    /*var errorDiv = $form.find('.form-error');
    return errorDiv.slideUp(100, function () {
        errorDiv.html('');
    })*/
};

FormHelper.removeFormValidationMessages = function ($form) {
    $form.find('.has-error').removeClass('has-error');
    return $form.find('.error-text').slideUp(FormHelper.messageAnimDurationMs, function () {
        $(this).html('');
    });
};

FormHelper.handleAjaxErrors = function ($form, xhr) {
    FormHelper.removeAllFormMessagesAndErrors($form)
        .done(function () {
            if (xhr.status === 400) {
                var response = Utils.convertXhrResponseToJsonIfPossible(xhr);
                if (!response) {
                    Utils.handleAjaxError(xhr);
                    return;
                }
                if (response._message) {
                    FormHelper.setFormMessage($form, response._message);
                }
                if (response.errors && $.isPlainObject(response.errors)) {
                    for (var inputName in response.errors) {
                        FormHelper.showErrorForInput($form, inputName, response.errors[inputName]);
                    }
                }
                return;
            }
            Utils.handleAjaxError(xhr);
        });
};

FormHelper.showErrorForInput = function ($form, inputName, message) {
    if ($form[0][inputName]) {
        var container = $($form[0][inputName]).closest('.form-group, .checkbox').addClass('has-error');
        var errorEl = container.find('.error-text');
        if (errorEl.length == 0) {
            errorEl = $('

').hide();
            container.append(errorEl);
        }
        errorEl.html(message).slideDown(FormHelper.messageAnimDurationMs);
    }
};

var AdminUI = {
    $el: null,
    visible: false,
    userInfoTplSelector: '#user-panel-tpl',
    userInfoTpl: null,
    userInfoContainer: '#user-panel .info'
};

AdminUI.destroyUI = function () {
    var deferred = $.Deferred();
    var wrapper = Utils.getPageWrapper();
    wrapper.fadeOut(GlobalVars.contentChangeAnimationDurationMs, function () {
        Utils.showPreloader(wrapper);
        if (AdminUI.$el) {
            AdminUI.$el.detach();
        }
        wrapper.removeClass('with-ui').empty();
        wrapper.show();
        AdminUI.visible = false;
        deferred.resolve();
        $(document).trigger('appui:hidden');
    });
    return deferred;
};

AdminUI.showUI = function () {
    var deferred = $.Deferred();
    var wrapper = Utils.getPageWrapper();
    if (AdminUI.visible) {
        deferred.resolve();
    } else {
        Utils.showPreloader(wrapper);
        $.when(
            AdminUI.loadUI(),
            wrapper.fadeOut(GlobalVars.contentChangeAnimationDurationMs)
        ).done(function (uiEl) {
            wrapper.addClass('with-ui').empty().append(uiEl[0]);
            AdminUI.visible = true;
            AdminUI.updateUserInfo();
            wrapper.fadeIn(GlobalVars.contentChangeAnimationDurationMs);
            Utils.hidePreloader(wrapper);
            Utils.highlightLinks(window.adminApp.request.path);
            deferred.resolve();
            $(document).trigger('appui:shown');
        });
    }
    return deferred;
};

AdminUI.loadUI = function () {
    var deferred = $.Deferred();
    if (!AdminUI.$el) {
        Utils.downloadHtml(GlobalVars.uiUrl, true, false)
            .done(function (html) {
                AdminUI.$el = $('
' + html + '
');
                deferred.resolve(AdminUI.$el);
                $(document).trigger('appui:loaded');
            });
    } else {
        deferred.resolve(AdminUI.$el);
    }
    return deferred;
};

AdminUI.updateUserInfo = function (userInfo) {
    if (!AdminUI.visible) {
        return;
    }
    if (!userInfo) {
        Utils.getUser().done(function (userInfo) {
            AdminUI.updateUserInfo(userInfo);
        });
        return;
    }
    var container = $(AdminUI.userInfoContainer);
    if (!AdminUI.userInfoTpl) {
        AdminUI.userInfoTpl = html = Utils.makeTemplateFromText($(AdminUI.userInfoTplSelector).html(), 'User Info block template');
        container.addClass('fading fade-out').width();
        $(document).on('change:user', function (event, userInfo) {
            AdminUI.updateUserInfo(userInfo);
        });
    }
    container.html(AdminUI.userInfoTpl(userInfo)).removeClass('fade-out');
};<|endoftext|>


<commit_before>// @flow
import React from 'react'
import { StyleSheet, Text, TouchableHighlight, View } from 'react-native';
import {SRDarkColor, SRYellowColor, SRBrightColor, SRRedColor} from './utilities/SRColors'

export default class SRRatingView extends React.Component {

  constructor(props) {
    super(props)
    this.state = {

    }
  }

  render() {
    return (
      <View style={styles.transparentView}>
       <View style={styles.overlayView}>
         <View style={styles.contentView}>
           <Text style={styles.ratingBoxTitle}>How well did you do?</Text>

           <View style={styles.ratingBoxContainer}>

               <TouchableHighlight
                 style={styles.ratingTouchable}
                 underlayColor={'rgba(0, 0, 0, 0.06)'}
                 onPress={() => {
                   this.rated(0)
                 }}>
                    <View style={[styles.ratingBox, styles.ratingLeft]}>
                      <Text style={[styles.ratingTitle, styles.ratingLeftTitle]}>Bad</Text>
                    </View>
               </TouchableHighlight>

               <TouchableHighlight
                 style={styles.ratingTouchable}
                 underlayColor={'rgba(0, 0, 0, 0.06)'}
                 onPress={() => {
                   this.rated(1)
                 }}>
                    <View style={[styles.ratingBox, styles.ratingCenter]}>
                      <Text style={[styles.ratingTitle, styles.ratingCenterTitle]}>Okay</Text>
                    </View>
               </TouchableHighlight>

               <TouchableHighlight
                 style={styles.ratingTouchable}
                 underlayColor={'rgba(0, 0, 0, 0.06)'}
                 onPress={() => {
                   this.rated(2)
                 }}>
                    <View style={[styles.ratingBox, styles.ratingRight]}>
                      <Text style={[styles.ratingTitle, styles.ratingRightTitle]}>Good</Text>
                    </View>
               </TouchableHighlight>
           </View>

           <TouchableHighlight
             underlayColor={'rgba(0, 0, 0, 0.06)'}
             onPress={() => {
             {this.cancelAction()}
           }}>
             <Text style={styles.cancelButton}>Cancel</Text>
           </TouchableHighlight>
         </View>
       </View>
      </View>
    )
  }

  rated(indexPressed) {
    const {ratedCallback} = this.props
    if (typeof ratedCallback == 'function') {
      ratedCallback(indexPressed)
    }
  }

  cancelAction() {
    const { dismissAction } = this.props
    if (typeof dismissAction == 'function') {
      dismissAction()
    }
  }

}

const styles = StyleSheet.create({
  transparentView: {
    flexDirection: 'row',
    flex: 1,
    alignItems: 'center',
    paddingLeft: 15,
    paddingRight: 15,
    backgroundColor: 'rgba(4, 4, 4, 0.77)',
  },
  overlayView: {
    padding: 15,
    flex: 1,
    height: 240,// TODO: calculate right height
    backgroundColor: SRBrightColor,
    borderRadius: 8,
  },
  contentView: {
    flex: 1,
  },
  ratingBoxContainer: {
    flexDirection: 'row',
    flex: 1,
  },
  ratingBox: {
    flex: 1,
    margin: 5,
    borderRadius: 4,
    justifyContent: 'center',
    alignItems: 'center',
  },
  ratingBoxTitle: {
    color: SRDarkColor,
    fontSize: 20,
    textAlign: 'center',
    padding: 10,
  },
  cancelButton: {
    textAlign: 'center',
    fontSize: 20,
    paddingTop: 15,
    paddingBottom: 5,
  },
  ratingLeft: {
    backgroundColor: SRRedColor,
  },
  ratingCenter: {
    backgroundColor: SRYellowColor,
  },
  ratingRight: {
    backgroundColor: SRDarkColor,
  },
  ratingTouchable: {
    flex: 1,
    justifyContent: 'center',
    alignItems: 'stretch',
  },
  ratingTitle: {
    fontWeight: 'bold',
    fontSize: 20,
  },
  ratingLeftTitle: {
    color: SRDarkColor,
  },
  ratingCenterTitle: {
    color: SRDarkColor
  },
  ratingRightTitle: {
    color: SRBrightColor,
  },
})
<commit_msg>Removed unused constructor. Changed text color on red box.<commit_after>// @flow
import React from 'react'
import { StyleSheet, Text, TouchableHighlight, View } from 'react-native';
import {SRDarkColor, SRYellowColor, SRBrightColor, SRRedColor} from './utilities/SRColors'

export default class SRRatingView extends React.Component {

  render() {
    return (
      <View style={styles.transparentView}>
       <View style={styles.overlayView}>
         <View style={styles.contentView}>
           <Text style={styles.ratingBoxTitle}>How well did you do?</Text>

           <View style={styles.ratingBoxContainer}>

               <TouchableHighlight
                 style={styles.ratingTouchable}
                 underlayColor={'rgba(0, 0, 0, 0.06)'}
                 onPress={() => {
                   this.rated(0)
                 }}>
                    <View style={[styles.ratingBox, styles.ratingLeft]}>
                      <Text style={[styles.ratingTitle, styles.ratingLeftTitle]}>Bad</Text>
                    </View>
               </TouchableHighlight>

               <TouchableHighlight
                 style={styles.ratingTouchable}
                 underlayColor={'rgba(0, 0, 0, 0.06)'}
                 onPress={() => {
                   this.rated(1)
                 }}>
                    <View style={[styles.ratingBox, styles.ratingCenter]}>
                      <Text style={[styles.ratingTitle, styles.ratingCenterTitle]}>Okay</Text>
                    </View>
               </TouchableHighlight>

               <TouchableHighlight
                 style={styles.ratingTouchable}
                 underlayColor={'rgba(0, 0, 0, 0.06)'}
                 onPress={() => {
                   this.rated(2)
                 }}>
                    <View style={[styles.ratingBox, styles.ratingRight]}>
                      <Text style={[styles.ratingTitle, styles.ratingRightTitle]}>Good</Text>
                    </View>
               </TouchableHighlight>
           </View>

           <TouchableHighlight
             underlayColor={'rgba(0, 0, 0, 0.06)'}
             onPress={() => {
             {this.cancelAction()}
           }}>
             <Text style={styles.cancelButton}>Cancel</Text>
           </TouchableHighlight>
         </View>
       </View>
      </View>
    )
  }

  rated(indexPressed: number) {
    const {ratedCallback} = this.props
    if (typeof ratedCallback == 'function') {
      ratedCallback(indexPressed)
    }
  }

  cancelAction() {
    const { dismissAction } = this.props
    if (typeof dismissAction == 'function') {
      dismissAction()
    }
  }

}

const styles = StyleSheet.create({
  transparentView: {
    flexDirection: 'row',
    flex: 1,
    alignItems: 'center',
    paddingLeft: 15,
    paddingRight: 15,
    backgroundColor: 'rgba(4, 4, 4, 0.77)',
  },
  overlayView: {
    padding: 15,
    flex: 1,
    height: 240,// TODO: calculate right height
    backgroundColor: SRBrightColor,
    borderRadius: 8,
  },
  contentView: {
    flex: 1,
  },
  ratingBoxContainer: {
    flexDirection: 'row',
    flex: 1,
  },
  ratingBox: {
    flex: 1,
    margin: 5,
    borderRadius: 4,
    justifyContent: 'center',
    alignItems: 'center',
  },
  ratingBoxTitle: {
    color: SRDarkColor,
    fontSize: 20,
    textAlign: 'center',
    padding: 10,
  },
  cancelButton: {
    textAlign: 'center',
    fontSize: 20,
    paddingTop: 15,
    paddingBottom: 5,
  },
  ratingLeft: {
    backgroundColor: SRRedColor,
  },
  ratingCenter: {
    backgroundColor: SRYellowColor,
  },
  ratingRight: {
    backgroundColor: SRDarkColor,
  },
  ratingTouchable: {
    flex: 1,
    justifyContent: 'center',
    alignItems: 'stretch',
  },
  ratingTitle: {
    fontWeight: 'bold',
    fontSize: 20,
  },
  ratingLeftTitle: {
    color: SRBrightColor,
  },
  ratingCenterTitle: {
    color: SRDarkColor
  },
  ratingRightTitle: {
    color: SRBrightColor,
  },
})
<|endoftext|>


<commit_before>// Copyright 2013-2015, University of Colorado Boulder

/**
 * Converts a wavelength to a visible color.
 * If the wavelength is not in the visible spectrum, null is returned.
 */
define( function( require ) {
  'use strict';

  // modules
  var Color = require( 'SCENERY/util/Color' );
  var sceneryPhet = require( 'SCENERY_PHET/sceneryPhet' );

  /**
   * @constructor
   */
  function VisibleColor() {}

  sceneryPhet.register( 'VisibleColor', VisibleColor );

  // public constants
  VisibleColor.MIN_WAVELENGTH = 380;
  VisibleColor.MAX_WAVELENGTH = 780;

  /**
   * Creates a table that is used to map wavelength to Color.
   * @return {Color[]}
   */
  var createColorTable = function() {

    var colorTable = [];

    // Allocate the color-lookup array.
    var numWavelengths = Math.floor( VisibleColor.MAX_WAVELENGTH - VisibleColor.MIN_WAVELENGTH + 1 );

    // Populate the color array.
    var wl;
    var r;
    var g;
    var b;
    for ( var i = 0; i < numWavelengths; i++ ) {
      // Create the RGB component values.
      wl = VisibleColor.MIN_WAVELENGTH + i;
      r = g = b = 0;

      // Determine the RGB component values.
      if ( wl >= 380 && wl <= 440 ) {
        r = -1 * ( wl - 440 ) / ( 440 - 380 );
        g = 0;
        b = 1;
      }
      else if ( wl > 440 && wl <= 490 ) {
        r = 0;
        g = ( wl - 440 ) / ( 490 - 440 );
        b = 1;
      }
      else if ( wl > 490 && wl <= 510 ) {
        r = 0;
        g = 1;
        b = -1 * ( wl - 510 ) / ( 510 - 490 );
      }
      else if ( wl > 510 && wl <= 580 ) {
        r = ( wl - 510 ) / ( 580 - 510 );
        g = 1;
        b = 0;
      }
      else if ( wl > 580 && wl <= 645 ) {
        r = 1;
        g = -1 * ( wl - 645 ) / ( 645 - 580 );
        b = 0;
      }
      else if ( wl > 645 && wl <= 780 ) {
        r = 1;
        g = 0;
        b = 0;
      }

      // Let the intensity fall off near the vision limits.
      var intensity;
      if ( wl > 645 ) {
        intensity = 0.3 + 0.7 * ( 780 - wl ) / ( 780 - 645 );
      }
      else if ( wl < 420 ) {
        intensity = 0.3 + 0.7 * ( wl - 380 ) / ( 420 - 380 );
      }
      else {
        intensity = 1;
      }
      var red = Math.round( 255 * ( intensity * r ) );
      var green = Math.round( 255 * ( intensity * g ) );
      var blue = Math.round( 255 * ( intensity * b ) );
      var alpha = 1;

      // Add the color to the lookup array.
      colorTable[ i ] = new Color( red, green, blue, alpha );
    }

    return colorTable;
  };

  // Eagerly create the color table.
  var COLOR_TABLE = createColorTable();

  /**
   * Converts a wavelength to a visible color.
   * @param {number} wavelength will be rounded to the closest integer value
   * @return {number|null} null if wavelength is not in the visible spectrum
   */
  VisibleColor.wavelengthToColor = function( wavelength ) {
    if ( wavelength < VisibleColor.MIN_WAVELENGTH || wavelength > VisibleColor.MAX_WAVELENGTH ) {
      return null; // Wavelength is not visible.
    }
    else {
      return COLOR_TABLE[ Math.round( wavelength ) - VisibleColor.MIN_WAVELENGTH ];
    }
  };

  return VisibleColor;
} );
<commit_msg>complete the port of VisibleColor, #232<commit_after>// Copyright 2013-2016, University of Colorado Boulder

/**
 * Provides a 2-way mapping between wavelength and Color.
 * The mapping is performed using a color lookup table.
 *
 * Note that the sRGB colorspace is not capable of representing all visible colors.
 * So in converting visible wavelengths to Color, it is possible to lose some color information.
 *
 * @author Chris Malley (PixelZoom, Inc.)
 */
define( function( require ) {
  'use strict';

  // modules
  var Color = require( 'SCENERY/util/Color' );
  var sceneryPhet = require( 'SCENERY_PHET/sceneryPhet' );
  var Util = require( 'DOT/Util' );

  // constants
  var COLOR_MATCH_DELTA = 2; // Two colors match if their RGB components each differ by less than this amount.

  var VisibleColor = {

    // public constants
    MIN_WAVELENGTH: 380,
    MAX_WAVELENGTH: 780,
    WHITE_WAVELENGTH: 0,

    /**
     * Converts a wavelength to a visible color.
     *
     * @param {number} wavelength will be rounded to the closest integer value
     * @param {Object} [options]
     * @return {Color|null}
     */
    wavelengthToColor: function( wavelength, options ) {

      options = _.extend( {
        irColor: null, // {Color|string|null} color to use for IR wavelengths
        uvColor: null  // {Color|string|null} color to use for UV wavelengths
      }, options );

      var color = null;
      if ( wavelength === VisibleColor.WHITE_WAVELENGTH ) { // white light
        color = Color.WHITE;
      }
      else if ( wavelength < VisibleColor.MIN_WAVELENGTH ) { // IR
        color = Color.toColor( options.irColor );
      }
      else if ( wavelength > VisibleColor.MAX_WAVELENGTH ) { // UV
        color = Color.toColor( options.uvColor );
      }
      else { // lookup visible color
        assert && assert( COLOR_TABLE );
        color = COLOR_TABLE[ Util.roundSymmetric( wavelength ) - VisibleColor.MIN_WAVELENGTH ];
      }

      assert && assert( color, 'color not found for wavelength ' + wavelength );
      return color;
    },

    /**
     * Converts a Color to its corresponding wavelength.
     * Relies on a color lookup table that is initialized the first time
     * that this method is called.  Color lookup is based on RGB component
     * value; the alpha value is ignored.
     *
     * @param {Color|string} color - the color
     * @return {number} the wavelength
     */
    colorToWavelength: function( color ) {

      color = Color.toColor( color );

      var wavelength = -1;

      if ( color.equals( Color.WHITE ) ) {
        wavelength = VisibleColor.WHITE_WAVELENGTH;
      }
      else {
        assert && assert( COLOR_TABLE );
        for ( var i = 0; i < COLOR_TABLE.length; i++ ) {
          if ( Math.abs( color.getRed() - COLOR_TABLE[ i ].getRed() ) < COLOR_MATCH_DELTA &&
               Math.abs( color.getGreen() - COLOR_TABLE[ i ].getGreen() ) < COLOR_MATCH_DELTA &&
               Math.abs( color.getBlue() - COLOR_TABLE[ i ].getBlue() ) < COLOR_MATCH_DELTA ) {
            wavelength = VisibleColor.MIN_WAVELENGTH + i;
            break;
          }
        }
      }

      assert && assert( wavelength !== -1, 'no wavelength found for color ' + color.toString() );
      return wavelength;
    }
  };

  sceneryPhet.register( 'VisibleColor', VisibleColor );

  /**
   * Creates a table that is used to map wavelength to Color.
   * @return {Color[]}
   */
  var createColorTable = function() {

    var colorTable = [];

    // Allocate the lookup table
    var numWavelengths = Math.floor( VisibleColor.MAX_WAVELENGTH - VisibleColor.MIN_WAVELENGTH + 1 );

    // Populate the lookup table
    var wavelength;
    var r;
    var g;
    var b;
    for ( var i = 0; i < numWavelengths; i++ ) {

      // Create the RGB component values.
      wavelength = VisibleColor.MIN_WAVELENGTH + i;
      r = g = b = 0;

      // Determine the RGB component values.
      if ( wavelength >= 380 && wavelength <= 440 ) {
        r = -1 * ( wavelength - 440 ) / ( 440 - 380 );
        g = 0;
        b = 1;
      }
      else if ( wavelength > 440 && wavelength <= 490 ) {
        r = 0;
        g = ( wavelength - 440 ) / ( 490 - 440 );
        b = 1;
      }
      else if ( wavelength > 490 && wavelength <= 510 ) {
        r = 0;
        g = 1;
        b = -1 * ( wavelength - 510 ) / ( 510 - 490 );
      }
      else if ( wavelength > 510 && wavelength <= 580 ) {
        r = ( wavelength - 510 ) / ( 580 - 510 );
        g = 1;
        b = 0;
      }
      else if ( wavelength > 580 && wavelength <= 645 ) {
        r = 1;
        g = -1 * ( wavelength - 645 ) / ( 645 - 580 );
        b = 0;
      }
      else if ( wavelength > 645 && wavelength <= 780 ) {
        r = 1;
        g = 0;
        b = 0;
      }

      // Let the intensity fall off near the vision limits.
      var intensity;
      if ( wavelength > 645 ) {
        intensity = 0.3 + 0.7 * ( 780 - wavelength ) / ( 780 - 645 );
      }
      else if ( wavelength < 420 ) {
        intensity = 0.3 + 0.7 * ( wavelength - 380 ) / ( 420 - 380 );
      }
      else {
        intensity = 1;
      }
      var red = Math.round( 255 * ( intensity * r ) );
      var green = Math.round( 255 * ( intensity * g ) );
      var blue = Math.round( 255 * ( intensity * b ) );
      var alpha = 1;

      // Add the color to the lookup array.
      colorTable[ i ] = new Color( red, green, blue, alpha );
    }

    return colorTable;
  };

  // Eagerly create the color table.
  var COLOR_TABLE = createColorTable();

  return VisibleColor;
} );
<|endoftext|>


<commit_before>const browserBookmarks = require('browser-bookmarks');

/**
 * Converts the bookmark object to Dext item
 *
 * @param {Object} item - The bookmark object
 * @return {Object} - The Dext bookmark object
 */
const mapDextItem = item => ({
  title: item.title,
  subtitle: `(${item.folder || 'misc'}) - ${item.url}`,
  arg: item.url,
  icon: {
    path: item.favicon,
  },
});

module.exports = {
  action: 'openurl',
  execute: q => new Promise(resolve => {
    browserBookmarks.getChrome().then(bookmarks => {
      // resolve and exist if there's no bookmarks
      if (!bookmarks.length) {
        resolve([]);
        return;
      }
      // map to Dext
      const items = bookmarks.map(mapDextItem);
      // apply scores
      items.forEach(i => {
        i.score = i.title.score(q); // eslint-disable-line no-param-reassign
      });
      const sortedItems = items
        // filter out 0's
        .filter(i => i.score > 0)
        // sort by score
        .sort((a, b) => {
          const scoreA = a.title.score(q);
          const scoreB = b.title.score(q);
          if (scoreA === scoreB) {
            return 0;
          } else if (scoreA < scoreB) {
            return 1;
          }
          return -1;
        })
        // return only top 20
        .filter((a, b) => b < 20);
      resolve({ items: sortedItems });
    });
  }),
};
<commit_msg>fixed missing import string_score<commit_after>require('string_score');
const browserBookmarks = require('browser-bookmarks');

/**
 * Converts the bookmark object to Dext item
 *
 * @param {Object} item - The bookmark object
 * @return {Object} - The Dext bookmark object
 */
const mapDextItem = item => ({
  title: item.title,
  subtitle: `(${item.folder || 'misc'}) - ${item.url}`,
  arg: item.url,
  icon: {
    path: item.favicon,
  },
});

module.exports = {
  action: 'openurl',
  execute: q => new Promise(resolve => {
    browserBookmarks.getChrome().then(bookmarks => {
      // resolve and exist if there's no bookmarks
      if (!bookmarks.length) {
        resolve([]);
        return;
      }
      // map to Dext
      const items = bookmarks.map(mapDextItem);
      // apply scores
      items.forEach(i => {
        i.score = i.title.score(q); // eslint-disable-line no-param-reassign
      });
      const sortedItems = items
        // filter out 0's
        .filter(i => i.score > 0)
        // sort by score
        .sort((a, b) => {
          const scoreA = a.title.score(q);
          const scoreB = b.title.score(q);
          if (scoreA === scoreB) {
            return 0;
          } else if (scoreA < scoreB) {
            return 1;
          }
          return -1;
        })
        // return only top 20
        .filter((a, b) => b < 20);
      resolve({ items: sortedItems });
    });
  }),
};
<|endoftext|>


<commit_before>var achievements = [
	{
		'title': 'Complete your first project',
		'check': function(){
			return Stats.projects >= 1
		},
		'done': false
	},
	{
		'title': 'Raise your money up to 1.000.000',
		'check': function(){
			return Stats.money >= 1000000
		},
		'done': false
	},
	{
		'title': 'Raise your money up to 10.000.000',
		'check': function(){
			return Stats.money >= 10000000
		},
		'done': false
	},
	{
		'title': 'Raise your money up to 100.000.000',
		'check': function(){
			return Stats.money >= 100000000
		},
		'done': false
	},
	{
		'title': 'Unlock the intranet skin',
		'check': function(){
			return Stats.improvements.indexOf('intranet') !== -1
		},
		'done': false
	},
	{
		'title': 'Unlock the new intranet skin',
		'check': function(){
			return Stats.improvements.indexOf('intranet2') !== -1
		},
		'done': false
	},
	{
		'title': 'Hire your first employee',
		'check': function(){
			return Stats.employees.length >= 1
		},
		'done': false
	},
	{
		'title': 'Upgrade your computer to version 20',
		'check': function(){
			return Stats.computerVersion >= 20
		},
		'done': false
	},
	{
		'title': 'Rent your first room',
		'check': function(){
			return Stats.rooms >= 1
		},
		'done': false
	},
	{
		'title': 'Rent your first floor',
		'check': function(){
			return Stats.floors >= 1
		},
		'done': false
	},
	{
		'title': 'Rent your first building',
		'check': function(){
			return Stats.buildings >= 1
		},
		'done': false
	},
	{
		'title': 'Rent your first warehouse',
		'check': function(){
			return Stats.warehouses >= 1
		},
		'done': false
	},
	{
		'title': 'Drop all your jobs',
		'check': function(){
			return Stats.jobs.length <= 0
		},
		'done': false
	},
	{
		'title': 'Achieve the minimum pulse speed',
		'check': function(){
			return Core.base.pulseDuration <= Core.base.minPulseDuration
		},
		'done': false
	},
	{
		'title': 'Unlock a parallel project',
		'check': function(){
			return Stats.improvements.indexOf('addProject') !== -1
		},
		'done': false
	}

]
<commit_msg>Update achievements.js<commit_after>var achievements = [
	{
		'title': 'Complete your first project',
		'check': function(){
			return Stats.projects >= 1
		},
		'done': false
	},
	{
		'title': 'Raise your money up to 1.000.000',
		'check': function(){
			return Stats.money >= 1000000
		},
		'done': false
	},
	{
		'title': 'Raise your money up to 10.000.000',
		'check': function(){
			return Stats.money >= 10000000
		},
		'done': false
	},
	{
		'title': 'Raise your money up to 100.000.000',
		'check': function(){
			return Stats.money >= 100000000
		},
		'done': false
	},
	{
		'title': 'Unlock the intranet skin',
		'check': function(){
			return Stats.improvements.indexOf('intranet') !== -1
		},
		'done': false
	},
	{
		'title': 'Unlock the new intranet skin',
		'check': function(){
			return Stats.improvements.indexOf('intranet2') !== -1
		},
		'done': false
	},
	{
		'title': 'Hire your first employee',
		'check': function(){
			return Stats.employees.length >= 1
		},
		'done': false
	},
	{
		'title': 'Upgrade your computer to version 20',
		'check': function(){
			return Stats.computerVersion >= 20
		},
		'done': false
	},
	{
		'title': 'Rent your first room',
		'check': function(){
			return Stats.rooms >= 1
		},
		'done': false
	},
	{
		'title': 'Rent your first floor',
		'check': function(){
			return Stats.floors >= 1
		},
		'done': false
	},
	{
		'title': 'Rent your first building',
		'check': function(){
			return Stats.buildings >= 1
		},
		'done': false
	},
	{
		'title': 'Rent your first warehouse',
		'check': function(){
			return Stats.warehouses >= 1
		},
		'done': false
	},
	{
		'title': 'Drop all your jobs',
		'check': function(){
			return Stats.jobs.length <= 0
		},
		'done': false
	},
	{
		'title': 'Achieve the minimum pulse speed',
		'check': function(){
			return Core.base.pulseDuration <= Core.base.minPulseDuration
		},
		'done': false
	},
	{
		'title': 'Unlock a parallel project',
		'check': function(){
			return Stats.improvements.indexOf('addProject') !== -1
		},
		'done': false
	},
	{
		'title': 'Buy your first ticket for the lottery',
		'check': function(){
			return Stats.ticketsBought === 1
		},
		'done': false
	},
	{
		'title': 'Spend 100¢ in the lottery',
		'check': function(){
			return Stats.ticketsBought * Core.base.lotteryTicketCost >= 100
		},
		'done': false
	},
	{
		'title': 'Win a partial in the lottery',
		'check': function(){
			return Stats.partialWon
		},
		'done': false
	},
	{
		'title': 'Win the lottery',
		'check': function(){
			return Stats.lotteryWon
		},
		'done': false
	},
	{
		'title': 'Caffeine addict',
		'check': function(){
			return Stats.coffeesBought >= 500
		},
		'done': false
	},
	{
		'title': 'Taurine addict',
		'check': function(){
			return Stats.energyDrinksBought >= 500
		},
		'done': false
	},
	{
		'title': 'Lottery addict',
		'check': function(){
			return Stats.ticketsBought >= 500
		},
		'done': false
	}

]
<|endoftext|>


<commit_before>import {baseSchema} from "./../validation/validation-schema";
import cloneDeep from "lodash/cloneDeep";
import {urlReEx} from "../constants";
import {handlersMap, getConfig} from "../config";
import {getAppData, setAppData, isIE} from './../utils';
import {singleHopDropOutFunction, singleHopDropInFunction} from "./singleHop";
import {refineMotoResponse} from "./response";
import {custFetch} from "../interceptor";

let winRef = null;
let cancelApiResp;
const regExMap = {
    'cardNumber': /^[0-9]{15,19}$/,
    'name': /^(?!\s*$)[a-zA-Z .]{1,50}$/,
    'CVV': /^[0-9]{3,4}$/, //todo: handle cases for amex
    url: urlReEx
};
let txnId;
const motoCardValidationSchema = Object.assign(cloneDeep(baseSchema), {
    paymentDetails: {
        presence: true,
        cardCheck: true,
        keysCheck: ['type', 'number', 'holder', 'cvv', 'expiry']
    },
    "paymentDetails.holder": {presence: true, format: regExMap.name}
});

motoCardValidationSchema.mainObjectCheck.keysCheck.push('paymentDetails');
const makePayment = (paymentObj) => {

    txnId = paymentObj.merchantTxnId;
    const paymentMode = paymentObj.paymentDetails.paymentMode.toLowerCase().replace(/\s+/g, '');
    const win = document.getElementById("citrusnumber-" + paymentObj.paymentDetails.type.toLowerCase()).contentWindow;
    paymentObj.pgSettingsData = getAppData('pgSettingsData');
    paymentObj.config = getConfig();

    if (paymentObj.mode.toLowerCase() !== "dropout")
        {
            // winRef = openPopupWindow("");
            // winRef.document.write(' <meta name="viewport" content="width=device-width"/> <meta http-equiv="Cache-control" content="public"/> <title>Redirecting to Bank</title>

Processing Payment

We are redirecting you to the bank\'s page

DO NOT CLOSE THIS POP-UP

');
        }
            setAppData('paymentObj', paymentObj);
    //todo : change the star value to citruspay domain string
            win.postMessage(paymentObj, "*");
    };

const listener = (event) => {
    try{
     if(!event.data.isValidRequest) {
        const motoResponse = event.data;
        const paymentObj = getAppData('paymentObj');
        if (event.origin === ("http://localhost") && motoResponse.redirectUrl) { //url check has to configured, currently its hardcoded
            if (paymentObj.mode.toLowerCase() === "dropout") {
                singleHopDropOutFunction(motoResponse.redirectUrl);
            }
            else {
                // if(winRef && winRef.closed)
                // {
                //     //handlersMap["serverErrorHandler"](response);
                //     return;
                // }
                singleHopDropInFunction(motoResponse.redirectUrl).then(function (response) {
                    if (winRef && winRef.closed !== true) {
                        let el = document.createElement('body');
                        el.innerHTML = response;
                        let form = el.getElementsByTagName('form');
                        try {
                            let paymentForm = document.createElement('form');
                            switch (Object.prototype.toString.call(form)) {
                                case "[object NodeList]" :
                                    paymentForm.setAttribute("action", form[0].action),
                                        paymentForm.setAttribute("method", form[0].method),
                                        paymentForm.setAttribute("target", winRef.name),
                                        paymentForm.innerHTML = form[0].innerHTML,
                                        document.documentElement.appendChild(paymentForm),
                                        paymentForm.submit(),
                                        document.documentElement.removeChild(paymentForm);
                                    break;
                                case "[object HTMLCollection]" :
                                    paymentForm.setAttribute("action", form.submitForm.action),
                                        paymentForm.setAttribute("method", form.submitForm.method),
                                        paymentForm.setAttribute("target", winRef.name),
                                        paymentForm.innerHTML = form.submitForm.innerHTML,
                                        document.documentElement.appendChild(paymentForm),
                                        paymentForm.submit(),
                                        document.documentElement.removeChild(paymentForm);
                                    break;
                            }
                        } catch (e) {
                            console.log(e);
                            let paymentForm = document.createElement('form');
                            paymentForm.setAttribute("action", form.returnForm.action),
                                paymentForm.setAttribute("method", form.returnForm.method),
                                paymentForm.setAttribute("target", winRef.name),
                                paymentForm.innerHTML = form.returnForm.innerHTML,
                                document.body.appendChild(paymentForm),
                                paymentForm.submit(),
                                document.body.removeChild(paymentForm);
                        }
                    }
                    if (!isIE()) {
                        workFlowForModernBrowsers(winRef);
                    } else {
                        workFlowForIE(winRef);
                    }
                });
            }
        } else {
            if (winRef) {
                winRef.close();
            }
            const response = refineMotoResponse(motoResponse);
            handlersMap['serverErrorHandler'](response);
        }
     }else if(event.data.isValidRequest && getAppData('paymentObj')['mode'].toLowerCase() === 'dropin') {
         winRef = openPopupWindow("");
         winRef.document.write(' <meta name="viewport" content="width=device-width"/> <meta http-equiv="Cache-control" content="public"/> <title>Redirecting to Bank</title>

Processing Payment

We are redirecting you to the bank\'s page

DO NOT CLOSE THIS POP-UP

');
    }
    if(event.data.responseType === "errorHandler") handlersMap['errorHandler'](event.data.error);
    if(event.data.responseType === "serverErrorHandler") handlersMap['serverErrorHandler'](event.data.error);
    }
    catch(e){
        console.log(e);
    }
}

const openPopupWindow = (url) => {
    if (winRef == null || winRef.closed) {
        var width = window.innerWidth ? window.innerWidth : document.documentElement.clientWidth ? document.documentElement.clientWidth : screen.width;
        var height = window.innerHeight ? window.innerHeight : document.documentElement.clientHeight ? document.documentElement.clientHeight : screen.height;
        var w = 800;
        var h = 600;
        var left = ((width - w) / 2);
        var top = height / 10;
        winRef = window.open(url, 'CitrusOverlay', 'scrollbars=yes, width=' + w + ', height=' + h + ', top=' + top + ', left=' + left + 'visible=none;');
    } else {
        winRef.focus();
    }
    return winRef;
};

let transactionCompleted = false;

const workFlowForModernBrowsers = (winRef) => {
    var intervalId = setInterval(function () {
        if (transactionCompleted) {
            return clearInterval(intervalId);
        }
        if (winRef) {
            if (winRef.closed === true) {
                clearInterval(intervalId);
                let form = new FormData();
                form.append("merchantAccessKey", `${getConfig().merchantAccessKey}`);
                form.append("transactionId", txnId);
                const url = `${getConfig().adminUrl}/api/v1/txn/enquiry`;
                return custFetch(url, {
                    method: 'post',
                    mode: 'cors',
                    body: form
                }).then(function (resp) {
                    handlersMap['transactionHandler'](resp.data.enquiry);
                });
            }
        } else {
            clearInterval(intervalId);
        }
    }, 500);
};

const workFlowForIE = (winRef) => {
    const intervalId = setInterval(function () {
        if (transactionCompleted) {
            return clearInterval(intervalId);
        }
        if (winRef) {
            if (winRef.closed) {
                clearInterval(intervalId);
                let form = new FormData();
                form.append("merchantAccessKey", `${getConfig().merchantAccessKey}`);
                form.append("transactionId", txnId);
                const url = `${getConfig().adminUrl}/api/v1/txn/enquiry`;
                return custFetch(url, {
                    method: 'post',
                    mode: 'cors',
                    body: form
                }).then(function (resp) {
                    handlersMap['transactionHandler'](resp.data.enquiry);
                });
            }
        }
    }, 500);
};
export {makePayment, listener};<commit_msg>handled the test scenario for single tab for both credit/debit card<commit_after>import {baseSchema} from "./../validation/validation-schema";
import cloneDeep from "lodash/cloneDeep";
import {urlReEx} from "../constants";
import {handlersMap, getConfig} from "../config";
import {getAppData, setAppData, isIE} from "./../utils";
import {singleHopDropOutFunction, singleHopDropInFunction} from "./singleHop";
import {refineMotoResponse} from "./response";
import {custFetch} from "../interceptor";

let winRef = null;
let cancelApiResp;
const regExMap = {
    'cardNumber': /^[0-9]{15,19}$/,
    'name': /^(?!\s*$)[a-zA-Z .]{1,50}$/,
    'CVV': /^[0-9]{3,4}$/, //todo: handle cases for amex
    url: urlReEx
};
let txnId;
const motoCardValidationSchema = Object.assign(cloneDeep(baseSchema), {
    paymentDetails: {
        presence: true,
        cardCheck: true,
        keysCheck: ['type', 'number', 'holder', 'cvv', 'expiry']
    },
    "paymentDetails.holder": {presence: true, format: regExMap.name}
});

motoCardValidationSchema.mainObjectCheck.keysCheck.push('paymentDetails');
const makePayment = (paymentObj) => {
    txnId = paymentObj.merchantTxnId;
    const paymentMode = paymentObj.paymentDetails.paymentMode.toLowerCase().replace(/\s+/g, '');
    let element = document.getElementById("citrusnumber-" + paymentObj.paymentDetails.type.toLowerCase());
    if (typeof(element) === 'undefined' || element === null)
        element = document.getElementById("citrusnumber-card");
    const win = element.contentWindow;
    paymentObj.pgSettingsData = getAppData('pgSettingsData');
    paymentObj.config = getConfig();

    if (paymentObj.mode.toLowerCase() !== "dropout") {
        // winRef = openPopupWindow("");
        // winRef.document.write(' <meta name="viewport" content="width=device-width"/> <meta http-equiv="Cache-control" content="public"/> <title>Redirecting to Bank</title>

Processing Payment

We are redirecting you to the bank\'s page

DO NOT CLOSE THIS POP-UP

');
    }
    setAppData('paymentObj', paymentObj);
    //todo : change the star value to citruspay domain string
    win.postMessage(paymentObj, "*");
};

const listener = (event) => {
    try {
        if (!event.data.isValidRequest) {
            const motoResponse = event.data;
            const paymentObj = getAppData('paymentObj');
            if (event.origin === ("http://localhost") && motoResponse.redirectUrl) { //url check has to configured, currently its hardcoded
                if (paymentObj.mode.toLowerCase() === "dropout") {
                    singleHopDropOutFunction(motoResponse.redirectUrl);
                }
                else {
                    // if(winRef && winRef.closed)
                    // {
                    //     //handlersMap["serverErrorHandler"](response);
                    //     return;
                    // }
                    singleHopDropInFunction(motoResponse.redirectUrl).then(function (response) {
                        if (winRef && winRef.closed !== true) {
                            let el = document.createElement('body');
                            el.innerHTML = response;
                            let form = el.getElementsByTagName('form');
                            try {
                                let paymentForm = document.createElement('form');
                                switch (Object.prototype.toString.call(form)) {
                                    case "[object NodeList]" :
                                        paymentForm.setAttribute("action", form[0].action),
                                            paymentForm.setAttribute("method", form[0].method),
                                            paymentForm.setAttribute("target", winRef.name),
                                            paymentForm.innerHTML = form[0].innerHTML,
                                            document.documentElement.appendChild(paymentForm),
                                            paymentForm.submit(),
                                            document.documentElement.removeChild(paymentForm);
                                        break;
                                    case "[object HTMLCollection]" :
                                        paymentForm.setAttribute("action", form.submitForm.action),
                                            paymentForm.setAttribute("method", form.submitForm.method),
                                            paymentForm.setAttribute("target", winRef.name),
                                            paymentForm.innerHTML = form.submitForm.innerHTML,
                                            document.documentElement.appendChild(paymentForm),
                                            paymentForm.submit(),
                                            document.documentElement.removeChild(paymentForm);
                                        break;
                                }
                            } catch (e) {
                                console.log(e);
                                let paymentForm = document.createElement('form');
                                paymentForm.setAttribute("action", form.returnForm.action),
                                    paymentForm.setAttribute("method", form.returnForm.method),
                                    paymentForm.setAttribute("target", winRef.name),
                                    paymentForm.innerHTML = form.returnForm.innerHTML,
                                    document.body.appendChild(paymentForm),
                                    paymentForm.submit(),
                                    document.body.removeChild(paymentForm);
                            }
                        }
                        if (!isIE()) {
                            workFlowForModernBrowsers(winRef);
                        } else {
                            workFlowForIE(winRef);
                        }
                    });
                }
            } else {
                if (winRef) {
                    winRef.close();
                }
                const response = refineMotoResponse(motoResponse);
                handlersMap['serverErrorHandler'](response);
            }
        } else if (event.data.isValidRequest && getAppData('paymentObj')['mode'].toLowerCase() === 'dropin') {
            winRef = openPopupWindow("");
            winRef.document.write(' <meta name="viewport" content="width=device-width"/> <meta http-equiv="Cache-control" content="public"/> <title>Redirecting to Bank</title>

Processing Payment

We are redirecting you to the bank\'s page

DO NOT CLOSE THIS POP-UP

');
        }
        if (event.data.responseType === "errorHandler") handlersMap['errorHandler'](event.data.error);
        if (event.data.responseType === "serverErrorHandler") handlersMap['serverErrorHandler'](event.data.error);
    }
    catch (e) {
        console.log(e);
    }
}

const openPopupWindow = (url) => {
    if (winRef == null || winRef.closed) {
        var width = window.innerWidth ? window.innerWidth : document.documentElement.clientWidth ? document.documentElement.clientWidth : screen.width;
        var height = window.innerHeight ? window.innerHeight : document.documentElement.clientHeight ? document.documentElement.clientHeight : screen.height;
        var w = 800;
        var h = 600;
        var left = ((width - w) / 2);
        var top = height / 10;
        winRef = window.open(url, 'CitrusOverlay', 'scrollbars=yes, width=' + w + ', height=' + h + ', top=' + top + ', left=' + left + 'visible=none;');
    } else {
        winRef.focus();
    }
    return winRef;
};

let transactionCompleted = false;

const workFlowForModernBrowsers = (winRef) => {
    var intervalId = setInterval(function () {
        if (transactionCompleted) {
            return clearInterval(intervalId);
        }
        if (winRef) {
            if (winRef.closed === true) {
                clearInterval(intervalId);
                let form = new FormData();
                form.append("merchantAccessKey", `${getConfig().merchantAccessKey}`);
                form.append("transactionId", txnId);
                const url = `${getConfig().adminUrl}/api/v1/txn/enquiry`;
                return custFetch(url, {
                    method: 'post',
                    mode: 'cors',
                    body: form
                }).then(function (resp) {
                    handlersMap['transactionHandler'](resp.data.enquiry);
                });
            }
        } else {
            clearInterval(intervalId);
        }
    }, 500);
};

const workFlowForIE = (winRef) => {
    const intervalId = setInterval(function () {
        if (transactionCompleted) {
            return clearInterval(intervalId);
        }
        if (winRef) {
            if (winRef.closed) {
                clearInterval(intervalId);
                let form = new FormData();
                form.append("merchantAccessKey", `${getConfig().merchantAccessKey}`);
                form.append("transactionId", txnId);
                const url = `${getConfig().adminUrl}/api/v1/txn/enquiry`;
                return custFetch(url, {
                    method: 'post',
                    mode: 'cors',
                    body: form
                }).then(function (resp) {
                    handlersMap['transactionHandler'](resp.data.enquiry);
                });
            }
        }
    }, 500);
};
export {makePayment, listener};<|endoftext|>


<commit_before>'use strict';

const passport = require('passport');
const getStrategy = require('./../../modules/gcalstrategy');

/**
 * Initialize passport object if possible
 */
exports.init = function(config) {
    try {
        passport.use(getStrategy(config));
    } catch(e) {
        // display configuration error on server load if google calendar enabled
        if (config.complay.calendar.google.enabled) {
            console.error(e);
        }
    }
};

/**
 * First click. call the google interface
 */
exports.login = function(req, res, next) {
    return passport.authenticate('google', {
        session: false,
        accessType: 'offline',
        approvalPrompt: 'force'
    })(req, res, next);
};

/**
 * Google reply on this callback
 */
exports.callback = passport.authenticate('google', {
    session: false,
    failureRedirect: '/#/user/settings/calendar',
    assignProperty: 'googleCalendarUser',
    accessType: 'offline',
    approvalPrompt: 'force' // if we do not force approval, the refresh token will not be sent after a disconnect
                            // so this is mandatory beecause we clear the refresh token on disconnect
});

/**
 * This is the next function of the callback route
 * @param {object}   req [[Description]]
 * @param {object}   res [[Description]]
 */
exports.next = (req, res) => {

    let profile = req.googleCalendarUser;

    if (!profile.refreshToken) {
        throw new Error('the refresh token is required');
    }

    req.user.google.accessToken = profile.accessToken;

    // refresh token is used to get new access tokens when the user is offline.
    req.user.google.refreshToken = profile.refreshToken;

    let expiry = new Date();
    expiry.setSeconds(expiry.getSeconds() + profile.expire_in);
    req.user.google.expire_in = expiry;
    req.user.save()
    .then((savedUser) => {
        res.redirect('/#/user/settings/calendar');
    })
    .catch(err => {
        res.end(err.message);
    });
};

/**
 * Disconnect google calendar
 * @param {object}   req [[Description]]
 * @param {object}   res [[Description]]
 */
exports.logout = (req, res) => {

    let gt = req.app.utility.gettext;
    let workflow = req.app.utility.workflow(req, res);

    req.user.google.accessToken = null;
    req.user.google.refreshToken = null;
    req.user.google.expire_in = null;

    req.user.save()
    .then((savedUser) => {
        workflow.outcome.alert.push({
            type: 'info',
            message: gt.gettext('You are disconnected from your google calendar')
        });
        workflow.emit('response');
    })
    .catch(err => {
        res.end(err.message);
    });
};
<commit_msg>Fix typo<commit_after>'use strict';

const passport = require('passport');
const getStrategy = require('./../../modules/gcalstrategy');

/**
 * Initialize passport object if possible
 */
exports.init = function(config) {
    try {
        passport.use(getStrategy(config));
    } catch(e) {
        // display configuration error on server load if google calendar enabled
        if (config.company.calendar.google.enabled) {
            console.error(e);
        }
    }
};

/**
 * First click. call the google interface
 */
exports.login = function(req, res, next) {
    return passport.authenticate('google', {
        session: false,
        accessType: 'offline',
        approvalPrompt: 'force'
    })(req, res, next);
};

/**
 * Google reply on this callback
 */
exports.callback = passport.authenticate('google', {
    session: false,
    failureRedirect: '/#/user/settings/calendar',
    assignProperty: 'googleCalendarUser',
    accessType: 'offline',
    approvalPrompt: 'force' // if we do not force approval, the refresh token will not be sent after a disconnect
                            // so this is mandatory beecause we clear the refresh token on disconnect
});

/**
 * This is the next function of the callback route
 * @param {object}   req [[Description]]
 * @param {object}   res [[Description]]
 */
exports.next = (req, res) => {

    let profile = req.googleCalendarUser;

    if (!profile.refreshToken) {
        throw new Error('the refresh token is required');
    }

    req.user.google.accessToken = profile.accessToken;

    // refresh token is used to get new access tokens when the user is offline.
    req.user.google.refreshToken = profile.refreshToken;

    let expiry = new Date();
    expiry.setSeconds(expiry.getSeconds() + profile.expire_in);
    req.user.google.expire_in = expiry;
    req.user.save()
    .then((savedUser) => {
        res.redirect('/#/user/settings/calendar');
    })
    .catch(err => {
        res.end(err.message);
    });
};

/**
 * Disconnect google calendar
 * @param {object}   req [[Description]]
 * @param {object}   res [[Description]]
 */
exports.logout = (req, res) => {

    let gt = req.app.utility.gettext;
    let workflow = req.app.utility.workflow(req, res);

    req.user.google.accessToken = null;
    req.user.google.refreshToken = null;
    req.user.google.expire_in = null;

    req.user.save()
    .then((savedUser) => {
        workflow.outcome.alert.push({
            type: 'info',
            message: gt.gettext('You are disconnected from your google calendar')
        });
        workflow.emit('response');
    })
    .catch(err => {
        res.end(err.message);
    });
};
<|endoftext|>


<commit_before>define( ["three", "camera"], function( THREE, camera ) {
  controls = new THREE.TrackballControls( camera );
  return controls;
} );
<commit_msg>Fix controls only using canvas<commit_after>define( ["three", "camera", "container"], function( THREE, camera, container ) {
  controls = new THREE.TrackballControls( camera, container );
  return controls;
} );
<|endoftext|>