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

/**
 * Tandem is a general instance registry that can be used to track creation/disposal of instances in PhET Simulations.
 * It is used for phetio.js instrumentation for PhET-iO support.
 *
 * @author Sam Reid (PhET Interactive Simulations)
 */
define( function( require ) {
  'use strict';

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

  // text
  var packageString = require( 'text!REPOSITORY/package.json' );

  // constants
  var packageJSON = JSON.parse( packageString );
  var defaultTandemMap = {}; // {string} => {number} Keep track of number of each type of default tandem

  // variables
  var launched = false;

  /**
   * @param {string} id - id as a string (or '' for a root id)
   * @param {Object} [options]
   * @constructor
   */
  function Tandem( id, options ) {

    options = _.extend( {
      static: false,
      isDefaultTandem: false,
      enabled: true
    }, options );

    // @public (read-only)
    this.id = ( id !== undefined ) ? id : '';

    // @private (read-only)
    this.static = options.static;
    this.isDefaultTandem = options.isDefaultTandem;
    this.enabled = options.enabled;
  }

  var staticInstances = [];

  tandemNamespace.register( 'Tandem', Tandem );

  // Listeners that will be notified when items are registered/deregistered
  var instanceListeners = [];

  inherit( Object, Tandem, {

    // @public (read-only) permit checking whether something is probably a Tandem instance for error checking
    isTandem: true,

    /**
     * Adds an instance of any type.  For example, it could be an axon Property, scenery Node or Sun button.  Each
     * item should only be added to the registry once, but that is not enforced here in Tandem.  For PhET-iO, phet-io.js
     * enforces one entry per ID in phetio.addInstance
     *
     * This is used to register instances with PhET-iO.
     * @param {Object} instance - the instance to add
     * @param {function} type - the PhET-iO type function, such as TString or TProperty(TNumber('volts'))
     * @public
     */
    addInstance: function( instance, type ) {

      if ( window.phet && window.phet.chipper && phet.chipper.brand === 'phet-io' && this.enabled ) {

        if ( !type ) {
          console.log( 'Missing type declaration for ' + this.id );
        }

        // ifphetio returns a no-op function, so to test whether a valid T wrapper type was passed, we search for the typeName
        assert && assert( type && type.typeName, 'type must be specified and have a typeName' );

        if ( this.static && !launched ) {
          staticInstances.push( { tandem: this, instance: instance, type: type } );
        }
        else {
          for ( var i = 0; i < instanceListeners.length; i++ ) {
            instanceListeners[ i ].addInstance( this.id, instance, type );
          }
        }
      }
    },

    /**
     * Removes an instance from the
     * @param {Object} instance - the instance to remove
     * @public
     */
    removeInstance: function( instance ) {

      // Only active when running as phet-io
      if ( phet.chipper.brand === 'phet-io' && this.enabled ) {
        for ( var i = 0; i < instanceListeners.length; i++ ) {
          instanceListeners[ i ].removeInstance( this.id, instance );
        }
      }
    },

    /**
     * Create a new Tandem by appending the given id
     * @param {string} id
     * @param {Object} [options]
     * @returns {Tandem}
     * @public
     */
    createTandem: function( id, options ) {
      var string = ( this.id.length > 0 ) ? ( this.id + '.' + id ) : id;

      // Any child of something static is also static
      options = _.extend( { static: this.static, enabled: this.enabled }, options );

      return new Tandem( string, options );
    },

    /**
     * Creates a group tandem for creating multiple indexed child tandems, such as:
     * sim.screen.model.electron_0
     * sim.screen.model.electron_1
     *
     * In this case, 'sim.screen.model.electron' is the group tandem id.
     *
     * Used for arrays, observable arrays, or when many elements of the same type are created and they do not otherwise
     * have unique identifiers.
     * @param id
     * @returns {GroupTandem}
     */
    createGroupTandem: function( id ) {

      // Unfortunately we must resort to globals here since loading through the namespace would create a cycle
      return new GroupTandem( this.id + '.' + id );
    },

    /**
     * Get the last part of the tandem (after the last .), used in Joist for creating button names dynamically based
     * on screen names
     * @return {string} the tail of the tandem
     */
    get tail() {
      assert && assert( this.id.indexOf( '.' ) >= 0, 'tandem ID does not have a tail' );

      var lastIndexOfDot = this.id.lastIndexOf( '.' );
      var tail = this.id.substring( lastIndexOfDot + 1 );
      assert && assert( tail.length > 0, 'tandem ID did not have a tail' );
      return tail;
    },

    /**
     * Returns a Tandem for everything except the tail.
     * @returns {Tandem}
     */
    get parentTandem() {
      assert && assert( this.id.indexOf( '.' ) >= 0, 'tandem ID does not have a tail' );

      var lastIndexOfDot = this.id.lastIndexOf( '.' );
      var headID = this.id.substring( 0, lastIndexOfDot );

      return new Tandem( headID, {
        static: this.static,
        isDefaultTandem: this.isDefaultTandem,
        enabled: this.enabled
      } );
    },

    /**
     * When using subtyping, the instance listeners must only be notified once rather than once for every level
     * in the inheritance hierarchy.  When a subtype constructor has a tandem.addInstance call, it should
     * pass a supertype tandem to the parent constructor so that it won't try to register the item twice.
     * @returns {SupertypeTandem}
     */
    createSupertypeTandem: function() {
      return new SupertypeTandem( this.id );
    }
  }, {

    /**
     * In common code (sun, scenery-phet, etc), default tandems are created in the options hash to simplify
     * the logic (instead of being null).
     * @param {string} name - the name of the tandem
     * @returns {Tandem}
     */
    createDefaultTandem: function( name ) {
      if ( !defaultTandemMap.hasOwnProperty( name ) ) {
        defaultTandemMap[ name ] = 0;
      }

      // Name the tandems as derivedProperty0
      // OR: chargesAndFields.derivedProperty0
      var tandem = rootTandem.createTandem( name + '' + defaultTandemMap[ name ], {
        isDefaultTandem: true // for checking in validateTandems
      } );
      defaultTandemMap[ name ]++;
      return tandem;
    },

    /**
     * Adds a listener that will be notified when items are registered/deregistered
     * Listeners have the form
     * {
     *   addInstance(id,instance),
     *   removeInstance(id,instance)
     * }
     * where id is of type {string} and instance is of type {Object}
     *
     * @param {Object} instanceListener - described above
     * @public
     * @static
     */
    addInstanceListener: function( instanceListener ) {
      instanceListeners.push( instanceListener );
    },

    /**
     * Create a tandem based on the name of the running simulation.
     * @returns {Tandem}
     */
    createRootTandem: function() {
      return new Tandem( toCamelCase( packageJSON.name ) );
    },

    /**
     * Create a child of the root tandem.
     * @param {string} name
     * @returns {Tandem}
     */
    createStaticTandem: function( name ) {
      return Tandem.createRootTandem().createTandem( name, { static: true } );
    },

    /**
     * When the simulation is launched, all static instances are registered.
     */
    launch: function() {
      assert && assert( !launched, 'Tandem was launched twice' );
      launched = true;
      while ( staticInstances.length > 0 ) {
        var staticInstance = staticInstances.shift();
        staticInstance.tandem.addInstance( staticInstance.instance, staticInstance.type );
      }
    },

    /**
     * When running as phet-io, User Interface components must be registered with tandem.  This function checks the
     * options to make sure tandem exists.  See https://github.com/phetsims/phet-io/issues/77
     * @param options
     */
    validateOptions: function( options ) {

      // Check to see whether the tandem is "filled in" as opposed to being a default Tandem.createOptionalTandem one.
      if ( window.phet && window.phet.chipper && phet.chipper.brand === 'phet-io' && phet.chipper.queryParameters.phetioValidateTandems ) {
        assert && assert( options.tandem, 'tandem should be defined in common code components' );
        assert && assert( !options.tandem.isDefaultTandem, 'Default tandem instance cannot be used when running as PhET-iO' );
      }
    }
  } );

  var rootTandem = Tandem.createRootTandem();

  // Tandem checks for listeners added before the Tandem module was loaded.  This is necessary so that phetio.js can
  // receive notifications about items created during static initialization such as Solute.js
  // which is created before Sim.js runs.
  if ( window.tandemPreloadInstanceListeners ) {
    for ( var i = 0; i < window.tandemPreloadInstanceListeners.length; i++ ) {
      Tandem.addInstanceListener( window.tandemPreloadInstanceListeners[ i ] );
    }
  }

  /**
   * @param {string} id - id as a string (or '' for a root id)
   * @constructor
   * @private create with Tandem.createGroupTandem
   * Declared in the same file to avoid circular reference errors in module loading.
   */
  function GroupTandem( id ) {

    Tandem.call( this, id );

    // @private for generating indices from a pool
    this.groupElementIndex = 0;
  }

  tandemNamespace.register( 'Tandem.GroupTandem', GroupTandem );

  inherit( Tandem, GroupTandem, {

    createNextTandem: function() {
      return new Tandem( this.id + '_' + ( this.groupElementIndex++ ) );
    }
  } );

  /**
   * @param {string} id - id as a string (or '' for a root id)
   * @constructor
   * @private create with Tandem.createSupertypeTandem
   */
  function SupertypeTandem( id ) {
    Tandem.call( this, id );
  }

  tandemNamespace.register( 'Tandem.SupertypeTandem', SupertypeTandem );

  inherit( Tandem, SupertypeTandem, {

    // @public - Override to make no-op, see createSupertypeTandem
    addInstance: function( instance, type ) {},

    // @public - Override to make no-op, see createSupertypeTandem
    removeInstance: function( instance ) {}
  } );

  return Tandem;
} );

<commit_msg>added assert that checks the id<commit_after>// Copyright 2015, University of Colorado Boulder

/**
 * Tandem is a general instance registry that can be used to track creation/disposal of instances in PhET Simulations.
 * It is used for phetio.js instrumentation for PhET-iO support.
 *
 * @author Sam Reid (PhET Interactive Simulations)
 */
