<commit_before>define(["Maneuver", "Phase", "Pilot", "RangeRuler", "Team", "UpgradeCard", "process/Action", "process/ActivationAction", "process/CombatAction", "process/EndPhaseAction", "process/PlanningAction"],
   function(Maneuver, Phase, Pilot, RangeRuler, Team, UpgradeCard, Action, ActivationAction, CombatAction, EndPhaseAction, PlanningAction)
   {
      "use strict";

      function Engine(environment, adjudicator, delayIn)
      {
         InputValidator.validateNotNull("environment", environment);
         InputValidator.validateNotNull("adjudicator", adjudicator);
         // delayIn optional.

         var delay = (delayIn !== undefined ? delayIn : 1000);

         this.environment = function()
         {
            return environment;
         };

         this.adjudicator = function()
         {
            return adjudicator;
         };

         this.delay = function()
         {
            return delay;
         };

         var that = this;
         var firstTokenToManeuver, secondTokenToManeuver;
         var activationQueue = [];
         var combatQueue = [];
         var endQueue = [];
         var decloakCount = 0;

         this.firstTokenToManeuver = function()
         {
            return firstTokenToManeuver;
         };

         this.performActivationPhase = function()
         {
            if (!isGameOver())
            {
               LOGGER.trace("Engine.performActivationPhase() start");
               environment.phase(Phase.ACTIVATION_START);
               var store = environment.store();

               // FIXME: Perform start of activation phase actions.

               // Perform decloak action for all ships.
               decloakCount = 0;
               var tokens = environment.getTokensForActivation(true);

               tokens.forEach(function(token)
               {
                  if (token.isCloaked && token.isCloaked())
                  {
                     LOGGER.debug("checking decloak for " + token);
                     var agent = token.agent();
                     agent.getDecloakAction(environment, adjudicator, token, this.setDecloakAction.bind(this));

                     // Wait for agent to respond.
                  }
                  else
                  {
                     this.setDecloakAction(token);
                  }
               }, this);
            }
         };

         this.performCombatPhase = function(callback)
         {
            // callback optional.
            if (callback)
            {
               combatPhaseCallback = callback;
            }

            if (!isGameOver())
            {
               LOGGER.trace("Engine.performCombatPhase() start");
               environment.phase(Phase.COMBAT_START);
               var store = environment.store();

               // FIXME: Perform start of combat phase actions.

               // Search for Epsilon Leader.
               var tokens = environment.getTokensForCombat().filter(function(token)
               {
                  return token.pilotKey() === Pilot.EPSILON_LEADER;
               });

               if (tokens.length > 0)
               {
                  var epsilonLeader = tokens[0];
                  var friendlies = environment.getFriendlyTokensAtRange(epsilonLeader, RangeRuler.ONE);

                  friendlies.forEach(function(token)
                  {
                     token.removeStress();
                  });
               }

               // Search for a ship upgraded with Ysanne Isard.
               tokens = environment.getTokensForCombat().filter(function(token)
               {
                  return token.isUpgradedWith(UpgradeCard.YSANNE_ISARD);
               });

               if (tokens.length > 0)
               {
                  var ysanneIsard = tokens[0];

                  if (ysanneIsard.shieldCount() === 0 &&
                     (ysanneIsard.damageCount() > 0 || ysanneIsard.criticalDamageCount() > 0))
                  {
                     store.dispatch(Action.addEvadeCount(ysanneIsard));
                  }
               }

               combatQueue = environment.getTokensForCombat();
               this.processCombatQueue();
            }
            else
            {
               combatPhaseCallback();
            }
         };

         this.performEndPhase = function(callback)
         {
            // callback optional.
            if (callback)
            {
               endPhaseCallback = callback;
            }

            if (!isGameOver())
            {
               LOGGER.trace("Engine.performEndPhase() start");
               environment.phase(Phase.END_START);

               endQueue = environment.getTokensForCombat();
               this.processEndQueue();
            }
            else
            {
               endPhaseCallback();
            }
         };

         this.performPlanningPhase = function(planningCallback, activationCallback)
         {
            // planningCallback optional.
            // activationCallback optional.

            if (planningCallback)
            {
               planningPhaseCallback = planningCallback;
            }

            if (activationCallback)
            {
               activationPhaseCallback = activationCallback;
            }

            if (!isGameOver())
            {
               LOGGER.trace("Engine.performPlanningPhase() start");

               environment.phase(Phase.PLANNING_START);
               environment.incrementRound();

               var firstAgent = environment.firstAgent();
               var firstPlanningAction = new PlanningAction(environment, adjudicator, firstAgent, that.setTokenToManeuver);
               firstPlanningAction.doIt();

               var secondAgent = environment.secondAgent();
               var secondPlanningAction = new PlanningAction(environment, adjudicator, secondAgent, that.setTokenToManeuver);
               secondPlanningAction.doIt();

               // Wait for agents to respond.
            }
            else
            {
               planningPhaseCallback();
            }
         };

         this.processActivationQueue = function()
         {
            LOGGER.trace("Engine.processActivationQueue() start");

            var store = environment.store();

            if (activationQueue.length === 0)
            {
               firstTokenToManeuver = undefined;
               secondTokenToManeuver = undefined;

               environment.activeToken(undefined);
               store.dispatch(Action.setUserMessage(""));
               LOGGER.trace("Engine.processActivationQueue() done");
               environment.phase(Phase.ACTIVATION_END);
               setTimeout(function()
               {
                  activationPhaseCallback();
               }, delay);
               return;
            }

            var token = activationQueue.shift();
            environment.activeToken(token);
            var factionKey = token.pilot().shipTeam.teamKey;
            var myToken = token;

            if (token.parent && token.pilot().value.endsWith("fore"))
            {
               myToken = token.parent;
            }

            var maneuverKey;

            if (Team.isFriendly(factionKey, environment.firstTeam()))
            {
               maneuverKey = firstTokenToManeuver[myToken];
            }
            else
            {
               maneuverKey = secondTokenToManeuver[myToken];
            }

            var activationAction = new ActivationAction(store, token.id(), this.processActivationQueue.bind(this), delay);
            var maneuver = Maneuver.properties[maneuverKey];
            store.dispatch(Action.setTokenManeuver(token, maneuver));

            setTimeout(function()
            {
               activationAction.doIt();
            }, delay);

            LOGGER.trace("Engine.processActivationQueue() end");
         };

         this.processCombatQueue = function()
         {
            LOGGER.trace("Engine.processCombatQueue() start");

            var store = environment.store();

            if (combatQueue.length === 0)
            {
               // Search for a ship upgraded with R5-P9.
               var tokens = environment.getTokensForCombat().filter(function(token)
               {
                  return token.isUpgradedWith(UpgradeCard.R5_P9);
               });

               if (tokens.length > 0)
               {
                  var r5p9 = tokens[0];

                  if (r5p9.focusCount() > 0 && r5p9.shieldCount() < r5p9.shieldValue())
                  {
                     store.dispatch(Action.addFocusCount(token, -1));
                     r5p9.recoverShield();
                  }
               }

               environment.activeToken(undefined);
               store.dispatch(Action.setUserMessage(""));
               LOGGER.trace("Engine.processCombatQueue() done");
               environment.phase(Phase.COMBAT_END);
               setTimeout(function()
               {
                  combatPhaseCallback();
               }, delay);
               return;
            }

            var attacker = combatQueue.shift();

            if (attacker)
            {
               environment.activeToken(attacker);

               if (adjudicator.canAttack(attacker))
               {
                  // Perform combat steps.
                  LOGGER.debug("attacker = " + attacker.name());

                  // Declare target.
                  var agent = attacker.agent();
                  agent.chooseWeaponAndDefender(environment, adjudicator, attacker, that.setWeaponAndDefender);

                  // Wait for agent to respond.
               }
               else
               {
                  // Proceed.
                  setTimeout(that.processCombatQueue, delay);
               }
            }

            LOGGER.trace("Engine.processCombatQueue() end");
         };

         this.processEndQueue = function()
         {
            LOGGER.trace("Engine.processEndQueue() start");

            var store = environment.store();

            if (endQueue.length === 0)
            {
               environment.activeToken(undefined);
               store.dispatch(Action.setUserMessage(""));
               LOGGER.trace("Engine.processEndQueue() done");
               environment.phase(Phase.END_END);
               setTimeout(function()
               {
                  endPhaseCallback();
               }, delay);
               return;
            }

            var token = endQueue.shift();

            if (token)
            {
               environment.activeToken(token);

               var action = new EndPhaseAction(environment, token, this.processEndQueue.bind(this));
               action.doIt();
            }
            else
            {
               this.processEndQueue();
            }

            LOGGER.trace("Engine.processEndQueue() end");
         };

         this.secondTokenToManeuver = function()
         {
            return secondTokenToManeuver;
         };

         this.setDecloakAction = function(token, decloakAction)
         {
            LOGGER.trace("Engine.setDecloakAction() start");

            InputValidator.validateNotNull("token", token);

            LOGGER.debug("token = " + token + " decloakAction = " + decloakAction);

            if (decloakAction !== undefined)
            {
               decloakAction.doIt(this.finishDecloakAction.bind(this));
               LOGGER.debug("token.isCloaked() ? " + token.isCloaked());
               LOGGER.debug("token.cloakCount() = " + token.cloakCount());
            }
            else
            {
               this.finishDecloakAction();
            }

            LOGGER.trace("Engine.setDecloakAction() end");
         };

         this.finishDecloakAction = function()
         {
            LOGGER.info("Engine.finishDecloakAction() start");

            decloakCount++;

            if (decloakCount === environment.tokens().length)
            {
               activationQueue = environment.getTokensForActivation(true);
               setTimeout(this.processActivationQueue.bind(this), delay);
            }

            LOGGER.trace("Engine.finishDecloakAction() end");
         };

         this.setTokenToManeuver = function(agent, tokenToManeuver)
         {
            if (agent === environment.firstAgent())
            {
               firstTokenToManeuver = tokenToManeuver;
               LOGGER.trace("firstTokenToManeuver = " + firstTokenToManeuver);
            }
            else if (agent === environment.secondAgent())
            {
               secondTokenToManeuver = tokenToManeuver;
               LOGGER.trace("secondTokenToManeuver = " + secondTokenToManeuver);
            }
            else
            {
               LOGGER.error("planningAction agent = " + agent);
            }

            if (firstTokenToManeuver && secondTokenToManeuver)
            {
               LOGGER.trace("Engine.performPlanningPhase() end");
               environment.phase(Phase.PLANNING_END);
               setTimeout(function()
               {
                  planningPhaseCallback();
               }, delay);
            }
         };

         this.setWeaponAndDefender = function(weapon, defender)
         {
            if (weapon && defender)
            {
               var attacker = environment.activeToken();

               if (defender)
               {
                  var store = environment.store();
                  store.dispatch(Action.setUserMessage(attacker + " fires upon " + defender));

                  var combatAction = new CombatAction(store, attacker, weapon, defender, that.processCombatQueue, delay);

                  setTimeout(function()
                  {
                     combatAction.doIt();
                  }, delay);
               }
            }
            else
            {
               that.processCombatQueue();
            }
         };

         var planningPhaseCallback = this.performActivationPhase.bind(this);
         var activationPhaseCallback = this.performCombatPhase.bind(this);
         var combatPhaseCallback = this.performEndPhase.bind(this);
         var endPhaseCallback = this.performPlanningPhase.bind(this);

         function isGameOver()
         {
            var store = environment.store();
            var answer = store.getState().isGameOver;

            if (!answer)
            {
               answer = adjudicator.isGameOver(environment);

               if (answer)
               {
                  LOGGER.debug("adjudicator.isGameOver() ? " + adjudicator.isGameOver(environment));
                  processGameOver();
               }
            }

            return answer;
         }

         function processGameOver()
         {
            var winner = adjudicator.determineWinner(environment);
            var store = environment.store();
            store.dispatch(Action.setGameOver(winner));

            var message = (winner === undefined ? "Game is a draw." : winner.name() + " won! ");
            store.dispatch(Action.setUserMessage(message));
         }
      }

      return Engine;
   });
