<commit_before>"use strict";

class claraConfigurator {
  constructor(config) {
    this.api                    = null;
    this.claraSceneId           = null;
    this.playerDivId            = null;
    this.configuratorDivId      = null;
    this.configuratorInputDivId = null;
    this.configuratorForm       = null;
    this.addtocartClassName     = null;
    this.addtocartButton        = null;
    this.addtocartEnabled       = false;
    this.variation_idClassName  = null;
    this.variation_idInput      = null;
    this.variationInputId       = null;
    this.variationInputDiv      = null;
    this.priceId                = null;
    this.priceDiv               = null;
    this.basePrice              = 0;
    /*
    *
    */
    this.attributes           = null;
    /*
    *
    */
    this.available_attributes = null;

    this.usingAddons          = false;

    if (config) {
      var self = this;
      // init variables
      this.playerDivId            = config.playerDivId;
      this.configuratorDivId      = config.configuratorDivId;
      this.claraSceneId           = config.claraSceneId;
      this.attributes             = config.attributes;
      this.available_attributes   = config.available_attributes;
      this.configuratorInputDivId = config.configuratorInputDivId;
      this.addtocartClassName     = config.addtocartClassName;
      this.variation_idClassName  = config.variation_idClassName;
      this.variationInputId       = config.variationInputId;
      this.priceId                = config.priceId;
      this.usingAddons            = config.usingAddons;
      this.basePrice              = parseInt(config.basePrice);

      this.variation_idInput = document.getElementsByClassName(this.variation_idClassName)[0];
      this.variationInputDiv = document.getElementById(this.variationInputId);
      this.addtocartButton = document.getElementsByClassName(this.addtocartClassName)[0];
      this.priceDiv = document.getElementById(this.priceId);

      if (this.usingAddons) {
        this.addtocartEnabled = true;
      }

      if (this.addtocartButton) {
        this.addtocartButton.onclick = (ev) => {
          if (!self.addtocartEnabled) {
            event.preventDefault();
          }
        };
      }

    }

    this._initClara();
  }

  _initClara() {
    var self = this;
    // Fetch and initialize the sceneId
    this.api = claraplayer(this.playerDivId);
    this.api.sceneIO
      .fetchAndUse(this.claraSceneId, null, { waitForPublish: true })
      .then(() => {

        // use the first form in the scene
        self._getConfiguratorForm();

        var configuratorEl = document.getElementById(self.configuratorDivId);

        if (self.configuratorForm && configuratorEl) {
          self.api.configuration.initConfigurator({
            id    : self.claraSceneId,
            form  : self.configuratorForm,
            el    : configuratorEl
          });

          if (self.usingAddons) {
            self.api.on('configurationChange', (ev) => {
              self._onConfigurationChangeAddon();
            });
          }
          else {
            self.api.on('configurationChange', (ev) => {
              self._onConfigurationChange();
            });
          }

        }
      });
  }

  _getConfiguratorForm() {
    if (!this.api) {
      return;
    }
    var forms = this.api.configuration.getForms();
    if (forms.length > 0) {
      this.configuratorForm = forms[0].name;
    }
  }

  _onConfigurationChangeAddon() {
    var self = this;
    var price  = 0;
    var config = this.api.configuration.getConfiguration();
    console.log(config);
    console.log(this.attributes);

    var configuratorInputDiv = document.getElementById(this.configuratorInputDivId);
    if (!configuratorInputDiv) {
      return;
    }

    var selectedVaration = {};

    for (var key in config) {
      // looking for key in attributes
      var nameFound = false;
      for (var ele in this.attributes) {
        nameFound = true;
        if (key === this.attributes[ele].name) {
          switch (this.attributes[ele].type) {
            case 'select':
              // looking for config[key] in attributes[ele].options
              var optionFound = false;
              for (var opt in this.attributes[ele].options) {
                if (config[key] === this.attributes[ele].options[opt].label) {
                  optionFound = true;
                  // add input to form
                  var tailNumber =  parseInt(opt) + 1;
                  selectedVaration['addon-' + this.attributes[ele]['field-name']] = config[key].toLowerCase() + '-' + tailNumber;
                  // calculate price
                  var cPrice = parseInt(this.attributes[ele].options[opt].price);
                  if (cPrice != NaN) {
                    price += cPrice;
                  }
                }
              }
              if ( !optionFound ) {
                console.warn("Option " + config[key] + " not found in " + key);
              }
            break;
            case 'checkbox':
              if (config[key]) {
                selectedVaration['addon-' + this.attributes[ele]['field-name'] + '[]'] = this.attributes[ele].options[0].label;
                var cPrice = parseInt(this.attributes[ele].options[opt].price);
                if (cPrice != NaN) {
                  price += cPrice;
                }
              }
            break;
            case 'custom':
              selectedVaration['addon-' + this.attributes[ele]['field-name'] + '[0]'] = config[key];
              var cPrice = parseInt(this.attributes[ele].options[opt].price);
                if (cPrice != NaN) {
                price += cPrice;
              }
            break;
          }
        }
      }
      if (!nameFound) {
        console.warn("Configuration " + key + " not found, unable to post to server");
      }
    }

    if (this.variationInputDiv.hasChildNodes()) {
      // remove all child
      while (this.variationInputDiv.firstChild) {
        this.variationInputDiv.removeChild(this.variationInputDiv.firstChild);
      }
    }

    // update form
    for (var key in selectedVaration) {
      var keyInput = document.createElement('input');
      keyInput.setAttribute('name', key);
      keyInput.setAttribute('value', selectedVaration[key].replace(/ /g, '-'));
      keyInput.setAttribute('type','hidden');
      this.variationInputDiv.appendChild(keyInput);
    }

    // update display price
    this.priceDiv.innerHTML = '$' + (this.basePrice + price).toString();
  }

  _onConfigurationChange() {
    var self = this;
    var config = this.api.configuration.getConfiguration();
    console.log(config);

    var configuratorInputDiv = document.getElementById(this.configuratorInputDivId);
    if (!configuratorInputDiv) {
      return;
    }

    // check if config attribute name and value exist for the current product
    var additionalAttrs = [];
    var attrValueTobeSubmited = [];
    if (Object.keys(this.attributes).length < Object.keys(config).length) {
      console.warn("Threekit attribute number is smaller than in WooCommerce, product will not be able to added to cart");
    }
    for (var key in config) {
      // looking for "key" in attributes
      var found = false;
      var legal = true;
      for (var ele in this.attributes) {
        // remove "pa_"
        var trimEle = ele;
        if (trimEle.startsWith('pa_')) {
          trimEle = trimEle.substr(3);
        }
        if (this.ignoreCaseStrcmp(trimEle, key)) {
          found = true;
          if (!this.ignoreCaseIncludes(this.attributes[ele], config[key])) {
            // config attribute value is illegal
            legal = false;
          }
          break;
        }
      }
      if (!legal) {
        this._disableAddtocartButton();
        return;
      }
      if (!found) {
        // additional attributes will be posted to server as text
        additionalAttrs.push(key);
      }
    }

    /*
    *  Check if the product is available
    *  Attributes in WooCommerce can be overlapping,
    *  using the first matching attribute in this.available_attributes
    */
    var foundMatch = false;
    var selectedVaration = {};
    for (var i = 0; i < this.available_attributes.length; i++) {
      var attrs = this.available_attributes[i].attributes;
      if (Object.keys(attrs).length != Object.keys(config).length) {
        continue;
      }
      var match = true;
      selectedVaration = {};
      for (var key in config) {
        var found = false;
        for(var ele in attrs) {
          // remove "attribute_pa_"
          var trimEle = ele;
          if (trimEle.startsWith('attribute_pa_')) {
            trimEle = trimEle.substr(13);
          }
          if (this.ignoreCaseStrcmp(trimEle, key)) {
            if (attrs[ele] === "" || this.ignoreCaseStrcmp(attrs[ele], config[key])) {
              found = true;
              selectedVaration[ele] = config[key].toLowerCase();
              break;
            }
          }
        }
        if (!found) {
          // matching fail
          match = false;
          break;
        }
      }
      if (match && this.available_attributes[i].is_in_stock && this.available_attributes[i].is_purchasable) {
        // find a match!
        foundMatch = true;

        this.priceDiv.innerHTML = '$' + this.available_attributes[i].display_price;
        console.log(this.available_attributes[i].variation_id);
        this._enableAddtocartButton();
        this.variation_idInput.setAttribute('value', this.available_attributes[i].variation_id);

        if (this.variationInputDiv.hasChildNodes()) {
          // remove all child
          while (this.variationInputDiv.firstChild) {
            this.variationInputDiv.removeChild(this.variationInputDiv.firstChild);
          }
        }
        for (var key in selectedVaration) {
          var keyInput = document.createElement('input');
          keyInput.setAttribute('name', key);
          keyInput.setAttribute('value', selectedVaration[key]);
          keyInput.setAttribute('type','hidden');
          this.variationInputDiv.appendChild(keyInput);
        }
        break;
      }
    }
    if (!foundMatch) {
      this._disableAddtocartButton();
    }

    // calculate price

  }

  _disableAddtocartButton() {
    if (!this.addtocartButton) {
      return;
    }
    this.addtocartEnabled = false;
    this.addtocartButton.classList.add('disabled');
    if (this.priceDiv) {
      this.priceDiv.innerHTML = '';
    }
  }

  _enableAddtocartButton() {
    if (!this.addtocartButton) {
      return;
    }
    this.addtocartEnabled = true;
    this.addtocartButton.classList.remove('disabled');
  }