define( function( require ) {
  'use strict';

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

  // text
  var packageString = require( 'text!REPOSITORY/package.json' );

  // constants
  var packageJSON = JSON.parse( packageString );
  var defaultTandemMap = {}; // {string} => {number} Keep track of number of each type of default tandem

  // variables
  var launched = false;

  /**
   * @param {string} id - id as a string (or '' for a root id)
   * @param {Object} [options]
   * @constructor
   */
  function Tandem( id, options ) {

    options = _.extend( {
      static: false,
      isDefaultTandem: false,
      enabled: true
    }, options );

    // @public (read-only)
    this.id = ( id !== undefined ) ? id : '';

    // @private (read-only)
    this.static = options.static;
    this.isDefaultTandem = options.isDefaultTandem;
    this.enabled = options.enabled;
  }

  var staticInstances = [];

  tandemNamespace.register( 'Tandem', Tandem );

  // Listeners that will be notified when items are registered/deregistered
  var instanceListeners = [];

  inherit( Object, Tandem, {

    // @public (read-only) permit checking whether something is probably a Tandem instance for error checking
    isTandem: true,

    /**
     * Adds an instance of any type.  For example, it could be an axon Property, scenery Node or Sun button.  Each
     * item should only be added to the registry once, but that is not enforced here in Tandem.  For PhET-iO, phet-io.js
     * enforces one entry per ID in phetio.addInstance
     *
     * This is used to register instances with PhET-iO.
     * @param {Object} instance - the instance to add
     * @param {function} type - the PhET-iO type function, such as TString or TProperty(TNumber('volts'))
     * @public
     */
    addInstance: function( instance, type ) {

      if ( window.phet && window.phet.chipper && phet.chipper.brand === 'phet-io' && this.enabled ) {

        if ( !type ) {
          console.log( 'Missing type declaration for ' + this.id );
        }

        // ifphetio returns a no-op function, so to test whether a valid T wrapper type was passed, we search for the typeName
        assert && assert( type && type.typeName, 'type must be specified and have a typeName' );

        if ( this.static && !launched ) {
          staticInstances.push( { tandem: this, instance: instance, type: type } );
        }
        else {
          for ( var i = 0; i < instanceListeners.length; i++ ) {
            instanceListeners[ i ].addInstance( this.id, instance, type );
          }
        }
      }
    },

    /**
     * Removes an instance from the
     * @param {Object} instance - the instance to remove
     * @public
     */
    removeInstance: function( instance ) {

      // Only active when running as phet-io
      if ( phet.chipper.brand === 'phet-io' && this.enabled ) {
        for ( var i = 0; i < instanceListeners.length; i++ ) {
          instanceListeners[ i ].removeInstance( this.id, instance );
        }
      }
    },

    /**
     * Create a new Tandem by appending the given id
     * @param {string} id
     * @param {Object} [options]
     * @returns {Tandem}
     * @public
     */
    createTandem: function( id, options ) {
      assert && assert( typeof id === 'string' && id.length > 0, 'id must be defined' );
      var string = ( this.id.length > 0 ) ? ( this.id + '.' + id ) : id;

      // Any child of something static is also static
      options = _.extend( { static: this.static, enabled: this.enabled }, options );

      return new Tandem( string, options );
    },

    /**
     * Creates a group tandem for creating multiple indexed child tandems, such as:
     * sim.screen.model.electron_0
     * sim.screen.model.electron_1
     *
     * In this case, 'sim.screen.model.electron' is the group tandem id.
     *
     * Used for arrays, observable arrays, or when many elements of the same type are created and they do not otherwise
     * have unique identifiers.
     * @param id
     * @returns {GroupTandem}
     */
    createGroupTandem: function( id ) {

      // Unfortunately we must resort to globals here since loading through the namespace would create a cycle
      return new GroupTandem( this.id + '.' + id );
    },

    /**
     * Get the last part of the tandem (after the last .), used in Joist for creating button names dynamically based
     * on screen names
     * @return {string} the tail of the tandem
     */
    get tail() {
      assert && assert( this.id.indexOf( '.' ) >= 0, 'tandem ID does not have a tail' );

      var lastIndexOfDot = this.id.lastIndexOf( '.' );
      var tail = this.id.substring( lastIndexOfDot + 1 );
      assert && assert( tail.length > 0, 'tandem ID did not have a tail' );
      return tail;
    },

    /**
     * Returns a Tandem for everything except the tail.
     * @returns {Tandem}
     */
    get parentTandem() {
      assert && assert( this.id.indexOf( '.' ) >= 0, 'tandem ID does not have a tail' );

      var lastIndexOfDot = this.id.lastIndexOf( '.' );
      var headID = this.id.substring( 0, lastIndexOfDot );

      return new Tandem( headID, {
        static: this.static,
        isDefaultTandem: this.isDefaultTandem,
        enabled: this.enabled
      } );
    },

    /**
     * When using subtyping, the instance listeners must only be notified once rather than once for every level
     * in the inheritance hierarchy.  When a subtype constructor has a tandem.addInstance call, it should
     * pass a supertype tandem to the parent constructor so that it won't try to register the item twice.
     * @returns {SupertypeTandem}
     */
    createSupertypeTandem: function() {
      return new SupertypeTandem( this.id );
    }
  }, {

    /**
     * In common code (sun, scenery-phet, etc), default tandems are created in the options hash to simplify
     * the logic (instead of being null).
     * @param {string} name - the name of the tandem
     * @returns {Tandem}
     */
    createDefaultTandem: function( name ) {
      if ( !defaultTandemMap.hasOwnProperty( name ) ) {
        defaultTandemMap[ name ] = 0;
      }

      // Name the tandems as derivedProperty0
      // OR: chargesAndFields.derivedProperty0
      var tandem = rootTandem.createTandem( name + '' + defaultTandemMap[ name ], {
        isDefaultTandem: true // for checking in validateTandems
      } );
      defaultTandemMap[ name ]++;
      return tandem;
    },

    /**
     * Adds a listener that will be notified when items are registered/deregistered
     * Listeners have the form
     * {
     *   addInstance(id,instance),
     *   removeInstance(id,instance)
     * }
     * where id is of type {string} and instance is of type {Object}
     *
     * @param {Object} instanceListener - described above
     * @public
     * @static
     */
    addInstanceListener: function( instanceListener ) {
      instanceListeners.push( instanceListener );
    },

    /**
     * Create a tandem based on the name of the running simulation.
     * @returns {Tandem}
     */
    createRootTandem: function() {
      return new Tandem( toCamelCase( packageJSON.name ) );
    },

    /**
     * Create a child of the root tandem.
     * @param {string} name
     * @returns {Tandem}
     */
    createStaticTandem: function( name ) {
      return Tandem.createRootTandem().createTandem( name, { static: true } );
    },

    /**
     * When the simulation is launched, all static instances are registered.
     */
    launch: function() {
      assert && assert( !launched, 'Tandem was launched twice' );
      launched = true;
      while ( staticInstances.length > 0 ) {
        var staticInstance = staticInstances.shift();
        staticInstance.tandem.addInstance( staticInstance.instance, staticInstance.type );
      }
    },

    /**
     * When running as phet-io, User Interface components must be registered with tandem.  This function checks the
     * options to make sure tandem exists.  See https://github.com/phetsims/phet-io/issues/77
     * @param options
     */
    validateOptions: function( options ) {

      // Check to see whether the tandem is "filled in" as opposed to being a default Tandem.createOptionalTandem one.
      if ( window.phet && window.phet.chipper && phet.chipper.brand === 'phet-io' && phet.chipper.queryParameters.phetioValidateTandems ) {
        assert && assert( options.tandem, 'tandem should be defined in common code components' );
        assert && assert( !options.tandem.isDefaultTandem, 'Default tandem instance cannot be used when running as PhET-iO' );
      }
    }
  } );

  var rootTandem = Tandem.createRootTandem();

  // Tandem checks for listeners added before the Tandem module was loaded.  This is necessary so that phetio.js can
  // receive notifications about items created during static initialization such as Solute.js
  // which is created before Sim.js runs.
  if ( window.tandemPreloadInstanceListeners ) {
    for ( var i = 0; i < window.tandemPreloadInstanceListeners.length; i++ ) {
      Tandem.addInstanceListener( window.tandemPreloadInstanceListeners[ i ] );
    }
  }

  /**
   * @param {string} id - id as a string (or '' for a root id)
   * @constructor
   * @private create with Tandem.createGroupTandem
   * Declared in the same file to avoid circular reference errors in module loading.
   */
  function GroupTandem( id ) {

    Tandem.call( this, id );

    // @private for generating indices from a pool
    this.groupElementIndex = 0;
  }

  tandemNamespace.register( 'Tandem.GroupTandem', GroupTandem );

  inherit( Tandem, GroupTandem, {

    createNextTandem: function() {
      return new Tandem( this.id + '_' + ( this.groupElementIndex++ ) );
    }
  } );

  /**
   * @param {string} id - id as a string (or '' for a root id)
   * @constructor
   * @private create with Tandem.createSupertypeTandem
   */
  function SupertypeTandem( id ) {
    Tandem.call( this, id );
  }

  tandemNamespace.register( 'Tandem.SupertypeTandem', SupertypeTandem );

  inherit( Tandem, SupertypeTandem, {

    // @public - Override to make no-op, see createSupertypeTandem
    addInstance: function( instance, type ) {},

    // @public - Override to make no-op, see createSupertypeTandem
    removeInstance: function( instance ) {}
  } );

  return Tandem;
} );

<|endoftext|>


<commit_before>//takes the value of a select-option (form: "Resolution [id]: [topic]/[name]") as an argument and return the id
function getId(txt) {
    var result = "";

   	var writing = false;

    for (i = 0; i < txt.length; i++) {
        if (!writing) {
            if (txt.charAt(i) == ' ')
                writing = true;
        } else {
            if (txt.charAt(i) == ' ')
                break;
            else
                result += txt.charAt(i);
        }
    }

    return parseInt(result);
}

function uploadDateAndTime(id) {
    var resolutionRef = firebase.database().ref().child("metadata").child(id.toString()).child("uploaded");

    var currentDate = new Date();
    var dateAndTime = "";

    var day = currentDate.getDay();

    //translate the day from a number to a string
    if (day == 0) {
        dateAndTime += "Sun, ";
    } else if (day == 1) {
        dateAndTime += "Mon, ";
    } else if (day == 2) {
        dateAndTime += "Tue, ";
    } else if (day == 3) {
        dateAndTime += "Wed, ";
    } else if(day == 4) {
        dateAndTime += "Thu, ";
    } else if(day == 5) {
        dateAndTime += "Fri, ";
    } else {
        dateAndTime += "Sat, ";
    }

    //se the time
    dateAndTime += currentDate.getHours() + ':' + currentDate.getMinutes() + ":" + currentDate.getSeconds();

    resolutionRef.set(dateAndTime);
}

function addChild(name, id, listName) {
    var list = document.getElementById(listName);
    var item = document.createElement("option");

    if (id == -1)
    	item.text += "ID [not registered]: ";
    else
    	item.text += "ID " + id.toString();

    item.text += ": " + name;
    list.add(item);
}

function changeChild(name, index, id, listName) {
    var list = document.getElementById(listName);
    var item = document.createElement("option");

    if (id == -1)
    	item.text += "ID [not registered]";
    else
    	item.text += "ID " + id.toString();

    item.text += ": " + name;

    list.remove(index);
    list.add(item, index);
}

function removeChild(index, listName) {
    var list = document.getElementById(listName);
    list.remove(index);
}