<commit_msg>Rearranged methods into flow order.<commit_after>define(["Maneuver", "Phase", "Pilot", "RangeRuler", "Team", "UpgradeCard", "process/Action", "process/ActivationAction", "process/CombatAction", "process/EndPhaseAction", "process/PlanningAction"],
   function(Maneuver, Phase, Pilot, RangeRuler, Team, UpgradeCard, Action, ActivationAction, CombatAction, EndPhaseAction, PlanningAction)
   {
      "use strict";

      function Engine(environment, adjudicator, delayIn)
      {
         InputValidator.validateNotNull("environment", environment);
         InputValidator.validateNotNull("adjudicator", adjudicator);
         // delayIn optional.

         var delay = (delayIn !== undefined ? delayIn : 1000);

         this.environment = function()
         {
            return environment;
         };

         this.adjudicator = function()
         {
            return adjudicator;
         };

         this.delay = function()
         {
            return delay;
         };

         var that = this;
         var firstTokenToManeuver, secondTokenToManeuver;
         var activationQueue = [];
         var combatQueue = [];
         var endQueue = [];
         var decloakCount = 0;

         //////////////////////////////////////////////////////////////////////////
         // Accessor methods.

         this.firstTokenToManeuver = function()
         {
            return firstTokenToManeuver;
         };

         this.secondTokenToManeuver = function()
         {
            return secondTokenToManeuver;
         };

         //////////////////////////////////////////////////////////////////////////
         // Behavior methods.

         this.performPlanningPhase = function(planningCallback, activationCallback)
         {
            // planningCallback optional.
            // activationCallback optional.

            if (planningCallback)
            {
               planningPhaseCallback = planningCallback;
            }

            if (activationCallback)
            {
               activationPhaseCallback = activationCallback;
            }

            if (!isGameOver())
            {
               LOGGER.trace("Engine.performPlanningPhase() start");

               environment.phase(Phase.PLANNING_START);
               environment.incrementRound();

               var firstAgent = environment.firstAgent();
               var firstPlanningAction = new PlanningAction(environment, adjudicator, firstAgent, that.setTokenToManeuver);
               firstPlanningAction.doIt();

               var secondAgent = environment.secondAgent();
               var secondPlanningAction = new PlanningAction(environment, adjudicator, secondAgent, that.setTokenToManeuver);
               secondPlanningAction.doIt();

               // Wait for agents to respond.
            }
            else
            {
               planningPhaseCallback();
            }
         };

         this.setTokenToManeuver = function(agent, tokenToManeuver)
         {
            if (agent === environment.firstAgent())
            {
               firstTokenToManeuver = tokenToManeuver;
               LOGGER.trace("firstTokenToManeuver = " + firstTokenToManeuver);
            }
            else if (agent === environment.secondAgent())
            {
               secondTokenToManeuver = tokenToManeuver;
               LOGGER.trace("secondTokenToManeuver = " + secondTokenToManeuver);
            }
            else
            {
               LOGGER.error("planningAction agent = " + agent);
            }

            if (firstTokenToManeuver && secondTokenToManeuver)
            {
               LOGGER.trace("Engine.performPlanningPhase() end");
               environment.phase(Phase.PLANNING_END);
               setTimeout(function()
               {
                  planningPhaseCallback();
               }, delay);
            }
         };

         this.performActivationPhase = function()
         {
            if (!isGameOver())
            {
               LOGGER.trace("Engine.performActivationPhase() start");
               environment.phase(Phase.ACTIVATION_START);
               var store = environment.store();

               // FIXME: Perform start of activation phase actions.

               // Perform decloak action for all ships.
               decloakCount = 0;
               var tokens = environment.getTokensForActivation(true);

               tokens.forEach(function(token)
               {
                  if (token.isCloaked && token.isCloaked())
                  {
                     LOGGER.debug("checking decloak for " + token);
                     var agent = token.agent();
                     agent.getDecloakAction(environment, adjudicator, token, this.setDecloakAction.bind(this));

                     // Wait for agent to respond.
                  }
                  else
                  {
                     this.setDecloakAction(token);
                  }
               }, this);
            }
         };

         this.setDecloakAction = function(token, decloakAction)
         {
            LOGGER.trace("Engine.setDecloakAction() start");

            InputValidator.validateNotNull("token", token);

            LOGGER.debug("token = " + token + " decloakAction = " + decloakAction);

            if (decloakAction !== undefined)
            {
               decloakAction.doIt(this.finishDecloakAction.bind(this));
               LOGGER.debug("token.isCloaked() ? " + token.isCloaked());
               LOGGER.debug("token.cloakCount() = " + token.cloakCount());
            }
            else
            {
               this.finishDecloakAction();
            }

            LOGGER.trace("Engine.setDecloakAction() end");
         };

         this.finishDecloakAction = function()
         {
            LOGGER.trace("Engine.finishDecloakAction() start");

            decloakCount++;

            if (decloakCount === environment.tokens().length)
            {
               activationQueue = environment.getTokensForActivation(true);
               setTimeout(this.processActivationQueue.bind(this), delay);
            }

            LOGGER.trace("Engine.finishDecloakAction() end");
         };

         this.processActivationQueue = function()
         {
            LOGGER.trace("Engine.processActivationQueue() start");

            var store = environment.store();

            if (activationQueue.length === 0)
            {
               firstTokenToManeuver = undefined;
               secondTokenToManeuver = undefined;

               environment.activeToken(undefined);
               store.dispatch(Action.setUserMessage(""));
               LOGGER.trace("Engine.processActivationQueue() done");
               environment.phase(Phase.ACTIVATION_END);
               setTimeout(function()
               {
                  activationPhaseCallback();
               }, delay);
               return;
            }

            var token = activationQueue.shift();
            environment.activeToken(token);
            var factionKey = token.pilot().shipTeam.teamKey;
            var myToken = token;

            if (token.parent && token.pilot().value.endsWith("fore"))
            {
               myToken = token.parent;
            }

            var maneuverKey;

            if (Team.isFriendly(factionKey, environment.firstTeam()))
            {
               maneuverKey = firstTokenToManeuver[myToken];
            }
            else
            {
               maneuverKey = secondTokenToManeuver[myToken];
            }

            var activationAction = new ActivationAction(store, token.id(), this.processActivationQueue.bind(this), delay);
            var maneuver = Maneuver.properties[maneuverKey];
            store.dispatch(Action.setTokenManeuver(token, maneuver));

            setTimeout(function()
            {
               activationAction.doIt();
            }, delay);

            LOGGER.trace("Engine.processActivationQueue() end");
         };

         this.performCombatPhase = function(callback)
         {
            // callback optional.
            if (callback)
            {
               combatPhaseCallback = callback;
            }

            if (!isGameOver())
            {
               LOGGER.trace("Engine.performCombatPhase() start");
               environment.phase(Phase.COMBAT_START);
               var store = environment.store();

               // FIXME: Perform start of combat phase actions.

               // Search for Epsilon Leader.
               var tokens = environment.getTokensForCombat().filter(function(token)
               {
                  return token.pilotKey() === Pilot.EPSILON_LEADER;
               });

               if (tokens.length > 0)
               {
                  var epsilonLeader = tokens[0];
                  var friendlies = environment.getFriendlyTokensAtRange(epsilonLeader, RangeRuler.ONE);

                  friendlies.forEach(function(token)
                  {
                     token.removeStress();
                  });
               }

               // Search for a ship upgraded with Ysanne Isard.
               tokens = environment.getTokensForCombat().filter(function(token)
               {
                  return token.isUpgradedWith(UpgradeCard.YSANNE_ISARD);
               });

               if (tokens.length > 0)
               {
                  var ysanneIsard = tokens[0];

                  if (ysanneIsard.shieldCount() === 0 &&
                     (ysanneIsard.damageCount() > 0 || ysanneIsard.criticalDamageCount() > 0))
                  {
                     store.dispatch(Action.addEvadeCount(ysanneIsard));
                  }
               }

               combatQueue = environment.getTokensForCombat();
               this.processCombatQueue();
            }
            else
            {
               combatPhaseCallback();
            }
         };

         this.processCombatQueue = function()
         {
            LOGGER.trace("Engine.processCombatQueue() start");

            var store = environment.store();

            if (combatQueue.length === 0)
            {
               // Search for a ship upgraded with R5-P9.
               var tokens = environment.getTokensForCombat().filter(function(token)
               {
                  return token.isUpgradedWith(UpgradeCard.R5_P9);
               });

               if (tokens.length > 0)
               {
                  var r5p9 = tokens[0];

                  if (r5p9.focusCount() > 0 && r5p9.shieldCount() < r5p9.shieldValue())
                  {
                     store.dispatch(Action.addFocusCount(token, -1));
                     r5p9.recoverShield();
                  }
               }

               environment.activeToken(undefined);
               store.dispatch(Action.setUserMessage(""));
               LOGGER.trace("Engine.processCombatQueue() done");
               environment.phase(Phase.COMBAT_END);
               setTimeout(function()
               {
                  combatPhaseCallback();
               }, delay);
               return;
            }

            var attacker = combatQueue.shift();

            if (attacker)
            {
               environment.activeToken(attacker);

               if (adjudicator.canAttack(attacker))
               {
                  // Perform combat steps.
                  LOGGER.debug("attacker = " + attacker.name());

                  // Declare target.
                  var agent = attacker.agent();
                  agent.chooseWeaponAndDefender(environment, adjudicator, attacker, that.setWeaponAndDefender);

                  // Wait for agent to respond.
               }
               else
               {
                  // Proceed.
                  setTimeout(that.processCombatQueue, delay);
               }
            }

            LOGGER.trace("Engine.processCombatQueue() end");
         };

         this.setWeaponAndDefender = function(weapon, defender)
         {
            if (weapon && defender)
            {
               var attacker = environment.activeToken();

               if (defender)
               {
                  var store = environment.store();
                  store.dispatch(Action.setUserMessage(attacker + " fires upon " + defender));

                  var combatAction = new CombatAction(store, attacker, weapon, defender, that.processCombatQueue, delay);

                  setTimeout(function()
                  {
                     combatAction.doIt();
                  }, delay);
               }
            }
            else
            {
               that.processCombatQueue();
            }
         };

         this.performEndPhase = function(callback)
         {
            // callback optional.
            if (callback)
            {
               endPhaseCallback = callback;
            }

            if (!isGameOver())
            {
               LOGGER.trace("Engine.performEndPhase() start");
               environment.phase(Phase.END_START);

               endQueue = environment.getTokensForCombat();
               this.processEndQueue();
            }
            else
            {
               endPhaseCallback();
            }
         };

         this.processEndQueue = function()
         {
            LOGGER.trace("Engine.processEndQueue() start");

            var store = environment.store();

            if (endQueue.length === 0)
            {
               environment.activeToken(undefined);
               store.dispatch(Action.setUserMessage(""));
               LOGGER.trace("Engine.processEndQueue() done");
               environment.phase(Phase.END_END);
               setTimeout(function()
               {
                  endPhaseCallback();
               }, delay);
               return;
            }

            var token = endQueue.shift();

            if (token)
            {
               environment.activeToken(token);

               var action = new EndPhaseAction(environment, token, this.processEndQueue.bind(this));
               action.doIt();
            }
            else
            {
               this.processEndQueue();
            }

            LOGGER.trace("Engine.processEndQueue() end");
         };

         var planningPhaseCallback = this.performActivationPhase.bind(this);
         var activationPhaseCallback = this.performCombatPhase.bind(this);
         var combatPhaseCallback = this.performEndPhase.bind(this);
         var endPhaseCallback = this.performPlanningPhase.bind(this);

         //////////////////////////////////////////////////////////////////////////
         // Utility methods.

         function isGameOver()
         {
            var store = environment.store();
            var answer = store.getState().isGameOver;

            if (!answer)
            {
               answer = adjudicator.isGameOver(environment);

               if (answer)
               {
                  LOGGER.debug("adjudicator.isGameOver() ? " + adjudicator.isGameOver(environment));
                  processGameOver();
               }
            }

            return answer;
         }

         function processGameOver()
         {
            var winner = adjudicator.determineWinner(environment);
            var store = environment.store();
            store.dispatch(Action.setGameOver(winner));

            var message = (winner === undefined ? "Game is a draw." : winner.name() + " won! ");
            store.dispatch(Action.setUserMessage(message));
         }
      }

      return Engine;
   });