  /*
  * Utility functions
  */
  ignoreCaseStrcmp(str1, str2) {
    return str1.toLowerCase() === str2.toLowerCase();
  }
  ignoreCaseIncludes(arr, ele) {
    var self = this;
    for (var iter in arr) {
      if (self.ignoreCaseStrcmp(arr[iter], ele)) {
        return true;
      }
    }
    return false;
  }
}

(function() {
  var opts = {
    addtocartClassName    : 'single_add_to_cart_button',
    variation_idClassName : 'variation_id',
    variationInputId      : 'threekit-add-to-cart-inputs',
    playerDivId           : 'clara-player',
    configuratorDivId     : 'panel-embed',
    configuratorInputDivId: 'threekit-add-to-cart-inputs',
    priceId               : 'threekit_price',
    claraSceneId          : php_vars.clarauuid,
    available_attributes  : php_vars.available_attributes,
    attributes            : php_vars.attributes,
    basePrice             : basePrice,
    usingAddons           : php_vars.usingAddons
  };
  var cc = new claraConfigurator(opts);

}());
<commit_msg>debug<commit_after>"use strict";

class claraConfigurator {
  constructor(config) {
    this.api                    = null;
    this.claraSceneId           = null;
    this.playerDivId            = null;
    this.configuratorDivId      = null;
    this.configuratorInputDivId = null;
    this.configuratorForm       = null;
    this.addtocartClassName     = null;
    this.addtocartButton        = null;
    this.addtocartEnabled       = false;
    this.variation_idClassName  = null;
    this.variation_idInput      = null;
    this.variationInputId       = null;
    this.variationInputDiv      = null;
    this.priceId                = null;
    this.priceDiv               = null;
    this.basePrice              = 0;
    /*
    *
    */
    this.attributes           = null;
    /*
    *
    */
    this.available_attributes = null;

    this.usingAddons          = false;

    if (config) {
      var self = this;
      // init variables
      this.playerDivId            = config.playerDivId;
      this.configuratorDivId      = config.configuratorDivId;
      this.claraSceneId           = config.claraSceneId;
      this.attributes             = config.attributes;
      this.available_attributes   = config.available_attributes;
      this.configuratorInputDivId = config.configuratorInputDivId;
      this.addtocartClassName     = config.addtocartClassName;
      this.variation_idClassName  = config.variation_idClassName;
      this.variationInputId       = config.variationInputId;
      this.priceId                = config.priceId;
      this.usingAddons            = config.usingAddons;
      this.basePrice              = parseInt(config.basePrice);

      this.variation_idInput = document.getElementsByClassName(this.variation_idClassName)[0];
      this.variationInputDiv = document.getElementById(this.variationInputId);
      this.addtocartButton = document.getElementsByClassName(this.addtocartClassName)[0];
      this.priceDiv = document.getElementById(this.priceId);

      if (this.usingAddons) {
        this.addtocartEnabled = true;
      }

      if (this.addtocartButton) {
        this.addtocartButton.onclick = (ev) => {
          if (!self.addtocartEnabled) {
            event.preventDefault();
          }
        };
      }

    }

    this._initClara();
  }

  _initClara() {
    var self = this;
    // Fetch and initialize the sceneId
    this.api = claraplayer(this.playerDivId);
    this.api.sceneIO
      .fetchAndUse(this.claraSceneId, null, { waitForPublish: true })
      .then(() => {

        // use the first form in the scene
        self._getConfiguratorForm();

        var configuratorEl = document.getElementById(self.configuratorDivId);

        if (self.configuratorForm && configuratorEl) {
          self.api.configuration.initConfigurator({
            id    : self.claraSceneId,
            form  : self.configuratorForm,
            el    : configuratorEl
          });

          if (self.usingAddons) {
            self.api.on('configurationChange', (ev) => {
              self._onConfigurationChangeAddon();
            });
          }
          else {
            self.api.on('configurationChange', (ev) => {
              self._onConfigurationChange();
            });
          }

        }
      });
  }

  _getConfiguratorForm() {
    if (!this.api) {
      return;
    }
    var forms = this.api.configuration.getForms();
    if (forms.length > 0) {
      this.configuratorForm = forms[0].name;
    }
  }

  _onConfigurationChangeAddon() {
    var self = this;
    var price  = 0;
    var config = this.api.configuration.getConfiguration();
    console.log(config);
    console.log(this.attributes);

    var configuratorInputDiv = document.getElementById(this.configuratorInputDivId);
    if (!configuratorInputDiv) {
      return;
    }

    var selectedVaration = {};

    for (var key in config) {
      // looking for key in attributes
      var nameFound = false;
      for (var ele in this.attributes) {
        nameFound = true;
        if (key === this.attributes[ele].name) {
          switch (this.attributes[ele].type) {
            case 'select':
              // looking for config[key] in attributes[ele].options
              var optionFound = false;
              for (var opt in this.attributes[ele].options) {
                if (config[key] === this.attributes[ele].options[opt].label) {
                  optionFound = true;
                  // add input to form
                  var tailNumber =  parseInt(opt) + 1;
                  selectedVaration['addon-' + this.attributes[ele]['field-name']] = config[key].toLowerCase() + '-' + tailNumber;
                  // calculate price
                  var cPrice = parseInt(this.attributes[ele].options[opt].price);
                  if (cPrice != NaN) {
                    price += cPrice;
                  }
                }
              }
              if ( !optionFound ) {
                console.warn("Option " + config[key] + " not found in " + key);
              }
            break;
            case 'checkbox':
              if (config[key]) {
                selectedVaration['addon-' + this.attributes[ele]['field-name'] + '[]'] = this.attributes[ele].options[0].label;
                var cPrice = parseInt(this.attributes[ele].options[opt].price);
                if (cPrice != NaN) {
                  price += cPrice;
                }
              }
            break;
            case 'custom':
              selectedVaration['addon-' + this.attributes[ele]['field-name'] + '[0]'] = config[key];
              var cPrice = parseInt(this.attributes[ele].options[opt].price);
                if (cPrice != NaN) {
                price += cPrice;
              }
            break;
          }
        }
      }
      if (!nameFound) {
        console.warn("Configuration " + key + " not found, unable to post to server");
      }
    }

    if (this.variationInputDiv.hasChildNodes()) {
      // remove all child
      while (this.variationInputDiv.firstChild) {
        this.variationInputDiv.removeChild(this.variationInputDiv.firstChild);
      }
    }

    // update form
    for (var key in selectedVaration) {
      var keyInput = document.createElement('input');
      keyInput.setAttribute('name', key);
      keyInput.setAttribute('value', selectedVaration[key].replace(/ /g, '-'));
      keyInput.setAttribute('type','hidden');
      this.variationInputDiv.appendChild(keyInput);
    }

    // update display price
    this.priceDiv.innerHTML = '$' + (this.basePrice + price).toString();
  }

  _onConfigurationChange() {
    var self = this;
    var config = this.api.configuration.getConfiguration();
    console.log(config);

    var configuratorInputDiv = document.getElementById(this.configuratorInputDivId);
    if (!configuratorInputDiv) {
      return;
    }

    // check if config attribute name and value exist for the current product
    var additionalAttrs = [];
    var attrValueTobeSubmited = [];
    if (Object.keys(this.attributes).length < Object.keys(config).length) {
      console.warn("Threekit attribute number is smaller than in WooCommerce, product will not be able to added to cart");
    }
    for (var key in config) {
      // looking for "key" in attributes
      var found = false;
      var legal = true;
      for (var ele in this.attributes) {
        // remove "pa_"
        var trimEle = ele;
        if (trimEle.startsWith('pa_')) {
          trimEle = trimEle.substr(3);
        }
        if (this.ignoreCaseStrcmp(trimEle, key)) {
          found = true;
          if (!this.ignoreCaseIncludes(this.attributes[ele], config[key])) {
            // config attribute value is illegal
            legal = false;
          }
          break;
        }
      }
      if (!legal) {
        this._disableAddtocartButton();
        return;
      }
      if (!found) {
        // additional attributes will be posted to server as text
        additionalAttrs.push(key);
      }
    }

    /*
    *  Check if the product is available
    *  Attributes in WooCommerce can be overlapping,
    *  using the first matching attribute in this.available_attributes
    */
    var foundMatch = false;
    var selectedVaration = {};
    for (var i = 0; i < this.available_attributes.length; i++) {
      var attrs = this.available_attributes[i].attributes;
      if (Object.keys(attrs).length != Object.keys(config).length) {
        continue;
      }
      var match = true;
      selectedVaration = {};
      for (var key in config) {
        var found = false;
        for(var ele in attrs) {
          // remove "attribute_pa_"
          var trimEle = ele;
          if (trimEle.startsWith('attribute_pa_')) {
            trimEle = trimEle.substr(13);
          }
          if (this.ignoreCaseStrcmp(trimEle, key)) {
            if (attrs[ele] === "" || this.ignoreCaseStrcmp(attrs[ele], config[key])) {
              found = true;
              selectedVaration[ele] = config[key].toLowerCase();
              break;
            }
          }
        }
        if (!found) {
          // matching fail
          match = false;
          break;
        }
      }
      if (match && this.available_attributes[i].is_in_stock && this.available_attributes[i].is_purchasable) {
        // find a match!
        foundMatch = true;

        this.priceDiv.innerHTML = '$' + this.available_attributes[i].display_price;
        console.log(this.available_attributes[i].variation_id);
        this._enableAddtocartButton();
        this.variation_idInput.setAttribute('value', this.available_attributes[i].variation_id);

        if (this.variationInputDiv.hasChildNodes()) {
          // remove all child
          while (this.variationInputDiv.firstChild) {
            this.variationInputDiv.removeChild(this.variationInputDiv.firstChild);
          }
        }
        for (var key in selectedVaration) {
          var keyInput = document.createElement('input');
          keyInput.setAttribute('name', key);
          keyInput.setAttribute('value', selectedVaration[key]);
          keyInput.setAttribute('type','hidden');
          this.variationInputDiv.appendChild(keyInput);
        }
        break;
      }
    }
    if (!foundMatch) {
      this._disableAddtocartButton();
    }

    // calculate price

  }