//listen for changes to the children of "reference" and update "resList" accordingly
//TODO: find another way of getting the resolutions
function listen(reference, topic, listName) {
    //add an item to list when a child is added to the database
    reference.on('child_added', function(childSnapshot, prevChildKey) {
        if (prevChildKey == null)
            prevChildKey = "0";

        var id = -1;

        firebase.database().ref().child("D").child(parseInt(childSnapshot.key)).child("n").once("value", function(snapshot) {
        	if (snapshot.exists())
        		id = parseInt(snapshot.val());

            addChild(topic + '/' + childSnapshot.val(), id, listName);
        });
    });

    //change an item's text when the value of the corresponding child is changed in the database
    reference.on('child_changed', function(childSnapshot, prevChildKey) {
        if (prevChildKey == null)
            prevChildKey = "0";

        var id = -1;

        firebase.database().ref().child("D").child(parseInt(childSnapshot.key)).child("n").once("value", function(snapshot) {
        	if (snapshot.exists())
        		id = parseInt(snapshot.key);

            changeChild(topic + '/' + childSnapshot.val(), parseInt(childSnapshot.key) -1, id, listName);
        });
    });

    //remove an item when the corresponding child is removed from the database
    reference.on('child_removed', function(oldChildSnapshot) {
        removeChild(parseInt(oldChildSnapshot.key-1), listName);
    });
}

function init() {
    var currentCommittee = "null";

    //hide the debateMsg
    document.getElementById("debateMsg").style.visibility = "hidden";

    //reset the upload elements
    document.getElementById("fileChooser").value = "";
    document.getElementById("resName").value = "";
    document.getElementById("topicView").selectedIndex = 0;
    document.getElementById("resList").selectedIndex = 0;
    document.getElementById("resList2").selectedIndex = 0;

    //set the title and subtitle of the site
    //TODO: set studen officers and remove this variable
    var studentOfficer = "[tbd] - Student officer";

    //add listener to the logout button
    document.getElementById("logout_link").onclick = function () {
    	firebase.auth().signOut();
    	document.location.href = "index.html";

    	//make sure the default link behaviour isn't followed
    	return false;
    };

    var fired = false;
    firebase.auth().onAuthStateChanged(firebaseUser => {
        if (!fired) {
            fired = true;

            var email = firebaseUser.email;

            if (email == "political@dsamun.com") {
                //TODO: set student officer
                document.getElementById("studentOfficer_text").innerHTML = studentOfficer;
                document.getElementById("committee_text").innerHTML = "Special Political and Decolonization Committee";
                currentCommittee = "political";
            } else if (email == "disarmament@dsamun.com") {
                //TODO: set student officer
                document.getElementById("studentOfficer_text").innerHTML = studentOfficer;
                document.getElementById("committee_text").innerHTML = "Disarmament and International Security Commitee";
                currentCommittee = "disarmament";
            } else if (email == "humanitarian@dsamun.com") {
                //TODO: set student officer
                document.getElementById("studentOfficer_text").innerHTML = studentOfficer;
                document.getElementById("committee_text").innerHTML = "Social, Humanitarian and Cultural Committee";
                currentCommittee = "humanitarian";
            } else if (email == "environmental@dsamun.com") {
                //TODO: set student officer
                document.getElementById("studentOfficer_text").innerHTML = studentOfficer;
                document.getElementById("committee_text").innerHTML = "Environmental Committee";
                currentCommittee = "environmental";
            }
        }

        const resolutionRef = firebase.database().ref().child('resolutions').child(currentCommittee);

        listen(resolutionRef.child("topic 1"), "topic 1", "resList");
        listen(resolutionRef.child("topic 2"), "topic 2", "resList");
        listen(resolutionRef.child("topic 3"), "topic 3", "resList");
        listen(resolutionRef.child("topic 4"), "topic 4", "resList");

        listen(resolutionRef.child("topic 1"), "topic 1", "resList2");
        listen(resolutionRef.child("topic 2"), "topic 2", "resList2");
        listen(resolutionRef.child("topic 3"), "topic 3", "resList2");
        listen(resolutionRef.child("topic 4"), "topic 4", "resList2");
    });

    //hide the msg_text message
    document.getElementById("msg_text").style.visibility = "hidden";

    var fileChooser = document.getElementById("fileChooser");
    var resName = document.getElementById("resName");
    var topicView = document.getElementById("topicView");

    var file = null;

    //set listener on the filechooser
    fileChooser.addEventListener('change', function(e) {
        //get file
        file = e.target.files[0];
    });

    //add listener to the "upload" button
    var upload_link = document.getElementById("upload_link");
    upload_link.onclick = function() {
        if (currentCommittee != "null") {
            //hide the successfule_text message
            document.getElementById("msg_text").style.visibility = "hidden";

            if (resName.value == "") {
                alert("You must choose a name for the resolution");
            } else if (file == null) {
                alert("You must choose a file to upload");
            } else if (topicView.selectedIndex == -1 || topicView.options[topicView.selectedIndex].text == "- Topic -") {
                alert("You must choose a topic");
            } else {
                //Get the selected topic
                var topic = topicView.options[topicView.selectedIndex].text;

                var storageRef = firebase.storage().ref("resolutions/" + currentCommittee + "/" + topic + "/" + resName.value);

                //upload file
                var uploadTask = storageRef.put(file);

                //handle the file upload
                uploadTask.on('state_changed',

                    function progress(snapshot) {},

                    function error(err) {
                        alert("An error occurred while uploading the file");
                    },

                    function complete() {
                        //make the msg_text message visible
                        document.getElementById("msg_text").style.visibility = "visible";

                        //add the resolution to the realtime database
                        var rootRef = firebase.database().ref();
                        var counterRef = rootRef.child('counter');

                        var counter;

                        //boolean to make sure the code doesn't execute every time the counter changes
                        var read = false;

                        //get the value of the counter
                        counterRef.on('value', function(snapshot) {
                            if (!read) {
                                read = true;

                                counter = parseInt(snapshot.val()) + 1;

                                //create the new resolution-reference
                                var databaseRef = firebase.database().ref().child('resolutions').child(currentCommittee).child(topic).child(counter.toString());

                                //set the name of the new resolution
                                databaseRef.set(resName.value);

                                //add the resolution metadata to the realtime database
                                uploadDateAndTime(counter, "uploaded");

                                //update the counter
                                counterRef.set(counter.toString());
                            }
                        });
                    }
                );
            }
        } else {
            alert("An error occurred while uploading resolution");
        }

        //make sure the default link behaviour doesn't happen
        return false;
    }

    //add listener to the "check" button
    document.getElementById("check_link").onclick = function() {
    	document.getElementById("uploaded_txt").innerHTML = "";
    	document.getElementById("archived_txt").innerHTML = "";
		document.getElementById("approoval_txt").innerHTML = "";
		document.getElementById("aNumber_txt").innerHTML = "";
		document.getElementById("debate_txt").innerHTML = "";

        var resList = document.getElementById("resList");

        if (resList.selectedIndex != -1) {
        	var id = getId(resList.options[resList.selectedIndex].text);

            var metaReference = firebase.database().ref().child("metadata").child(id);

            var uploadedRef = metaReference.child("uploaded");
            var registeredRef = metaReference.child("registered");
            var aPanelRef = metaReference.child("aPanel");
            var aNumberRef = metaReference.child("aNumber");
            var debateRef = metaReference.child("debate");

            uploadedRef.once("value", function (snapshot) {
            	if (snapshot.exists())
            		document.getElementById("uploaded_txt").innerHTML = snapshot.val();
            });

            registeredRef.once("value", function (snapshot) {
            	if (snapshot.exists())
            		document.getElementById("archived_txt").innerHTML = snapshot.val();

            });

            firebase.database().ref().child("D").child(id).child("n").once("value", function (snapshot) {
            	if (snapshot.exists())
                	document.getElementById("id_txt").innerHTML = snapshot.val().toString();
	        	else
	        		document.getElementById("id_txt").innerHTML = "Resolution not yet registered";

            });

            aPanelRef.once("value", function (snapshot) {
            	if (snapshot.exists())
            		document.getElementById("approoval_txt").innerHTML = snapshot.val();
            });

            aNumberRef.once("value", function (snapshot) {
            	if (snapshot.exists())
            		document.getElementById("aNumber_txt").innerHTML = snapshot.val();
            });

            debateRef.once("value", function(snapshot) {
            	if (snapshot.exists())
            		document.getElementById("debate_txt").innerHTML = snapshot.val();
            });

        } else {
            alert("You must choose a resolution to check");
        }

        return false;
    };

    //add listener to the "submit" button
    document.getElementById("debateSubmit_link").onclick = function () {
        //hide the debateMsg
        document.getElementById("debateMsg").style.visibility = "hidden";

    	var debatePassed_radio= document.getElementById("debatePassed_radio");
    	var resList2 = document.getElementById("resList2");

    	//make sure an item is selected
    	if (resList2.selectedIndex != -1) {
	        var metaReference = firebase.database().ref().child("metadata").child(getId(resList2.options[resList2.selectedIndex].text));
	        //check if the resolution already has a debate status
	        metaReference.once('value', function(snapshot) {
	        	if (snapshot.hasChild("debate")) {
	        	    //make the dabteMsg visible
	        	    document.getElementById("debateMsg").style.visibility = "visible";
	        	} else {
	        		var debateReference = metaReference.child("debate");

	    	        if (debatePassed_radio.checked == true) {
	    	    		debateReference.set("passed");
	    	    	} else {
	    	    		debateReference.set("failed");
	    	    	}
	        	}
	        });

    	} else {
    		alert("You must choose a resolution to update its debate status");
    	}

    	return false;
    };
}

window.onload = init;
<commit_msg>changed the way the resolutions are shown and ordered in the select boxes on chair.html. They are now classified by ther registration id.<commit_after>//takes the value of a select-option (form: "Resolution [id]: [topic]/[name]") as an argument and return the id
function getId(txt) {
    var result = "";

   	var writing = false;

    for (i = 0; i < txt.length; i++) {
        if (!writing) {
            if (txt.charAt(i) == ' ')
                writing = true;
        } else {
            if (txt.charAt(i) == ' ')
                break;
            else
                result += txt.charAt(i);
        }
    }

    return parseInt(result);
}