<|endoftext|>


<commit_before>/*global QUnit:false, module:false, test:false, asyncTest:false, expect:false*/
/*global start:false, stop:false ok:false, equal:false, notEqual:false, deepEqual:false*/
/*global notDeepEqual:false, strictEqual:false, notStrictEqual:false, raises:false*/

define(function(require){
	var $ = require('jquery');
	var html = require('text!test/markup/selectlist-markup.html');
	/* FOR DEV TESTING */
	//var html = require('text!dev.html!strip');
	html = $('
'+html+'
');

	$('body').append(html);

	require('bootstrap');
	require('fuelux/selectlist');

	module("Fuel UX Selectlist");

	test("should be defined on jquery object", function () {
		ok($().selectlist, 'selectlist method is defined');
	});

	test("should return element", function () {
		var $selectlist = $(html).find('#MySelectlist').selectlist();
		ok($selectlist.selectlist() === $selectlist, 'selectlist should be initialized');
	});

	test("should autosize correctly", function () {
		var $selectlist8 = $('body').find('#MySelectlist8').selectlist();
		var $selectlist9 = $('body').find('#MySelectlist9').selectlist();
		var minWidth;

		//measure all children of selectlist to be tested (add them all to a span and see how wide the span is) and make sure the selectlist is actually big enough to fit that
		var $textLengthTester = $('').appendTo('body');
		$selectlist8.find('li').each(function(index, element){
			$('
' + $(element).text() + '
').appendTo($textLengthTester);
		});
		minWidth = $textLengthTester.width();
		ok(($selectlist8.width() >= minWidth), 'selectlist autoresized to ' + $selectlist8.width() + ' should be greater than ' + minWidth);

		//hidden selectlists have no size
		ok($selectlist9.width() === 0, 'selectlist hidden, sized 0');

		//remove hidden to prepare to measure its new size
		$selectlist9.removeClass('hidden');

		//measure all children of selectlist to be tested (add them all to a span and see how wide the span is) and make sure the selectlist is actually big enough to fit that
		$textLengthTester = $('').appendTo('body');
		$selectlist9.find('li').each(function(index, element){
			$('
' + $(element).text() + '
').appendTo($textLengthTester);
		});
		minWidth = $textLengthTester.width();
		ok(($selectlist9.width() >= minWidth), 'selectlist was hidden, now shown, sized ' + $selectlist9.width() + ' should be greater than ' + minWidth);
	});

	test("should set disabled state", function () {
		var $selectlist = $(html).find('#MySelectlist').selectlist();
		$selectlist.selectlist('disable');
		equal($selectlist.find('.btn').hasClass('disabled'), true, 'element disabled');
	});

	test("should set enabled state", function () {
		var $selectlist = $(html).find('#MySelectlist').selectlist();
		$selectlist.selectlist('disable');
		$selectlist.selectlist('enable');
		equal($selectlist.find('.btn').hasClass('disabled'), false, 'element enabled');
	});

	test("should set default selection", function () {
		var $selectlist = $(html).find('#MySelectlist2').selectlist(); //.selectlist();
		var item = $selectlist.selectlist('selectedItem');
		var expectedItem = { selected: true, text: 'Two', value: 2 };
		deepEqual(item, expectedItem, 'default item selected');
	});

	test("should select by index", function () {
		var $selectlist = $(html).find('#MySelectlist3').selectlist();
		$selectlist.selectlist('selectByIndex', 0);

		var item = $selectlist.selectlist('selectedItem');
		var expectedItem = {selected: true, text: 'One', value: 1 };
		deepEqual(item, expectedItem, 'item selected');
	});

	test("should select by value", function () {
		var $selectlist = $(html.find('#MySelectlist4').selectlist()); //.selectlist();
		$selectlist.selectlist('selectByValue', 2);

		var item = $selectlist.selectlist('selectedItem');
		var expectedItem = {selected: true, text: 'Two', value: 2 }; //weird
		deepEqual(item, expectedItem, 'item selected');
	});

	test("should select by value with whitespace", function () {
		var $selectlist = $(html).find('#MySelectlist5').selectlist();
		$selectlist.selectlist('selectByValue', 'Item Five');

		var item = $selectlist.selectlist('selectedItem');
		var expectedItem = {selected: true, text: 'Item Five', value: 'Item Five' }; //weird
		deepEqual(item, expectedItem, 'item selected');
	});

	test("should select by text", function () {
		var $selectlist = $(html).find('#MySelectlist6').selectlist();
		$selectlist.selectlist('selectByText', 'THREE');

		var item = $selectlist.selectlist('selectedItem');
		var expectedItem = {selected: true, text: 'Three', value: 3 };
		deepEqual(item, expectedItem, 'item selected');
	});

	test("should select by text with whitespace", function () {
		var $selectlist = $(html).find('#MySelectlist').selectlist();
		$selectlist.selectlist('selectByText', 'Item Five');

		var item = $selectlist.selectlist('selectedItem');
		var expectedItem = {selected: true, text: 'Item Five', value: 'Item Five' };
		deepEqual(item, expectedItem, 'item selected');
	});

	test("should select by selector", function () {
		var $selectlist = $(html).find('#MySelectlist').selectlist();
		$selectlist.selectlist('selectBySelector', 'li[data-fizz=buzz]');

		var item = $selectlist.selectlist('selectedItem');
		var expectedItem = {selected: true, text: 'Buzz', value: 4, foo: 'bar', fizz: 'buzz' };
		deepEqual(item, expectedItem, 'item selected');
	});

	test("should fire change event", function () {
		var eventFired = false;
		var selectedText = '';
		var selectedValue = '';

		var $selectlist = $(html).find('#MySelectlist').selectlist().on('changed.fu.selectlist', function (evt, data) {
			eventFired = true;
			selectedText = data.text;
			selectedValue = data.value;
		});

		// simulate changed event
		$selectlist.find('.dropdown-menu a:first').click();

		equal(eventFired, true, 'change event fired');
		equal(selectedText, 'One', 'text passed in from change event');
		equal(selectedValue, 1, 'value passed in from change event');
	});

	test("should destroy control", function () {
		var $el = $(html).find('#MySelectlist').selectlist();

		equal(typeof( $el.selectlist('destroy')) , 'string', 'returns string (markup)');
		equal( $el.parent().length, false, 'control has been removed from DOM');
	});

});
<commit_msg>selectlist-unittest-fix: fixes #1288 by making lengthTester p tag padding driven by selectlist button padding<commit_after>/*global QUnit:false, module:false, test:false, asyncTest:false, expect:false*/
/*global start:false, stop:false ok:false, equal:false, notEqual:false, deepEqual:false*/
/*global notDeepEqual:false, strictEqual:false, notStrictEqual:false, raises:false*/

define(function(require){
	var $ = require('jquery');
	var html = require('text!test/markup/selectlist-markup.html');
	/* FOR DEV TESTING */
	//var html = require('text!dev.html!strip');
	html = $('
'+html+'
');

	$('body').append(html);

	require('bootstrap');
	require('fuelux/selectlist');

	module("Fuel UX Selectlist");

	test("should be defined on jquery object", function () {
		ok($().selectlist, 'selectlist method is defined');
	});

	test("should return element", function () {
		var $selectlist = $(html).find('#MySelectlist').selectlist();
		ok($selectlist.selectlist() === $selectlist, 'selectlist should be initialized');
	});

	test("should autosize correctly", function () {
		var $selectlist8 = $('body').find('#MySelectlist8').selectlist();
		var $selectlist9 = $('body').find('#MySelectlist9').selectlist();
		var $btn, minWidth;

		//measure all children of selectlist to be tested (add them all to a span and see how wide the span is) and make sure the selectlist is actually big enough to fit that
		$btn = $selectlist8.find('button.dropdown-toggle');
		var $textLengthTester = $('').appendTo('body');
		$selectlist8.find('li').each(function(index, element){
			//set the p tag right/left padding to that of the selectlist button right/left padding
			$('
' + $(element).text() + '
').appendTo($textLengthTester);
		});
		minWidth = $textLengthTester.width();
		ok(($selectlist8.width() >= minWidth), 'selectlist autoresized to ' + $selectlist8.width() + ' should be greater than ' + minWidth);

		//hidden selectlists have no size
		ok($selectlist9.width() === 0, 'selectlist hidden, sized 0');

		//remove hidden to prepare to measure its new size
		$selectlist9.removeClass('hidden');

		//measure all children of selectlist to be tested (add them all to a span and see how wide the span is) and make sure the selectlist is actually big enough to fit that
		$btn = $selectlist9.find('button.dropdown-toggle');
		$textLengthTester = $('').appendTo('body');
		$selectlist9.find('li').each(function(index, element){
			//set the p tag right/left padding to that of the selectlist button right/left padding
			$('
' + $(element).text() + '
').appendTo($textLengthTester);
		});
		minWidth = $textLengthTester.width();
		ok(($selectlist9.width() >= minWidth), 'selectlist was hidden, now shown, sized ' + $selectlist9.width() + ' should be greater than ' + minWidth);
	});

	test("should set disabled state", function () {
		var $selectlist = $(html).find('#MySelectlist').selectlist();
		$selectlist.selectlist('disable');
		equal($selectlist.find('.btn').hasClass('disabled'), true, 'element disabled');
	});

	test("should set enabled state", function () {
		var $selectlist = $(html).find('#MySelectlist').selectlist();
		$selectlist.selectlist('disable');
		$selectlist.selectlist('enable');
		equal($selectlist.find('.btn').hasClass('disabled'), false, 'element enabled');
	});

	test("should set default selection", function () {
		var $selectlist = $(html).find('#MySelectlist2').selectlist(); //.selectlist();
		var item = $selectlist.selectlist('selectedItem');
		var expectedItem = { selected: true, text: 'Two', value: 2 };
		deepEqual(item, expectedItem, 'default item selected');
	});

	test("should select by index", function () {
		var $selectlist = $(html).find('#MySelectlist3').selectlist();
		$selectlist.selectlist('selectByIndex', 0);

		var item = $selectlist.selectlist('selectedItem');
		var expectedItem = {selected: true, text: 'One', value: 1 };
		deepEqual(item, expectedItem, 'item selected');
	});

	test("should select by value", function () {
		var $selectlist = $(html.find('#MySelectlist4').selectlist()); //.selectlist();
		$selectlist.selectlist('selectByValue', 2);

		var item = $selectlist.selectlist('selectedItem');
		var expectedItem = {selected: true, text: 'Two', value: 2 }; //weird
		deepEqual(item, expectedItem, 'item selected');
	});

	test("should select by value with whitespace", function () {
		var $selectlist = $(html).find('#MySelectlist5').selectlist();
		$selectlist.selectlist('selectByValue', 'Item Five');

		var item = $selectlist.selectlist('selectedItem');
		var expectedItem = {selected: true, text: 'Item Five', value: 'Item Five' }; //weird
		deepEqual(item, expectedItem, 'item selected');
	});

	test("should select by text", function () {
		var $selectlist = $(html).find('#MySelectlist6').selectlist();
		$selectlist.selectlist('selectByText', 'THREE');

		var item = $selectlist.selectlist('selectedItem');
		var expectedItem = {selected: true, text: 'Three', value: 3 };
		deepEqual(item, expectedItem, 'item selected');
	});

	test("should select by text with whitespace", function () {
		var $selectlist = $(html).find('#MySelectlist').selectlist();
		$selectlist.selectlist('selectByText', 'Item Five');

		var item = $selectlist.selectlist('selectedItem');
		var expectedItem = {selected: true, text: 'Item Five', value: 'Item Five' };
		deepEqual(item, expectedItem, 'item selected');
	});

	test("should select by selector", function () {
		var $selectlist = $(html).find('#MySelectlist').selectlist();
		$selectlist.selectlist('selectBySelector', 'li[data-fizz=buzz]');

		var item = $selectlist.selectlist('selectedItem');
		var expectedItem = {selected: true, text: 'Buzz', value: 4, foo: 'bar', fizz: 'buzz' };
		deepEqual(item, expectedItem, 'item selected');
	});

	test("should fire change event", function () {
		var eventFired = false;
		var selectedText = '';
		var selectedValue = '';

		var $selectlist = $(html).find('#MySelectlist').selectlist().on('changed.fu.selectlist', function (evt, data) {
			eventFired = true;
			selectedText = data.text;
			selectedValue = data.value;
		});

		// simulate changed event
		$selectlist.find('.dropdown-menu a:first').click();

		equal(eventFired, true, 'change event fired');
		equal(selectedText, 'One', 'text passed in from change event');
		equal(selectedValue, 1, 'value passed in from change event');
	});

	test("should destroy control", function () {
		var $el = $(html).find('#MySelectlist').selectlist();

		equal(typeof( $el.selectlist('destroy')) , 'string', 'returns string (markup)');
		equal( $el.parent().length, false, 'control has been removed from DOM');
	});

});
<|endoftext|>


<commit_before>Package.describe({
  name: 'ostrio:flow-router-extra',
  summary: 'Carefully extended flow-router with waitOn and template context',
  version: '3.4.5',
  git: 'https://github.com/VeliovGroup/flow-router'
});

Package.onUse(function (api) {
  api.versionsFrom('1.4');
  api.use([
    'modules',
    'ecmascript',
    'promise',
    'modules',
    'underscore',
    'tracker',
    'reactive-dict',
    'reactive-var',
    'ejson'
  ], ['client', 'server']);

  api.mainModule('client/_init.js', 'client');
  api.mainModule('server/_init.js', 'server');
});

Package.onTest(function(api) {
  api.use(['ecmascript', 'tinytest', 'underscore', 'reactive-var', 'tracker', 'check', 'mongo', 'http', 'random', 'tmeasday:html5-history-api', 'staringatlights:fast-render', 'staringatlights:inject-data', 'ostrio:flow-router-extra']);

  api.addFiles('test/common/fast_render_route.js', ['client', 'server']);

  api.addFiles('test/client/_helpers.js', 'client');
  api.addFiles('test/server/_helpers.js', 'server');

  api.addFiles('test/client/loader.spec.js', 'client');
  api.addFiles('test/client/route.reactivity.spec.js', 'client');
  api.addFiles('test/client/router.core.spec.js', 'client');
  api.addFiles('test/client/router.subs_ready.spec.js', 'client');
  api.addFiles('test/client/router.reactivity.spec.js', 'client');
  api.addFiles('test/client/group.spec.js', 'client');
  api.addFiles('test/client/trigger.spec.js', 'client');
  api.addFiles('test/client/triggers.js', 'client');

  api.addFiles('test/server/plugins/fast_render.js', 'server');

  api.addFiles('test/common/router.path.spec.js', ['client', 'server']);
  api.addFiles('test/common/router.url.spec.js', ['client', 'server']);
  api.addFiles('test/common/router.addons.spec.js', ['client', 'server']);
  api.addFiles('test/common/route.spec.js', ['client', 'server']);
  api.addFiles('test/common/group.spec.js', ['client', 'server']);
});

Npm.depends({
  'page': '1.8.3',
  'qs': '6.5.1'
});
<commit_msg>Add Weak dependency on `templating` and `blaze`<commit_after>Package.describe({
  name: 'ostrio:flow-router-extra',
  summary: 'Carefully extended flow-router with waitOn and template context',
  version: '3.4.5',
  git: 'https://github.com/VeliovGroup/flow-router'
});

Package.onUse(function (api) {
  api.versionsFrom('1.4');
  api.use([
    'modules',
    'ecmascript',
    'promise',
    'modules',
    'underscore',
    'tracker',
    'reactive-dict',
    'reactive-var',
    'ejson'
  ], ['client', 'server']);

  api.use(['templating', 'blaze'], 'client', { weak: true });

  api.mainModule('client/_init.js', 'client');
  api.mainModule('server/_init.js', 'server');
});

Package.onTest(function(api) {
  api.use(['ecmascript', 'tinytest', 'underscore', 'reactive-var', 'tracker', 'check', 'mongo', 'http', 'random', 'tmeasday:html5-history-api', 'staringatlights:fast-render', 'staringatlights:inject-data', 'ostrio:flow-router-extra']);

  api.addFiles('test/common/fast_render_route.js', ['client', 'server']);

  api.addFiles('test/client/_helpers.js', 'client');
  api.addFiles('test/server/_helpers.js', 'server');

  api.addFiles('test/client/loader.spec.js', 'client');
  api.addFiles('test/client/route.reactivity.spec.js', 'client');
  api.addFiles('test/client/router.core.spec.js', 'client');
  api.addFiles('test/client/router.subs_ready.spec.js', 'client');
  api.addFiles('test/client/router.reactivity.spec.js', 'client');
  api.addFiles('test/client/group.spec.js', 'client');
  api.addFiles('test/client/trigger.spec.js', 'client');
  api.addFiles('test/client/triggers.js', 'client');

  api.addFiles('test/server/plugins/fast_render.js', 'server');

  api.addFiles('test/common/router.path.spec.js', ['client', 'server']);
  api.addFiles('test/common/router.url.spec.js', ['client', 'server']);
  api.addFiles('test/common/router.addons.spec.js', ['client', 'server']);
  api.addFiles('test/common/route.spec.js', ['client', 'server']);
  api.addFiles('test/common/group.spec.js', ['client', 'server']);
});

Npm.depends({
  'page': '1.8.3',
  'qs': '6.5.1'
});
<|endoftext|>


<commit_before>
function assert(condition, message)
{
    if (!condition)
    {
        throw new Error(message || "Assertion failed");
    }
}

function glCompileShader(gl, type, name, source)
{
    console.log("Compiling " + name);

    // Compile the shader
    let shader = gl.createShader(type);
    gl.shaderSource(shader, source);
    gl.compileShader(shader);

    // Report any errors
    if (!gl.getShaderParameter(shader, gl.COMPILE_STATUS))
    {
        console.log("Error compiling " + name);
        console.log(gl.getShaderInfoLog(shader));
        console.trace();
    }

    return shader;
}

function glCreateProgram(gl, vshader, fshader)
{
    // Attach shaders and link
    let program = gl.createProgram();
    gl.attachShader(program, vshader);
    gl.attachShader(program, fshader);
    gl.linkProgram(program);

    // Report any errors
    if (!gl.getProgramParameter(program, gl.LINK_STATUS))
    {
        console.log("Failed to link program");
        console.trace();
    }

    return program;
}

function glSetUniform(gl, program, name, value, index)
{
    // Get location
    const location = gl.getUniformLocation(program, name);
    assert(location != null, "Can't find uniform " + name);

    // Dispatch to uniform function by type
    assert(value != null, "Value is null");
    const type = Object.prototype.toString.call(value).slice(8, -1);
    switch (type)
    {
        case "Number":
            gl.uniform1f(location, value);
            break;

        case "WebGLTexture":
            gl.activeTexture(gl.TEXTURE0 + index);
            gl.bindTexture(gl.TEXTURE_2D, value);
            gl.uniform1i(location, index);
            break;

        default:
            assert(false, "Unhandled type " + type);
            break;
    }
}

function glCreateTexture(gl, width, height, data)
{
    const texture = gl.createTexture();

    // Set filtering/wrapping to nearest/clamp
    gl.bindTexture(gl.TEXTURE_2D, texture);
    gl.texParameteri(gl.TEXTURE_2D, gl.TEXTURE_MIN_FILTER, gl.NEAREST);
    gl.texParameteri(gl.TEXTURE_2D, gl.TEXTURE_MAG_FILTER, gl.NEAREST);
    gl.texParameteri(gl.TEXTURE_2D, gl.TEXTURE_WRAP_S, gl.CLAMP_TO_EDGE);
    gl.texParameteri(gl.TEXTURE_2D, gl.TEXTURE_WRAP_T, gl.CLAMP_TO_EDGE);

    gl.texImage2D(gl.TEXTURE_2D, 0, gl.RGBA, width, height, 0, gl.RGBA, gl.UNSIGNED_BYTE, data);

    return texture;
}

const glDynamicBufferType = Object.freeze({
    Buffer: 1,
    Texture: 2
});

class glDynamicBuffer
{
    constructor(gl, element_type, nb_elements, nb_entries, buffer_type)
    {
        this.gl = gl;
        this.elementType = element_type;
        this.nbElements = nb_elements;
        this.bufferType = buffer_type == undefined ? glDynamicBufferType.Buffer : buffer_type;
        this.dirty = false;

        this.Resize(nb_entries);
    }

    BindAsInstanceAttribute(program, attrib_name)
    {
        assert(this.bufferType == glDynamicBufferType.Buffer, "Can only call BindAsInstanceAttribute with Buffer types");

        let gl = this.gl;

        gl.bindBuffer(gl.ARRAY_BUFFER, this.buffer);

        // The attribute referenced in the program
        const attrib_location = gl.getAttribLocation(program, attrib_name);

        gl.enableVertexAttribArray(attrib_location);
        gl.vertexAttribPointer(attrib_location, this.nbElements, this.elementType, false, 0, 0);

        // One per instance
        gl.vertexAttribDivisor(attrib_location, 1);
    }

    UploadData()
    {
        let gl = this.gl;

        switch (this.bufferType)
        {
            case glDynamicBufferType.Buffer:
                gl.bindBuffer(gl.ARRAY_BUFFER, this.buffer);
                gl.bufferSubData(gl.ARRAY_BUFFER, 0, this.cpuArray);
                break;

            case glDynamicBufferType.Texture:
                // Single element formats for now
                assert(this.elementType == gl.BYTE || this.elementType == gl.FLOAT);
                assert(this.nbElements == 1);
                gl.bindTexture(gl.TEXTURE_2D, this.texture);
                const internal_format = this.elementType == gl.BYTE ? gl.ALPHA : gl.R32F;
                const format = this.elementType == gl.BYTE ? gl.ALPHA : gl.RED;
                const type = this.elementType == gl.BYTE ? gl.UNSIGNED_BYTE : gl.FLOAT;
                gl.texImage2D(gl.TEXTURE_2D, 0, internal_format, this.nbEntries, 1, 0, format, type, this.cpuArray);
                break;
        }
    }

    UploadDirtyData()
    {
        if (this.dirty)
        {
            this.UploadData();
            this.dirty = false;
        }
    }

    ResizeToFitNextPow2(target_count)
    {
        let nb_entries = this.nbEntries;
        while (target_count > nb_entries)
        {
            nb_entries <<= 1;
        }

        if (nb_entries > this.nbEntries)
        {
            this.Resize(nb_entries);
        }
    }

    Resize(nb_entries)
    {
        let gl = this.gl;

        this.nbEntries = nb_entries;

        // Create the CPU array
        const old_array = this.cpuArray;
        switch (this.elementType)
        {
            case gl.FLOAT:
                this.nbElementBytes = 4;
                this.cpuArray = new Float32Array(this.nbElements * this.nbEntries);
                break;

            case gl.BYTE:
                this.nbElementBytes = 1;
                this.cpuArray = new Uint8Array(this.nbElements * this.nbEntries);
                break;

            default:
                assert(false, "Unsupported dynamic buffer element type");
        }

        // Calculate byte size of the buffer
        this.nbBytes = this.nbElementBytes * this.nbElements * this.nbEntries;

        if (old_array != undefined)
        {
            // Copy the values of the previous array over
            this.cpuArray.set(old_array);

            console.log(`glDynamicBuffer: Resizing to ${nb_entries} entries, ${this.nbElements} elements per entry, ${this.nbElementBytes} bytes per element, ${this.nbBytes} bytes total.`);
        }
        else
        {
            console.log(`glDynamicBuffer: Creating ${nb_entries} entries, ${this.nbElements} elements per entry, ${this.nbElementBytes} bytes per element, ${this.nbBytes} bytes total.`);
        }

        // Create the GPU buffer
        switch (this.bufferType)
        {
            case glDynamicBufferType.Buffer:
                this.buffer = gl.createBuffer();
                gl.bindBuffer(gl.ARRAY_BUFFER, this.buffer);
                gl.bufferData(gl.ARRAY_BUFFER, this.nbBytes, gl.DYNAMIC_DRAW);
                break;

            case glDynamicBufferType.Texture:
                this.texture = gl.createTexture();

                // Point sampling with clamp for indexing
                gl.bindTexture(gl.TEXTURE_2D, this.texture);
                gl.texParameteri(gl.TEXTURE_2D, gl.TEXTURE_MIN_FILTER, gl.NEAREST);
                gl.texParameteri(gl.TEXTURE_2D, gl.TEXTURE_MAG_FILTER, gl.NEAREST);
                gl.texParameteri(gl.TEXTURE_2D, gl.TEXTURE_WRAP_S, gl.CLAMP_TO_EDGE);
                gl.texParameteri(gl.TEXTURE_2D, gl.TEXTURE_WRAP_T, gl.CLAMP_TO_EDGE);
                break;

            default:
                assert(false, "Unsupported dynamic buffer type");
        }

        this.UploadData();
    }
};

<commit_msg>glCreateProgramFromSource<commit_after>
function assert(condition, message)
{
    if (!condition)
    {
        throw new Error(message || "Assertion failed");
    }
}

function glCompileShader(gl, type, name, source)
{
    console.log("Compiling " + name);

    // Compile the shader
    let shader = gl.createShader(type);
    gl.shaderSource(shader, source);
    gl.compileShader(shader);

    // Report any errors
    if (!gl.getShaderParameter(shader, gl.COMPILE_STATUS))
    {
        console.log("Error compiling " + name);
        console.log(gl.getShaderInfoLog(shader));
        console.trace();
    }

    return shader;
}

function glCreateProgram(gl, vshader, fshader)
{
    // Attach shaders and link
    let program = gl.createProgram();
    gl.attachShader(program, vshader);
    gl.attachShader(program, fshader);
    gl.linkProgram(program);

    // Report any errors
    if (!gl.getProgramParameter(program, gl.LINK_STATUS))
    {
        console.log("Failed to link program");
        console.trace();
    }

    return program;
}

function glCreateProgramFromSource(gl, vshader_name, vshader_source, fshader_name, fshader_source)
{
    const vshader = glCompileShader(gl, gl.VERTEX_SHADER, vshader_name, vshader_source);
    const fshader = glCompileShader(gl, gl.FRAGMENT_SHADER, fshader_name, fshader_source);
    return glCreateProgram(gl, vshader, fshader);
}

function glSetUniform(gl, program, name, value, index)
{
    // Get location
    const location = gl.getUniformLocation(program, name);
    assert(location != null, "Can't find uniform " + name);

    // Dispatch to uniform function by type
    assert(value != null, "Value is null");
    const type = Object.prototype.toString.call(value).slice(8, -1);
    switch (type)
    {
        case "Number":
            gl.uniform1f(location, value);
            break;

        case "WebGLTexture":
            gl.activeTexture(gl.TEXTURE0 + index);
            gl.bindTexture(gl.TEXTURE_2D, value);
            gl.uniform1i(location, index);
            break;

        default:
            assert(false, "Unhandled type " + type);
            break;
    }
}

function glCreateTexture(gl, width, height, data)
{
    const texture = gl.createTexture();

    // Set filtering/wrapping to nearest/clamp
    gl.bindTexture(gl.TEXTURE_2D, texture);
    gl.texParameteri(gl.TEXTURE_2D, gl.TEXTURE_MIN_FILTER, gl.NEAREST);
    gl.texParameteri(gl.TEXTURE_2D, gl.TEXTURE_MAG_FILTER, gl.NEAREST);
    gl.texParameteri(gl.TEXTURE_2D, gl.TEXTURE_WRAP_S, gl.CLAMP_TO_EDGE);
    gl.texParameteri(gl.TEXTURE_2D, gl.TEXTURE_WRAP_T, gl.CLAMP_TO_EDGE);

    gl.texImage2D(gl.TEXTURE_2D, 0, gl.RGBA, width, height, 0, gl.RGBA, gl.UNSIGNED_BYTE, data);

    return texture;
}

const glDynamicBufferType = Object.freeze({
    Buffer: 1,
    Texture: 2
});

class glDynamicBuffer
{
    constructor(gl, element_type, nb_elements, nb_entries, buffer_type)
    {
        this.gl = gl;
        this.elementType = element_type;
        this.nbElements = nb_elements;
        this.bufferType = buffer_type == undefined ? glDynamicBufferType.Buffer : buffer_type;
        this.dirty = false;

        this.Resize(nb_entries);
    }

    BindAsInstanceAttribute(program, attrib_name)
    {
        assert(this.bufferType == glDynamicBufferType.Buffer, "Can only call BindAsInstanceAttribute with Buffer types");

        let gl = this.gl;

        gl.bindBuffer(gl.ARRAY_BUFFER, this.buffer);

        // The attribute referenced in the program
        const attrib_location = gl.getAttribLocation(program, attrib_name);

        gl.enableVertexAttribArray(attrib_location);
        gl.vertexAttribPointer(attrib_location, this.nbElements, this.elementType, false, 0, 0);

        // One per instance
        gl.vertexAttribDivisor(attrib_location, 1);
    }

    UploadData()
    {
        let gl = this.gl;

        switch (this.bufferType)
        {
            case glDynamicBufferType.Buffer:
                gl.bindBuffer(gl.ARRAY_BUFFER, this.buffer);
                gl.bufferSubData(gl.ARRAY_BUFFER, 0, this.cpuArray);
                break;

            case glDynamicBufferType.Texture:
                // Single element formats for now
                assert(this.elementType == gl.BYTE || this.elementType == gl.FLOAT);
                assert(this.nbElements == 1);
                gl.bindTexture(gl.TEXTURE_2D, this.texture);
                const internal_format = this.elementType == gl.BYTE ? gl.ALPHA : gl.R32F;
                const format = this.elementType == gl.BYTE ? gl.ALPHA : gl.RED;
                const type = this.elementType == gl.BYTE ? gl.UNSIGNED_BYTE : gl.FLOAT;
                gl.texImage2D(gl.TEXTURE_2D, 0, internal_format, this.nbEntries, 1, 0, format, type, this.cpuArray);
                break;
        }
    }

    UploadDirtyData()
    {
        if (this.dirty)
        {
            this.UploadData();
            this.dirty = false;
        }
    }

    ResizeToFitNextPow2(target_count)
    {
        let nb_entries = this.nbEntries;
        while (target_count > nb_entries)
        {
            nb_entries <<= 1;
        }

        if (nb_entries > this.nbEntries)
        {
            this.Resize(nb_entries);
        }
    }

    Resize(nb_entries)
    {
        let gl = this.gl;

        this.nbEntries = nb_entries;

        // Create the CPU array
        const old_array = this.cpuArray;
        switch (this.elementType)
        {
            case gl.FLOAT:
                this.nbElementBytes = 4;
                this.cpuArray = new Float32Array(this.nbElements * this.nbEntries);
                break;

            case gl.BYTE:
                this.nbElementBytes = 1;
                this.cpuArray = new Uint8Array(this.nbElements * this.nbEntries);
                break;

            default:
                assert(false, "Unsupported dynamic buffer element type");
        }

        // Calculate byte size of the buffer
        this.nbBytes = this.nbElementBytes * this.nbElements * this.nbEntries;

        if (old_array != undefined)
        {
            // Copy the values of the previous array over
            this.cpuArray.set(old_array);

            console.log(`glDynamicBuffer: Resizing to ${nb_entries} entries, ${this.nbElements} elements per entry, ${this.nbElementBytes} bytes per element, ${this.nbBytes} bytes total.`);
        }
        else
        {
            console.log(`glDynamicBuffer: Creating ${nb_entries} entries, ${this.nbElements} elements per entry, ${this.nbElementBytes} bytes per element, ${this.nbBytes} bytes total.`);
        }

        // Create the GPU buffer
        switch (this.bufferType)
        {
            case glDynamicBufferType.Buffer:
                this.buffer = gl.createBuffer();
                gl.bindBuffer(gl.ARRAY_BUFFER, this.buffer);
                gl.bufferData(gl.ARRAY_BUFFER, this.nbBytes, gl.DYNAMIC_DRAW);
                break;

            case glDynamicBufferType.Texture:
                this.texture = gl.createTexture();

                // Point sampling with clamp for indexing
                gl.bindTexture(gl.TEXTURE_2D, this.texture);
                gl.texParameteri(gl.TEXTURE_2D, gl.TEXTURE_MIN_FILTER, gl.NEAREST);
                gl.texParameteri(gl.TEXTURE_2D, gl.TEXTURE_MAG_FILTER, gl.NEAREST);
                gl.texParameteri(gl.TEXTURE_2D, gl.TEXTURE_WRAP_S, gl.CLAMP_TO_EDGE);
                gl.texParameteri(gl.TEXTURE_2D, gl.TEXTURE_WRAP_T, gl.CLAMP_TO_EDGE);
                break;

            default:
                assert(false, "Unsupported dynamic buffer type");
        }

        this.UploadData();
    }
};

<|endoftext|>


<commit_before>import {mapThrough, nullMap} from "./map"

export class Step {
  constructor(name, from, to, pos, param = null) {
    this.name = name
    this.from = from
    this.to = to
    this.pos = pos
    this.param = param
  }
}

const steps = Object.create(null)

export function defineStep(name, impl) { steps[name] = impl }

export function applyStep(doc, step) {
  if (!(step.name in steps))
    throw new Error("Undefined transform " + transform.name)
  return steps[step.name].apply(doc, step)
}

export function invertStep(result, step) {
  return steps[step.name].invert(result, step)
}

export class Result {
  constructor(before, after = before, map = nullMap) {
    this.before = before
    this.doc = after
    this.map = map
  }
}

export class Transform {
  constructor(doc, storeInverses) {
    this.before = this.doc = doc
    this.steps = []
    this.maps = []
    this.inverted = storeInverses && []
  }

  step(step, from, to, pos, param) {
    if (typeof step == "string")
      step = new Step(step, from, to, pos, param)
    let result = applyStep(this.doc, step)
    if (result) {
      this.steps.push(step)
      this.maps.push(result.map)
      if (this.inverted) this.inverted.unshift(invertStep(result, step))
      this.doc = result.doc
    }
    return result
  }

  invert() {
    let inverted = Tr(this.doc)
    this.inverted.forEach(s => inverted.step(s))
    return inverted
  }

  map(pos, bias = 0, back = false, offsets = null, from = null) {
    let maps = this.maps
    if (from != null) maps = back ? maps.slice(0, from) : maps.slice(from)
    return mapThrough(maps, pos, bias, back, offsets)
  }

  mapSimple(pos, bias = 0, back = false) {
    return this.map(pos, bias, back).pos
  }
}

export function Tr(doc, storeInverses) { return new Transform(doc, storeInverses) }
<commit_msg>Back out storeInverted flag<commit_after>import {mapThrough, nullMap} from "./map"

export class Step {
  constructor(name, from, to, pos, param = null) {
    this.name = name
    this.from = from
    this.to = to
    this.pos = pos
    this.param = param
  }
}

const steps = Object.create(null)

export function defineStep(name, impl) { steps[name] = impl }

export function applyStep(doc, step) {
  if (!(step.name in steps))
    throw new Error("Undefined transform " + transform.name)
  return steps[step.name].apply(doc, step)
}

export function invertStep(result, step) {
  return steps[step.name].invert(result, step)
}

export class Result {
  constructor(before, after = before, map = nullMap) {
    this.before = before
    this.doc = after
    this.map = map
  }
}

export class Transform {
  constructor(doc) {
    this.before = this.doc = doc
    this.steps = []
    this.maps = []
  }

  step(step, from, to, pos, param) {
    if (typeof step == "string")
      step = new Step(step, from, to, pos, param)
    let result = applyStep(this.doc, step)
    if (result) {
      this.steps.push(step)
      this.maps.push(result.map)
      this.doc = result.doc
    }
    return result
  }

  invert() {
    let doc = this.before, inverted = []
    for (let i = 0; i < this.steps.length; i++) {
      let result = applyStep(doc, this.steps[i])
      inverted.push(invertStep(result, this.steps[i]))
      doc = result.doc
    }
    let out = Tr(this.doc)
    for (let i = inverted.length - 1; i >= 0; i--)
      out.step(inverted[i])
    return out
  }

  map(pos, bias = 0, back = false, offsets = null, from = null) {
    let maps = this.maps
    if (from != null) maps = back ? maps.slice(0, from) : maps.slice(from)
    return mapThrough(maps, pos, bias, back, offsets)
  }

  mapSimple(pos, bias = 0, back = false) {
    return this.map(pos, bias, back).pos
  }
}

export function Tr(doc) { return new Transform(doc) }
<|endoftext|>


<commit_before>'use strict';

const test = require('tape');
const mock = require('mock-require');
const diff = require('sinon-called-with-diff');
const sinon = diff(require('sinon'));

const stub = require('mock-require');
const clean = require('clear-module');

const configPath = '../../server/config';
const terminalPath = '../../server/terminal';

test('cloudcmd: terminal: disabled', (t) => {
    clean(terminalPath);
    stub(configPath, () => {
        return false;
    });

    const terminal = require('../../server/terminal');

    const fn = terminal();

    t.notOk(fn(), 'should return noop');

    clean(configPath);
    require(configPath);

    t.end();
});

test('cloudcmd: terminal: disabled: listen', (t) => {
    clean(terminalPath);
    stub(configPath, () => false);

    const terminal = require(terminalPath);

    const fn = terminal().listen();

    t.notOk(fn, 'should return noop');

    clean(configPath);
    require(configPath);

    t.end();
});

test('cloudcmd: terminal: enabled', (t) => {
    const term = sinon.stub();
    const arg = 'hello';

    clean(terminalPath);
    stub(configPath, () => '/terminal');
    stub('/terminal', term);

    const terminal = require(terminalPath);
    terminal(arg);

    t.ok(term.calledWith(arg), 'should call terminal');
    t.end();
});

test('cloudcmd: terminal: enabled: no string', (t) => {
    const {log} = console;
    console.log = sinon.stub();

    clean(terminalPath);
    stub(configPath, () => true);

    const terminal = require(terminalPath);
    terminal();

    const msg = 'cloudcmd --terminal: path must be a string';

    t.ok(console.log.calledWith(msg), 'should call exit');

    console.log = log;

    t.end();
});

test('cloudcmd: terminal: no arg', (t) => {
    const gritty = {};

    mock('gritty', gritty);

    clean(terminalPath);
    stub(configPath, (a) => {
        if (a === 'terminal')
            return true;

        return 'gritty';
    });

    const terminal = require(terminalPath);
    const result = terminal();

    t.equal(result, gritty, 'should equal');

    clean(configPath);
    require(configPath);

    t.end();
});

<commit_msg>test(terminal) enabled: no string<commit_after>'use strict';

const test = require('tape');
const mock = require('mock-require');
const diff = require('sinon-called-with-diff');
const sinon = diff(require('sinon'));

const stub = require('mock-require');
const clean = require('clear-module');

const configPath = '../../server/config';
const terminalPath = '../../server/terminal';

test('cloudcmd: terminal: disabled', (t) => {
    clean(terminalPath);
    stub(configPath, () => {
        return false;
    });

    const terminal = require('../../server/terminal');

    const fn = terminal();

    t.notOk(fn(), 'should return noop');

    clean(configPath);
    require(configPath);

    t.end();
});

test('cloudcmd: terminal: disabled: listen', (t) => {
    clean(terminalPath);
    stub(configPath, () => false);

    const terminal = require(terminalPath);

    const fn = terminal().listen();

    t.notOk(fn, 'should return noop');

    clean(configPath);
    require(configPath);

    t.end();
});

test('cloudcmd: terminal: enabled', (t) => {
    const term = sinon.stub();
    const arg = 'hello';

    clean(terminalPath);
    stub(configPath, () => '/terminal');
    stub('/terminal', term);

    const terminal = require(terminalPath);
    terminal(arg);

    t.ok(term.calledWith(arg), 'should call terminal');
    t.end();
});

test('cloudcmd: terminal: enabled: no string', (t) => {
    const {log:originalLog} = console;
    const log = sinon.stub();

    clean(terminalPath);
    stub(configPath, () => 'hello');

    console.log = log;
    const terminal = require(terminalPath);
    terminal();
    console.log = originalLog;

    const msg = 'cloudcmd --terminal: Cannot find module \'hello\'';

    t.ok(log.calledWith(msg), 'should call exit');

    t.end();
});

test('cloudcmd: terminal: no arg', (t) => {
    const gritty = {};

    mock('gritty', gritty);

    clean(terminalPath);
    stub(configPath, (a) => {
        if (a === 'terminal')
            return true;

        return 'gritty';
    });

    const terminal = require(terminalPath);
    const result = terminal();

    t.equal(result, gritty, 'should equal');

    clean(configPath);
    require(configPath);

    t.end();
});

<|endoftext|>


<commit_before>Package.describe({
  summary: "Profile fields based log in, extended version of loginWithPassword() function"
});

Package.on_use(function (api) {
  var both = ['client', 'server'];
  api.use(['accounts-base' , 'accounts-password'], both);

  //api.export && api.export('Roles');

  api.add_files('accounts-profile-fields-server.js', 'server');
  api.add_files('accounts-profile-fields-client.js', 'client');
});
<commit_msg>change version<commit_after>Package.describe({
  summary: "Profile fields based log in, extended version of loginWithPassword() function"
});

Package.on_use(function (api) {
  var both = ['client', 'server'];
  api.use(['accounts-base' , 'accounts-password'], both);
  api.add_files('accounts-profile-fields-server.js', 'server');
  api.add_files('accounts-profile-fields-client.js', 'client');
});
<|endoftext|>


<commit_before>// TODO: REMOVE UNECCESARY VIEWS

const DIRECTION = {
    "FORWARDS": +1,
    "BACKWARDS": -1
};
exports.DIRECTION = DIRECTION;

var child = require('./child.js')

exports.rdft = function(n, dir, aBuffer, ipBuffer, wBuffer) {
    let ip = new Int16Array(ipBuffer);
    let a = new Float64Array(aBuffer);
    let w = new Float64Array(wBuffer);

    let nw = ip[0];
    let nc = ip[1];

    if (dir == DIRECTION.FORWARDS)
    {
        if (n > 4)
        {
            child.bitrv2(n, ip.buffer, 2, a.buffer);
            child.cftfsub(n, a.buffer, w.buffer);
            child.rftfsub(n, a.buffer, nc, w.buffer, nw);
        }
        else if (n == 4)
        {
            child.cftfsub(n, a.buffer, w.buffer);
        }
        let xi = a[0] - a[1];
        a[0] += a[1];
        a[1] = xi;
    }
    else
    {
        a[1] = 0.5 * (a[0] - a[1]);
        a[0] -= a[1];
        if (n > 4)
        {
            child.rftbsub(n, a.buffer, nc, w.buffer, nw);
            child.bitrv2(n, ip.buffer, 2, a.buffer);
            child.cftbsub(n, a.buffer, w.buffer);
        }
        else if (n == 4)
        {
            child.cftfsub(n, a.buffer, w.buffer);
        }
    }
}

exports.cdft = function(n, dir, aBuffer, ipBuffer, wBuffer) {
    if (n > 4) {
        if (dir == DIRECTION.FORWARDS) {
            child.bitrv2(n, ipBuffer, 2, aBuffer);
            child.cftfsub(n, aBuffer, wBuffer);
        } else {
            child.bitrv2conj(n, ipBuffer, 2, aBuffer);
            child.cftbsub(n, aBuffer, wBuffer);
        }
    } else if (n == 4) {
        cftfsub(n, aBuffer, wBuffer);
    }
}
<commit_msg>skipped some unecessary buffer calls<commit_after>// TODO: REMOVE UNECCESARY VIEWS

const DIRECTION = {
    "FORWARDS": +1,
    "BACKWARDS": -1
};
exports.DIRECTION = DIRECTION;

var child = require('./child.js')

exports.rdft = function(n, dir, aBuffer, ipBuffer, wBuffer) {
    let ip = new Int16Array(ipBuffer);
    let a = new Float64Array(aBuffer);
    let nw = ip[0];
    let nc = ip[1];

    if (dir == DIRECTION.FORWARDS)
    {
        if (n > 4)
        {
            child.bitrv2(n, ipBuffer, 2, aBuffer);
            child.cftfsub(n, aBuffer, wBuffer);
            child.rftfsub(n, aBuffer, nc, wBuffer, nw);
        }
        else if (n == 4)
        {
            child.cftfsub(n, aBuffer, wBuffer);
        }
        let xi = a[0] - a[1];
        a[0] += a[1];
        a[1] = xi;
    }
    else
    {
        a[1] = 0.5 * (a[0] - a[1]);
        a[0] -= a[1];
        if (n > 4)
        {
            child.rftbsub(n, aBuffer, nc, wBuffer, nw);
            child.bitrv2(n, ipBuffer, 2, aBuffer);
            child.cftbsub(n, aBuffer, wBuffer);
        }
        else if (n == 4)
        {
            child.cftfsub(n, aBuffer, wBuffer);
        }
    }
}

exports.cdft = function(n, dir, aBuffer, ipBuffer, wBuffer) {
    if (n > 4) {
        if (dir == DIRECTION.FORWARDS) {
            child.bitrv2(n, ipBuffer, 2, aBuffer);
            child.cftfsub(n, aBuffer, wBuffer);
        } else {
            child.bitrv2conj(n, ipBuffer, 2, aBuffer);
            child.cftbsub(n, aBuffer, wBuffer);
        }
    } else if (n == 4) {
        cftfsub(n, aBuffer, wBuffer);
    }
}
<|endoftext|>


<commit_before>Package.describe({
  name: 'mfpierre:chartist-js',
  summary: 'Simple responsive charts',
  version: '1.6.2',
  git: 'https://github.com/mfpierre/meteor-chartist-js'
});

Package.onUse(function(api) {
  api.versionsFrom('1.0');
  api.use('fourseven:scss@3.4.1');
  api.addFiles([
    'before.js',
    'chartist-js/dist/chartist.js',
    'chartist-js/dist/scss/settings/_chartist-settings.scss',
    'chartist-js/dist/scss/chartist.scss',
    'after.js'
  ], 'client');
  api.export('Chartist');
});
<commit_msg>Bumped fourseven:scss for support for Meteor 1.4.<commit_after>Package.describe({
  name: 'mfpierre:chartist-js',
  summary: 'Simple responsive charts',
  version: '1.6.2',
  git: 'https://github.com/mfpierre/meteor-chartist-js'
});

Package.onUse(function(api) {
  api.versionsFrom('1.0');
  api.use('fourseven:scss@3.8.0_1');
  api.addFiles([
    'before.js',
    'chartist-js/dist/chartist.js',
    'chartist-js/dist/scss/settings/_chartist-settings.scss',
    'chartist-js/dist/scss/chartist.scss',
    'after.js'
  ], 'client');
  api.export('Chartist');
});
<|endoftext|>


<commit_before>var SettingsDetailsWS = (function(){
    "use strict";

    var formID = '#frmPersonalDetails';
    var frmBtn = formID + ' button',
        RealAccElements = '.RealAcc',
        errorClass = 'errorfield';
    var fieldIDs = {
        address1 : '#Address1',
        address2 : '#Address2',
        city     : '#City',
        state    : '#State',
        postcode : '#Postcode',
        phone    : '#Phone'
    };
    var isValid;

    var init = function(){
        BinarySocket.send({"get_settings": "1"});
    };

    var getDetails = function(response){
        var data = response.get_settings;

        // Check if it is a real account or not
        var isReal = !(/VRT/.test($.cookie('loginid')));

        $('#lblCountry').text(data.country);
        $('#lblEmail').text(data.email);

        if(!isReal){ // Virtual Account
            $(RealAccElements).remove();
        }
        else { // Real Account
            BinarySocket.send({"authorize": $.cookie('login')});
            $('#lblBirthDate').text(moment.utc(new Date(data.date_of_birth * 1000)).format("YYYY-MM-DD"));
            $(fieldIDs.address1).val(data.address_line_1);
            $(fieldIDs.address2).val(data.address_line_2);
            $(fieldIDs.city).val(data.address_city);

            // Generate states list
            var residence = $.cookie('residence');
            BinarySocket.send({"states_list": residence, "passthrough": {"value": data.address_state}});

            $(fieldIDs.postcode).val(data.address_postcode);
            $(fieldIDs.phone).val(data.phone);

            $(RealAccElements).removeClass('hidden');

            $(frmBtn).click(function(e){
                e.preventDefault();
                e.stopPropagation();
                return setDetails();
            });
        }

    };

    var setFullName = function(response){
        $('#lblName').text(response.authorize.fullname);
    };

    var populateStates = function(response){
        $(fieldIDs.state).empty();
        var states = response.states_list;
        if(states) {
            for(var i = 0; i < states.length; i++){
                $(fieldIDs.state).append($('<option/>', {value: states[i].value, text: states[i].text}));
            }
            // set Current value
            $(fieldIDs.state).val(response.echo_req.passthrough.value);
        }
        else {
            $('#State'). closest('.grd-row-padding').addClass('hidden');
        }
    };

    var formValidate = function(){
        clearError();
        isValid = true;

        var address1 = $(fieldIDs.address1).val(),
            address2 = $(fieldIDs.address2).val(),
            city     = $(fieldIDs.city).val(),
            state    = $(fieldIDs.state).val(),
            postcode = $(fieldIDs.postcode).val(),
            phone    = $(fieldIDs.phone).val();

        if(!(/.+/).test(address1)){
            showError(fieldIDs.address1, text.localize('Please enter the first line of your home address.'));
        }
        if(!(/.+/).test(city)){
            showError(fieldIDs.city, text.localize('Please enter a town or city.'));
        }
        if((/^.{1,3}$/).test(postcode) || !(/^.{0,20}$/).test(postcode)){
            showError(fieldIDs.postcode, text.localize('Postcode is invalid.'));
        } else if(!(/(^[\w\s-]+$)/).test(postcode)){
            showError(fieldIDs.postcode, text.localize('Please use only alphanumeric characters or spaces.'));
        }
        if(!(/^(|.{6}.*)$/).test(phone)){
            showError(fieldIDs.phone, text.localize('Invalid telephone number (too short).'));
        } else if(!(/^.{0,35}$/).test(phone)){
            showError(fieldIDs.phone, text.localize('Invalid telephone number (too long).'));
        } else if(!(/^(|\+?[0-9\s]+)$/).test(phone)){
            showError(fieldIDs.phone, text.localize('Invalid telephone number.'));
        }

        if(isValid){
            return {
                address1 : address1,
                address2 : address2,
                city     : city,
                state    : state,
                postcode : postcode,
                phone    : phone
            };
        }
        else {
            return false;
        }
    };

    var showError = function(fieldID, errMsg){
        $(fieldID).after($('<p/>', {class: errorClass, text: errMsg}));
        isValid = false;
    };

    var clearError = function(fieldID){
        $(fieldID ? fieldID : formID + ' .' + errorClass).remove();
    };

    var setDetails = function(){
        var formData = formValidate();
        if(!formData)
            return false;

        var req =
        {
            "set_settings"    : 1,
            "address_line_1"  : formData.address1,
            "address_line_2"  : formData.address2,
            "address_city"    : formData.city,
            "address_state"   : formData.state,
            "address_postcode": formData.postcode,
            "phone"           : formData.phone
        };
        if(!formData.state){
            delete req.address_state;
        }
        BinarySocket.send(req);
    };

    var setDetailsResponse = function(response){
        var isError = response.set_settings !== 1;
        $('#formMessage')
            .attr('class', isError ? 'error-msg' : 'success-msg')
            .text(text.localize(isError ? 'Sorry, an error occurred while processing your account.' : 'Your settings have been updated successfully.'));
    };

    return {
        init: init,
        getDetails: getDetails,
        setDetails: setDetails,
        setDetailsResponse: setDetailsResponse,
        setFullName: setFullName,
        populateStates: populateStates
    };
}());

pjax_config_page("settings/detailsws", function(){
    return {
        onLoad: function() {
            if (!$.cookie('login')) {
                window.location.href = page.url.url_for('login');
                return;
            }

            BinarySocket.init({
                onmessage: function(msg){
                    var response = JSON.parse(msg.data);
                    if (response) {
                        var type = response.msg_type;
                        switch(type){
                            case "get_settings":
                                SettingsDetailsWS.getDetails(response);
                                break;
                            case "set_settings":
                                SettingsDetailsWS.setDetailsResponse(response);
                                break;
                            case "authorize":
                                SettingsDetailsWS.setFullName(response);
                                break;
                            case "states_list":
                                SettingsDetailsWS.populateStates(response);
                                break;
                            case "error":
                                $('#formMessage').attr('class', 'error-msg').text(response.error.message);
                                break;
                            default:
                                break;
                        }
                    }
                    else {
                        console.log('some error occured');
                    }
                }
            });

            SettingsDetailsWS.init();
        }
    };
});
<commit_msg>fix state<commit_after>var SettingsDetailsWS = (function(){
    "use strict";

    var formID = '#frmPersonalDetails';
    var frmBtn = formID + ' button',
        RealAccElements = '.RealAcc',
        errorClass = 'errorfield';
    var fieldIDs = {
        address1 : '#Address1',
        address2 : '#Address2',
        city     : '#City',
        state    : '#State',
        postcode : '#Postcode',
        phone    : '#Phone'
    };
    var isValid;

    var init = function(){
        BinarySocket.send({"get_settings": "1"});
    };

    var getDetails = function(response){
        var data = response.get_settings;

        // Check if it is a real account or not
        var isReal = !(/VRT/.test($.cookie('loginid')));

        $('#lblCountry').text(data.country);
        $('#lblEmail').text(data.email);

        if(!isReal){ // Virtual Account
            $(RealAccElements).remove();
        }
        else { // Real Account
            BinarySocket.send({"authorize": $.cookie('login')});
            $('#lblBirthDate').text(moment.utc(new Date(data.date_of_birth * 1000)).format("YYYY-MM-DD"));
            $(fieldIDs.address1).val(data.address_line_1);
            $(fieldIDs.address2).val(data.address_line_2);
            $(fieldIDs.city).val(data.address_city);

            // Generate states list
            var residence = $.cookie('residence');
            BinarySocket.send({"states_list": residence, "passthrough": {"value": data.address_state}});

            $(fieldIDs.postcode).val(data.address_postcode);
            $(fieldIDs.phone).val(data.phone);

            $(RealAccElements).removeClass('hidden');

            $(frmBtn).click(function(e){
                e.preventDefault();
                e.stopPropagation();
                return setDetails();
            });
        }

    };

    var setFullName = function(response){
        $('#lblName').text(response.authorize.fullname);
    };

    var populateStates = function(response){
        $(fieldIDs.state).empty();
        var states = response.states_list;
        if(states.length > 0) {
            for(var i = 0; i < states.length; i++){
                $(fieldIDs.state).append($('<option/>', {value: states[i].value, text: states[i].text}));
            }
            // set Current value
            $(fieldIDs.state).val(response.echo_req.passthrough.value);
        }
        else {
            $('#State'). closest('.grd-row-padding').addClass('hidden');
        }
    };

    var formValidate = function(){
        clearError();
        isValid = true;

        var address1 = $(fieldIDs.address1).val(),
            address2 = $(fieldIDs.address2).val(),
            city     = $(fieldIDs.city).val(),
            state    = $(fieldIDs.state).val(),
            postcode = $(fieldIDs.postcode).val(),
            phone    = $(fieldIDs.phone).val();

        if(!(/.+/).test(address1)){
            showError(fieldIDs.address1, text.localize('Please enter the first line of your home address.'));
        }
        if(!(/.+/).test(city)){
            showError(fieldIDs.city, text.localize('Please enter a town or city.'));
        }
        if((/^.{1,3}$/).test(postcode) || !(/^.{0,20}$/).test(postcode)){
            showError(fieldIDs.postcode, text.localize('Postcode is invalid.'));
        } else if(!(/(^[\w\s-]+$)/).test(postcode)){
            showError(fieldIDs.postcode, text.localize('Please use only alphanumeric characters or spaces.'));
        }
        if(!(/^(|.{6}.*)$/).test(phone)){
            showError(fieldIDs.phone, text.localize('Invalid telephone number (too short).'));
        } else if(!(/^.{0,35}$/).test(phone)){
            showError(fieldIDs.phone, text.localize('Invalid telephone number (too long).'));
        } else if(!(/^(|\+?[0-9\s]+)$/).test(phone)){
            showError(fieldIDs.phone, text.localize('Invalid telephone number.'));
        }

        if(isValid){
            return {
                address1 : address1,
                address2 : address2,
                city     : city,
                state    : state,
                postcode : postcode,
                phone    : phone
            };
        }
        else {
            return false;
        }
    };

    var showError = function(fieldID, errMsg){
        $(fieldID).after($('<p/>', {class: errorClass, text: errMsg}));
        isValid = false;
    };

    var clearError = function(fieldID){
        $(fieldID ? fieldID : formID + ' .' + errorClass).remove();
    };

    var setDetails = function(){
        var formData = formValidate();
        if(!formData)
            return false;

        var req =
        {
            "set_settings"    : 1,
            "address_line_1"  : formData.address1,
            "address_line_2"  : formData.address2,
            "address_city"    : formData.city,
            "address_state"   : formData.state,
            "address_postcode": formData.postcode,
            "phone"           : formData.phone
        };
        if(!formData.state){
            delete req.address_state;
        }
        BinarySocket.send(req);
    };

    var setDetailsResponse = function(response){
        var isError = response.set_settings !== 1;
        $('#formMessage')
            .attr('class', isError ? 'error-msg' : 'success-msg')
            .text(text.localize(isError ? 'Sorry, an error occurred while processing your account.' : 'Your settings have been updated successfully.'));
    };

    return {
        init: init,
        getDetails: getDetails,
        setDetails: setDetails,
        setDetailsResponse: setDetailsResponse,
        setFullName: setFullName,
        populateStates: populateStates
    };
}());

pjax_config_page("settings/detailsws", function(){
    return {
        onLoad: function() {
            if (!$.cookie('login')) {
                window.location.href = page.url.url_for('login');
                return;
            }

            BinarySocket.init({
                onmessage: function(msg){
                    var response = JSON.parse(msg.data);
                    if (response) {
                        var type = response.msg_type;
                        switch(type){
                            case "get_settings":
                                SettingsDetailsWS.getDetails(response);
                                break;
                            case "set_settings":
                                SettingsDetailsWS.setDetailsResponse(response);
                                break;
                            case "authorize":
                                SettingsDetailsWS.setFullName(response);
                                break;
                            case "states_list":
                                SettingsDetailsWS.populateStates(response);
                                break;
                            case "error":
                                $('#formMessage').attr('class', 'error-msg').text(response.error.message);
                                break;
                            default:
                                break;
                        }
                    }
                    else {
                        console.log('some error occured');
                    }
                }
            });

            SettingsDetailsWS.init();
        }
    };
});
<|endoftext|>


<commit_before>Package.describe({
  name: 'bfla:witai',
  version: '0.0.1',
  // Brief, one-line summary of the package.
  summary: 'Wit.ai clients for Browser and iOS',
  // URL to the Git repository containing the source code for this package.
  git: 'https://github.com/bfla/meteor-witai',
  // By default, Meteor will default to using README.md for documentation.
  // To avoid submitting documentation, set this field to null.
  documentation: 'README.md'
});

Package.onUse(function(api) {
  api.export('WitaiClient');
  api.versionsFrom('1.2.1');

  // api.use('ecmascript');
  api.use(["templating", "ui", "blaze", "less", "reactive-var"]);
  // api.use("isobuild:cordova@5.2.0");

  // Include official Wit.ai browser integration
  api.addFiles('browser/witai-browser-client/witai.min.css', ['web.browser']);
  api.addfiles('browser/witai-browser-client/witai.min.js', ['web.browser']);
  api.addFiles('browser/witai-browser-client/fonts/microphone.eot', ['web.browser'], {isAsset:true});
  api.addFiles('browser/witai-browser-client/fonts/microphone.svg', ['web.browser'], {isAsset:true});
  api.addFiles('browser/witai-browser-client/fonts/microphone.ttf', ['web.browser'], {isAsset:true});
  api.addFiles('browser/witai-browser-client/fonts/microphone.woff', ['web.browser'], {isAsset:true});
  // Include Meteor interface for Wit.ai's browser integration
  api.addFiles('browser/witai-interface.html', ['web.browser']);
  api.addFiles('browser/witai-interface.js', ['web.browser']);

  // api.addFiles('witai.less', ['web.browser']);
  // api.addFiles('witai-browser.js', ['web.browser']);
  // api.addFiles('witai-cordova.js', ['web.cordova']);
});

Package.onTest(function(api) {
  api.use('ecmascript');
  api.use('tinytest');
  api.use('bfla:witai');
  api.addFiles('witai-tests.js');
});
<commit_msg>updated package.js so that package builds correctly<commit_after>Package.describe({
  name: 'bfla:witai',
  version: '0.0.1',
  // Brief, one-line summary of the package.
  summary: 'Wit.ai clients for Browser and iOS',
  // URL to the Git repository containing the source code for this package.
  git: 'https://github.com/bfla/meteor-witai',
  // By default, Meteor will default to using README.md for documentation.
  // To avoid submitting documentation, set this field to null.
  documentation: 'README.md'
});

Package.onUse(function(api) {
  // api.export('WitaiClient');
  api.versionsFrom('1.2.1');

  // api.use('ecmascript');
  api.use(["templating", "ui", "blaze", "less", "reactive-var"]);
  // api.use("isobuild:cordova@5.2.0");

  // Include official Wit.ai browser integration
  api.addFiles('browser/witai-browser-client/microphone.min.css', ['web.browser']);
  api.addFiles('browser/witai-browser-client/microphone.min.js', ['web.browser']);
  api.addFiles(
    [
      'browser/witai-browser-client/fonts/microphone.eot',
      'browser/witai-browser-client/fonts/microphone.svg',
      'browser/witai-browser-client/fonts/microphone.ttf',
      'browser/witai-browser-client/fonts/microphone.woff'
    ],
    ['web.browser'],
    {isAsset:true}
  );
  // Include Meteor interface for Wit.ai's browser integration
  api.addFiles('browser/witai-interface.html', ['web.browser']);
  api.addFiles('browser/witai-interface.js', ['web.browser']);

  // api.addFiles('witai-cordova.js', ['web.cordova']);
});

Package.onTest(function(api) {
  api.use('ecmascript');
  api.use('tinytest');
  api.use('bfla:witai');
  api.addFiles('witai-tests.js');
});
<|endoftext|>