  _disableAddtocartButton() {
    if (!this.addtocartButton) {
      return;
    }
    this.addtocartEnabled = false;
    this.addtocartButton.classList.add('disabled');
    if (this.priceDiv) {
      this.priceDiv.innerHTML = '';
    }
  }

  _enableAddtocartButton() {
    if (!this.addtocartButton) {
      return;
    }
    this.addtocartEnabled = true;
    this.addtocartButton.classList.remove('disabled');
  }

  /*
  * Utility functions
  */
  ignoreCaseStrcmp(str1, str2) {
    return str1.toLowerCase() === str2.toLowerCase();
  }
  ignoreCaseIncludes(arr, ele) {
    var self = this;
    for (var iter in arr) {
      if (self.ignoreCaseStrcmp(arr[iter], ele)) {
        return true;
      }
    }
    return false;
  }
}

(function() {
  var opts = {
    addtocartClassName    : 'single_add_to_cart_button',
    variation_idClassName : 'variation_id',
    variationInputId      : 'threekit-add-to-cart-inputs',
    playerDivId           : 'clara-player',
    configuratorDivId     : 'panel-embed',
    configuratorInputDivId: 'threekit-add-to-cart-inputs',
    priceId               : 'threekit_price',
    claraSceneId          : php_vars.clarauuid,
    available_attributes  : php_vars.available_attributes,
    attributes            : php_vars.attributes,
    basePrice             : php_vars.basePrice,
    usingAddons           : php_vars.usingAddons
  };
  var cc = new claraConfigurator(opts);

}());
<|endoftext|>


<commit_before>jQuery.fn.extend({

	// overwrite the old show method
	_show: jQuery.fn.show,

	/**
	 * The effects module overloads the show method to now allow
	 * for a speed to the show operation. What actually happens is
	 * that the height, width, and opacity to the matched elements
	 * are changed dynamically. The only three current speeds are
	 * "slow", "normal", and "fast". For example:
	 *   $("p").show("slow");
	 * Note: You should not run the show method on things
	 * that are already shown. This can be circumvented by doing this:
	 *   $("p:hidden").show("slow");
	 */
	show: function(speed,callback){
		return speed ? this.animate({
			height: "show", width: "show", opacity: "show"
		}, speed, callback) : this._show();
	},

	// Overwrite the old hide method
	_hide: jQuery.fn.hide,

	/**
	 * The hide function behaves very similary to the show function,
	 * but is just the opposite.
	 *   $("p:visible").hide("slow");
	 */
	hide: function(speed,callback){
		return speed ? this.animate({
			height: "hide", width: "hide", opacity: "hide"
		}, speed, callback) : this._hide();
	},

	/**
	 * This function increases the height and opacity for all matched
	 * elements. This is very similar to 'show', but does not change
	 * the width - creating a neat sliding effect.
	 *   $("p:hidden").slideDown("slow");
	 */
	slideDown: function(speed,callback){
		return this.animate({height: "show"}, speed, callback);
	},

	/**
	 * Just like slideDown, only it hides all matched elements.
	 *   $("p:visible").slideUp("slow");
	 */
	slideUp: function(speed,callback){
		return this.animate({height: "hide"}, speed, callback);
	},

	/**
	 * Adjusts the opacity of all matched elements from a hidden,
	 * to a fully visible, state.
	 *   $("p:hidden").fadeIn("slow");
	 */
	fadeIn: function(speed,callback){
		return this.animate({opacity: "show"}, speed, callback);
	},

	/**
	 * Same as fadeIn, but transitions from a visible, to a hidden state.
	 *   $("p:visible").fadeOut("slow");
	 */
	fadeOut: function(speed,callback){
		return this.animate({opacity: "hide"}, speed, callback);
	},

	/**
	 * ...
	 */
	fadeTo: function(speed,to,callback){
		return this.animate({opacity: to}, speed, callback);
	},

	/**
	 *
	 */
	animate: function(prop,speed,callback) {
		return this.queue(function(){
			var i = 0;
			for ( var p in prop ) {
				var e = new jQuery.fx( this, jQuery.speed(speed,callback,i++), p );
				if ( prop[p].constructor == Number )
					e.custom( e.cur(), prop[p] );
				else
					e[ prop[p] ]();
			}
		});
	},

	/**
	 *
	 * @private
	 */
	queue: function(type,fn){
		if ( !fn ) {
			fn = type;
			type = "fx";
		}

		return this.each(function(){
			if ( !this.queue )
				this.queue = {};

			if ( !this.queue[type] )
				this.queue[type] = [];

			this.queue[type].push( fn );

			if ( this.queue[type].length == 1 )
				fn.apply(this);
		});
	}

});

jQuery.extend({

	setAuto: function(e,p) {
		var a = e.style[p];
		var o = jQuery.css(e,p);
		e.style[p] = "auto";
		var n = jQuery.css(e,p);
		if ( o != n )
			e.style[p] = a;
	},

	speed: function(s,o,i) {
		o = o || {};

		if ( o.constructor == Function )
			o = { complete: o };

		var ss = { slow: 600, fast: 200 };
		o.duration = (s && s.constructor == Number ? s : ss[s]) || 400;

		// Queueing
		o.oldComplete = o.complete;
		o.complete = function(){
			jQuery.dequeue(this, "fx");
			if ( o.oldComplete && o.oldComplete.constructor == Function )
				o.oldComplete.apply( this );
		};

		if ( i > 0 )
			o.complete = null;

		return o;
	},

	queue: {},

	dequeue: function(elem,type){
		type = type || "fx";

		if ( elem.queue && elem.queue[type] ) {
			// Remove self
			elem.queue[type].shift();

			// Get next function
			var f = elem.queue[type][0];

			if ( f )
				f.apply( elem );
		}
	},

	/*
	 * I originally wrote fx() as a clone of moo.fx and in the process
	 * of making it small in size the code became illegible to sane
	 * people. You've been warned.
	 */

	fx: function( elem, options, prop ){

		var z = this;

		// The users options
		z.o = {
			duration: options.duration || 400,
			complete: options.complete
		};

		// The element
		z.el = elem;

		// The styles
		var y = z.el.style;

		// Simple function for setting a style value
		z.a = function(){
			if ( prop == "opacity" ) {
				if (z.now == 1) z.now = 0.9999;
				if (window.ActiveXObject)
					y.filter = "alpha(opacity=" + z.now*100 + ")";
				y.opacity = z.now;
			} else
				y[prop] = z.now+"px";
		};

		// Figure out the maximum number to run to
		z.max = function(){
			return parseFloat( jQuery.css(z.el,prop) );
		};

		// Get the current size
		z.cur = function(){
			return parseFloat( jQuery.curCSS(z.el,prop) ) || z.max();
		};

		// Start an animation from one number to another
		z.custom = function(from,to){
			z.startTime = (new Date()).getTime();
			z.now = from;
			z.a();

			z.timer = setInterval(function(){
				z.step(from, to);
			}, 13);
		};

		// Simple 'show' function
		z.show = function(){
			// Remember where we started, so that we can go back to it later
			z.el["orig"+prop] = this.cur();

			z.o.auto = true;
			z.custom(0,z.max());
			y.display = "block";
		};

		// Simple 'hide' function
		z.hide = function(){
			// Remember where we started, so that we can go back to it later
			z.el["orig"+prop] = this.cur();

			// Begin the animation
			z.custom(z.cur(),0);
		};

		// IE has trouble with opacity if it does not have layout
		if ( jQuery.browser.msie && !z.el.currentStyle.hasLayout )
			y.zoom = 1;

		// Remember  the overflow of the element
		z.oldOverflow = y.overflow;

		// Make sure that nothing sneaks out
		y.overflow = "hidden";

		// Each step of an animation
		z.step = function(firstNum, lastNum){
			var t = (new Date()).getTime();

			if (t > z.o.duration + z.startTime) {
				// Stop the timer
				clearInterval(z.timer);
				z.timer = null;

				z.now = lastNum;
				z.a();

				// Reset the overflow
				y.overflow = z.oldOverflow;

				// If the element was shown, and not using a custom number,
				// set its height and/or width to auto
				if ( (prop == "height" || prop == "width") && z.o.auto )
					jQuery.setAuto( z.el, prop );

				// If a callback was provided, execute it
				if( z.o.complete && z.o.complete.constructor == Function ) {

					// Yes, this is a weird place for this, but it needs to be executed
					// only once per cluster of effects.
					// If the element is, effectively, hidden - hide it
					if ( y.height == "0px" || y.width == "0px" )  {
						y.display = "none";
						if ( z.el.origheight )
							y.height = z.el.origheight;
						if ( z.el.origwidth )
							y.width = z.el.origwidth;
					}

					// Execute the complete function
					z.o.complete.apply( z.el );
				}
			} else {
				// Figure out where in the animation we are and set the number
				var p = (t - this.startTime) / z.o.duration;
				z.now = ((-Math.cos(p*Math.PI)/2) + 0.5) * (lastNum-firstNum) + firstNum;

				// Perform the next step of the animation
				z.a();
			}
		};

	}

});
<commit_msg>Made a number of changes/improvements to how the effects are handled.<commit_after>jQuery.fn.extend({

	// overwrite the old show method
	_show: jQuery.fn.show,

	/**
	 * The effects module overloads the show method to now allow
	 * for a speed to the show operation. What actually happens is
	 * that the height, width, and opacity to the matched elements
	 * are changed dynamically. The only three current speeds are
	 * "slow", "normal", and "fast". For example:
	 *   $("p").show("slow");
	 * Note: You should not run the show method on things
	 * that are already shown. This can be circumvented by doing this:
	 *   $("p:hidden").show("slow");
	 */
	show: function(speed,callback){
		return speed ? this.animate({
			height: "show", width: "show", opacity: "show"
		}, speed, callback) : this._show();
	},

	// Overwrite the old hide method
	_hide: jQuery.fn.hide,

	/**
	 * The hide function behaves very similary to the show function,
	 * but is just the opposite.
	 *   $("p:visible").hide("slow");
	 */
	hide: function(speed,callback){
		return speed ? this.animate({
			height: "hide", width: "hide", opacity: "hide"
		}, speed, callback) : this._hide();
	},

	/**
	 * This function increases the height and opacity for all matched
	 * elements. This is very similar to 'show', but does not change
	 * the width - creating a neat sliding effect.
	 *   $("p:hidden").slideDown("slow");
	 */
	slideDown: function(speed,callback){
		return this.animate({height: "show"}, speed, callback);
	},

	/**
	 * Just like slideDown, only it hides all matched elements.
	 *   $("p:visible").slideUp("slow");
	 */
	slideUp: function(speed,callback){
		return this.animate({height: "hide"}, speed, callback);
	},

	/**
	 * Adjusts the opacity of all matched elements from a hidden,
	 * to a fully visible, state.
	 *   $("p:hidden").fadeIn("slow");
	 */
	fadeIn: function(speed,callback){
		return this.animate({opacity: "show"}, speed, callback);
	},

	/**
	 * Same as fadeIn, but transitions from a visible, to a hidden state.
	 *   $("p:visible").fadeOut("slow");
	 */
	fadeOut: function(speed,callback){
		return this.animate({opacity: "hide"}, speed, callback);
	},

	/**
	 * ...
	 */
	fadeTo: function(speed,to,callback){
		return this.animate({opacity: to}, speed, callback);
	},

	/**
	 *
	 */
	animate: function(prop,speed,callback) {
		return this.queue(function(){
			var i = 0;
			for ( var p in prop ) {
				var e = new jQuery.fx( this, jQuery.speed(speed,callback,i++), p );
				if ( prop[p].constructor == Number )
					e.custom( e.cur(), prop[p] );
				else
					e[ prop[p] ]();
			}
		});
	},

	/**
	 *
	 * @private
	 */
	queue: function(type,fn){
		if ( !fn ) {
			fn = type;
			type = "fx";
		}

		return this.each(function(){
			if ( !this.queue )
				this.queue = {};

			if ( !this.queue[type] )
				this.queue[type] = [];

			this.queue[type].push( fn );

			if ( this.queue[type].length == 1 )
				fn.apply(this);
		});
	}

});