function uploadDateAndTime(id) {
    var resolutionRef = firebase.database().ref().child("metadata").child(id.toString()).child("uploaded");

    var currentDate = new Date();
    var dateAndTime = "";

    var day = currentDate.getDay();

    //translate the day from a number to a string
    if (day == 0) {
        dateAndTime += "Sun, ";
    } else if (day == 1) {
        dateAndTime += "Mon, ";
    } else if (day == 2) {
        dateAndTime += "Tue, ";
    } else if (day == 3) {
        dateAndTime += "Wed, ";
    } else if(day == 4) {
        dateAndTime += "Thu, ";
    } else if(day == 5) {
        dateAndTime += "Fri, ";
    } else {
        dateAndTime += "Sat, ";
    }

    //se the time
    dateAndTime += currentDate.getHours() + ':' + currentDate.getMinutes() + ":" + currentDate.getSeconds();

    resolutionRef.set(dateAndTime);
}

var notRegistered = 0;

function addChild(name, id, listName) {
    var list = document.getElementById(listName);
    var item = document.createElement("option");

    if (id == -1) {
    	item.text += "ID [not registered]";
    	notRegistered++;
    	id = 1 - notRegistered;
    } else
    	item.text += "ID " + id.toString();

    item.text += ": " + name;
    list.add(item, id -1 + notRegistered);
}

var notRegistered2 = 0;

function changeChild(name, id, listName) {
    var list = document.getElementById(listName);
    var item = document.createElement("option");

    if (id == -1) {
    	item.text += "ID [not registered]";
		notRegistered2++;
		id = 1 - notRegistered2;
    } else
    	item.text += "ID " + id.toString();

    item.text += ": " + name;

    list.remove(index);
    list.add(item, id -1 + notRegistered2);
}

//listen for changes to the children of "reference" and update "resList" accordingly
//TODO: find another way of getting the resolutions
function listen(reference, topic, listName) {
    //add an item to list when a child is added to the database
    reference.on('child_added', function(childSnapshot, prevChildKey) {
        if (prevChildKey == null)
            prevChildKey = "0";

        var id = -1;

        firebase.database().ref().child("D").child(parseInt(childSnapshot.key)).child("n").once("value", function(snapshot) {
        	if (snapshot.exists())
        		id = parseInt(snapshot.val());

            addChild(topic + '/' + childSnapshot.val(), id, listName);
        });
    });

    //change an item's text when the value of the corresponding child is changed in the database
    reference.on('child_changed', function(childSnapshot, prevChildKey) {
        if (prevChildKey == null)
            prevChildKey = "0";

        var id = -1;

        firebase.database().ref().child("D").child(parseInt(childSnapshot.key)).child("n").once("value", function(snapshot) {
        	if (snapshot.exists())
        		id = parseInt(snapshot.key);

            changeChild(topic + '/' + childSnapshot.val(), id, listName);
        });
    });
}

function init() {
    var currentCommittee = "null";

    //hide the debateMsg
    document.getElementById("debateMsg").style.visibility = "hidden";

    //reset the upload elements
    document.getElementById("fileChooser").value = "";
    document.getElementById("resName").value = "";
    document.getElementById("topicView").selectedIndex = 0;
    document.getElementById("resList").selectedIndex = 0;
    document.getElementById("resList2").selectedIndex = 0;

    //set the title and subtitle of the site
    //TODO: set studen officers and remove this variable
    var studentOfficer = "[tbd] - Student officer";

    //add listener to the logout button
    document.getElementById("logout_link").onclick = function () {
    	firebase.auth().signOut();
    	document.location.href = "index.html";

    	//make sure the default link behaviour isn't followed
    	return false;
    };

    var fired = false;
    firebase.auth().onAuthStateChanged(firebaseUser => {
        if (!fired) {
            fired = true;

            var email = firebaseUser.email;

            if (email == "political@dsamun.com") {
                //TODO: set student officer
                document.getElementById("studentOfficer_text").innerHTML = studentOfficer;
                document.getElementById("committee_text").innerHTML = "Special Political and Decolonization Committee";
                currentCommittee = "political";
            } else if (email == "disarmament@dsamun.com") {
                //TODO: set student officer
                document.getElementById("studentOfficer_text").innerHTML = studentOfficer;
                document.getElementById("committee_text").innerHTML = "Disarmament and International Security Commitee";
                currentCommittee = "disarmament";
            } else if (email == "humanitarian@dsamun.com") {
                //TODO: set student officer
                document.getElementById("studentOfficer_text").innerHTML = studentOfficer;
                document.getElementById("committee_text").innerHTML = "Social, Humanitarian and Cultural Committee";
                currentCommittee = "humanitarian";
            } else if (email == "environmental@dsamun.com") {
                //TODO: set student officer
                document.getElementById("studentOfficer_text").innerHTML = studentOfficer;
                document.getElementById("committee_text").innerHTML = "Environmental Committee";
                currentCommittee = "environmental";
            }
        }

        const resolutionRef = firebase.database().ref().child('resolutions').child(currentCommittee);

        listen(resolutionRef.child("topic 1"), "topic 1", "resList");
        listen(resolutionRef.child("topic 2"), "topic 2", "resList");
        listen(resolutionRef.child("topic 3"), "topic 3", "resList");
        listen(resolutionRef.child("topic 4"), "topic 4", "resList");

        listen(resolutionRef.child("topic 1"), "topic 1", "resList2");
        listen(resolutionRef.child("topic 2"), "topic 2", "resList2");
        listen(resolutionRef.child("topic 3"), "topic 3", "resList2");
        listen(resolutionRef.child("topic 4"), "topic 4", "resList2");
    });

    //hide the msg_text message
    document.getElementById("msg_text").style.visibility = "hidden";

    var fileChooser = document.getElementById("fileChooser");
    var resName = document.getElementById("resName");
    var topicView = document.getElementById("topicView");

    var file = null;

    //set listener on the filechooser
    fileChooser.addEventListener('change', function(e) {
        //get file
        file = e.target.files[0];
    });

    //add listener to the "upload" button
    var upload_link = document.getElementById("upload_link");
    upload_link.onclick = function() {
        if (currentCommittee != "null") {
            //hide the successfule_text message
            document.getElementById("msg_text").style.visibility = "hidden";

            if (resName.value == "") {
                alert("You must choose a name for the resolution");
            } else if (file == null) {
                alert("You must choose a file to upload");
            } else if (topicView.selectedIndex == -1 || topicView.options[topicView.selectedIndex].text == "- Topic -") {
                alert("You must choose a topic");
            } else {
                //Get the selected topic
                var topic = topicView.options[topicView.selectedIndex].text;

                var storageRef = firebase.storage().ref("resolutions/" + currentCommittee + "/" + topic + "/" + resName.value);

                //upload file
                var uploadTask = storageRef.put(file);

                //handle the file upload
                uploadTask.on('state_changed',

                    function progress(snapshot) {},

                    function error(err) {
                        alert("An error occurred while uploading the file");
                    },

                    function complete() {
                        //make the msg_text message visible
                        document.getElementById("msg_text").style.visibility = "visible";

                        //add the resolution to the realtime database
                        var rootRef = firebase.database().ref();
                        var counterRef = rootRef.child('counter');

                        var counter;

                        //boolean to make sure the code doesn't execute every time the counter changes
                        var read = false;

                        //get the value of the counter
                        counterRef.on('value', function(snapshot) {
                            if (!read) {
                                read = true;

                                counter = parseInt(snapshot.val()) + 1;

                                //create the new resolution-reference
                                var databaseRef = firebase.database().ref().child('resolutions').child(currentCommittee).child(topic).child(counter.toString());

                                //set the name of the new resolution
                                databaseRef.set(resName.value);

                                //add the resolution metadata to the realtime database
                                uploadDateAndTime(counter, "uploaded");

                                //update the counter
                                counterRef.set(counter.toString());
                            }
                        });
                    }
                );
            }
        } else {
            alert("An error occurred while uploading resolution");
        }

        //make sure the default link behaviour doesn't happen
        return false;
    }

    //add listener to the "check" button
    document.getElementById("check_link").onclick = function() {
    	document.getElementById("uploaded_txt").innerHTML = "";
    	document.getElementById("archived_txt").innerHTML = "";
		document.getElementById("approoval_txt").innerHTML = "";
		document.getElementById("aNumber_txt").innerHTML = "";
		document.getElementById("debate_txt").innerHTML = "";

        var resList = document.getElementById("resList");

        if (resList.selectedIndex != -1) {
        	var id = getId(resList.options[resList.selectedIndex].text);

            var metaReference = firebase.database().ref().child("metadata").child(id);

            var uploadedRef = metaReference.child("uploaded");
            var registeredRef = metaReference.child("registered");
            var aPanelRef = metaReference.child("aPanel");
            var aNumberRef = metaReference.child("aNumber");
            var debateRef = metaReference.child("debate");

            uploadedRef.once("value", function (snapshot) {
            	if (snapshot.exists())
            		document.getElementById("uploaded_txt").innerHTML = snapshot.val();
            });

            registeredRef.once("value", function (snapshot) {
            	if (snapshot.exists())
            		document.getElementById("archived_txt").innerHTML = snapshot.val();

            });

            firebase.database().ref().child("D").child(id).child("n").once("value", function (snapshot) {
            	if (snapshot.exists())
                	document.getElementById("id_txt").innerHTML = snapshot.val().toString();
	        	else
	        		document.getElementById("id_txt").innerHTML = "Resolution not yet registered";

            });

            aPanelRef.once("value", function (snapshot) {
            	if (snapshot.exists())
            		document.getElementById("approoval_txt").innerHTML = snapshot.val();
            });

            aNumberRef.once("value", function (snapshot) {
            	if (snapshot.exists())
            		document.getElementById("aNumber_txt").innerHTML = snapshot.val();
            });

            debateRef.once("value", function(snapshot) {
            	if (snapshot.exists())
            		document.getElementById("debate_txt").innerHTML = snapshot.val();
            });

        } else {
            alert("You must choose a resolution to check");
        }

        return false;
    };

    //add listener to the "submit" button
    document.getElementById("debateSubmit_link").onclick = function () {
        //hide the debateMsg
        document.getElementById("debateMsg").style.visibility = "hidden";

    	var debatePassed_radio= document.getElementById("debatePassed_radio");
    	var resList2 = document.getElementById("resList2");

    	//make sure an item is selected
    	if (resList2.selectedIndex != -1) {
	        var metaReference = firebase.database().ref().child("metadata").child(getId(resList2.options[resList2.selectedIndex].text));
	        //check if the resolution already has a debate status
	        metaReference.once('value', function(snapshot) {
	        	if (snapshot.hasChild("debate")) {
	        	    //make the dabteMsg visible
	        	    document.getElementById("debateMsg").style.visibility = "visible";
	        	} else {
	        		var debateReference = metaReference.child("debate");

	    	        if (debatePassed_radio.checked == true) {
	    	    		debateReference.set("passed");
	    	    	} else {
	    	    		debateReference.set("failed");
	    	    	}
	        	}
	        });

    	} else {
    		alert("You must choose a resolution to update its debate status");
    	}

    	return false;
    };
}

window.onload = init;
<|endoftext|>


<commit_before>/*!
 * jQuery UI Touch Punch 0.2.3
 *
 * Copyright 2011–2014, Dave Furfero
 * Dual licensed under the MIT or GPL Version 2 licenses.
 *
 * Depends:
 *  jquery.ui.widget.js
 *  jquery.ui.mouse.js
 */
define([], function() {
	!function(a){function f(a,b){if(!(a.originalEvent.touches.length>1)){a.preventDefault();var c=a.originalEvent.changedTouches[0],d=document.createEvent("MouseEvents");d.initMouseEvent(b,!0,!0,window,1,c.screenX,c.screenY,c.clientX,c.clientY,!1,!1,!1,!1,0,null),a.target.dispatchEvent(d)}}if(a.support.touch="ontouchend"in document,a.support.touch){var e,b=a.ui.mouse.prototype,c=b._mouseInit,d=b._mouseDestroy;b._touchStart=function(a){var b=this;!e&&b._mouseCapture(a.originalEvent.changedTouches[0])&&(e=!0,b._touchMoved=!1,f(a,"mouseover"),f(a,"mousemove"),f(a,"mousedown"))},b._touchMove=function(a){e&&(this._touchMoved=!0,f(a,"mousemove"))},b._touchEnd=function(a){e&&(f(a,"mouseup"),f(a,"mouseout"),this._touchMoved||f(a,"click"),e=!1)},b._mouseInit=function(){var b=this;b.element.bind({touchstart:a.proxy(b,"_touchStart"),touchmove:a.proxy(b,"_touchMove"),touchend:a.proxy(b,"_touchEnd")}),c.call(b)},b._mouseDestroy=function(){var b=this;b.element.unbind({touchstart:a.proxy(b,"_touchStart"),touchmove:a.proxy(b,"_touchMove"),touchend:a.proxy(b,"_touchEnd")}),d.call(b)}}}(jQuery);
});<commit_msg>Revert "Modified touchpunch library to allow for build optimization"<commit_after>/*!
 * jQuery UI Touch Punch 0.2.3
 *
 * Copyright 2011–2014, Dave Furfero
 * Dual licensed under the MIT or GPL Version 2 licenses.
 *
 * Depends:
 *  jquery.ui.widget.js
 *  jquery.ui.mouse.js
 */
!function(a){function f(a,b){if(!(a.originalEvent.touches.length>1)){a.preventDefault();var c=a.originalEvent.changedTouches[0],d=document.createEvent("MouseEvents");d.initMouseEvent(b,!0,!0,window,1,c.screenX,c.screenY,c.clientX,c.clientY,!1,!1,!1,!1,0,null),a.target.dispatchEvent(d)}}if(a.support.touch="ontouchend"in document,a.support.touch){var e,b=a.ui.mouse.prototype,c=b._mouseInit,d=b._mouseDestroy;b._touchStart=function(a){var b=this;!e&&b._mouseCapture(a.originalEvent.changedTouches[0])&&(e=!0,b._touchMoved=!1,f(a,"mouseover"),f(a,"mousemove"),f(a,"mousedown"))},b._touchMove=function(a){e&&(this._touchMoved=!0,f(a,"mousemove"))},b._touchEnd=function(a){e&&(f(a,"mouseup"),f(a,"mouseout"),this._touchMoved||f(a,"click"),e=!1)},b._mouseInit=function(){var b=this;b.element.bind({touchstart:a.proxy(b,"_touchStart"),touchmove:a.proxy(b,"_touchMove"),touchend:a.proxy(b,"_touchEnd")}),c.call(b)},b._mouseDestroy=function(){var b=this;b.element.unbind({touchstart:a.proxy(b,"_touchStart"),touchmove:a.proxy(b,"_touchMove"),touchend:a.proxy(b,"_touchEnd")}),d.call(b)}}}(jQuery);<|endoftext|>


<commit_before>angular
.module('app', [], function($routeProvider, $locationProvider) {
  $locationProvider.html5Mode(true);

  $routeProvider
    .when('/', {
      templateUrl: '/partials/create.html',
      controller: CreateCtrl
    })
    .when('/q/:qid', {
      templateUrl: '/partials/q.html',
      controller: QCtrl
    })
    ;
})
.factory('ws', function($rootScope) {
  var id = localStorage.id || (localStorage.id = (Math.random() * 1e9 | 0).toString(16));
  var name = localStorage.name;
  var room = location.pathname.split('/').pop();
  var ws = eio('ws://' + location.host, { query: { id: id, name: name, room: room }});
  ws.msg = new eio.Emitter;
  ws.on('message', function(msg) {
    var data = JSON.parse(msg);
    ws.msg.emit(data.name, data.args);
    $rootScope.$apply();
  });
  ws.json = function() {
    var args = Array.prototype.slice.call(arguments);
    ws.send(JSON.stringify(args));
  };
  return ws;
})
;

function CreateCtrl($scope, $http, $location) {
  $scope.type = 'draft';
  $scope.seats = 8;

  $scope.sets = [
    'Alara Reborn',
    'Alliances',
    'Antiquities',
    'Apocalypse',
    'Arabian Nights',
    'Avacyn Restored',
    'Betrayers of Kamigawa',
    'Champions of Kamigawa',
    'Chronicles',
    'Classic Sixth Edition',
    'Coldsnap',
    'Conflux',
    'Dark Ascension',
    'Darksteel',
    'Dissension',
    'Dragon\'s Maze',
    'Eighth Edition',
    'Eventide',
    'Exodus',
    'Fallen Empires',
    'Fifth Dawn',
    'Fifth Edition',
    'Fourth Edition',
    'Future Sight',
    'Gatecrash',
    'Guildpact',
    'Homelands',
    'Ice Age',
    'Innistrad',
    'Invasion',
    'Judgment',
    'Legends',
    'Legions',
    'Limited Edition Alpha',
    'Limited Edition Beta',
    'Lorwyn',
    'Magic 2010',
    'Magic 2011',
    'Magic 2012',
    'Magic 2013',
    'Mercadian Masques',
    'Mirage',
    'Mirrodin',
    'Mirrodin Besieged',
    'Modern Masters',
    'Morningtide',
    'Nemesis',
    'New Phyrexia',
    'Ninth Edition',
    'Odyssey',
    'Onslaught',
    'Planar Chaos',
    'Planeshift',
    'Portal',
    'Portal Second Age',
    'Portal Three Kingdoms',
    'Prophecy',
    'Ravnica: City of Guilds',
    'Return to Ravnica',
    'Revised Edition',
    'Rise of the Eldrazi',
    'Saviors of Kamigawa',
    'Scars of Mirrodin',
    'Scourge',
    'Seventh Edition',
    'Shadowmoor',
    'Shards of Alara',
    'Starter 1999',
    'Starter 2000',
    'Stronghold',
    'Tempest',
    'Tenth Edition',
    'The Dark',
    'Time Spiral',
    'Torment',
    'Unglued',
    'Unhinged',
    'Unlimited Edition',
    'Urza\'s Destiny',
    'Urza\'s Legacy',
    'Urza\'s Saga',
    'Visions',
    'Weatherlight',
    'Worldwake',
    'Zendikar'
  ];

  $scope.set1 = "Dragon's Maze";
  $scope.set2 = 'Gatecrash';
  $scope.set3 = 'Return to Ravnica';
  $scope.set4 = "Dragon's Maze";
  $scope.set5 = 'Gatecrash';
  $scope.set6 = 'Return to Ravnica';
  $scope.create = function() {
    var id = localStorage.id || (localStorage.id = (Math.floor(Math.random() * 9e9)).toString(16));
    var data = {
      type: $scope.type, seats: $scope.seats, host: id
    };
    switch(data.type) {
      case 'draft':
        data.sets = [$scope.set1, $scope.set2, $scope.set3];
        break;
      case 'sealed':
        data.sets = [$scope.set1, $scope.set2, $scope.set3, $scope.set4, $scope.set5, $scope.set6];
        break;
      case 'cube':
        var cube = $scope.cube;
        if (cube)
          var match = cube.match(/([^/]+)\/?$/);
        if (!match)
          return alert('which cube are you drafting?');
        data.cube = $scope.cube = match[1];
    }
    $http.post('/create', data)
      .success(function(qid, status) {
        $location.path('/q/' + qid);
      })
      ;
  };
}