jQuery.extend({

	setAuto: function(e,p) {
		var a = e.style[p];
		var o = jQuery.css(e,p);
		e.style[p] = "auto";
		var n = jQuery.css(e,p);
		if ( o != n )
			e.style[p] = a;
	},

	speed: function(s,o,i) {
		o = o || {};

		if ( o.constructor == Function )
			o = { complete: o };

		var ss = { slow: 600, fast: 200 };
		o.duration = (s && s.constructor == Number ? s : ss[s]) || 400;

		// Queueing
		o.oldComplete = o.complete;
		o.complete = function(){
			jQuery.dequeue(this, "fx");
			if ( o.oldComplete && o.oldComplete.constructor == Function )
				o.oldComplete.apply( this );
		};

		if ( i > 0 )
			o.complete = null;

		return o;
	},

	queue: {},

	dequeue: function(elem,type){
		type = type || "fx";

		if ( elem.queue && elem.queue[type] ) {
			// Remove self
			elem.queue[type].shift();

			// Get next function
			var f = elem.queue[type][0];

			if ( f )
				f.apply( elem );
		}
	},

	/*
	 * I originally wrote fx() as a clone of moo.fx and in the process
	 * of making it small in size the code became illegible to sane
	 * people. You've been warned.
	 */

	fx: function( elem, options, prop ){

		var z = this;

		// The users options
		z.o = {
			duration: options.duration || 400,
			complete: options.complete
		};

		// The element
		z.el = elem;

		// The styles
		var y = z.el.style;

		// Simple function for setting a style value
		z.a = function(){
			if ( prop == "opacity" ) {
				if (z.now == 1) z.now = 0.9999;
				if (window.ActiveXObject)
					y.filter = "alpha(opacity=" + z.now*100 + ")";
				y.opacity = z.now;
			} else
				y[prop] = z.now+"px";
		};

		// Figure out the maximum number to run to
		z.max = function(){
			return parseFloat( jQuery.css(z.el,prop) );
		};

		// Get the current size
		z.cur = function(){
			return parseFloat( jQuery.curCSS(z.el,prop) ) || z.max();
		};

		// Start an animation from one number to another
		z.custom = function(from,to){
			z.startTime = (new Date()).getTime();
			z.now = from;
			z.a();

			z.timer = setInterval(function(){
				z.step(from, to);
			}, 13);
		};

		// Simple 'show' function
		z.show = function(){
			if ( !z.el.orig ) z.el.orig = {};

			// Remember where we started, so that we can go back to it later
			z.el.orig[prop] = this.cur();

			if ( !y[prop] ) z.o.auto = true;
			z.custom(0,z.max());
			y.display = "block";
		};

		// Simple 'hide' function
		z.hide = function(){
			if ( !z.el.orig ) z.el.orig = {};

			// Remember where we started, so that we can go back to it later
			z.el.orig[prop] = this.cur();

			z.o.hide = true;
			// Begin the animation
			z.custom(z.cur(),0);
		};

		// IE has trouble with opacity if it does not have layout
		if ( jQuery.browser.msie && !z.el.currentStyle.hasLayout )
			y.zoom = 1;

		// Remember  the overflow of the element
		z.oldOverflow = y.overflow;

		// Make sure that nothing sneaks out
		y.overflow = "hidden";

		// Each step of an animation
		z.step = function(firstNum, lastNum){
			var t = (new Date()).getTime();

			if (t > z.o.duration + z.startTime) {
				// Stop the timer
				clearInterval(z.timer);
				z.timer = null;

				z.now = lastNum;
				z.a();

				// Reset the overflow
				y.overflow = z.oldOverflow;

				// If the element was shown, and not using a custom number,
				// set its height and/or width to auto
				if ( (prop == "height" || prop == "width") && z.o.auto )
					jQuery.setAuto( z.el, prop );

				// If a callback was provided, execute it
				if( z.o.complete && z.o.complete.constructor == Function ) {

					// Yes, this is a weird place for this, but it needs to be executed
					// only once per cluster of effects.
					// If the element is, effectively, hidden - hide it
					if ( z.o.hide ) y.display = "none";

					// Execute the complete function
					z.o.complete.apply( z.el );
				}

				// Reset the property, if the item has been hidden
				if ( z.o.hide )
					y[ prop ] = z.el.orig[ prop ].constructor == Number && prop != "opacity" ? z.el.orig[prop] + "px" : z.el.orig[prop];
			} else {
				// Figure out where in the animation we are and set the number
				var p = (t - this.startTime) / z.o.duration;
				z.now = ((-Math.cos(p*Math.PI)/2) + 0.5) * (lastNum-firstNum) + firstNum;

				// Perform the next step of the animation
				z.a();
			}
		};

	}

});
<|endoftext|>


<commit_before>'use strict';

module.exports = {
  rules: {
    'block-indentation': 2,
    'html-comments': true,
    'nested-interactive': true,
    'self-closing-void-elements': true,
    'triple-curlies': true,
    'deprecated-each-syntax': true,
    'deprecated-inline-view-helper': true
  },

  pending: []
};
<commit_msg>Remove deprecated-inline-view-helper from recommended.<commit_after>'use strict';

module.exports = {
  rules: {
    'block-indentation': 2,
    'html-comments': true,
    'nested-interactive': true,
    'self-closing-void-elements': true,
    'triple-curlies': true,
    'deprecated-each-syntax': true
  },

  pending: []
};
<|endoftext|>


<commit_before>(function() {
  "use strict";
  console.log(php_vars);
}());
<commit_msg>load clara player<commit_after>(function() {
  "use strict";

  var clara = claraplayer('clara-player');

  clara.on('loaded', function() {
    console.log('Clara player is loaded and ready');
  });

  // Fetch and initialize the sceneId
  clara.sceneIO.fetchAndUse(php_vars.clarauuid);

}());
<|endoftext|>