function QCtrl($scope, $timeout, $http, $routeParams, ws) {
  var selected = null
  var audio = document.querySelector('audio');

  document.getElementById('chat').style.display = 'none';
  $scope.addBots = true;
  $scope.beep = 'never';
  $scope.order = 'color';
  $scope.main = [];
  $scope.side = [];
  $scope.jank = [];
  $scope.land = [
  { land: true, cmc: 0, color: 'L', url: 'http://gatherer.wizards.com/Handlers/Image.ashx?type=card&multiverseid=73946', name: 'Forest'   },
  { land: true, cmc: 0, color: 'L', url: 'http://gatherer.wizards.com/Handlers/Image.ashx?type=card&multiverseid=73951', name: 'Island'   },
  { land: true, cmc: 0, color: 'L', url: 'http://gatherer.wizards.com/Handlers/Image.ashx?type=card&multiverseid=73958', name: 'Mountain' },
  { land: true, cmc: 0, color: 'L', url: 'http://gatherer.wizards.com/Handlers/Image.ashx?type=card&multiverseid=73963', name: 'Plains'   },
  { land: true, cmc: 0, color: 'L', url: 'http://gatherer.wizards.com/Handlers/Image.ashx?type=card&multiverseid=73973', name: 'Swamp'    }
  ];

  function decrement() {
    angular.forEach($scope.players, function(player) {
      if (player.time)
        --player.time;
    });
    $timeout(decrement, 1000);
  }

  $timeout(decrement, 1000);

  ws.on('open', function() {
    console.log('open');
  });
  ws.on('error', function(error) {
    console.log(error);
  });
  ws.on('close', function() {
    console.log('close');
  });

  var msg = ws.msg;
  msg.on('error', function(error) {
    $scope.error = error;
  });
  msg.on('set', function(data) {
    angular.extend($scope, data);

    if (!(data.pack && data.pack.length)) return;
    var d = document;
    var hidden = d.hidden || d.webkitHidden;
    switch ($scope.beep) {
      case 'if tab is hidden': if (!hidden) return;
      case 'always': audio.play();
    }
  });
  msg.on('add', function(card) {
    $scope.main.push(card);
  });

  $scope.pick = function(index) {
    if (selected !== index) {
      selected = index
      return
    }
    ws.json('pick', index);
    $scope.pack = null;
    selected = null;
  };
  $scope.editName = function(p, index) {
    if ($scope.self === index)
      p.edit = true;
  };
  $scope.name = function(p) {
    p.edit = false;
    name = p.name.slice(0, 15);
    ws.json('name', name);
    localStorage.name = name;
  };
  $scope.fromMain = function(card, e) {
    var main = $scope.main;
    main.splice(main.indexOf(card), 1);
    if (card.land) return;
    if (e.shiftKey)
      $scope.jank.push(card);
    else
      $scope.side.push(card);
  };
  $scope.fromSide = function(card, e) {
    var side = $scope.side;
    side.splice(side.indexOf(card), 1);
    if (card.land) return;
    if (e.shiftKey)
      $scope.jank.push(card);
    else
      $scope.main.push(card);
  };
  $scope.fromJank = function(card, e) {
    var jank = $scope.jank;
    jank.splice(jank.indexOf(card), 1);
    if (e.shiftKey)
      $scope.main.push(card);
    else
      $scope.side.push(card);
  };
  $scope.addLand = function(card, e) {
    if (e.shiftKey)
      $scope.side.push(card);
    else
      $scope.main.push(card);
  };
  $scope.generateDeck = function() {
    var main = {}
      , side = {}
      , deck
      ;
    angular.forEach($scope.main, function(card) {
      var name = card.name;
      main[name] || (main[name] = 0);
      main[name] += 1;
    });
    angular.forEach($scope.side, function(card) {
      var name = card.name;
      side[name] || (side[name] = 0);
      side[name] += 1;
    });
    deck = {
      main: main,
      side: side
    };
    $scope.deckJSON = JSON.stringify(deck);
    ws.json('hash', deck);
  };
  $scope.start = function() {
    if (!$scope.isHost) return;
    $scope.round = 1;
    ws.json('start', $scope.addBots);
  };
}
<commit_msg>add 5 basics to side<commit_after>angular
.module('app', [], function($routeProvider, $locationProvider) {
  $locationProvider.html5Mode(true);

  $routeProvider
    .when('/', {
      templateUrl: '/partials/create.html',
      controller: CreateCtrl
    })
    .when('/q/:qid', {
      templateUrl: '/partials/q.html',
      controller: QCtrl
    })
    ;
})
.factory('ws', function($rootScope) {
  var id = localStorage.id || (localStorage.id = (Math.random() * 1e9 | 0).toString(16));
  var name = localStorage.name;
  var room = location.pathname.split('/').pop();
  var ws = eio('ws://' + location.host, { query: { id: id, name: name, room: room }});
  ws.msg = new eio.Emitter;
  ws.on('message', function(msg) {
    var data = JSON.parse(msg);
    ws.msg.emit(data.name, data.args);
    $rootScope.$apply();
  });
  ws.json = function() {
    var args = Array.prototype.slice.call(arguments);
    ws.send(JSON.stringify(args));
  };
  return ws;
})
;

function CreateCtrl($scope, $http, $location) {
  $scope.type = 'draft';
  $scope.seats = 8;

  $scope.sets = [
    'Alara Reborn',
    'Alliances',
    'Antiquities',
    'Apocalypse',
    'Arabian Nights',
    'Avacyn Restored',
    'Betrayers of Kamigawa',
    'Champions of Kamigawa',
    'Chronicles',
    'Classic Sixth Edition',
    'Coldsnap',
    'Conflux',
    'Dark Ascension',
    'Darksteel',
    'Dissension',
    'Dragon\'s Maze',
    'Eighth Edition',
    'Eventide',
    'Exodus',
    'Fallen Empires',
    'Fifth Dawn',
    'Fifth Edition',
    'Fourth Edition',
    'Future Sight',
    'Gatecrash',
    'Guildpact',
    'Homelands',
    'Ice Age',
    'Innistrad',
    'Invasion',
    'Judgment',
    'Legends',
    'Legions',
    'Limited Edition Alpha',
    'Limited Edition Beta',
    'Lorwyn',
    'Magic 2010',
    'Magic 2011',
    'Magic 2012',
    'Magic 2013',
    'Mercadian Masques',
    'Mirage',
    'Mirrodin',
    'Mirrodin Besieged',
    'Modern Masters',
    'Morningtide',
    'Nemesis',
    'New Phyrexia',
    'Ninth Edition',
    'Odyssey',
    'Onslaught',
    'Planar Chaos',
    'Planeshift',
    'Portal',
    'Portal Second Age',
    'Portal Three Kingdoms',
    'Prophecy',
    'Ravnica: City of Guilds',
    'Return to Ravnica',
    'Revised Edition',
    'Rise of the Eldrazi',
    'Saviors of Kamigawa',
    'Scars of Mirrodin',
    'Scourge',
    'Seventh Edition',
    'Shadowmoor',
    'Shards of Alara',
    'Starter 1999',
    'Starter 2000',
    'Stronghold',
    'Tempest',
    'Tenth Edition',
    'The Dark',
    'Time Spiral',
    'Torment',
    'Unglued',
    'Unhinged',
    'Unlimited Edition',
    'Urza\'s Destiny',
    'Urza\'s Legacy',
    'Urza\'s Saga',
    'Visions',
    'Weatherlight',
    'Worldwake',
    'Zendikar'
  ];

  $scope.set1 = "Dragon's Maze";
  $scope.set2 = 'Gatecrash';
  $scope.set3 = 'Return to Ravnica';
  $scope.set4 = "Dragon's Maze";
  $scope.set5 = 'Gatecrash';
  $scope.set6 = 'Return to Ravnica';
  $scope.create = function() {
    var id = localStorage.id || (localStorage.id = (Math.floor(Math.random() * 9e9)).toString(16));
    var data = {
      type: $scope.type, seats: $scope.seats, host: id
    };
    switch(data.type) {
      case 'draft':
        data.sets = [$scope.set1, $scope.set2, $scope.set3];
        break;
      case 'sealed':
        data.sets = [$scope.set1, $scope.set2, $scope.set3, $scope.set4, $scope.set5, $scope.set6];
        break;
      case 'cube':
        var cube = $scope.cube;
        if (cube)
          var match = cube.match(/([^/]+)\/?$/);
        if (!match)
          return alert('which cube are you drafting?');
        data.cube = $scope.cube = match[1];
    }
    $http.post('/create', data)
      .success(function(qid, status) {
        $location.path('/q/' + qid);
      })
      ;
  };
}

function QCtrl($scope, $timeout, $http, $routeParams, ws) {
  var selected = null
  var audio = document.querySelector('audio');

  document.getElementById('chat').style.display = 'none';
  $scope.addBots = true;
  $scope.beep = 'never';
  $scope.order = 'color';
  $scope.main = [];
  $scope.side = [];
  $scope.jank = [];
  $scope.land = [
  { land: true, cmc: 0, color: 'L', url: 'http://gatherer.wizards.com/Handlers/Image.ashx?type=card&multiverseid=73946', name: 'Forest'   },
  { land: true, cmc: 0, color: 'L', url: 'http://gatherer.wizards.com/Handlers/Image.ashx?type=card&multiverseid=73951', name: 'Island'   },
  { land: true, cmc: 0, color: 'L', url: 'http://gatherer.wizards.com/Handlers/Image.ashx?type=card&multiverseid=73958', name: 'Mountain' },
  { land: true, cmc: 0, color: 'L', url: 'http://gatherer.wizards.com/Handlers/Image.ashx?type=card&multiverseid=73963', name: 'Plains'   },
  { land: true, cmc: 0, color: 'L', url: 'http://gatherer.wizards.com/Handlers/Image.ashx?type=card&multiverseid=73973', name: 'Swamp'    }
  ];

  function decrement() {
    angular.forEach($scope.players, function(player) {
      if (player.time)
        --player.time;
    });
    $timeout(decrement, 1000);
  }

  $timeout(decrement, 1000);

  ws.on('open', function() {
    console.log('open');
  });
  ws.on('error', function(error) {
    console.log(error);
  });
  ws.on('close', function() {
    console.log('close');
  });

  var msg = ws.msg;
  msg.on('error', function(error) {
    $scope.error = error;
  });
  msg.on('set', function(data) {
    angular.extend($scope, data);

    if (!(data.pack && data.pack.length)) return;
    var d = document;
    var hidden = d.hidden || d.webkitHidden;
    switch ($scope.beep) {
      case 'if tab is hidden': if (!hidden) return;
      case 'always': audio.play();
    }
  });
  msg.on('add', function(card) {
    $scope.main.push(card);
  });

  $scope.pick = function(index) {
    if (selected !== index) {
      selected = index
      return
    }
    ws.json('pick', index);
    $scope.pack = null;
    selected = null;
  };
  $scope.editName = function(p, index) {
    if ($scope.self === index)
      p.edit = true;
  };
  $scope.name = function(p) {
    p.edit = false;
    name = p.name.slice(0, 15);
    ws.json('name', name);
    localStorage.name = name;
  };
  $scope.fromMain = function(card, e) {
    var main = $scope.main;
    main.splice(main.indexOf(card), 1);
    if (card.land) return;
    if (e.shiftKey)
      $scope.jank.push(card);
    else
      $scope.side.push(card);
  };
  $scope.fromSide = function(card, e) {
    var side = $scope.side;
    side.splice(side.indexOf(card), 1);
    if (card.land) return;
    if (e.shiftKey)
      $scope.jank.push(card);
    else
      $scope.main.push(card);
  };
  $scope.fromJank = function(card, e) {
    var jank = $scope.jank;
    jank.splice(jank.indexOf(card), 1);
    if (e.shiftKey)
      $scope.main.push(card);
    else
      $scope.side.push(card);
  };
  $scope.addLand = function(card, e) {
    if (e.shiftKey)
      $scope.side.push(card);
    else
      $scope.main.push(card);
  };
  $scope.generateDeck = function() {
    var main = {}
      , side = {}
      , deck, i, j
      ;

    if (!$scope.players[$scope.self].hash)
      for (i = 0; i < 5; i++)
        for (j = 0; j < 5; j++)
          $scope.side.push($scope.land[i]);

    angular.forEach($scope.main, function(card) {
      var name = card.name;
      main[name] || (main[name] = 0);
      main[name] += 1;
    });
    angular.forEach($scope.side, function(card) {
      var name = card.name;
      side[name] || (side[name] = 0);
      side[name] += 1;
    });
    deck = {
      main: main,
      side: side
    };
    $scope.deckJSON = JSON.stringify(deck);
    ws.json('hash', deck);
  };
  $scope.start = function() {
    if (!$scope.isHost) return;
    $scope.round = 1;
    ws.json('start', $scope.addBots);
  };
}
<|endoftext|>


<commit_before>// constructor
function Player(name) {
	this.name = name;
	this.cards = [];
	this.score = 0;
}

// constructor
function PlayerUI(){
  	this.cardDom = undefined;
  	this.scoreDom = undefined;
}