<commit_before>module.exports = function (sails) {

	/**
	 * Module dependencies.
	 */

	var _			= require( 'lodash' ),
	async			= require('async'),
	CaptainsLog		= require('../logger')(sails),
	Modules			= require('../moduleloader'),
	deepMerge		= require('../util').deepMerge; // todo: use lodash deepmerge instead

	/**
	 * Expose Configuration loader
	 */

	return function (cb) {

		var self = this;

		async.auto({

			appConfig: function (cb) {

				// Immediately instantiate default logger in case a log-worthy event occurs
				// before the custom logger can be initialized
				sails.log = CaptainsLog();

				// If appPath not specified, use process.cwd() to get the app dir
				var userConfig = {};
				userConfig.appPath = userConfig.appPath || process.cwd();

				// Get config files (must be in /config)
				userConfig = _.extend(userConfig, Modules.aggregate({
					dirname		: userConfig.appPath + '/config',
					exclude		: ['locales', 'local.js', 'local.coffee'],
					excludeDirs: ['locales'],
					filter		: /(.+)\.(js|coffee)$/,
					identity	: false
				}));

				// TODO: Extend with environment-specific config

				// Extend with local config
				userConfig = self.build(userConfig, _.extend(userConfig, Modules.aggregate({
					dirname		: userConfig.appPath + '/config',
					filter		: /local\.(js|coffee)$/,
					identity	: false
				})));

				// Map command line options to configurations
				if (!sails.config) {}
				else if (sails.config.dev && sails.config.prod) {
					sails.log.error('You cannot specify both production AND development!');
					throw new Error('You cannot specify both production AND development!');
				} else if (sails.config.dev) {
					sails.config = {environment: 'development'};
				} else if (sails.config.prod) {
					sails.config = {environment: 'production'};
				}

				// Extend with whatever's in sails.config (CLI or env override)
				userConfig = deepMerge(userConfig, sails.config);

				// Override the environment variable so express mirrors the sails env:
				sails.log.verbose('Setting Node environment...');
				process.env['NODE_ENV'] = sails.config.environment || userConfig.environment;

				// Merge user config with defaults
				sails.config = deepMerge(sails.config, self.build(self.defaults(userConfig), userConfig));

				// Validate user config
				sails.config = self.validate(sails.config, userConfig);

				// Expose route config and policy tree, and mixin defaults
				sails.config.policies = deepMerge({ "*" : true }, _.clone(sails.config.policies));
				sails.routes = sails.config.routes || {};

				cb();
			},

			logger: ['appConfig', function (cb) {

				// Rebuild logger using app config
				sails.log = CaptainsLog(sails.config.log);
				cb();
			}],

			'package.json': ['appConfig', function (cb) {

				// Extend w/ data from Sails package.json
				var packageConfig = self.package();
				sails.version = packageConfig.version;
				sails.majorVersion = sails.version.split('.')[0].replace(/[^0-9]/g,'');
				sails.minorVersion = sails.version.split('.')[1].replace(/[^0-9]/g,'');
				sails.dependencies = packageConfig.dependencies;
				cb();
			}]

		}, function (err) {
			if (err) {
				sails.log.error('Error encountered loading config:', err);
				return cb(err);
			}
			cb();
		});
	};

};
<commit_msg>configuration/load now uses asynchronous moduleloader<commit_after>module.exports = function (sails) {

	/**
	 * Module dependencies.
	 */

	var _			= require( 'lodash' ),
	async			= require('async'),
	CaptainsLog		= require('../logger')(sails),
	Modules			= require('../moduleloader'),
	deepMerge		= require('../util').deepMerge; // todo: use lodash deepmerge instead

	/**
	 * Expose Configuration loader
	 */

	return function (cb) {

		var self = this;

		async.auto({

			loadAndBuild: function (cb) {

				// Immediately instantiate default logger in case a log-worthy event occurs
				// before the custom logger can be initialized
				sails.log = CaptainsLog();

				// If appPath not specified, use process.cwd() to get the app dir
				var userConfig = {};
				userConfig.appPath = userConfig.appPath || process.cwd();

				// Load config dictionary from app modules
				async.auto([

					_.bind(Modules.aggregate, this, [{
						dirname		: userConfig.appPath + '/config',
						exclude		: ['locales', 'local.js', 'local.coffee'],
						excludeDirs: ['locales'],
						filter		: /(.+)\.(js|coffee)$/,
						identity	: false
					}]),

					// Load local config module after everything else
					// (it's an override)
					_.bind(Modules.aggregate, this, [{
						dirname		: userConfig.appPath + '/config',
						filter		: /local\.(js|coffee)$/,
						identity	: false
					}])

				], function loadedAppConfigModules (err, results) {
					if (err) return cb(err);

					// Mix in main app configuration modules
					var mainConfig = results[0];
					userConfig = _.extend(userConfig, mainConfig);

					// Finally, mix in app's local configuration (i.e. `config/local.js`)
					var localConfig = results[1];
					userConfig = self.build(userConfig, _.extend(userConfig, localConfig));

					// Map command line options to configurations
					if (!sails.config) {}
					else if (sails.config.dev && sails.config.prod) {
						sails.log.error('You cannot specify both production AND development!');
						throw new Error('You cannot specify both production AND development!');
					} else if (sails.config.dev) {
						sails.config = {environment: 'development'};
					} else if (sails.config.prod) {
						sails.config = {environment: 'production'};
					}

					// TODO: Extend with environment-specific config

					// Extend with whatever's in sails.config (CLI or env override)
					userConfig = deepMerge(userConfig, sails.config);

					// Override the environment variable so express mirrors the sails env:
					sails.log.verbose('Setting Node environment...');
					process.env['NODE_ENV'] = sails.config.environment || userConfig.environment;

					cb(null, userConfig);
				});
			},

			validate: ['loadAndBuild', function (cb, results) {

				// Original app config (from user)
				var userConfig = results.loadAndBuild;

				// Merge user config with defaults, and run config `build` script
				var confWithDefaults	= self.defaults(userConfig),
					confAfterBuild		= self.build(confWithDefaults, userConfig);
				sails.config = deepMerge(sails.config, confAfterBuild);

				// Validate user config
				sails.config = self.validate(sails.config, userConfig);

				// Expose route config and policy tree, and mixin defaults
				var policiesClone = _.clone(sails.config.policies);
				sails.config.policies = deepMerge({ "*" : true }, policiesClone);
				sails.routes = sails.config.routes || {};

				cb();
			}],

			logger: ['validate', function (cb) {

				// Rebuild logger using app config
				sails.log = CaptainsLog(sails.config.log);
				cb();
			}],

			'package.json': ['validate', function (cb) {

				// Extend w/ data from Sails package.json
				var packageConfig = self.package();
				sails.version = packageConfig.version;
				sails.majorVersion = sails.version.split('.')[0].replace(/[^0-9]/g,'');
				sails.minorVersion = sails.version.split('.')[1].replace(/[^0-9]/g,'');
				sails.dependencies = packageConfig.dependencies;
				cb();
			}]

		},

		function configLoaded (err) {
			if (err) {
				sails.log.error('Error encountered loading config:', err);
				return cb(err);
			}
			cb();
		});
	};

};
<|endoftext|>


<commit_before>/* smooth-scroll.js v1.2 */
(function(e,t){"use strict";var n=0,r=500,i=15,s=document.getElementsByTagName("a"),o;for(var u=0;u<s.length;u++){o=s[u].attributes.href===t?null:s[u].attributes.href.nodeValue.toString();if(o!==null&&o.length>1&&o.indexOf("#")!=-1){s[u].onclick=function(){var n,s=this.attributes.href.nodeValue.toString(),o=s.substr(0,s.indexOf("#")),u=s.substr(s.indexOf("#")+1);if(n=document.getElementById(u)){var l=(r-r%i)/i,c=f(),h=(a(n)-c)/l;if(e.history&&typeof e.history.pushState=="function")e.history.pushState({},t,o+"#"+u);for(var p=1;p<=l;p++){(function(){var t=h*p;setTimeout(function(){e.scrollTo(0,t+c)},i*p)})()}return false}}}}var a=function(e){var r=n*-1;while(e.offsetParent!=t&&e.offsetParent!=null){r+=e.offsetTop+(e.clientTop!=null?e.clientTop:0);e=e.offsetParent}return r};var f=function(){return document.documentElement.scrollTop!==t?document.documentElement.scrollTop:document.body.scrollTop}})(window)
<commit_msg>v1.3 : Fix Chrome bug #4<commit_after>/* smooth-scroll.js v1.3 */
(function(e,t){"use strict";var n=0,r=500,i=15,s=document.getElementsByTagName("a"),o;for(var u=0;u<s.length;u++){o=s[u].attributes.href===t?null:s[u].attributes.href.nodeValue.toString();if(o!==null&&o.length>1&&o.indexOf("#")!=-1){s[u].onclick=function(){var n,s=this.attributes.href.nodeValue.toString(),o=s.substr(0,s.indexOf("#")),u=s.substr(s.indexOf("#")+1);if(n=document.getElementById(u)){var l=(r-r%i)/i,c=f(),h=(a(n)-c)/l;if(e.history&&typeof e.history.pushState=="function")e.history.pushState({},t,o+"#"+u);for(var p=1;p<=l;p++){(function(){var t=h*p;setTimeout(function(){e.scrollTo(0,t+c)},i*p)})()}return false}}}}var a=function(e){var r=n*-1;while(e.offsetParent!=t&&e.offsetParent!=null){r+=e.offsetTop+(e.clientTop!=null?e.clientTop:0);e=e.offsetParent}return r};var f=function(){return e.pageYOffset!==t?e.pageYOffset:document.documentElement.scrollTop!==t?document.documentElement.scrollTop:document.body.scrollTop}})(window)
<|endoftext|>


<commit_before>var MapRouter = Backbone.Router.extend({
  routes: {
    "auditoriums": "auditoriums",
    "buildings": "buildings",
    "parkingspaces": "parkingspaces",
    "*actions": "defaultRoute"
  },

  defaultRoute: function (actions) {
    var appView = new AppView({
      el: $('#page-map'),
      model: new AppModel()
    });
    appView.render();

    $('#page-map').trigger("pagecreate");
  },

  auditoriums: function () {
    var appView = new AppView({
      el: $('#page-map'),
      model: new AppModel({ types: ["auditorium"] }),
      title: "Hör- & skrivsalar"
    });
    appView.render();
    appView.updateLocations();
  },

  buildings: function () {
    var appView = new AppView({
      el: $('#page-map'),
      model: new AppModel({
        menu: true,
        types: ["building"]
      }),
      title: "Hus"
    });
    appView.render();
    appView.updateLocations();
  },

  parkingspaces: function () {
    var appView = new AppView({
      el: $('#page-map'),
      model: new AppModel({
        types: ["parkingspace"]
      }),
      title: "Parkeringar"
    });
    appView.render();
    appView.updateLocations();
  }
});
<commit_msg>MOB-108 - Renamed types in broker.<commit_after>var MapRouter = Backbone.Router.extend({
  routes: {
    "auditoriums": "auditoriums",
    "buildings": "buildings",
    "parkingspaces": "parkingspaces",
    "*actions": "defaultRoute"
  },

  defaultRoute: function (actions) {
    var appView = new AppView({
      el: $('#page-map'),
      model: new AppModel()
    });
    appView.render();

    $('#page-map').trigger("pagecreate");
  },

  auditoriums: function () {
    var appView = new AppView({
      el: $('#page-map'),
      model: new AppModel({ types: ["auditorium"] }),
      title: "Hör- & skrivsalar"
    });
    appView.render();
    appView.updateLocations();
  },

  buildings: function () {
    var appView = new AppView({
      el: $('#page-map'),
      model: new AppModel({
        menu: true,
        types: ["building"]
      }),
      title: "Hus"
    });
    appView.render();
    appView.updateLocations();
  },

  parkingspaces: function () {
    var appView = new AppView({
      el: $('#page-map'),
      model: new AppModel({
        types: ["parking", "handicap_parking"]
      }),
      title: "Parkeringar"
    });
    appView.render();
    appView.updateLocations();
  }
});
<|endoftext|>


<commit_before>/*
Language: Django
Requires: xml.js
Author: Ivan Sagalaev <maniac@softwaremaniacs.org>
Contributors: Ilya Baryshev <baryshev@gmail.com>
*/

function(hljs) {

  function allowsDjangoSyntax(mode, parent) {
    return (
      parent == undefined || // default mode
      (!mode.className && parent.className == 'tag') || // tag_internal
      mode.className == 'value' // value
    );
  }

  function copy(mode, parent) {
    var result = {};
    for (var key in mode) {
      if (key != 'contains') {
        result[key] = mode[key];
      }
      var contains = [];
      for (var i = 0; mode.contains && i < mode.contains.length; i++) {
        contains.push(copy(mode.contains[i], mode));
      }
      if (allowsDjangoSyntax(mode, parent)) {
        contains = DJANGO_CONTAINS.concat(contains);
      }
      if (contains.length) {
        result.contains = contains;
      }
    }
    return result;
  }

  var FILTER = {
    className: 'filter',
    begin: '\\|[A-Za-z]+\\:?', excludeEnd: true,
    keywords:
      'truncatewords removetags linebreaksbr yesno get_digit timesince random striptags ' +
      'filesizeformat escape linebreaks length_is ljust rjust cut urlize fix_ampersands ' +
      'title floatformat capfirst pprint divisibleby add make_list unordered_list urlencode ' +
      'timeuntil urlizetrunc wordcount stringformat linenumbers slice date dictsort ' +
      'dictsortreversed default_if_none pluralize lower join center default ' +
      'truncatewords_html upper length phone2numeric wordwrap time addslashes slugify first ' +
      'escapejs force_escape iriencode last safe safeseq truncatechars localize unlocalize ' +
      'localtime utc timezone',
    contains: [
      {className: 'argument', begin: '"', end: '"'}
    ]
  };

  var DJANGO_CONTAINS = [
    {
      className: 'template_comment',
      begin: '{%\\s*comment\\s*%}', end: '{%\\s*endcomment\\s*%}'
    },
    {
      className: 'template_comment',
      begin: '{#', end: '#}'
    },
    {
      className: 'template_tag',
      begin: '{%', end: '%}',
      keywords:
        'comment endcomment load templatetag ifchanged endifchanged if endif firstof for ' +
        'endfor in ifnotequal endifnotequal widthratio extends include spaceless ' +
        'endspaceless regroup by as ifequal endifequal ssi now with cycle url filter ' +
        'endfilter debug block endblock else autoescape endautoescape csrf_token empty elif ' +
        'endwith static trans blocktrans endblocktrans get_static_prefix get_media_prefix ' +
        'plural get_current_language language get_available_languages ' +
        'get_current_language_bidi get_language_info get_language_info_list localize ' +
        'endlocalize localtime endlocaltime timezone endtimezone get_current_timezone',
      contains: [FILTER]
    },
    {
      className: 'variable',
      begin: '{{', end: '}}',
      contains: [FILTER]
    }
  ];

  var result = copy(hljs.LANGUAGES.xml);
  result.case_insensitive = true;
  return result;
}
<commit_msg>Add 'verbatim' to Django tags<commit_after>/*
Language: Django
Requires: xml.js
Author: Ivan Sagalaev <maniac@softwaremaniacs.org>
Contributors: Ilya Baryshev <baryshev@gmail.com>
*/

function(hljs) {

  function allowsDjangoSyntax(mode, parent) {
    return (
      parent == undefined || // default mode
      (!mode.className && parent.className == 'tag') || // tag_internal
      mode.className == 'value' // value
    );
  }

  function copy(mode, parent) {
    var result = {};
    for (var key in mode) {
      if (key != 'contains') {
        result[key] = mode[key];
      }
      var contains = [];
      for (var i = 0; mode.contains && i < mode.contains.length; i++) {
        contains.push(copy(mode.contains[i], mode));
      }
      if (allowsDjangoSyntax(mode, parent)) {
        contains = DJANGO_CONTAINS.concat(contains);
      }
      if (contains.length) {
        result.contains = contains;
      }
    }
    return result;
  }

  var FILTER = {
    className: 'filter',
    begin: '\\|[A-Za-z]+\\:?', excludeEnd: true,
    keywords:
      'truncatewords removetags linebreaksbr yesno get_digit timesince random striptags ' +
      'filesizeformat escape linebreaks length_is ljust rjust cut urlize fix_ampersands ' +
      'title floatformat capfirst pprint divisibleby add make_list unordered_list urlencode ' +
      'timeuntil urlizetrunc wordcount stringformat linenumbers slice date dictsort ' +
      'dictsortreversed default_if_none pluralize lower join center default ' +
      'truncatewords_html upper length phone2numeric wordwrap time addslashes slugify first ' +
      'escapejs force_escape iriencode last safe safeseq truncatechars localize unlocalize ' +
      'localtime utc timezone',
    contains: [
      {className: 'argument', begin: '"', end: '"'}
    ]
  };

  var DJANGO_CONTAINS = [
    {
      className: 'template_comment',
      begin: '{%\\s*comment\\s*%}', end: '{%\\s*endcomment\\s*%}'
    },
    {
      className: 'template_comment',
      begin: '{#', end: '#}'
    },
    {
      className: 'template_tag',
      begin: '{%', end: '%}',
      keywords:
        'comment endcomment load templatetag ifchanged endifchanged if endif firstof for ' +
        'endfor in ifnotequal endifnotequal widthratio extends include spaceless ' +
        'endspaceless regroup by as ifequal endifequal ssi now with cycle url filter ' +
        'endfilter debug block endblock else autoescape endautoescape csrf_token empty elif ' +
        'endwith static trans blocktrans endblocktrans get_static_prefix get_media_prefix ' +
        'plural get_current_language language get_available_languages ' +
        'get_current_language_bidi get_language_info get_language_info_list localize ' +
        'endlocalize localtime endlocaltime timezone endtimezone get_current_timezone ' +
        'verbatim',
      contains: [FILTER]
    },
    {
      className: 'variable',
      begin: '{{', end: '}}',
      contains: [FILTER]
    }
  ];

  var result = copy(hljs.LANGUAGES.xml);
  result.case_insensitive = true;
  return result;
}
<|endoftext|>


<commit_before>/* eslint-env mocha */

"use strict";

const request = require("supertest");
const assert = require("proclaim");
const vm = require("vm");
const host = require("../helpers").host;

describe("OPTIONS /v3/polyfill.min.js", function() {
	this.timeout(30000);
	it("responds with a 200 status", () => {
		return request(host)
			.options("/v3/polyfill.min.js")
			.expect(200)
			.expect("Allow", "OPTIONS, GET, HEAD");
	});
});

describe("POST /v3/polyfill.min.js", function() {
	this.timeout(30000);
	it("responds with a 405 status", () => {
		return request(host)
			.post("/v3/polyfill.min.js")
			.expect(405);
	});
});

describe("DELETE /v3/polyfill.min.js", function() {
	this.timeout(30000);
	it("responds with a 405 status", () => {
		return request(host)
			.delete("/v3/polyfill.min.js")
			.expect(405);
	});
});

describe("PURGE /v3/polyfill.min.js", function() {
	this.timeout(30000);
	it("responds with a 401 status", () => {
		return request(host)
			.purge("/v3/polyfill.min.js")
			.expect(401);
	});
});

describe("HEAD /v3/polyfill.min.js", function() {
	this.timeout(30000);
	it("responds with a 200 status", () => {
		return request(host)
			.head("/v3/polyfill.min.js")
			.set("Fastly-Debug", "true")
			.expect(200)
			.expect("Content-Type", "text/javascript; charset=utf-8")
			.expect("cache-control", "public, s-maxage=31536000, max-age=604800, stale-while-revalidate=604800, stale-if-error=604800")
			.expect("surrogate-key", "polyfill-service");
	});
});