function Card(definedCard) {
	if (definedCard !== undefined && 'object' !== typeof definedCard) {
		throw new Error('');
	}

	this.suit = undefined;
	this.symbol = undefined;
	this.color = undefined;
	this.face = undefined;
	this.name = undefined;
	this.value = undefined;
}

function Deck(){
	this.suits = {
		0: {
			'suit': 'diamonds',
			'symbol': '♦',
			'color': 'red'
		},

		1: {
			'suit': 'hearts',
			'symbol': '♥',
			'color': 'red'
		},

		2: {
			'suit': 'clubs',
			'symbol': '♣',
			'color': 'black'
		},

		3: {
			'suit': 'spades',
			'symbol': '♠',
			'color': 'black'
		}
	}; // close suits

	this.cards = {
		1: {
			'name': 'ace',
			'face': 'A',
			'value': 1
		},

		2: {
			'name': 'two',
			'face': '2',
			'value': 2
		},

		3: {
			'name': 'three',
			'face': 3,
			'value': 3
		},

		4: {
			'name': 'four',
			'face': '4',
			'value': 4
		},

		5: {
			'name': 'five',
			'face': '5',
			'value': 5
		},

		6: {
			'name': 'six',
			'face': '6',
			'value': 6
		},

		7: {
			'name': 'seven',
			'face': '7',
			'value': 7
		},

		8: {
			'name': 'eight',
			'face': '8',
			'value': 8
		},

		9: {
			'name': 'nine',
			'face': '9',
			'value': 9
		},

		10: {
			'name': 'ten',
			'face': '10',
			'value': 10
		},

		11: {
			'name': 'jack',
			'face': 'J',
			'value': 10
		},

		12: {
			'name': 'queen',
			'face': 'Q',
			'value': 10
		},

		13: {
			'name': 'king',
			'face': 'K',
			'value': 10
		},

		14: {
			'name': 'ace',
			'face': 'A',
			'value': 11
		}
	}; // close cards
}

Deck.prototype.getRandomCard = function(){
	var scope = this;
	var suitType = Math.floor(Math.random() * 4);
	var cardNumber = Math.floor(Math.random() * 13) + 1;

	var randomCard = new Card({
		suit: scope.suits[suitType].suit,
		symbol: scope.suits[suitType].symbol,
		color: scope.suits[suitType].color,
		face: scope.cards[cardNumber].face,
		name: scope.cards[cardNumber].name,
		value: scope.cards[cardNumber].value
	});

	console.log(suitType);
	console.log(cardNumber);
	console.log(randomCard);
};

var playerOne = new Player('John');
var myDeck = new Deck();

myDeck.getRandomCard();<commit_msg>add player instance called dealer and continue tidying up the code<commit_after>// constructor
function Player() {
	this.cards = [];
	this.score = 0;
	this.wager = 0;
}

// constructor
function PlayerUI(name){
	this.name = name;
  	this.cardDom = undefined;
  	this.scoreDom = undefined;
}

function GameUI(){
	this.dealButton = document.getElementById('deal-button');
	this.hitButton = document.getElementById('hit-me');
	this.stayButton = document.getElementById('stay');
	this.resetButton = document.getElementById('reset');
}

// constructor
function Card(definedCard) {
	// this ensures that if we're not passed an object, we throw an error
	if (definedCard !== undefined && 'object' !== typeof definedCard) {
		throw new Error('');
	}

	this.suit = definedCard.suit;
	this.symbol = definedCard.symbol;
	this.color = definedCard.color;
	this.face = definedCard.face;
	this.name = definedCard.name;
	this.value = definedCard.value;
}

function Deck(){
	this.suits = {
		0: {
			'suit': 'diamonds',
			'symbol': '♦',
			'color': 'red'
		},

		1: {
			'suit': 'hearts',
			'symbol': '♥',
			'color': 'red'
		},

		2: {
			'suit': 'clubs',
			'symbol': '♣',
			'color': 'black'
		},

		3: {
			'suit': 'spades',
			'symbol': '♠',
			'color': 'black'
		}
	}; // close suits

	this.cards = {
		1: {
			'name': 'ace',
			'face': 'A',
			'value': 1
		},

		2: {
			'name': 'two',
			'face': '2',
			'value': 2
		},

		3: {
			'name': 'three',
			'face': 3,
			'value': 3
		},

		4: {
			'name': 'four',
			'face': '4',
			'value': 4
		},

		5: {
			'name': 'five',
			'face': '5',
			'value': 5
		},

		6: {
			'name': 'six',
			'face': '6',
			'value': 6
		},

		7: {
			'name': 'seven',
			'face': '7',
			'value': 7
		},

		8: {
			'name': 'eight',
			'face': '8',
			'value': 8
		},

		9: {
			'name': 'nine',
			'face': '9',
			'value': 9
		},

		10: {
			'name': 'ten',
			'face': '10',
			'value': 10
		},

		11: {
			'name': 'jack',
			'face': 'J',
			'value': 10
		},

		12: {
			'name': 'queen',
			'face': 'Q',
			'value': 10
		},

		13: {
			'name': 'king',
			'face': 'K',
			'value': 10
		},

		14: {
			'name': 'ace',
			'face': 'A',
			'value': 11
		}
	}; // close cards
}

Deck.prototype.getRandomCard = function(){
	var suitType = Math.floor(Math.random() * 4);
	var cardNumber = Math.floor(Math.random() * 13) + 1;

	var randomCard = new Card({
		suit: this.suits[suitType].suit,
		symbol: this.suits[suitType].symbol,
		color: this.suits[suitType].color,
		face: this.cards[cardNumber].face,
		name: this.cards[cardNumber].name,
		value: this.cards[cardNumber].value
	});

	// console.log(randomCard);
	return randomCard;
};

var playerOne = new Player();
var playerRender = new PlayerUI('John');

var gameDealer = new Player();
var dealerRender = new PlayerUI('Dealer');

var myDeck = new Deck();

myDeck.getRandomCard();<|endoftext|>


<commit_before>/* Function to print job to panel in view. */
function printJob(id, title, description, hours, salary, startDate, state, city, percentageMatch){
    var display = document.getElementById("jobs");

    var panel = document.createElement("div");
    panel.className = "panel panel-default";

    var heading = document.createElement("div");
    heading.className = "panel-heading";
    heading.innerHTML += title + " • ";

    var match = document.createElement("strong");
    match.innerHTML = percentageMatch + "%";

    var body = document.createElement("div");
    body.className = "panel-body";

    var p1 = document.createElement("p");
    p1.innerHTML = description;

    var hr1 = document.createElement("hr");

    var p2 = document.createElement("p");
    var p2Title = document.createElement("strong");

    if(hours == "fulltime"){
        p2.innerHTML = "Full time";
    }
    else if(hours == "parttime"){
        p2.innerHTML = "Part time";
    }
    else{
        p2.innerHTML = "Casual";
    }

    p2Title.innerHTML = "Hours: ";

    var p3 = document.createElement("p");
    var p3Title = document.createElement("strong");

    /* https://stackoverflow.com/a/2901298 */
    p3.innerHTML = "$" + salary.toString().replace(/\B(?=(\d{3})+(?!\d))/g, ",");

    if(hours == "fulltime"){
        p3.innerHTML += " per annum.";
    }
    else{
        p3.innerHTML += " per hour.";
    }

    p3Title.innerHTML = "Salary: ";

    var p4 = document.createElement("p");
    var p4Title = document.createElement("strong");
    p4.innerHTML = startDate;
    p4Title.innerHTML = "Start date: ";

    var p5 = document.createElement("p");
    var p5Title = document.createElement("strong");
    p5.innerHTML = city;

    if(state == "vic"){
        p5.innerHTML += ", Victoria.";
    }
    else if(state == "nsw"){
        p5.innerHTML += ", New South Wales";
    }
    else if(state == "qld"){
        p5.innerHTML += ", Queensland";
    }
    else if(state == "wa"){
        p5.innerHTML += ", Western Australia";
    }
    else if(state == "sa"){
        p5.innerHTML += ", South Australia";
    }
    else if(state == "ta"){
        p5.innerHTML += ", Tasmania";
    }
    else if(state == "act"){
        p5.innerHTML += ", Australian Capital Territory";
    }
    else if(state == "nt"){
        p5.innerHTML += ", Northern Territory";
    }
    else{
        p5.innerHTML += ", Other Australian Region";
    }

    p5Title.innerHTML = "Location: ";

    var hr2 = document.createElement("hr");

    var p6 = document.createElement("p");

    var apply = document.createElement("a");
    apply.className = "btn btn-primary";
    apply.href = "/job/" + id;
    apply.innerHTML = "View";

    panel.appendChild(heading);
    panel.appendChild(body);
    heading.append(match);
    body.append(p1);
    body.append(hr1);
    body.append(p2);
    p2.prepend(p2Title);
    body.append(p3);
    p3.prepend(p3Title);
    body.append(p4);
    p4.prepend(p4Title);
    body.append(p5);
    p5.prepend(p5Title);
    body.append(hr2);
    body.append(p6);
    p6.append(apply);
    display.appendChild(panel);

    document.getElementById("loading").style.display = "none";
}