describe("GET /v3/polyfill.min.js", function() {
	this.timeout(30000);
	it("responds with a 200 status", () => {
		return request(host)
			.get("/v3/polyfill.min.js")
			.set("Fastly-Debug", "true")
			.expect(200)
			.expect("Content-Type", "text/javascript; charset=utf-8")
			.expect("cache-control", "public, s-maxage=31536000, max-age=604800, stale-while-revalidate=604800, stale-if-error=604800")
			.expect("surrogate-key", "polyfill-service")
			.then(response => {
				assert.isString(response.text);
				assert.doesNotThrow(() => new vm.Script(response.text));
				assert.notMatch(response.text, /\/\/#\ssourceMappingURL(.+)/);
			});
	});
});

describe("GET /v3/polyfill.min.js?callback=AAA&callback=BBB", function() {
	this.timeout(30000);
	it("responds with a 200 status", () => {
		return request(host)
			.get("/v3/polyfill.min.js?callback=AAA&callback=BBB")
			.set("Fastly-Debug", "true")
			.expect(200)
			.expect("Content-Type", "text/javascript; charset=utf-8")
			.expect("cache-control", "public, s-maxage=31536000, max-age=604800, stale-while-revalidate=604800, stale-if-error=604800")
			.expect("surrogate-key", "polyfill-service")
			.then(response => {
				assert.isString(response.text);
				assert.doesNotThrow(() => new vm.Script(response.text));
				assert.notMatch(response.text, /\/\/#\ssourceMappingURL(.+)/);
			});
	});
});

describe("GET /v3/polyfill.min.js?features=all&ua=non-existent-ua&unknown=polyfill&flags=gated&rum=1", function() {
	this.timeout(30000);
	it("responds with a 200 status", () => {
		return request(host)
			.get("/v3/polyfill.min.js?features=all&ua=non-existent-ua&unknown=polyfill&flags=gated&rum=1")
			.set("Fastly-Debug", "true")
			.expect(200)
			.expect("Content-Type", "text/javascript; charset=utf-8")
			.expect("cache-control", "public, s-maxage=31536000, max-age=604800, stale-while-revalidate=604800, stale-if-error=604800")
			.expect("surrogate-key", "polyfill-service")
			.then(response => {
				assert.isString(response.text);
				// vm.Script will cause the event loop to become blocked whilst it parses the large response
				assert.doesNotThrow(() => new vm.Script(response.text));
				assert.notMatch(response.text, /\/\/#\ssourceMappingURL(.+)/);
			});
	});
});
<commit_msg>update assertions<commit_after>/* eslint-env mocha */

"use strict";

const request = require("supertest");
const assert = require("proclaim");
const vm = require("vm");
const host = require("../helpers").host;

describe("OPTIONS /v3/polyfill.min.js", function() {
	this.timeout(30000);
	it("responds with a 200 status", () => {
		return request(host)
			.options("/v3/polyfill.min.js")
			.expect(200)
			.expect("Allow", "OPTIONS, GET, HEAD");
	});
});

describe("POST /v3/polyfill.min.js", function() {
	this.timeout(30000);
	it("responds with a 405 status", () => {
		return request(host)
			.post("/v3/polyfill.min.js")
			.expect(405);
	});
});

describe("DELETE /v3/polyfill.min.js", function() {
	this.timeout(30000);
	it("responds with a 405 status", () => {
		return request(host)
			.delete("/v3/polyfill.min.js")
			.expect(405);
	});
});

describe("PURGE /v3/polyfill.min.js", function() {
	this.timeout(30000);
	it("responds with a 401 status", () => {
		return request(host)
			.purge("/v3/polyfill.min.js")
			.expect(401);
	});
});

describe("HEAD /v3/polyfill.min.js", function() {
	this.timeout(30000);
	it("responds with a 200 status", () => {
		return request(host)
			.head("/v3/polyfill.min.js")
			.set("Fastly-Debug", "true")
			.expect(200)
			.expect("Content-Type", "text/javascript; charset=utf-8")
			.expect("cache-control", "public, s-maxage=31536000, max-age=604800, stale-while-revalidate=604800, stale-if-error=604800")
			.expect("surrogate-key", /polyfill-service/);
	});
});

describe("GET /v3/polyfill.min.js", function() {
	this.timeout(30000);
	it("responds with a 200 status", () => {
		return request(host)
			.get("/v3/polyfill.min.js")
			.set("Fastly-Debug", "true")
			.expect(200)
			.expect("Content-Type", "text/javascript; charset=utf-8")
			.expect("cache-control", "public, s-maxage=31536000, max-age=604800, stale-while-revalidate=604800, stale-if-error=604800")
			.expect("surrogate-key", /polyfill-service/)
			.then(response => {
				assert.isString(response.text);
				assert.doesNotThrow(() => new vm.Script(response.text));
				assert.notMatch(response.text, /\/\/#\ssourceMappingURL(.+)/);
			});
	});
});

describe("GET /v3/polyfill.min.js?callback=AAA&callback=BBB", function() {
	this.timeout(30000);
	it("responds with a 200 status", () => {
		return request(host)
			.get("/v3/polyfill.min.js?callback=AAA&callback=BBB")
			.set("Fastly-Debug", "true")
			.expect(200)
			.expect("Content-Type", "text/javascript; charset=utf-8")
			.expect("cache-control", "public, s-maxage=31536000, max-age=604800, stale-while-revalidate=604800, stale-if-error=604800")
			.expect("surrogate-key", /polyfill-service/)
			.then(response => {
				assert.isString(response.text);
				assert.doesNotThrow(() => new vm.Script(response.text));
				assert.notMatch(response.text, /\/\/#\ssourceMappingURL(.+)/);
			});
	});
});

describe("GET /v3/polyfill.min.js?features=all&ua=non-existent-ua&unknown=polyfill&flags=gated&rum=1", function() {
	this.timeout(30000);
	it("responds with a 200 status", () => {
		return request(host)
			.get("/v3/polyfill.min.js?features=all&ua=non-existent-ua&unknown=polyfill&flags=gated&rum=1")
			.set("Fastly-Debug", "true")
			.expect(200)
			.expect("Content-Type", "text/javascript; charset=utf-8")
			.expect("cache-control", "public, s-maxage=31536000, max-age=604800, stale-while-revalidate=604800, stale-if-error=604800")
			.expect("surrogate-key", /polyfill-service/)
			.then(response => {
				assert.isString(response.text);
				// vm.Script will cause the event loop to become blocked whilst it parses the large response
				assert.doesNotThrow(() => new vm.Script(response.text));
				assert.notMatch(response.text, /\/\/#\ssourceMappingURL(.+)/);
			});
	});
});
<|endoftext|>


<commit_before>

/**
 * Reusable components for each level
 * @param pgame current phaser game instance
 */
ajtxz_hcgame.levelbase = function (pgame) {
    //Constants
    var SLIDER_X_POS = 300;
    var SLIDER_Y_POS = 575;
    var CANNON_DEFAULT = -Math.PI/4.0; //45 degrees
    var MAX_VELOCITY = 1000; //NEED TO FIND BEST VALUE

    //Game
    var game = ajtxz_hcgame.game;
    var options = game.options;

    // Obstacle variable
    var crank, crank_knob;
    var cannon_body;
    var captain;
    var pool;

    //Global Game Components
    var bird, slider_button, slider_box, slider_bar;

    function collide_obstacles(){
        // Handle collision with obstacles

    }

    function drawCannon_captain() {

        var cb_x = 10,
            cb_y = (options.height * 0.6),
            cs_x = 20,
            cs_y = (options.height * 0.7) + 10;

        game.captain = game.addAsset(cb_x + 86, cb_y + 88, 'captain');
        captain = game.captain;
        captain.anchor.setTo(0.28, 0.78);

        cannon_body = game.addAsset(cb_x + 85, cb_y + 105, 'cannon_body');
        cannon_body.scale.setTo(0.5, 0.5);
        cannon_body.anchor.setTo(0.3,0.8);
        cannon_body.rotation = CANNON_DEFAULT;

        var cannon_stand = game.addAsset(cs_x + 40, cs_y + 20, 'cannon_stand')
            .scale.setTo(0.5, 0.5);

    }

    function drawObstacles(){
        game.obstacles = pgame.add.group();
        game.obstacles.enableBody = true;

        // Add pool
        pool = game.addAsset(590, 330, 'pool');
        pool.scale.setTo(0.7,0.7);

        // Add bird
        bird = game.obstacles.create(pgame.world.centerX, 300, 'bird');

        // Two animations, flying left and right.
        bird.animations.add('left', [0,1,2,3,4], 10, true);
        bird.animations.add('right', [5,6,7,8,9], 10, true);

        // Add water jet
        var waterjet = game.obstacles.create(400, 290, 'waterjet');
        waterjet.scale.setTo(1,1);
        waterjet.immovable = true;
        waterjet.animations.add('shooting', [0,1], 2, true);
        waterjet.animations.play('shooting');

        // Add fire rings
    }

    this.birdFly = function(motionDst, motionTime){
        var bird_orientation = 1;

        bird.animations.play('right');

        var tweenbird = pgame.add.tween(bird).to({ x: motionDst }, motionTime, Phaser.Easing.Linear.None, true, 0, Number.POSITIVE_INFINITY, true);

        tweenbird.onLoop.add(function(){
            if (bird_orientation == 1){
                bird.animations.play('left');
                bird_orientation = 0;
            }else{
                bird.animations.play('right');
                bird_orientation = 1;
            }
        });
    };

    //Returns velocity with respect to current gunpowder level
    function getVelocity()
    {
        var x_position = slider_button.x - slider_box.x; //Determine x position of slider button within box
        var percentage = x_position / (slider_box.width - slider_button.width); //Determine percentage of gunpowder bar filled
        return percentage * MAX_VELOCITY; //Determine velocity
    }

    function drawBackgrounds () {

        game.addAsset(0, 0, 'level_background');
        //game.controlBoard = game.addAsset(0, 480, 'control_board');
        var g = pgame.add.group();
        g.enableBody = true;

        game.controlBoard = g.create(0, pgame.world.height - 110, 'control_board');
        game.controlBoard.body.immovable = true;
    }

    function initControls()
    {
        ////Initialize Angle Crank////
        crank = game.addAsset(90, 609, 'crank');
        crank_knob = game.addAsset(crank.x, crank.y, 'crank_knob');

        crank.scale.setTo(0.8, 0.8);
        crank.anchor.setTo(0.5, 0.5);
        crank.blocked = false;

        crank_knob.scale.setTo(0.8, 0.8);
        crank_knob.anchor.setTo(0.5, 0.5);
        crank_knob.pivot = new PIXI.Point(-49, -1);
        crank_knob.inputEnabled = true;
        crank_knob.input.useHandCursor = true;

        ////Initialize Gunpowder Slider////
        slider_box = game.addAsset(SLIDER_X_POS, SLIDER_Y_POS, 'slider_box'); //Load slider button
        slider_bar = game.addAsset(SLIDER_X_POS+13, SLIDER_Y_POS+20, 'slider_bar'); //Load slider button
        slider_button = game.addAsset(SLIDER_X_POS, SLIDER_Y_POS+5, 'slider_button'); //Load slider box
        //Set up input handler
        slider_button.inputEnabled = true;
        slider_button.input.enableDrag(false);
        slider_button.input.allowVerticalDrag = false;
        slider_button.input.useHandCursor = true;
        slider_button.input.boundsSprite = slider_box;

        ////Initialize Fire Button////
        pgame.add.button(660, 565, 'fire_button', function() {
            game.captain.body.gravity.y = 800;

            //Velocity determined by current slider and wheel positions
            var velocity = getVelocity();
            new Phaser.Text(game, 300,300,velocity);
            //Need rotation angle to get velocity_x and velocity_y values from velocity
            game.captain.body.velocity.setTo(velocity, -velocity);
        }).scale.setTo(0.70, 0.70);
    }

    this.init = function() {
        drawBackgrounds();
        initControls();
        drawCannon_captain();
        drawObstacles();

        pgame.physics.arcade.enable(game.captain);
        game.captain.body.collideWorldBounds = true;
        game.captain.body.bounce.y = 0.3;

    };

    this.defaultUpdate = function()
    {
        pgame.physics.arcade.collide(game.captain, game.controlBoard);
        pgame.physics.arcade.collide(game.captain, game.obstacles, collide_obstacles);

        //Stretch slider bar with slider button
        if (slider_button.input.pointerDragged())
            slider_bar.width = slider_button.x - slider_box.x;

        //Crank Functionality
        var current_angle = Phaser.Math.ceilTo(cannon_body.angle);
        if (crank_knob.input.pointerDown())
        {
            var click = pgame.input.activePointer;
            var angle = Phaser.Math.angleBetween(crank.x, crank.y, click.x, click.y);

            if ((current_angle != -89 || angle < 0) && (current_angle != 0 || angle > 0))
            {
                crank_knob.rotation = crank.rotation = angle;
                //game.captain.rotation = angle;
                cannon_body.rotation = CANNON_DEFAULT + angle / 4;
            }
        }

    }

};
<commit_msg>code cleanup<commit_after>

/**
 * Reusable components for each level
 * @param pgame current phaser game instance
 */
ajtxz_hcgame.levelbase = function (pgame) {
    //Constants
    var SLIDER_X_POS = 300;
    var SLIDER_Y_POS = 575;
    var CANNON_DEFAULT = -Math.PI/4.0; //45 degrees
    var MAX_VELOCITY = 1000; //NEED TO FIND BEST VALUE

    //Game
    var game = ajtxz_hcgame.game;
    var options = game.options;

    // Obstacle variable
    var crank, crank_knob;
    var cannon_body;
    var captain;
    var pool;

    //Global Game Components
    var bird, slider_button, slider_box, slider_bar;

    function collide_obstacles(){
        // Handle collision with obstacles

    }

    function drawCannon_captain() {

        var cb_x = 10,
            cb_y = (options.height * 0.6),
            cs_x = 20,
            cs_y = (options.height * 0.7) + 10;

        game.captain = game.addAsset(cb_x + 86, cb_y + 88, 'captain');
        captain = game.captain;
        captain.anchor.setTo(0.28, 0.78);

        cannon_body = game.addAsset(cb_x + 85, cb_y + 105, 'cannon_body');
        cannon_body.scale.setTo(0.5, 0.5);
        cannon_body.anchor.setTo(0.3,0.8);
        cannon_body.rotation = CANNON_DEFAULT;

        var cannon_stand = game.addAsset(cs_x + 40, cs_y + 20, 'cannon_stand')
            .scale.setTo(0.5, 0.5);

    }

    function drawObstacles(){
        game.obstacles = pgame.add.group();
        game.obstacles.enableBody = true;

        // Add pool
        pool = game.addAsset(590, 330, 'pool');
        pool.scale.setTo(0.7,0.7);

        // Add bird
        bird = game.obstacles.create(pgame.world.centerX, 300, 'bird');

        // Two animations, flying left and right.
        bird.animations.add('left', [0,1,2,3,4], 10, true);
        bird.animations.add('right', [5,6,7,8,9], 10, true);

        // Add water jet
        var waterjet = game.obstacles.create(400, 290, 'waterjet');
        waterjet.scale.setTo(1,1);
        waterjet.immovable = true;
        waterjet.animations.add('shooting', [0,1], 2, true);
        waterjet.animations.play('shooting');

        // Add fire rings
    }

    this.birdFly = function(motionDst, motionTime){
        var bird_orientation = 1;

        bird.animations.play('right');

        var tweenbird = pgame.add.tween(bird).to({ x: motionDst }, motionTime, Phaser.Easing.Linear.None, true, 0, Number.POSITIVE_INFINITY, true);

        tweenbird.onLoop.add(function(){
            if (bird_orientation == 1){
                bird.animations.play('left');
                bird_orientation = 0;
            }else{
                bird.animations.play('right');
                bird_orientation = 1;
            }
        });
    };

    //Returns velocity with respect to current gunpowder level
    function getVelocity()
    {
        var x_position = slider_button.x - slider_box.x; //Determine x position of slider button within box
        var percentage = x_position / (slider_box.width - slider_button.width); //Determine percentage of gunpowder bar filled
        return percentage * MAX_VELOCITY; //Determine velocity
    }

    function drawBackgrounds () {

        game.addAsset(0, 0, 'level_background');
        //game.controlBoard = game.addAsset(0, 480, 'control_board');
        var g = pgame.add.group();
        g.enableBody = true;

        game.controlBoard = g.create(0, pgame.world.height - 110, 'control_board');
        game.controlBoard.body.immovable = true;
    }

    function initControls()
    {
        ////Initialize Angle Crank////
        crank = game.addAsset(90, 609, 'crank');
        crank_knob = game.addAsset(crank.x, crank.y, 'crank_knob');

        crank.scale.setTo(0.8, 0.8);
        crank.anchor.setTo(0.5, 0.5);

        crank_knob.scale.setTo(0.8, 0.8);
        crank_knob.anchor.setTo(0.5, 0.5);
        crank_knob.pivot = new PIXI.Point(-49, -1);
        crank_knob.inputEnabled = true;
        crank_knob.input.useHandCursor = true;

        ////Initialize Gunpowder Slider////
        slider_box = game.addAsset(SLIDER_X_POS, SLIDER_Y_POS, 'slider_box'); //Load slider button
        slider_bar = game.addAsset(SLIDER_X_POS+13, SLIDER_Y_POS+20, 'slider_bar'); //Load slider button
        slider_button = game.addAsset(SLIDER_X_POS, SLIDER_Y_POS+5, 'slider_button'); //Load slider box
        //Set up input handler
        slider_button.inputEnabled = true;
        slider_button.input.enableDrag(false);
        slider_button.input.allowVerticalDrag = false;
        slider_button.input.useHandCursor = true;
        slider_button.input.boundsSprite = slider_box;

        ////Initialize Fire Button////
        pgame.add.button(660, 565, 'fire_button', function() {
            game.captain.body.gravity.y = 800;

            //Velocity determined by current slider and wheel positions
            var velocity = getVelocity();
            new Phaser.Text(game, 300,300,velocity);
            //Need rotation angle to get velocity_x and velocity_y values from velocity
            game.captain.body.velocity.setTo(velocity, -velocity);
        }).scale.setTo(0.70, 0.70);
    }

    this.init = function() {
        drawBackgrounds();
        initControls();
        drawCannon_captain();
        drawObstacles();

        pgame.physics.arcade.enable(game.captain);
        game.captain.body.collideWorldBounds = true;
        game.captain.body.bounce.y = 0.3;

    };

    this.defaultUpdate = function()
    {
        //////Determine collisions//////
        pgame.physics.arcade.collide(game.captain, game.controlBoard);
        pgame.physics.arcade.collide(game.captain, game.obstacles, collide_obstacles);

        /////Slider Functionality///////
        //If slider button is being dragged, fill slider box with bar
        if (slider_button.input.pointerDragged())
            slider_bar.width = slider_button.x - slider_box.x;

        /////Crank Functionality//////
        var current_angle = Phaser.Math.ceilTo(cannon_body.angle); //Current angle of cannon body
        //If crank knob is being selected, determine rotations
        if (crank_knob.input.pointerDown())
        {
            //Find angle between crank knob and crank center
            var click = pgame.input.activePointer;
            var angle = Phaser.Math.angleBetween(crank.x, crank.y, click.x, click.y);

            //Rotate crank and cannon accordingly. Block if 90 or 0 degrees is reached
            if ((current_angle != -89 || angle < 0) && (current_angle != 0 || angle > 0))
            {
                crank_knob.rotation = crank.rotation = angle;
                //game.captain.rotation = angle;
                cannon_body.rotation = CANNON_DEFAULT + angle / 4; //cannon max is 90, min is 0
            }
        }

    }

};
<|endoftext|>