/* Function to perform matchmaking. */
function match(){
    /* Get state filter from document. */
    var stateFilter = document.getElementById("state").value;

    /* Arbitrary number; no. of fields compared. */
    var noOfBits = 25;

    /* Input value (needs to be grabbed from user). */
    var input;

    /* Array of job indexes. */
    var jobIndex = [];

    /* Array of bitwise ints to compare. */
    var jobMatch = [];

    /* Array of percentage matches. */
    var percentageMatch = [];

    /* Get current authenticated user data. */
    $.getJSON("api/user/", function(data){
        input = parseInt("" + data.java + data.python + data.c + data.csharp + data.cplus + data.php + data.html + data.css + data.javascript + data.sql + data.unix + data.winserver + data.windesktop + data.linuxdesktop + data.macosdesktop + data.pearl + data.bash + data.batch + data.cisco + data.office + data.r + data.go + data.ruby + data.asp + data.scala, 2);
    }).then(function(){

        /* Populate values into jobIndex, jobMatch and percentageMatch arrays. */
        $.getJSON( "api/jobs/" + stateFilter, function(data){
            var i;
            for(i = 0; i < data.length; i++){
                jobIndex[i] = i;
                jobMatch[i] = parseInt("" + data[i].java + data[i].python + data[i].c + data[i].csharp + data[i].cplus + data[i].php + data[i].html + data[i].css + data[i].javascript + data[i].sql + data[i].unix + data[i].winserver + data[i].windesktop + data[i].linuxdesktop + data[i].macosdesktop + data[i].pearl + data[i].bash + data[i].batch + data[i].cisco + data[i].office + data[i].r + data[i].go + data[i].ruby + data[i].asp + data[i].scala, 2);

				/* Find number of comparisons. */
				var noOfComp = input | jobMatch[i];

				var bitComp = (noOfComparisons).toString(2);

				if(bitComp < 0){
                    bitComp = (noOfComp >>> 0).toString(2);
                    bitComp = bitComp.slice(-noOfBits);
                }

                var countComp = bitComp.replace(/[^1]/g, "").length;

				/* Find number of matches. */
                var matchCalc = ~(input ^ jobMatch[i]);

                var toBinary = (matchCalc).toString(2);

                if(toBinary < 0){
                    toBinary = (matchCalc >>> 0).toString(2);
                    toBinary = toBinary.slice(-noOfBits);
                }

                var count = toBinary.replace(/[^1]/g, "").length;

				/* Calculate percentage match. */
                percentageMatch[i] = (count / countComp) * 100;
            }

            /* Bubble sort. */
            var swapped;

            do{
                swapped = false;

                var i;
                for(i = 0; i < jobIndex.length-1; i++){
                    if(percentageMatch[i] < percentageMatch[i+1]){
                        var tempPer = percentageMatch[i];
                        percentageMatch[i] = percentageMatch[i+1];
                        percentageMatch[i+1] = tempPer;

                        var tempId = jobIndex[i];
                        jobIndex[i] = jobIndex[i+1];
                        jobIndex[i+1] = tempId;

                        var tempJob = jobMatch[i];
                        jobMatch[i] = jobMatch[i+1];
                        jobMatch[i+1] = tempJob;

                        swapped = true;
                    }
                }
            }
            while(swapped);
        })
        .then(function(){

            /* Display jobs. */
            $.getJSON( "api/jobs/" + stateFilter, function(data){
                if(data.length > 0){
                    var i;
                    for(i = 0; i < data.length; i++){
                        var order = jobIndex[i];
                        printJob(data[order].id, data[order].title, data[order].description, data[order].hours, data[order].salary, data[order].startdate, data[order].state, data[order].city, Math.round(percentageMatch[i]));
                    }
                }
                else{
                    document.getElementById("loading").style.display = "none";
                    document.getElementById("nomatches").style.display = "block";
                }
            })
            .fail(function(){
                document.getElementById("loading").style.display = "none";
                document.getElementById("error").style.display = "block";
            });
        })
        .fail(function(){
            document.getElementById("loading").style.display = "none";
            document.getElementById("error").style.display = "block";
        });
    })
    .fail(function(){
        document.getElementById("loading").style.display = "none";
        document.getElementById("error").style.display = "block";
    });
}

/* Initialisation function to test for JavaScript, display loading animation, and call match function. */
function init(){
    document.getElementById("jobs").innerHTML = "";

    document.getElementById("noscript").style.display = "none";
    document.getElementById("nomatches").style.display = "none";
    document.getElementById("error").style.display = "none";
    document.getElementById("loading").style.display = "block";

    match();
}

document.addEventListener('DOMContentLoaded', init);
document.getElementById("state").addEventListener('change', init);
<commit_msg>Updated matching (untested)<commit_after>/* Function to print job to panel in view. */
function printJob(id, title, description, hours, salary, startDate, state, city, percentageMatch){
    var display = document.getElementById("jobs");

    var panel = document.createElement("div");
    panel.className = "panel panel-default";

    var heading = document.createElement("div");
    heading.className = "panel-heading";
    heading.innerHTML += title + " • ";

    var match = document.createElement("strong");
    match.innerHTML = percentageMatch + "%";

    var body = document.createElement("div");
    body.className = "panel-body";

    var p1 = document.createElement("p");
    p1.innerHTML = description;

    var hr1 = document.createElement("hr");

    var p2 = document.createElement("p");
    var p2Title = document.createElement("strong");

    if(hours == "fulltime"){
        p2.innerHTML = "Full time";
    }
    else if(hours == "parttime"){
        p2.innerHTML = "Part time";
    }
    else{
        p2.innerHTML = "Casual";
    }

    p2Title.innerHTML = "Hours: ";

    var p3 = document.createElement("p");
    var p3Title = document.createElement("strong");

    /* https://stackoverflow.com/a/2901298 */
    p3.innerHTML = "$" + salary.toString().replace(/\B(?=(\d{3})+(?!\d))/g, ",");

    if(hours == "fulltime"){
        p3.innerHTML += " per annum.";
    }
    else{
        p3.innerHTML += " per hour.";
    }

    p3Title.innerHTML = "Salary: ";

    var p4 = document.createElement("p");
    var p4Title = document.createElement("strong");
    p4.innerHTML = startDate;
    p4Title.innerHTML = "Start date: ";

    var p5 = document.createElement("p");
    var p5Title = document.createElement("strong");
    p5.innerHTML = city;

    if(state == "vic"){
        p5.innerHTML += ", Victoria.";
    }
    else if(state == "nsw"){
        p5.innerHTML += ", New South Wales";
    }
    else if(state == "qld"){
        p5.innerHTML += ", Queensland";
    }
    else if(state == "wa"){
        p5.innerHTML += ", Western Australia";
    }
    else if(state == "sa"){
        p5.innerHTML += ", South Australia";
    }
    else if(state == "ta"){
        p5.innerHTML += ", Tasmania";
    }
    else if(state == "act"){
        p5.innerHTML += ", Australian Capital Territory";
    }
    else if(state == "nt"){
        p5.innerHTML += ", Northern Territory";
    }
    else{
        p5.innerHTML += ", Other Australian Region";
    }

    p5Title.innerHTML = "Location: ";

    var hr2 = document.createElement("hr");

    var p6 = document.createElement("p");

    var apply = document.createElement("a");
    apply.className = "btn btn-primary";
    apply.href = "/job/" + id;
    apply.innerHTML = "View";

    panel.appendChild(heading);
    panel.appendChild(body);
    heading.append(match);
    body.append(p1);
    body.append(hr1);
    body.append(p2);
    p2.prepend(p2Title);
    body.append(p3);
    p3.prepend(p3Title);
    body.append(p4);
    p4.prepend(p4Title);
    body.append(p5);
    p5.prepend(p5Title);
    body.append(hr2);
    body.append(p6);
    p6.append(apply);
    display.appendChild(panel);

    document.getElementById("loading").style.display = "none";
}

/* Function to perform matchmaking. */
function match(){
    /* Get state filter from document. */
    var stateFilter = document.getElementById("state").value;

    /* Arbitrary number; no. of fields compared. */
    var noOfBits = 25;

    /* Input value (needs to be grabbed from user). */
    var input;

    /* Array of job indexes. */
    var jobIndex = [];

    /* Array of bitwise ints to compare. */
    var jobMatch = [];

    /* Array of percentage matches. */
    var percentageMatch = [];

    /* Get current authenticated user data. */
    $.getJSON("api/user/", function(data){
        input = parseInt("" + data.java + data.python + data.c + data.csharp + data.cplus + data.php + data.html + data.css + data.javascript + data.sql + data.unix + data.winserver + data.windesktop + data.linuxdesktop + data.macosdesktop + data.pearl + data.bash + data.batch + data.cisco + data.office + data.r + data.go + data.ruby + data.asp + data.scala, 2);
    }).then(function(){

        /* Populate values into jobIndex, jobMatch and percentageMatch arrays. */
        $.getJSON( "api/jobs/" + stateFilter, function(data){
            var i;
            for(i = 0; i < data.length; i++){
                jobIndex[i] = i;
                jobMatch[i] = parseInt("" + data[i].java + data[i].python + data[i].c + data[i].csharp + data[i].cplus + data[i].php + data[i].html + data[i].css + data[i].javascript + data[i].sql + data[i].unix + data[i].winserver + data[i].windesktop + data[i].linuxdesktop + data[i].macosdesktop + data[i].pearl + data[i].bash + data[i].batch + data[i].cisco + data[i].office + data[i].r + data[i].go + data[i].ruby + data[i].asp + data[i].scala, 2);

				/* Find number of comparisons. */
				var noOfComp = input | jobMatch[i];

				var bitComp = (noOfComp).toString(2);

				if(bitComp < 0){
                    bitComp = (noOfComp >>> 0).toString(2);
                    bitComp = bitComp.slice(-noOfBits);
                }

                var countComp = bitComp.replace(/[^1]/g, "").length;

				/* Find number of matches. */
                var matchCalc = ~(input ^ jobMatch[i]);

                var toBinary = (matchCalc).toString(2);

                if(toBinary < 0){
                    toBinary = (matchCalc >>> 0).toString(2);
                    toBinary = toBinary.slice(-noOfBits);
                }

                var count = toBinary.replace(/[^1]/g, "").length;

				/* Calculate percentage match. */
                percentageMatch[i] = (count / countComp) * 100;
            }

            /* Bubble sort. */
            var swapped;

            do{
                swapped = false;

                var i;
                for(i = 0; i < jobIndex.length-1; i++){
                    if(percentageMatch[i] < percentageMatch[i+1]){
                        var tempPer = percentageMatch[i];
                        percentageMatch[i] = percentageMatch[i+1];
                        percentageMatch[i+1] = tempPer;

                        var tempId = jobIndex[i];
                        jobIndex[i] = jobIndex[i+1];
                        jobIndex[i+1] = tempId;

                        var tempJob = jobMatch[i];
                        jobMatch[i] = jobMatch[i+1];
                        jobMatch[i+1] = tempJob;

                        swapped = true;
                    }
                }
            }
            while(swapped);
        })
        .then(function(){

            /* Display jobs. */
            $.getJSON( "api/jobs/" + stateFilter, function(data){
                if(data.length > 0){
                    var i;
                    for(i = 0; i < data.length; i++){
                        var order = jobIndex[i];
                        printJob(data[order].id, data[order].title, data[order].description, data[order].hours, data[order].salary, data[order].startdate, data[order].state, data[order].city, Math.round(percentageMatch[i]));
                    }
                }
                else{
                    document.getElementById("loading").style.display = "none";
                    document.getElementById("nomatches").style.display = "block";
                }
            })
            .fail(function(){
                document.getElementById("loading").style.display = "none";
                document.getElementById("error").style.display = "block";
            });
        })
        .fail(function(){
            document.getElementById("loading").style.display = "none";
            document.getElementById("error").style.display = "block";
        });
    })
    .fail(function(){
        document.getElementById("loading").style.display = "none";
        document.getElementById("error").style.display = "block";
    });
}

/* Initialisation function to test for JavaScript, display loading animation, and call match function. */
function init(){
    document.getElementById("jobs").innerHTML = "";

    document.getElementById("noscript").style.display = "none";
    document.getElementById("nomatches").style.display = "none";
    document.getElementById("error").style.display = "none";
    document.getElementById("loading").style.display = "block";

    match();
}

document.addEventListener('DOMContentLoaded', init);
document.getElementById("state").addEventListener('change', init);
<|endoftext|>