<commit_before>/**
 * Build profile for butter. Replaces the use of requirejs with an AMD
 * loader shim, almond.js, since the built file does not need to use
 * all of requirejs.
 */
({
  // Where to find the module names listed below.
  baseUrl: '../src',

  // Use has branch trimming in the build to remove the document.write
  // code in src/butter.js after a minification is done.
  has: {
    'source-config': false
  },

  // Target the AMD loader shim as the main module to optimize,
  // so it shows up first in the built file,
  // since the butter modules use the define/require APIs that the almond
  // provides. Path is relative to baseUrl.
  name: '../tools/almond',

  // Files to include along with almond. Their nested dependencies will also be
  // included. Subsystems are listed explicitly because butter-src.js does not
  // have explicit dependencies for them, but uses them on demand. Also,
  // butter.js references butter-src in a document.write string, so it will
  // not be found by the AST analysis done in the optimizer.
  include: [
            'butter',
            'main'
           ],

  // Wraps Butter in a closure and adds license information
  wrap: {
    startFile: '../tools/wrap.start',
    endFile: '../tools/wrap.end'
  },

  // The built butter.min.js file for use by web sites.
  out: '../dist/butter.min.js'
})
<commit_msg>[t628] fixed build system for text plugin<commit_after>/**
 * Build profile for butter. Replaces the use of requirejs with an AMD
 * loader shim, almond.js, since the built file does not need to use
 * all of requirejs.
 */
({
  // Where to find the module names listed below.
  baseUrl: '../src',

  paths: {
    'text': '../external/require/text'
  },

  // Use has branch trimming in the build to remove the document.write
  // code in src/butter.js after a minification is done.
  has: {
    'source-config': false
  },

  // Target the AMD loader shim as the main module to optimize,
  // so it shows up first in the built file,
  // since the butter modules use the define/require APIs that the almond
  // provides. Path is relative to baseUrl.
  name: '../tools/almond',

  // Files to include along with almond. Their nested dependencies will also be
  // included. Subsystems are listed explicitly because butter-src.js does not
  // have explicit dependencies for them, but uses them on demand. Also,
  // butter.js references butter-src in a document.write string, so it will
  // not be found by the AST analysis done in the optimizer.
  include: [
            'butter',
            'main'
           ],

  // Wraps Butter in a closure and adds license information
  wrap: {
    startFile: '../tools/wrap.start',
    endFile: '../tools/wrap.end'
  },

  // The built butter.min.js file for use by web sites.
  out: '../dist/butter.min.js'
})
<|endoftext|>


<commit_before>module.exports = MainGameActivity;

var colors     = require('./maps/colors.js');
var EcsService = require('./services/EcsService.js');

/**
 * @constructor
 * @param {EcsService} ecs
 * @param {Canvas} screen
 */
function MainGameActivity(navigator, inputs, player, maps, screen, ecs, sound)
{
  this.paused    = true;
  this.screen    = screen;
  this.ecs       = ecs;
  this.maps      = maps;
  this.sound     = sound;
  this.player    = player;
  this.inputs    = inputs;
  this.navigator = navigator;

  this.fade = 1;

  this.startTime = 0;
}

MainGameActivity.prototype.onStart = function()
{
  this.maps.loadLevel('nicklevel');
  this.player.colorSpirit.setBoth(colors.green);
};

MainGameActivity.prototype.onResume = function()
{
  this.paused = false;
};

MainGameActivity.prototype.onPause = function()
{
  this.paused = true;
};

/**
 * @param {Number} dt
 * @param {Number} time
 */
MainGameActivity.prototype.update = function(dt, time)
{
  this.startTime = this.startTime || time;
  var fade = Math.max(0, 1 - (time - this.startTime) / 1000);
  this.fade = this.fade * 0.9 + fade * 0.1;

  if (this.inputs.button_k_27) {
    this.navigator.finish(this);
  }

  if(this.inputs.button_k_49)
    this.player.colorSpirit.set(colors.red);
  if(this.inputs.button_k_50)
    this.player.colorSpirit.set(colors.yellow);
  if(this.inputs.button_k_51)
    this.player.colorSpirit.set(colors.green);
  if(this.inputs.button_k_52)
    this.player.colorSpirit.set(colors.blue);
  if(this.inputs.button_k_53)
    this.player.colorSpirit.set(colors.purple);
  if(this.inputs.button_k_54)
    this.player.colorSpirit.set(colors.gray);

  if (this.paused) return;

  this.ecs.update(dt, time);
  this.drawFade();
};

MainGameActivity.prototype.drawFade = function()
{
  this.screen.save().setAlpha(this.fade).fill('black').restore();
};

<commit_msg>color overrides<commit_after>module.exports = MainGameActivity;

var colors     = require('./maps/colors.js');
var EcsService = require('./services/EcsService.js');

/**
 * @constructor
 * @param {EcsService} ecs
 * @param {Canvas} screen
 */
function MainGameActivity(navigator, inputs, player, maps, screen, ecs, sound)
{
  this.paused    = true;
  this.screen    = screen;
  this.ecs       = ecs;
  this.maps      = maps;
  this.sound     = sound;
  this.player    = player;
  this.inputs    = inputs;
  this.navigator = navigator;

  this.fade = 1;

  this.startTime = 0;
}

MainGameActivity.prototype.onStart = function()
{
  this.maps.loadLevel('level4');
  this.player.colorSpirit.setBoth(colors.green);
};

MainGameActivity.prototype.onResume = function()
{
  this.paused = false;
};

MainGameActivity.prototype.onPause = function()
{
  this.paused = true;
};

/**
 * @param {Number} dt
 * @param {Number} time
 */
MainGameActivity.prototype.update = function(dt, time)
{
  this.startTime = this.startTime || time;
  var fade = Math.max(0, 1 - (time - this.startTime) / 1000);
  this.fade = this.fade * 0.9 + fade * 0.1;

  if (this.inputs.button_k_27) {
    this.navigator.finish(this);
  }

  if(this.inputs.button_k_49)
    this.player.colorSpirit.setBoth(colors.red);
  if(this.inputs.button_k_50)
    this.player.colorSpirit.setBoth(colors.yellow);
  if(this.inputs.button_k_51)
    this.player.colorSpirit.setBoth(colors.green);
  if(this.inputs.button_k_52)
    this.player.colorSpirit.setBoth(colors.blue);
  if(this.inputs.button_k_53)
    this.player.colorSpirit.setBoth(colors.purple);
  if(this.inputs.button_k_54)
    this.player.colorSpirit.setBoth(colors.gray);

  if (this.paused) return;

  this.ecs.update(dt, time);
  this.drawFade();
};

MainGameActivity.prototype.drawFade = function()
{
  this.screen.save().setAlpha(this.fade).fill('black').restore();
};

<|endoftext|>


<commit_before>/**
 * @preserve
 * @source: https://raw.githubusercontent.com/lunarcloud/gameinputjs/master/gameinput.js
 * @license magnet:?xt=urn:btih:d3d9a9a6595521f9666a5e94cc830dab83b65699&dn=expat.txt MIT (Expat) License
 */
"use strict";

if (typeof(GameInput) == "undefined") throw "GameInput JS must be included first!";

/**
 * GameInput.CustomLearning
 * @brief   Game Input System Learning Functionality
 * @desc    System for mapping a gamepad or keyboard control scheme by prompts
 */
gi.CustomLearning = {};

// encapsulate
(function(){
    "use strict";

    var ignorableAxes = {};
    var customMappings = {};

    /**
      * @desc   Detects erratic / noisy axes to ignore while mapping, such as accelerometers or broken sticks
      * @param  player      index of the player whose noisy axes we're listening for
      */
    gi.CustomLearning.detectIgnorableAxes = function(player) {
        ignorableAxes[player] = {};
        //TODO
    }

    /**
      * @desc   Creates a new Custom Mapping
      * @param  player      index of the player to create a mapping for
      */
    gi.CustomLearning.beginCustomMapping = function(player) {
        customMappings[player] = {};
        //TODO
        //TODO listen for each item
    }

    /**
      * @desc   Listens for a mapping item
      * @param  player      index of the player whose gamepad to listen to
      * @param  schemaName  one of the gi.Schema.Names
      */
    gi.CustomLearning.listenForMappingItem = function(player, schemaName) {
        //TODO
    }

    /**
      * @desc   Sets an item in the custom mapping being made
      * @param  player      index of the player to configure this button for
      * @param  schemaName  one of the gi.Schema.Names
      * @param  button      button to assign to the schemaName'd item
      */
    gi.CustomLearning.setMappingItem = function(player, schemaName, button) {
        //TODO
    }

    /**
      * @desc   Finalized and assigns mapping
      * @param  player      index of the player to finish mapping for
      */
    gi.CustomLearning.completeCustomMapping = function(player) {
        //TODO
    }

})();

/**
 * @preserve
 * @license-end
 */
<commit_msg>Added listen event handling<commit_after>/**
 * @preserve
 * @source: https://raw.githubusercontent.com/lunarcloud/gameinputjs/master/gameinput.js
 * @license magnet:?xt=urn:btih:d3d9a9a6595521f9666a5e94cc830dab83b65699&dn=expat.txt MIT (Expat) License
 */
"use strict";

if (typeof(GameInput) == "undefined") throw "GameInput JS must be included first!";

/**
 * GameInput.CustomLearning
 * @brief   Game Input System Learning Functionality
 * @desc    System for mapping a gamepad or keyboard control scheme by prompts
 */
gi.CustomLearning = {};

// encapsulate
(function(){
    "use strict";

    var ignorableAxes = {};
    var customMappings = {};
    var mappingListeningHandlers = [];

    /**
      * @desc   Detects erratic / noisy axes to ignore while mapping, such as accelerometers or broken sticks
      * @param  player      index of the player whose noisy axes we're listening for
      */
    gi.CustomLearning.detectIgnorableAxes = function(player) {
        ignorableAxes[player] = {};
        //TODO
    }

    /**
      * @desc   Creates a new Custom Mapping
      * @param  player      index of the player to create a mapping for
      */
    gi.CustomLearning.beginCustomMapping = function(player) {
        customMappings[player] = {};
        //TODO
        //TODO listen for each item
    }

    /**
      * @desc   Setup a function to fire when listening event occurs, used for display purposes.
      * @param  handler     the function to handle the event
      */
    gi.CustomLearning.onListeningForMappingItem = function(handler) {
        mappingListeningHandlers.push(handler);
    }

    /**
      * @desc   Listens for a mapping item
      * @param  player      index of the player whose gamepad to listen to
      * @param  schemaName  one of the gi.Schema.Names
      */
    gi.CustomLearning.listenForMappingItem = function(player, schemaName) {
        //TODO
        //TODO fire mappingListeningHandlers handlers with the player and schemaName
    }

    /**
      * @desc   Sets an item in the custom mapping being made
      * @param  player      index of the player to configure this button for
      * @param  schemaName  one of the gi.Schema.Names
      * @param  button      button to assign to the schemaName'd item
      */
    gi.CustomLearning.setMappingItem = function(player, schemaName, button) {
        //TODO
    }

    /**
      * @desc   Finalized and assigns mapping
      * @param  player      index of the player to finish mapping for
      */
    gi.CustomLearning.completeCustomMapping = function(player) {
        //TODO
    }

})();

/**
 * @preserve
 * @license-end
 */
<|endoftext|>


<commit_before>{
	"stable": {
		"CSIDE_version": "1.1.3",
    "nw_version": "0.21.4",
    "desc": "v1.1.3 - Provides a criticial bug fix related to persistent sessions",
		"target": "https://choicescriptide.github.io/downloads/updates/targets/113.zip"
	},
	"latest": {
		"CSIDE_version": "1.1.3",
    "nw_version": "0.21.4",
    "desc": "v1.1.3 - Provides a criticial bug fix related to persistent sessions",
		"target": "https://choicescriptide.github.io/downloads/updates/targets/113.zip"
	},
	"development": {
		"CSIDE_version": "1.2.1",
    "nw_version": "0.21.4",
    "desc": "v1.2.1 - Provides a criticial bug fix related to persistent sessions",
		"target": "https://choicescriptide.github.io/downloads/updates/targets/121.zip"
	}
}
<commit_msg>Add accessibility channel<commit_after>{
	"stable": {
		"CSIDE_version": "1.1.3",
    "nw_version": "0.21.4",
    "desc": "v1.1.3 - Provides a criticial bug fix related to persistent sessions",
		"target": "https://choicescriptide.github.io/downloads/updates/targets/113.zip"
	},
	"latest": {
		"CSIDE_version": "1.1.3",
    "nw_version": "0.21.4",
    "desc": "v1.1.3 - Provides a criticial bug fix related to persistent sessions",
		"target": "https://choicescriptide.github.io/downloads/updates/targets/113.zip"
	},
	"development": {
		"CSIDE_version": "1.2.1",
    "nw_version": "0.21.4",
    "desc": "v1.2.1 - Provides a criticial bug fix related to persistent sessions",
		"target": "https://choicescriptide.github.io/downloads/updates/targets/121.zip"
	},
  "accessible": {
    "CSIDE_version": "1.1.2",
    "nw_version": "0.21.4",
    "desc": "",
    "target": ""
  }
}
<|endoftext|>


<commit_before>module.exports = (inc, contents) => {
    var pic = contents.picture;
    delete contents.picture;

    include(inc, 'phone', random(3, 3) + '-' + random(3, 3) + '-' + random(3, 4));
    include(inc, 'cell', random(3, 3) + '-' + random(3, 3) + '-' + random(3, 4));
    include(inc, 'id', {
        name: '',
        value: null
    });
    include(inc, 'picture', pic);
};<commit_msg>Format CA post codes properly<commit_after>module.exports = (inc, contents) => {
    var pic = contents.picture;
    delete contents.picture;

    include(inc, 'phone', random(3, 3) + '-' + random(3, 3) + '-' + random(3, 4));
    include(inc, 'cell', random(3, 3) + '-' + random(3, 3) + '-' + random(3, 4));
    include(inc, 'id', {
        name: '',
        value: null
    });
    include(inc, 'location', () => {
      var letters = 'ABCDEFGHIJKLMNOPQRSTUVWXYZ';

      var postcode = letters[range(0,25)] + random(3, 1) + letters[range(0,25)] + ' ' + random(3, 1) + letters[range(0,25)] + random(3, 1);

      contents.location.postcode = postcodes;
    });

    include(inc, 'picture', pic);
};
<|endoftext|>


<commit_before>import { GiphyContent, GiphyGridView, GiphyMediaType } from '@giphy/react-native-sdk';
import React, { useCallback, useState } from 'react';
import { useTranslation } from 'react-i18next';
import { useDispatch } from 'react-redux';

import { createGifSentEvent, sendAnalytics } from '../../../analytics';
import JitsiScreen from '../../../base/modal/components/JitsiScreen';
import { sendMessage } from '../../../chat/actions.any';
import { goBack } from '../../../mobile/navigation/components/conference/ConferenceNavigationContainerRef';
import ClearableInput from '../../../participants-pane/components/native/ClearableInput';
import { formatGifUrlMessage, getGifUrl } from '../../functions';
import GifsMenuFooter from './GifsMenuFooter';
import styles from './styles';

const GifsMenu = () => {
    const [ searchQuery, setSearchQuery ] = useState('');
    const dispatch = useDispatch();
    const { t } = useTranslation();

    const content = searchQuery === ''
        ? GiphyContent.trending({ mediaType: GiphyMediaType.Gif })
        : GiphyContent.search({
            searchQuery,
            mediaType: GiphyMediaType.Gif
        });

    const sendGif = useCallback(e => {
        const url = getGifUrl(e.nativeEvent.media);

        sendAnalytics(createGifSentEvent());

        dispatch(sendMessage(formatGifUrlMessage(url), true));
        goBack();
    }, []);

    return (
        <JitsiScreen
            footerComponent = { GifsMenuFooter }
            style = { styles.container }>
            <ClearableInput
                customStyles = { styles.clearableInput }
                onChange = { setSearchQuery }
                placeholder = { t('giphy.search') }
                value = { searchQuery } />
            <GiphyGridView
                cellPadding = { 5 }
                content = { content }
                onMediaSelect = { sendGif }
                style = { styles.grid } />
        </JitsiScreen>
    );
};

export default GifsMenu;
<commit_msg>feat(gifs/native): fixed linter<commit_after>import { GiphyContent, GiphyGridView, GiphyMediaType } from '@giphy/react-native-sdk';
import React, { useCallback, useState } from 'react';
import { useTranslation } from 'react-i18next';
import { useDispatch } from 'react-redux';

import { createGifSentEvent, sendAnalytics } from '../../../analytics';
import JitsiScreen from '../../../base/modal/components/JitsiScreen';
import { sendMessage } from '../../../chat/actions.any';
import { goBack } from '../../../mobile/navigation/components/conference/ConferenceNavigationContainerRef';
import ClearableInput from '../../../participants-pane/components/native/ClearableInput';
import { formatGifUrlMessage, getGifUrl } from '../../functions';

import GifsMenuFooter from './GifsMenuFooter';
import styles from './styles';

const GifsMenu = () => {
    const [ searchQuery, setSearchQuery ] = useState('');
    const dispatch = useDispatch();
    const { t } = useTranslation();

    const content = searchQuery === ''
        ? GiphyContent.trending({ mediaType: GiphyMediaType.Gif })
        : GiphyContent.search({
            searchQuery,
            mediaType: GiphyMediaType.Gif
        });

    const sendGif = useCallback(e => {
        const url = getGifUrl(e.nativeEvent.media);

        sendAnalytics(createGifSentEvent());

        dispatch(sendMessage(formatGifUrlMessage(url), true));
        goBack();
    }, []);

    return (
        <JitsiScreen
            footerComponent = { GifsMenuFooter }
            style = { styles.container }>
            <ClearableInput
                customStyles = { styles.clearableInput }
                onChange = { setSearchQuery }
                placeholder = { t('giphy.search') }
                value = { searchQuery } />
            <GiphyGridView
                cellPadding = { 5 }
                content = { content }
                onMediaSelect = { sendGif }
                style = { styles.grid } />
        </JitsiScreen>
    );
};

export default GifsMenu;
<|endoftext|>


<commit_before>var express   = require('express');
var fs        = require('fs');
var io        = require('socket.io');
var _         = require('underscore');
var Mustache  = require('mustache');
var crypto		= require('crypto');

var app       = express.createServer();
var staticDir = express.static;

io            = io.listen(app);

var opts = {
	port :      1948,
	baseDir :   __dirname + '/../../'
};

io.sockets.on('connection', function(socket) {
	socket.on('slidechanged', function(slideData) {
		console.log(slideData);
		if (createHash(slideData.secret) === slideData.socketId) {
			slideData.secret = null;
			socket.broadcast.emit(slideData.socketId, slideData);
		};
	});
});

app.configure(function() {
	[ 'css', 'js', 'plugin', 'lib' ].forEach(function(dir) {
		app.use('/' + dir, staticDir(opts.baseDir + dir));
	});
});

app.get("/", function(req, res) {
	fs.createReadStream(opts.baseDir + '/index.html').pipe(res);
});

app.get("/token", function(req,res) {
	var ts = new Date().getTime();
	var rand = Math.floor(Math.random()*9999999);
	var secret = ts.toString() + rand.toString();
	res.send({secret: secret, socketId: createHash(secret)});
});

var createHash = function(secret) {
	var cipher = crypto.createCipher('blowfish', secret);
	return(cipher.final('hex'));
};

// Actually listen
app.listen(opts.port || null);

var brown = '\033[33m',
	green = '\033[32m',
	reset = '\033[0m';

var slidesLocation = "http://localhost" + ( opts.port ? ( ':' + opts.port ) : '' );

console.log( brown + "reveal.js - Speaker Notes" + reset );
console.log( "1. Open the slides at " + green + slidesLocation + reset );
console.log( "2. Click on the link your JS console to go to the notes page" );
console.log( "3. Advance through your slides and your notes will advance automatically" );
<commit_msg>Removed unused code<commit_after>var express   = require('express');
var fs        = require('fs');
var io        = require('socket.io');
var crypto		= require('crypto');

var app       = express.createServer();
var staticDir = express.static;

io            = io.listen(app);

var opts = {
	port :      1948,
	baseDir :   __dirname + '/../../'
};

io.sockets.on('connection', function(socket) {
	socket.on('slidechanged', function(slideData) {
		console.log(slideData);
		if (createHash(slideData.secret) === slideData.socketId) {
			slideData.secret = null;
			socket.broadcast.emit(slideData.socketId, slideData);
		};
	});
});

app.configure(function() {
	[ 'css', 'js', 'plugin', 'lib' ].forEach(function(dir) {
		app.use('/' + dir, staticDir(opts.baseDir + dir));
	});
});

app.get("/", function(req, res) {
	fs.createReadStream(opts.baseDir + '/index.html').pipe(res);
});

app.get("/token", function(req,res) {
	var ts = new Date().getTime();
	var rand = Math.floor(Math.random()*9999999);
	var secret = ts.toString() + rand.toString();
	res.send({secret: secret, socketId: createHash(secret)});
});

var createHash = function(secret) {
	var cipher = crypto.createCipher('blowfish', secret);
	return(cipher.final('hex'));
};

// Actually listen
app.listen(opts.port || null);
<|endoftext|>


<commit_before>var fs = require('fs');
var parse = require('fast-plist').parse;

var musicLibrayXmlFilename = process.argv[2];

if(!musicLibrayXmlFilename){
	console.error("usage: " + process.argv[0] + " " + process.argv[1] + ' <path to "iTunes Music Library.xml">');
	process.exit(1);
}

var plist = parse(fs.readFileSync(musicLibrayXmlFilename, 'utf8'));

var tracks = plist.Tracks;

for(var id in tracks){
	var track = tracks[id];
	console.log(track.Name);
}

<commit_msg>Add basic functionality to generate sql for tracks<commit_after>var fs = require('fs');
var parse = require('fast-plist').parse;

var musicLibrayXmlFilename = process.argv[2];

if(!musicLibrayXmlFilename){
	console.error("usage: " + process.argv[0] + " " + process.argv[1] + ' <path to "iTunes Music Library.xml">');
	process.exit(1);
}

function escapeQuotes(s){
	return s.replace(/'/, "''");
}

function formatOptional(track, keyName, isString){
	var value = track[keyName];
	if(!value){
		return 'NULL';
	}
	if(isString){
		return `'${escapeQuotes(value)}'`;
	}
	return value;
}

function trackToSql(track){
	var trackTable = "tracks";
	var composer = formatOptional(track, 'Composer', true);
	var artist = formatOptional(track, 'Artist', true);
	return `INSERT INTO ${trackTable}(name, artist, file_size, total_time, year, composer) VALUES ('${escapeQuotes(track.Name)}', '${artist}', ${track["Size"]}, ${track["Total Time"]}, ${track["Year"]}, ${composer});`;
}

function printKeys(obj){
	function formatKey(s){
		return `'\${track["${s}"]}'`
	}
	console.log(Object.keys(obj).map(formatKey).join(', '));
}

function printKinds(tracks){
	var kinds = new Map();

	for(var id in tracks){
		var track = tracks[id];

		if(!kinds.has(track.Kind)){
			kinds.set(track.Kind, 1);
		}
		else{
			kinds.set(track.Kind, kinds.get(track.Kind) + 1);
		}
	}
	console.log(kinds.entries());
}

var plist = parse(fs.readFileSync(musicLibrayXmlFilename, 'utf8'));

var tracks = plist.Tracks;

for(var id in tracks){
	var track = tracks[id];
	if(!track.Kind.match(/\baudio\b/)){
		continue;
	}
	console.log(trackToSql(track));
	// printKeys(track);
	// break;
}

<|endoftext|>


<commit_before>enyo.kind({
	name: "moon.Item",
	classes: "moon-item",
	spotlight: true,
	handlers: {
		onSpotlightFocused: "spotlightFocused"
	},
	published: {
		//* When true, button is shown as disabled and does not generate tap
		//* events
		disabled: false,
		//* The relative position of the spotlight;
		//* valid values are "locale-specific", "left", "right", "top", and "bottom"
		//* The locale-specific setting selects either left or right, depending on the
		//* default text-direction of the current locale, when enyo-ilib is loaded
		//* (defaults to left if enyo-ilib is not loaded)
		spotlightPosition: "locale-default",
		//* The behavior of the spotlight
		spotlightOverlay: false
	},
	//* @protected
	overlayComponents: [
		{name: "overlay", classes: "moon-item-overlay", addBefore: true}
	],
	create: function() {
		this.inherited(arguments);
		this.disabledChanged();
	},
	initComponents: function() {
		this.inherited(arguments);
		this.spotlightConfig();
	},
	rendered: function() {
		this.inherited(arguments);
		this.setSpotlightBounds();
	},
	spotlightConfig: function() {
		if (this.spotlightOverlay) {
			this.createComponents(this.overlayComponents);
			this.addClass("overlay");
		}
		this.addClass(this.spotlightPosition);
	},
	setSpotlightBounds: function() {
		if (this.spotlightOverlay) {
			var b = this.getBounds();
			var ob;
			switch (this.spotlightPosition) {
				case "top":
					ob = {width: b.width};
					break;
				case "bottom":
					ob = {width: b.width, bottom: 0};
					break;
				case "left":
					ob = {height: b.height};
					break;
				case "right":
					ob = {height: b.height, right: 0};
					break;
			}
			this.$.overlay.setBounds(ob);
		}
	},
	spotlightPositionChanged: function(inOld) {
		this.removeClass(inOld);
		this.addClass(this.spotlightPosition);
	},
	disabledChanged: function() {
		this.addRemoveClass("disabled", this.disabled);
	},
	spotlightFocused: function(inSender, inEvent) {
		this.bubble("onRequestScrollIntoView", {side: "top"});
		return true;
	}
});
<commit_msg>Fix comment. Enyo-DCO-1.1-Signed-off-by: Kevin Schaaf <kevin.schaaf@lge.com><commit_after>enyo.kind({
	name: "moon.Item",
	classes: "moon-item",
	spotlight: true,
	handlers: {
		onSpotlightFocused: "spotlightFocused"
	},
	published: {
		//* When true, button is shown as disabled and does not generate tap
		//* events
		disabled: false,
		//* The relative position of the spotlight;
		//* valid values are "locale-default", "left", "right", "top", and "bottom"
		//* The locale-specific setting selects either left or right, depending on the
		//* default text-direction of the current locale, when enyo-ilib is loaded
		//* (defaults to left if enyo-ilib is not loaded)
		spotlightPosition: "locale-default",
		//* The behavior of the spotlight
		spotlightOverlay: false
	},
	//* @protected
	overlayComponents: [
		{name: "overlay", classes: "moon-item-overlay", addBefore: true}
	],
	create: function() {
		this.inherited(arguments);
		this.disabledChanged();
	},
	initComponents: function() {
		this.inherited(arguments);
		this.spotlightConfig();
	},
	rendered: function() {
		this.inherited(arguments);
		this.setSpotlightBounds();
	},
	spotlightConfig: function() {
		if (this.spotlightOverlay) {
			this.createComponents(this.overlayComponents);
			this.addClass("overlay");
		}
		this.addClass(this.spotlightPosition);
	},
	setSpotlightBounds: function() {
		if (this.spotlightOverlay) {
			var b = this.getBounds();
			var ob;
			switch (this.spotlightPosition) {
				case "top":
					ob = {width: b.width};
					break;
				case "bottom":
					ob = {width: b.width, bottom: 0};
					break;
				case "left":
					ob = {height: b.height};
					break;
				case "right":
					ob = {height: b.height, right: 0};
					break;
			}
			this.$.overlay.setBounds(ob);
		}
	},
	spotlightPositionChanged: function(inOld) {
		this.removeClass(inOld);
		this.addClass(this.spotlightPosition);
	},
	disabledChanged: function() {
		this.addRemoveClass("disabled", this.disabled);
	},
	spotlightFocused: function(inSender, inEvent) {
		this.bubble("onRequestScrollIntoView", {side: "top"});
		return true;
	}
});
<|endoftext|>


<commit_before>/**
 * dynamo.js
 * http://prezjordan.github.io/dynamo.js
 *
 * Copyright 2013 Jordan Scales (http://jordanscales.com)
 * Released under the MIT license
 * See LICENSE.txt
 */

/*jslint browser: true, evil: true, sloppy: true, vars: true,
         indent: 2, maxerr: 20, maxlen: 100 */
/*global jQuery */

(function ($) {

  $.fn.dynamo = function (options) {

    return this.each(function (i, v) {
      options = options || {};

      // select the element v
      var v$ = $(v);

      // we mark launched dynamos as "intialized" then check so we don't initialize them twice
      if (v$.data('initialized') === 'true') {
        return;
      }

      var delay = options.delay || parseInt(v$.data('delay'), 10) || 3000;
      var speed = options.speed || parseInt(v$.data('speed'), 10) || 350;
      var pause = options.pause || v$.data('pause') || false;
      var lines = options.lines || v$.data('lines').split(v$.data('delimiter') || ',');
      var callback = options.callback || new Function(v$.data('callback')) || function () {};
      var centered = options.centered || v$.data('center') || false;

      // wrap the original contents in a span
      v$.html($('').html(v$.html())).data('initialized', 'true');

      // construct a span for each line in lines
      lines.forEach(function (line) {
        v$.append($('').html(line));
      });

      // replace all the spans with inline-div$'s
      v$.find('span').each(function (i, ele) {
        var old$ = $(ele).remove();
        var div$ = $('

').html(old$.html());

        if (!i) {
          // our last element gets tagged
          div$.data('trigger', 'true');
        }

        v$.append(div$);
      });

      // set the height of the dynamo container
      var height = v$.find('>:first-child').height();

      // style
      v$.height(height)
        .css({
          'display' : 'inline-block',
          'position' : 'relative',
          'overflow' : 'hidden',
          'vertical-align' : 'bottom',
          'text-align' : 'left'
        });

      // manually center it if we need to
      if (centered) {
        v$.css('text-align', 'center');
      }

      // now, animate it
      var transition = function () {
        v$.dynamo_trigger({ speed: speed, callback: callback });
      };

      if (!pause) {
        setInterval(transition, delay);
      }
    });
  };

  $.fn.dynamo_trigger = function (options) {

    return this.each(function (i, v) {
      options = options || {};

      var v$ = $(v);
      var speed = options.speed || v$.data('speed') || 350;
      var callback = options.callback || new Function(v$.data('callback')) || function () {};

      v$.find('div:first').slideUp(speed, function () {
        v$.append($(this).show());

        // check if the first item has made its way to the top again
        if (v$.find('div:first').data('trigger') === 'true') {
          callback();
        }
      });
    });
  };

  // automatically initiate cycles on elements of class 'dynamo'
  $('.dynamo').dynamo();

}(jQuery));
<commit_msg>Allow for the pausing of dynamo elements by setting the 'pause' data attribute to true. Resetting it to anything else will unpause.<commit_after>/**
 * dynamo.js
 * http://prezjordan.github.io/dynamo.js
 *
 * Copyright 2013 Jordan Scales (http://jordanscales.com)
 * Released under the MIT license
 * See LICENSE.txt
 */

/*jslint browser: true, evil: true, sloppy: true, vars: true,
         indent: 2, maxerr: 20, maxlen: 100 */
/*global jQuery */

(function ($) {

  $.fn.dynamo = function (options) {

    return this.each(function (i, v) {
      options = options || {};

      // select the element v
      var v$ = $(v);

      // we mark launched dynamos as "intialized" then check so we don't initialize them twice
      if (v$.data('initialized') === 'true') {
        return;
      }

      var delay = options.delay || parseInt(v$.data('delay'), 10) || 3000;
      var speed = options.speed || parseInt(v$.data('speed'), 10) || 350;
      var pause = options.pause || v$.data('pause') || false;
      var lines = options.lines || v$.data('lines').split(v$.data('delimiter') || ',');
      var callback = options.callback || new Function(v$.data('callback')) || function () {};
      var centered = options.centered || v$.data('center') || false;

      // wrap the original contents in a span
      v$.html($('').html(v$.html())).data('initialized', 'true');

      // construct a span for each line in lines
      lines.forEach(function (line) {
        v$.append($('').html(line));
      });

      // replace all the spans with inline-div$'s
      v$.find('span').each(function (i, ele) {
        var old$ = $(ele).remove();
        var div$ = $('

').html(old$.html());

        if (!i) {
          // our last element gets tagged
          div$.data('trigger', 'true');
        }

        v$.append(div$);
      });

      // set the height of the dynamo container
      var height = v$.find('>:first-child').height();

      // style
      v$.height(height)
        .css({
          'display' : 'inline-block',
          'position' : 'relative',
          'overflow' : 'hidden',
          'vertical-align' : 'bottom',
          'text-align' : 'left'
        });

      // manually center it if we need to
      if (centered) {
        v$.css('text-align', 'center');
      }

      // now, animate it
      var transition = function () {
        v$.dynamo_trigger({ speed: speed, callback: callback });
      };

      if (!pause) {
        setInterval(transition, delay);
      }
    });
  };

  $.fn.dynamo_trigger = function (options) {

    return this.each(function (i, v) {
      options = options || {};

      var v$ = $(v);
      var speed = options.speed || v$.data('speed') || 350;
      var callback = options.callback || new Function(v$.data('callback')) || function () {};

      // check to see if this dynamo element has been paused since initialization
      if (!$(this).data('pause')) {
        v$.find('div:first').slideUp(speed, function () {
          v$.append($(this).show());

          // check if the first item has made its way to the top again
          if (v$.find('div:first').data('trigger') === 'true') {
            callback();
          }
        });
      }
    });
  };

  // automatically initiate cycles on elements of class 'dynamo'
  $('.dynamo').dynamo();

}(jQuery));
<|endoftext|>


<commit_before>// VCE Project - distillation_frontend.js
//
// This script facilitates the testing of a distillation simulation
// module.
//
//
// Requires:
// - p5.js or p5.min.js
// - vce_utils.js
//
// Andrew D. McGuire 2019
// a.mcguire227@gmail.com
//
// To do:
// - walls show functionality should just be handled by the boundaries themselves
// - add particles to conderser
//
// --------------------------------------------------
//               set-up variables
// --------------------------------------------------
var paused_log = false;
var debug = true;
var isDragging = false;
var Graphics, column,
    images = {};

// --------------------------------------------------
//             p5 visualisation functionality
// --------------------------------------------------
function preload() {
    // load the canvas images
    if (!vce_online) {
	var column_img_URL = "../../images/distillation_grey.svg";
	var feed_img_URL = "../../images/feed_pipe_with_hex.svg";
    } else {
	var column_img_URL = "http://visualchemeng.com/wp-content/uploads/2018/10/distillation_grey.svg";
	var feed_img_URL = "http://visualchemeng.com/wp-content/uploads/2018/10/feed_pipe.svg";
    };
    images.column = loadImage(column_img_URL, pic => print(pic), utils.loadImgErrFix);
    images.feed = loadImage(feed_img_URL, pic => print(pic), utils.loadImgErrFix);
};

function setup(first_time=true) {

    /* This function is called upon entry to create the
       simulation canvas which we draw onto.  */

    // Create the canvas
    canvas = new vceCanvas(id="#sim_container", xmax=null, ymax=window.innerHeight*0.75);

    // Initialise the backend column properties
    var options = {
	xf : 0.5,
	xd : 0.95,
	xb : 0.05,
	P : 101.3e3, // Pa
	q : 0.5, //7.0/6.0,
	R : 6.692,
	x_eq_data : data.equilibrium_data.x,
	y_eq_data : data.equilibrium_data.y,
	F : 100.0,
	F_max : settings.F_max,
    };
    column = new DistMcCabeTheile(options);
    column.solve();

    // Initialise the graphical column representation
    init_graphics();

    // Initialise the McCabe-Thiele plot
    plot_mccabe_thiele_diagram(column, 'mccabe_thiele_container');

    // Update any labels based on the initialised state
    update_labels();

    console.log(column);
    console.log(Graphics);
}

function draw() {

    /* Draws background and img to the canvas.
       This function is continuously called for the
       lifetime of the scripts executions after setup()
       has completed. Effectively advances time. */

    if (!(paused_log)) {
	// step the system forward in time
	Graphics.update();
    };

    // render graphics
    Graphics.show()

};

function init_graphics() {
    Graphics = new DistillationGraphics(canvas, column, images, debug);
};

// --------------------------------------------------
//                 Styling updaters
// --------------------------------------------------
function update_labels() {
    // Update the UI labels so that they are conistant wit the
    // application state.
    update_bounds_button_label();
};

function update_bounds_button_label() {
    // update bounds button label
    if (!Graphics.show_boundaries_log) {
	$("#bounds").text('Show Bounds');
    }
    else {
	$("#bounds").text('Hide Bounds');
    }
};

// --------------------------------------------------
//                 UI event listners
// --------------------------------------------------
// run/pause button
$('#run').click(async function(){
    console.log("You just clicked stream/pause!");
    paused_log = !(paused_log);
    if (paused_log) {
	$("#run").text('Run');
	$('#run').prop('title', 'Un-pause the reaction');
    }
    else {
	$("#run").text('Pause');
	$('#run').prop('title', 'Pause the reaction');
    }
});

// restart/reset button
$('#restart').click(async function(){
    console.log("You just clicked reset!");
    setup();
});

// show boundaries button
$('#bounds').click(async function(){

    // boundary show hide
    console.log("You just clicked show boundaries!");
    Graphics.show_boundaries_log = !(Graphics.show_boundaries_log);
    update_bounds_button_label();
});

// fullscreen functionality
const target = $('#target')[0]; // Get DOM element from jQuery collection
$('#fullscreen').on('click', () => {
    console.log("Fullscreen requested.");
    if (screenfull.enabled) {
	screenfull.toggle(target);
    };
});

// resize elements on window resize
window.onresize = function() {
    if (screenfull.isFullscreen) {
	canvas.stretch();
    } else {
	canvas.reset();
    };
    init_graphics();
    utils.resizePlotlyHeight('mccabe_thiele_container');
};

function mouseDragged() {
    if (isDragging) {
	for (var key in Graphics.valves) {
	    var valve = Graphics.valves[key];
	    if (valve.active) {
		valve.drag_handle(mouseX, mouseY);
		if (key == 'reflux') {
		    column.R = Graphics.valves.reflux.flow_capacity()*(settings.R_max - settings.R_min) + settings.R_min;
		    column.solve();
		    Graphics.reflux_update();
		} else if (key == 'feed') {
		    column.F = Graphics.valves.feed.position()*settings.F_max;
		    column.solve();
		    Graphics.feed_flow_update();
		} else if (key == 'preheater') {
		    column.q = Graphics.valves.preheater.position()*(settings.q_max - settings.q_min) + settings.q_min;
		    column.solve();
		    Graphics.q_update();
		};

	    };
	};
	plot_mccabe_thiele_diagram(column, 'mccabe_thiele_container');
    };
};

function mouseClicked() {
    for (var key in Graphics.valves) {
	var valve = Graphics.valves[key];
	if (valve.is_on_handle(mouseX, mouseY)) {
	    for (var key in Graphics.valves) {
		var alt_valve = Graphics.valves[key];
		alt_valve.unclick();
	    };
	    valve.click();
	    break;
	} else {
	    valve.unclick();
	};
    };
};

function mousePressed() {
    var m = createVector(mouseX, mouseY);
    console.log("mouse pressed!");
    for (var key in Graphics.valves) {
	var valve = Graphics.valves[key];
	if (valve.is_on_handle(mouseX, mouseY)) {
	    for (var key in Graphics.valves) {
		var alt_valve = Graphics.valves[key];
		alt_valve.unclick();
	    };
	    isDragging = true;
	    valve.click();
	    break;
	};
    };
};

function mouseReleased() {
    isDragging = false;
    for (var key in Graphics.valves) {
	var valve = Graphics.valves[key];
	valve.unclick();
    };
};
<commit_msg>binadry dist: updating the feed pipe svg url<commit_after>// VCE Project - distillation_frontend.js
//
// This script facilitates the testing of a distillation simulation
// module.
//
//
// Requires:
// - p5.js or p5.min.js
// - vce_utils.js
//
// Andrew D. McGuire 2019
// a.mcguire227@gmail.com
//
// To do:
// - walls show functionality should just be handled by the boundaries themselves
// - add particles to conderser
//
// --------------------------------------------------
//               set-up variables
// --------------------------------------------------
var paused_log = false;
var debug = true;
var isDragging = false;
var Graphics, column,
    images = {};

// --------------------------------------------------
//             p5 visualisation functionality
// --------------------------------------------------
function preload() {
    // load the canvas images
    if (!vce_online) {
	var column_img_URL = "../../images/distillation_grey.svg";
	var feed_img_URL = "../../images/feed_pipe_with_hex.svg";
    } else {
	var column_img_URL = "http://visualchemeng.com/wp-content/uploads/2018/10/distillation_grey.svg";
	var feed_img_URL = "http://visualchemeng.com/wp-content/uploads/2019/03/feed_pipe_with_hex.svg";
    };
    images.column = loadImage(column_img_URL, pic => print(pic), utils.loadImgErrFix);
    images.feed = loadImage(feed_img_URL, pic => print(pic), utils.loadImgErrFix);
};

function setup(first_time=true) {

    /* This function is called upon entry to create the
       simulation canvas which we draw onto.  */

    // Create the canvas
    canvas = new vceCanvas(id="#sim_container", xmax=null, ymax=window.innerHeight*0.75);

    // Initialise the backend column properties
    var options = {
	xf : 0.5,
	xd : 0.95,
	xb : 0.05,
	P : 101.3e3, // Pa
	q : 0.5, //7.0/6.0,
	R : 6.692,
	x_eq_data : data.equilibrium_data.x,
	y_eq_data : data.equilibrium_data.y,
	F : 100.0,
	F_max : settings.F_max,
    };
    column = new DistMcCabeTheile(options);
    column.solve();

    // Initialise the graphical column representation
    init_graphics();

    // Initialise the McCabe-Thiele plot
    plot_mccabe_thiele_diagram(column, 'mccabe_thiele_container');

    // Update any labels based on the initialised state
    update_labels();

    console.log(column);
    console.log(Graphics);
}

function draw() {

    /* Draws background and img to the canvas.
       This function is continuously called for the
       lifetime of the scripts executions after setup()
       has completed. Effectively advances time. */

    if (!(paused_log)) {
	// step the system forward in time
	Graphics.update();
    };

    // render graphics
    Graphics.show()

};

function init_graphics() {
    Graphics = new DistillationGraphics(canvas, column, images, debug);
};

// --------------------------------------------------
//                 Styling updaters
// --------------------------------------------------
function update_labels() {
    // Update the UI labels so that they are conistant wit the
    // application state.
    update_bounds_button_label();
};

function update_bounds_button_label() {
    // update bounds button label
    if (!Graphics.show_boundaries_log) {
	$("#bounds").text('Show Bounds');
    }
    else {
	$("#bounds").text('Hide Bounds');
    }
};

// --------------------------------------------------
//                 UI event listners
// --------------------------------------------------
// run/pause button
$('#run').click(async function(){
    console.log("You just clicked stream/pause!");
    paused_log = !(paused_log);
    if (paused_log) {
	$("#run").text('Run');
	$('#run').prop('title', 'Un-pause the reaction');
    }
    else {
	$("#run").text('Pause');
	$('#run').prop('title', 'Pause the reaction');
    }
});

// restart/reset button
$('#restart').click(async function(){
    console.log("You just clicked reset!");
    setup();
});

// show boundaries button
$('#bounds').click(async function(){

    // boundary show hide
    console.log("You just clicked show boundaries!");
    Graphics.show_boundaries_log = !(Graphics.show_boundaries_log);
    update_bounds_button_label();
});

// fullscreen functionality
const target = $('#target')[0]; // Get DOM element from jQuery collection
$('#fullscreen').on('click', () => {
    console.log("Fullscreen requested.");
    if (screenfull.enabled) {
	screenfull.toggle(target);
    };
});

// resize elements on window resize
window.onresize = function() {
    if (screenfull.isFullscreen) {
	canvas.stretch();
    } else {
	canvas.reset();
    };
    init_graphics();
    utils.resizePlotlyHeight('mccabe_thiele_container');
};

function mouseDragged() {
    if (isDragging) {
	for (var key in Graphics.valves) {
	    var valve = Graphics.valves[key];
	    if (valve.active) {
		valve.drag_handle(mouseX, mouseY);
		if (key == 'reflux') {
		    column.R = Graphics.valves.reflux.flow_capacity()*(settings.R_max - settings.R_min) + settings.R_min;
		    column.solve();
		    Graphics.reflux_update();
		} else if (key == 'feed') {
		    column.F = Graphics.valves.feed.position()*settings.F_max;
		    column.solve();
		    Graphics.feed_flow_update();
		} else if (key == 'preheater') {
		    column.q = Graphics.valves.preheater.position()*(settings.q_max - settings.q_min) + settings.q_min;
		    column.solve();
		    Graphics.q_update();
		};

	    };
	};
	plot_mccabe_thiele_diagram(column, 'mccabe_thiele_container');
    };
};

function mouseClicked() {
    for (var key in Graphics.valves) {
	var valve = Graphics.valves[key];
	if (valve.is_on_handle(mouseX, mouseY)) {
	    for (var key in Graphics.valves) {
		var alt_valve = Graphics.valves[key];
		alt_valve.unclick();
	    };
	    valve.click();
	    break;
	} else {
	    valve.unclick();
	};
    };
};

function mousePressed() {
    var m = createVector(mouseX, mouseY);
    console.log("mouse pressed!");
    for (var key in Graphics.valves) {
	var valve = Graphics.valves[key];
	if (valve.is_on_handle(mouseX, mouseY)) {
	    for (var key in Graphics.valves) {
		var alt_valve = Graphics.valves[key];
		alt_valve.unclick();
	    };
	    isDragging = true;
	    valve.click();
	    break;
	};
    };
};

function mouseReleased() {
    isDragging = false;
    for (var key in Graphics.valves) {
	var valve = Graphics.valves[key];
	valve.unclick();
    };
};
<|endoftext|>


<commit_before>(function (factory) {
	typeof exports === 'object' && typeof module !== 'undefined' ? (module['exports'] = factory()) :
		typeof define === 'function' && define['amd'] ? define(factory()) :
			(window['stylisByte'] = factory())
}(function () {

	'use strict'

	var maps = {}
	var heap = []
	var byte = []
	var stack = []
	var index = 0

	var RULE_START = 0
	var RULE_END = 1
	var SELECTOR = 3
	var PROPERTY = 10
	var VALUE = 11

	return function (context, content, selectors, parents, line, column, length) {
		var colon, name, value, cache, block

		switch (context) {
			case 1: {
				name = content.substring(0, colon = content.indexOf(':')).trim()
				value = content.substring(colon+1).trim()

				if ((cache = maps[name]) === void 0) {
					stack.push(PROPERTY, index)
					heap[maps[name] = index++] = name
				} else {
					stack.push(PROPERTY, cache)
				}

				if ((cache = maps[value]) === void 0) {
					stack.push(VALUE, index)
					heap[maps[value] = index++] = value
				} else {
					stack.push(VALUE, cache)
				}

				break
			}
			case 2: {
				value = selectors.join(',')

				if ((cache = maps[value]) === void 0) {
					block = [RULE_START, SELECTOR, index].concat(stack, RULE_END)
					heap[maps[value] = index++] = value
				} else {
					block = [RULE_START, SELECTOR, cache].concat(stack, RULE_END)
				}

				byte.push.apply(byte, block)
				stack = []

				break
			}
			case -2: {
				var program = {
					heap: heap,
					byte: byte
				}

				// release
				maps = {}
				heap = []
				byte = []
				stack = []
				index = 0

				return program
			}
		}
	}
}))
<commit_msg>plugin byte add map to exports<commit_after>(function (factory) {
	typeof exports === 'object' && typeof module !== 'undefined' ? (module['exports'] = factory()) :
		typeof define === 'function' && define['amd'] ? define(factory()) :
			(window['stylisByte'] = factory())
}(function () {

	'use strict'

	var map = {}
	var heap = []
	var byte = []
	var stack = []
	var index = 0

	var RULE_START = 0
	var RULE_END = 1
	var SELECTOR = 3
	var PROPERTY = 10
	var VALUE = 11

	return function (context, content, selectors, parents, line, column, length) {
		var colon, name, value, cache, block

		switch (context) {
			case 1: {
				name = content.substring(0, colon = content.indexOf(':')).trim()
				value = content.substring(colon+1).trim()

				if ((cache = map[name]) === void 0) {
					stack.push(PROPERTY, index)
					heap[map[name] = index++] = name
				} else {
					stack.push(PROPERTY, cache)
				}

				if ((cache = map[value]) === void 0) {
					stack.push(VALUE, index)
					heap[map[value] = index++] = value
				} else {
					stack.push(VALUE, cache)
				}

				break
			}
			case 2: {
				value = selectors.join(',')

				if ((cache = map[value]) === void 0) {
					block = [RULE_START, SELECTOR, index].concat(stack, RULE_END)
					heap[map[value] = index++] = value
				} else {
					block = [RULE_START, SELECTOR, cache].concat(stack, RULE_END)
				}

				byte.push.apply(byte, block)
				stack = []

				break
			}
			case -2: {
				var program = {
					heap: heap,
					byte: byte,
					map: map
				}

				// release
				map = {}
				heap = []
				byte = []
				stack = []
				index = 0

				return program
			}
		}
	}
}))
<|endoftext|>


<commit_before>//================================================
// fix_thumbnail_order.js
// Author: @iihoshi
//================================================

(function ($, jn) {

	var my_filename = 'fix_thumbnail_order.js';

	// プラグイン情報 ここから
	// プラグイン情報の初期化
	if(!jn.pluginInfo)
		jn.pluginInfo = {};
	// プラグイン情報本体
	jn.pluginInfo[my_filename.split('.')[0]] = {
		'name' : {
			'ja' : '複数サムネイル表示順固定',
			'en' : 'Fix the order of thumbnails'
		},
		'author' : {
			'en' : '@iihoshi'
		},
		'version' : '1.0.0',
		'file' : my_filename,
		'language' : ['en', 'ja'],
		'last_update' : "2015/4/23",
		'update_timezone' : '9',
		'jnVersion' : '4.3.0.2',
		'description' : {
			'ja' : 'ツイート一つにサムネイル画像が複数ある場合、その表示順を正しい順で固定します。',
			'en' : 'Fix a display order of thumbnails in each tweet.'
		},
		'updateinfo' : 'http://www.colorless-sight.jp/archives/JanetterPluginUpdateInfo.txt'
	};
	// プラグイン情報ここまで

	if ((_Janetter_Window_Type != "main") && (_Janetter_Window_Type != "profile")) {
		return;
	}

	// 本プラグインの初期化処理（onInitializeDone 時）
	function initOnInitialized() {
		var orig_janetterThumbnail = $.fn.janetterThumbnail.toString();

		var mod = orig_janetterThumbnail
			.replace(/^(\s*)(var new_image = new Image\(\);)$/m,
			         "$1_tweetThumb.append($$('<span/>').text(thumb_url).css({ display: 'none' }));  // inserted by " + my_filename + "\n$1$2")
			.replace(/^(\s*)_tweetThumb\.append\($/m,
			         "$1_tweetThumb.children('span:contains(\"' + thumb_url + '\")').replaceWith(  // replaced by " + my_filename)
			.replace(/^(\s*)\)\.(addClass\('disp'\));$/m,
			         "$1);  _tweetThumb.$2;  // replaced by " + my_filename)
		//console.log(mod);
		eval('$.fn.janetterThumbnail = ' + mod);

		console.log(my_filename + ' has been initialized.');
	}

	if (jn.temp.initialized) {
		// The original onInitializeDone() has already been called!
		initOnInitialized();
	} else {
		var orig_onInitializeDone = jn.onInitializeDone;
		jn.onInitializeDone = function() {
			orig_onInitializeDone && orig_onInitializeDone.apply(this, arguments);
			initOnInitialized();
		};
	}

})(jQuery, janet);
<commit_msg>fix_thumbnail_order.js ver. 1.0.1<commit_after>//================================================
// fix_thumbnail_order.js
// Author: @iihoshi
//================================================

(function ($, jn) {

	var my_filename = 'fix_thumbnail_order.js';

	// プラグイン情報 ここから
	// プラグイン情報の初期化
	if(!jn.pluginInfo)
		jn.pluginInfo = {};
	// プラグイン情報本体
	jn.pluginInfo[my_filename.split('.')[0]] = {
		'name' : {
			'ja' : '複数サムネイル表示順固定',
			'en' : 'Fix the order of thumbnails'
		},
		'author' : {
			'en' : '@iihoshi'
		},
		'version' : '1.0.1',
		'file' : my_filename,
		'language' : ['en', 'ja'],
		'last_update' : "2015/4/23",
		'update_timezone' : '9',
		'jnVersion' : '4.3.0.2',
		'description' : {
			'ja' : 'ツイート一つにサムネイル画像が複数ある場合、その表示順を正しい順で固定します。',
			'en' : 'Fix a display order of thumbnails in each tweet.'
		},
		'updateinfo' : 'http://www.colorless-sight.jp/archives/JanetterPluginUpdateInfo.txt'
	};
	// プラグイン情報ここまで

	if ((_Janetter_Window_Type != "main") && (_Janetter_Window_Type != "profile")) {
		return;
	}

	// 本プラグインの初期化処理（onInitializeDone 時）
	function initOnInitialized() {
		var orig_janetterThumbnail = $.fn.janetterThumbnail.toString();
		var re_new_image = /^(\s*)(var new_image = new Image\(\);)$/m;
		var re_tweetThumb_append = /^(\s*)_tweetThumb\.append\($/m;
		var re_tweetThumb_addClass = /^(\s*)\)\.(addClass\('disp'\));$/m;

		if (re_new_image.test(orig_janetterThumbnail) &&
		    re_tweetThumb_append.test(orig_janetterThumbnail) &&
		    re_tweetThumb_addClass.test(orig_janetterThumbnail)) {
			var replaced = orig_janetterThumbnail
				.replace(re_new_image,
				         "$1_tweetThumb.append($$('<span/>').text(thumb_url).css({ display: 'none' }));  // inserted by " + my_filename + "\n$1$2")
				.replace(re_tweetThumb_append,
				         "$1_tweetThumb.children('span:contains(\"' + thumb_url + '\")').replaceWith(  // replaced by " + my_filename)
				.replace(re_tweetThumb_addClass,
				         "$1);  _tweetThumb.$2;  // replaced by " + my_filename)
			//console.log(replaced);
			eval('$.fn.janetterThumbnail = ' + replaced);
		} else {
			new jn.msgdialog({
				title: my_filename,
				icon: '',
				message: 'Sorry, ' + my_filename+ ' cannot be installed.',
				buttons: [ janet.msg.ok ],
			});
		}

		console.log(my_filename + ' has been initialized.');
	}

	if (jn.temp.initialized) {
		// The original onInitializeDone() has already been called!
		initOnInitialized();
	} else {
		var orig_onInitializeDone = jn.onInitializeDone;
		jn.onInitializeDone = function() {
			orig_onInitializeDone && orig_onInitializeDone.apply(this, arguments);
			initOnInitialized();
		};
	}

})(jQuery, janet);
<|endoftext|>


<commit_before>module.exports = function(env, callback) {
  env.locals.urlbyid = function(contents, id) {
    var pages = env.helpers.getAllPages(contents);
    var url;
    for (var x = 0; x < pages.length; x++) {
      if (pages[x].metadata && pages[x].metadata.id == id) {
        url = pages[x].url;
        break;
      }
    }
    if (!url) {
      console.warn('URL not found for id: ' + id);
    }
    return url;
  }

  env.helpers.getAllPages = function(contents) {
    var output = env.locals.pages || [];

    for (var key in contents) {
      var currentObj = contents[key];

      if (isDirectory(currentObj)) {
        env.helpers.getAllPages(currentObj);
      }

      if (isFile(currentObj)) {
        if (currentObj.filepath) {
          // remove any index page at the end so that the page gets returned in the navigation list it should be in
          currentObj.filepath.navdir = currentObj.filepath.relative.replace(/\/index\.[a-zA-Z0-9]+$/, '');
          currentObj.filepath.navdir = currentObj.filepath.navdir.substring(0, currentObj.filepath.navdir.lastIndexOf("/"));
          currentObj.filepath.dir = currentObj.filepath.relative.substring(0, currentObj.filepath.relative.lastIndexOf("/"));
        }
        if (currentObj.metadata && currentObj.metadata.hasOwnProperty("primarynavorder")) {
          currentObj.primarynavorder = currentObj.metadata.primarynavorder;
        }
        if (currentObj.metadata && currentObj.metadata.hasOwnProperty("navorder")) {
          currentObj.navorder = currentObj.metadata.navorder;
        }

        if (output.indexOf(currentObj) == -1)
          output.push(currentObj);
      }
    }
    env.locals.pages = output;
    return output;
	};

  env.helpers.getPrimaryNavigation = function(contents) {
    var pages = env.helpers.getAllPages(contents);
    var primary_nav = pages.filter(function(page) {
      return page.metadata && page.metadata.primarynavorder;
    });
    sortByKey(primary_nav, 'primarynavorder');
    return primary_nav;
	};

  env.helpers.getNavigation = function(contents, folder) {
    var pages = env.helpers.getAllPages(contents);
    var nav = pages.filter(function(page) {
      return page.metadata && page.metadata.navorder && page.filepath.navdir == folder;
    });
    sortByKey(nav, 'navorder');
    return nav;
  };

  env.helpers.getBreadcrumb = function(contents, page) {
    var pages = env.helpers.getAllPages(contents);
    var breadcrumb = [];
    breadcrumb.push(page);
    if (page.filepath && page.filepath.navdir) {
      var dirs = page.filepath.navdir.split('/');
      for (var x = dirs.length; x >= 0; x--) {
        var dir = dirs.slice(0, x).join('/');
        if (dir)
          dir += '/'
        var parent = pages.find(function(p) {
          return p.url === '/' + dir;
        });
        if (parent)
          breadcrumb.push(parent);
      }
    }
    return breadcrumb;
  };

  env.helpers.rawjson = function(obj) {
    return JSON.stringify(obj);
  }

  callback();

  var isFile = function(currentItem) {
		return currentItem.hasOwnProperty('__filename');
	};
  var isDirectory = function(currentItem) {
    return !currentItem.hasOwnProperty('__filename');
  };

  function sortByKey(arr, key) {
    return arr.sort(function(a, b) {
      var x = a[key], y = b[key];
      return (x < y) ? -1 : ((x > y) ? 1 : 0);
    });
  }
};
<commit_msg>fix for pages in navigation missing<commit_after>module.exports = function(env, callback) {
  env.locals.urlbyid = function(contents, id) {
    var pages = env.helpers.getAllPages(contents);
    var url;
    for (var x = 0; x < pages.length; x++) {
      if (pages[x].metadata && pages[x].metadata.id == id) {
        url = pages[x].url;
        break;
      }
    }
    if (!url) {
      console.warn('URL not found for id: ' + id);
    }
    return url;
  }

  env.helpers.getAllPages = function(contents) {
    var output = env.locals.pages || [];

    for (var key in contents) {
      var currentObj = contents[key];

      if (isDirectory(currentObj)) {
        env.locals.pages = output;
        env.helpers.getAllPages(currentObj);
      }

      if (isFile(currentObj)) {
        if (currentObj.filepath) {
          // remove any index page at the end so that the page gets returned in the navigation list it should be in
          currentObj.filepath.navdir = currentObj.filepath.relative.replace(/\/index\.[a-zA-Z0-9]+$/, '');
          currentObj.filepath.navdir = currentObj.filepath.navdir.substring(0, currentObj.filepath.navdir.lastIndexOf("/"));
          currentObj.filepath.dir = currentObj.filepath.relative.substring(0, currentObj.filepath.relative.lastIndexOf("/"));
        }
        if (currentObj.metadata && currentObj.metadata.hasOwnProperty("primarynavorder")) {
          currentObj.primarynavorder = currentObj.metadata.primarynavorder;
        }
        if (currentObj.metadata && currentObj.metadata.hasOwnProperty("navorder")) {
          currentObj.navorder = currentObj.metadata.navorder;
        }

        if (output.indexOf(currentObj) == -1)
          output.push(currentObj);
      }
    }
    env.locals.pages = output;
    return output;
	};

  env.helpers.getPrimaryNavigation = function(contents) {
    var pages = env.helpers.getAllPages(contents);
    var primary_nav = pages.filter(function(page) {
      return page.metadata && page.metadata.primarynavorder;
    });
    sortByKey(primary_nav, 'primarynavorder');
    return primary_nav;
	};

  env.helpers.getNavigation = function(contents, folder) {
    var pages = env.helpers.getAllPages(contents);
    var nav = pages.filter(function(page) {
      return page.metadata && page.metadata.navorder && page.filepath.navdir == folder;
    });
    sortByKey(nav, 'navorder');
    return nav;
  };

  env.helpers.getBreadcrumb = function(contents, page) {
    var pages = env.helpers.getAllPages(contents);
    var breadcrumb = [];
    breadcrumb.push(page);
    if (page.filepath && page.filepath.navdir) {
      var dirs = page.filepath.navdir.split('/');
      for (var x = dirs.length; x >= 0; x--) {
        var dir = dirs.slice(0, x).join('/');
        if (dir)
          dir += '/'
        var parent = pages.find(function(p) {
          return p.url === '/' + dir;
        });
        if (parent)
          breadcrumb.push(parent);
      }
    }
    return breadcrumb;
  };

  env.helpers.rawjson = function(obj) {
    return JSON.stringify(obj);
  }

  callback();

  var isFile = function(currentItem) {
		return currentItem.hasOwnProperty('__filename');
	};
  var isDirectory = function(currentItem) {
    return !currentItem.hasOwnProperty('__filename');
  };

  function sortByKey(arr, key) {
    return arr.sort(function(a, b) {
      var x = a[key], y = b[key];
      return (x < y) ? -1 : ((x > y) ? 1 : 0);
    });
  }
};
<|endoftext|>


<commit_before>// @flow
import { getRates } from '../../../lib/marketApi';
import ActionTypes from './actionTypes';

export function loadSettings() {
    return (dispatch) => {
        if (localStorage) {
            let localeCurrency = localStorage.getItem('localeCurrency');
            localeCurrency = (localeCurrency === null) ? 'USD' : localeCurrency;
            dispatch({
                type: ActionTypes.SET_LOCALE_CURRENCY,
                currency: localeCurrency,
            });

          let showHiddenAccounts = JSON.parse(localStorage.getItem('showHiddenAccounts'));
          dispatch({
            type: ActionTypes.SET_SHOW_HIDDEN_ACCOUNTS,
            show: showHiddenAccounts
          });
        }
    };
}

export function getExchangeRates() {
    return (dispatch) => {
        getRates.call().then((result) => {
            dispatch({
                type: ActionTypes.EXCHANGE_RATES,
                rates: result,
            });
        });
    };
}

export function updateLocaleCurrency(currency: string) {
    return (dispatch) => {
        dispatch({
            type: ActionTypes.SET_LOCALE_CURRENCY,
            currency,
        });
    };
}

export function update(settings: { localeCurrency: string, showHiddenAccounts: boolean }) {
    return (dispatch) => {
        dispatch({
            type: ActionTypes.SET_LOCALE_CURRENCY,
            currency: settings.localeCurrency,
        });
        return dispatch({
            type: ActionTypes.SET_SHOW_HIDDEN_ACCOUNTS,
            show: settings.showHiddenAccounts,
        });
    };
}
<commit_msg>fix(guard localStorage not defined for showHiddenAccounts):<commit_after>// @flow
import { getRates } from '../../../lib/marketApi';
import ActionTypes from './actionTypes';

export function loadSettings() {
    return (dispatch) => {
        if (localStorage) {
            let localeCurrency = localStorage.getItem('localeCurrency');
            localeCurrency = (localeCurrency === null) ? 'USD' : localeCurrency;
            dispatch({
                type: ActionTypes.SET_LOCALE_CURRENCY,
                currency: localeCurrency,
            });

          const localStorageShowHiddenAccounts = localStorage.getItem('showHiddenAccounts') || "false";
          let showHiddenAccounts = JSON.parse(localStorageShowHiddenAccounts);
          dispatch({
            type: ActionTypes.SET_SHOW_HIDDEN_ACCOUNTS,
            show: showHiddenAccounts
          });
        }
    };
}

export function getExchangeRates() {
    return (dispatch) => {
        getRates.call().then((result) => {
            dispatch({
                type: ActionTypes.EXCHANGE_RATES,
                rates: result,
            });
        });
    };
}

export function updateLocaleCurrency(currency: string) {
    return (dispatch) => {
        dispatch({
            type: ActionTypes.SET_LOCALE_CURRENCY,
            currency,
        });
    };
}

export function update(settings: { localeCurrency: string, showHiddenAccounts: boolean }) {
    return (dispatch) => {
        dispatch({
            type: ActionTypes.SET_LOCALE_CURRENCY,
            currency: settings.localeCurrency,
        });
        return dispatch({
            type: ActionTypes.SET_SHOW_HIDDEN_ACCOUNTS,
            show: settings.showHiddenAccounts,
        });
    };
}
<|endoftext|>


<commit_before>/*
 * Copyright 2009 Matthew Eernisse (mde@fleegix.org)
 *
 * Licensed under the Apache License, Version 2.0 (the "License");
 * you may not use this file except in compliance with the License.
 * You may obtain a copy of the License at
 *
 *   http://www.apache.org/licenses/LICENSE-2.0
 *
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS,
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 * See the License for the specific language governing permissions and
 * limitations under the License.
 *
*/
if (typeof fleegix == 'undefined') { var fleegix = {}; }
if (typeof fleegix.event == 'undefined') {
  throw('fleegix.event.delegator depends on the base fleegix.event module in fleegix.js.'); }

fleegix.event.Periodic = function (func, interval, waitFirst) {
  var _this = this;
  var _paused = false;
  this.func = func || null;
  this.interval = interval || null;
  this.waitFirst = waitFirst || false;
  this.start = function (waitFirst) {
    this.waitFirst = waitFirst || this.waitFirst;
    if (this.waitFirst) {
      setTimeout(this.run, this.interval);
    }
    else {
      this.run();
    }
  };
  this.run = function () {
    if (!_paused) {
      _this.func();
      setTimeout(_this.run, _this.interval);
    }
  };
  this.pause = function () {
    _paused = true;
  };
  this.resume = function () {
    _paused = false;
    this.run();
  };
};

// Clean up listeners
fleegix.event.listen(window, 'onunload', function () {
  try {
    fleegix.event.flush();
  }
  catch (e) {} // Squelch
});

<commit_msg>Allow execution context to be passed into the periodic executor.<commit_after>/*
 * Copyright 2009 Matthew Eernisse (mde@fleegix.org)
 *
 * Licensed under the Apache License, Version 2.0 (the "License");
 * you may not use this file except in compliance with the License.
 * You may obtain a copy of the License at
 *
 *   http://www.apache.org/licenses/LICENSE-2.0
 *
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS,
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 * See the License for the specific language governing permissions and
 * limitations under the License.
 *
*/
if (typeof fleegix == 'undefined') { var fleegix = {}; }
if (typeof fleegix.event == 'undefined') {
  throw('fleegix.event.delegator depends on the base fleegix.event module in fleegix.js.'); }

fleegix.event.Periodic = function () {
  var _this = this;
  var _paused = false;

  var args = Array.prototype.slice.apply(arguments);
  var context;
  var methodName;
  if (typeof args[0] != 'function') {
    context = args.shift();
    methodName = args.shift();
  }
  else {
    var func = args.shift();
  }
  var interval = args.shift();
  var waitFirst = args.shift();

  this.context = context || null;
  this.methodName = methodName || null;
  this.func = func || null;
  this.interval = interval || null;
  this.waitFirst = waitFirst || false;
  this.start = function (waitFirst) {
    this.waitFirst = waitFirst || this.waitFirst;
    if (this.waitFirst) {
      setTimeout(this.run, this.interval);
    }
    else {
      this.run();
    }
  };
  this.run = function () {
    if (!_paused) {
      if (_this.context) {
        _this.context[_this.methodName].call(_this.context);
      }
      else {
        _this.func();
      }
      setTimeout(_this.run, _this.interval);
    }
  };
  this.pause = function () {
    _paused = true;
  };
  this.resume = function () {
    _paused = false;
    this.run();
  };
};

// Clean up listeners
fleegix.event.listen(window, 'onunload', function () {
  try {
    fleegix.event.flush();
  }
  catch (e) {} // Squelch
});

<|endoftext|>


<commit_before>(function ($) {
    var cache = [];
    var objId=function(obj){
        if(!obj.jqmCSS3AnimateId) obj.jqmCSS3AnimateId=$.uuid();
        return obj.jqmCSS3AnimateId;
    }
    var getEl=function(elID){
        if (typeof elID === "string" || elID instanceof String) {
            return document.getElementById(elID);
        } else if($.is$(elID)){
            return elID[0];
        } else {
            return elID;
        }
    }
    var getCSS3Animate=function(obj, options){
        var tmp, id, el = getEl(obj);
        //first one
        id = objId(el);
        if(cache[id]){
            cache[id].animate(options);
            tmp = cache[id];
        } else {
            tmp = css3Animate(el, options);
            cache[id] = tmp;
        }
        return tmp;
    }
    $.fn["css3Animate"] = function (opts) {
        //keep old callback system - backwards compatibility - should be deprecated in future versions
        if(!opts.complete && opts.callback) opts.complete = opts.callback;
        //first on
        var tmp = getCSS3Animate(this[0], opts);
        opts.complete=null;
        opts.sucess=null;
        opts.failure=null;
        for (var i = 1; i < this.length; i++) {
            tmp.link(this[i], opts);
        }
        return tmp;
    };

    $["css3AnimateQueue"] = function () {
        return new css3Animate.queue();
    }

    //if (!window.WebKitCSSMatrix) return;
    var translateOpen =$.feat.cssTransformStart;
    var translateClose = $.feat.cssTransformEnd;
    var transitionEnd=$.feat.cssPrefix.replace(/-/g,"")+"TransitionEnd";
    transitionEnd=($.os.fennec||$.feat.cssPrefix==""||$.os.ie)?"transitionend":transitionEnd;

    transitionEnd=transitionEnd.replace(transitionEnd.charAt(0),transitionEnd.charAt(0).toLowerCase());

    var css3Animate = (function () {

        var css3Animate = function (elID, options) {
            if(!(this instanceof css3Animate)) return new css3Animate(elID, options);

            //start doing stuff
            this.callbacksStack = [];
            this.activeEvent = null;
            this.countStack = 0;
            this.isActive = false;
            this.el = elID;
            this.linkFinishedProxy_ = $.proxy(this.linkFinished, this);

            if (!this.el) return;

            this.animate(options);

            var that = this;
            jq(this.el).bind('destroy', function(){
                var id = that.el.jqmCSS3AnimateId;
                that.callbacksStack = [];
                if(cache[id]) delete cache[id];
            });
        };
        css3Animate.prototype = {
            animate:function(options){

                //cancel current active animation on this object
                if(this.isActive) this.cancel();
                this.isActive = true;

                if (!options) {
                    alert("Please provide configuration options for animation of " + this.el.id);
                    return;
                }

                var classMode = !!options["addClass"];

                if(classMode){
                    //class defines properties being changed
                    if(options["removeClass"]){
                        jq(this.el).replaceClass(options["removeClass"], options["addClass"]);
                    } else {
                        jq(this.el).addClass(options["addClass"]);
                    }

                } else {
                    //property by property
                    var timeNum = numOnly(options["time"]);
                    if(timeNum==0) options["time"]=0;

                    if (!options["y"]) options["y"] = 0;
                    if (!options["x"]) options["x"] = 0;
                    if (options["previous"]) {
                        var cssMatrix = new $.getCssMatrix(this.el);
                        options.y += numOnly(cssMatrix.f);
                        options.x += numOnly(cssMatrix.e);
                    }
                    if (!options["origin"]) options.origin = "0% 0%";

                    if (!options["scale"]) options.scale = "1";

                    if (!options["rotateY"]) options.rotateY = "0";
                    if (!options["rotateX"]) options.rotateX = "0";
                    if (!options["skewY"]) options.skewY = "0";
                    if (!options["skewX"]) options.skewX = "0";

                    if (!options["timingFunction"]) options["timingFunction"] = "linear";

                    //check for percent or numbers
                    if (typeof (options.x) === "number" || (options.x.indexOf("%") == -1 && options.x.toLowerCase().indexOf("px") == -1 && options.x.toLowerCase().indexOf("deg") == -1)) options.x = parseInt(options.x) + "px";
                    if (typeof (options.y) === "number" || (options.y.indexOf("%") == -1 && options.y.toLowerCase().indexOf("px") == -1 && options.y.toLowerCase().indexOf("deg") == -1)) options.y = parseInt(options.y) + "px";

                    var trans= "translate" + translateOpen + (options.x) + "," + (options.y) + translateClose + " scale(" + parseFloat(options.scale) + ") rotate(" + options.rotateX + ")";
                    if(!$.os.opera)
                        trans+=" rotateY(" + options.rotateY + ")";
                    trans+=" skew(" + options.skewX + "," + options.skewY + ")";
                    this.el.style[$.feat.cssPrefix+"Transform"]=trans;
                    this.el.style[$.feat.cssPrefix+"BackfaceVisibility"] = "hidden";
                    var properties = $.feat.cssPrefix+"Transform";
                    if (options["opacity"]!==undefined) {
                        this.el.style.opacity = options["opacity"];
                        properties+=", opacity";
                    }
                    if (options["width"]) {
                        this.el.style.width = options["width"];
                        properties = "all";
                    }
                    if (options["height"]) {
                        this.el.style.height = options["height"];
                        properties = "all";
                    }
                    this.el.style[$.feat.cssPrefix+"TransitionProperty"] = "all";

                    if((""+options["time"]).indexOf("s")===-1) {
                        var scale = 'ms';
                        var time = options["time"]+scale;
                    } else if(options["time"].indexOf("ms")!==-1){
                        var scale = 'ms';
                        var time = options["time"];
                    } else {
                        var scale = 's';
                        var time = options["time"]+scale;
                    }

                    this.el.style[$.feat.cssPrefix+"TransitionDuration"] = time;
                    this.el.style[$.feat.cssPrefix+"TransitionTimingFunction"] = options["timingFunction"];
                    this.el.style[$.feat.cssPrefix+"TransformOrigin"] = options.origin;

                }

                //add callback to the stack

                this.callbacksStack.push({
                    complete : options["complete"],
                    success : options["success"],
                    failure : options["failure"]
                });
                this.countStack++;

                var that = this;
                var style = window.getComputedStyle(this.el);
                if(classMode){
                    //get the duration
                    var duration = style[$.feat.cssPrefix+"TransitionDuration"];
                    var timeNum = numOnly(duration);
                    options["time"]=timeNum;
                    if(duration.indexOf("ms")!==-1){
                        scale = 'ms';
                    } else {
                        options["time"]*=1000;
                        scale = 's';
                    }
                }

                //finish asap
                if(timeNum==0 || (scale=='ms' && timeNum<5) || style.display=='none'){
                    //the duration is nearly 0 or the element is not displayed, finish immediatly
                    $.asap($.proxy(this.finishAnimation, this, [false]));
                    //this.finishAnimation();
                    //set transitionend event
                } else {
                    //setup the event normally

                   var that=this;
                    this.activeEvent = function(event){
                        clearTimeout(that.timeout);
                        that.finishAnimation(event);
                        that.el.removeEventListener(transitionEnd, that.activeEvent, false);
                    };
                    that.timeout=setTimeout(this.activeEvent, numOnly(options["time"]) + 50);
                    this.el.addEventListener(transitionEnd, this.activeEvent, false);

                }

            },
            addCallbackHook:function(callback){
                if(callback) this.callbacksStack.push(callback);
                this.countStack++;
                return this.linkFinishedProxy_;
            },
            linkFinished:function(canceled){
                if(canceled) this.cancel();
                else this.finishAnimation();
            },
            finishAnimation: function (event) {
                if(event) event.preventDefault();
                if(!this.isActive) return;

                this.countStack--;

                if(this.countStack==0) this.fireCallbacks(false);
            },
            fireCallbacks:function(canceled){
                this.clearEvents();

                //keep callbacks after cleanup
                // (if any of the callbacks overrides this object, callbacks will keep on fire as expected)
                var callbacks = this.callbacksStack;

                //cleanup
                this.cleanup();

                //fire all callbacks
                for(var i=0; i<callbacks.length; i++) {
                    var complete = callbacks[i]['complete'];
                    var success = callbacks[i]['success'];
                    var failure = callbacks[i]['failure'];
                    //fire callbacks
                    if(complete && typeof (complete) === "function") complete(canceled);
                    //success/failure
                    if(canceled && failure && typeof (failure) === "function") failure();
                    else if(success && typeof (success) === "function") success();
                }
            },
            cancel:function(){
                if(!this.isActive) return;
                this.fireCallbacks(true); //fire failure callbacks
            },
            cleanup:function(){
                this.callbacksStack=[];
                this.isActive = false;
                this.countStack = 0;
            },
            clearEvents:function(){
                if(this.activeEvent) {
                    this.el.removeEventListener(transitionEnd, this.activeEvent, false);
                }
                this.activeEvent = null;
            },
            link: function (elID, opts) {
                var callbacks = {complete:opts.complete,success:opts.success,failure:opts.failure};
                opts.complete = this.addCallbackHook(callbacks);
                opts.success = null;
                opts.failure = null;
                //run the animation with the replaced callbacks
                getCSS3Animate(elID, opts);
                //set the old callback back in the obj to avoid strange stuff
                opts.complete = callbacks.complete;
                opts.success = callbacks.success;
                opts.failure = callbacks.failure;
                return this;
            }
        }

        return css3Animate;
    })();

    css3Animate.queue = function () {
        return {
            elements: [],
            push: function (el) {
                this.elements.push(el);
            },
            pop: function () {
                return this.elements.pop();
            },
            run: function () {
                var that = this;
                if (this.elements.length == 0) return;
                if (typeof (this.elements[0]) === "function") {
                    var func = this.shift();
                    func();
                }
                if (this.elements.length == 0) return;
                var params = this.shift();
                if (this.elements.length > 0) params.complete = function (canceled) {
                    if(!canceled) that.run();
                };
                css3Animate(document.getElementById(params.id), params);
            },
            shift: function () {
                return this.elements.shift();
            }
        }
    };
})(jq);
<commit_msg># === for indexOf equals -1 comparison<commit_after>(function ($) {
    var cache = [];
    var objId=function(obj){
        if(!obj.jqmCSS3AnimateId) obj.jqmCSS3AnimateId=$.uuid();
        return obj.jqmCSS3AnimateId;
    }
    var getEl=function(elID){
        if (typeof elID === "string" || elID instanceof String) {
            return document.getElementById(elID);
        } else if($.is$(elID)){
            return elID[0];
        } else {
            return elID;
        }
    }
    var getCSS3Animate=function(obj, options){
        var tmp, id, el = getEl(obj);
        //first one
        id = objId(el);
        if(cache[id]){
            cache[id].animate(options);
            tmp = cache[id];
        } else {
            tmp = css3Animate(el, options);
            cache[id] = tmp;
        }
        return tmp;
    }
    $.fn["css3Animate"] = function (opts) {
        //keep old callback system - backwards compatibility - should be deprecated in future versions
        if(!opts.complete && opts.callback) opts.complete = opts.callback;
        //first on
        var tmp = getCSS3Animate(this[0], opts);
        opts.complete=null;
        opts.sucess=null;
        opts.failure=null;
        for (var i = 1; i < this.length; i++) {
            tmp.link(this[i], opts);
        }
        return tmp;
    };

    $["css3AnimateQueue"] = function () {
        return new css3Animate.queue();
    }

    //if (!window.WebKitCSSMatrix) return;
    var translateOpen =$.feat.cssTransformStart;
    var translateClose = $.feat.cssTransformEnd;
    var transitionEnd=$.feat.cssPrefix.replace(/-/g,"")+"TransitionEnd";
    transitionEnd=($.os.fennec||$.feat.cssPrefix==""||$.os.ie)?"transitionend":transitionEnd;

    transitionEnd=transitionEnd.replace(transitionEnd.charAt(0),transitionEnd.charAt(0).toLowerCase());

    var css3Animate = (function () {

        var css3Animate = function (elID, options) {
            if(!(this instanceof css3Animate)) return new css3Animate(elID, options);

            //start doing stuff
            this.callbacksStack = [];
            this.activeEvent = null;
            this.countStack = 0;
            this.isActive = false;
            this.el = elID;
            this.linkFinishedProxy_ = $.proxy(this.linkFinished, this);

            if (!this.el) return;

            this.animate(options);

            var that = this;
            jq(this.el).bind('destroy', function(){
                var id = that.el.jqmCSS3AnimateId;
                that.callbacksStack = [];
                if(cache[id]) delete cache[id];
            });
        };
        css3Animate.prototype = {
            animate:function(options){

                //cancel current active animation on this object
                if(this.isActive) this.cancel();
                this.isActive = true;

                if (!options) {
                    alert("Please provide configuration options for animation of " + this.el.id);
                    return;
                }

                var classMode = !!options["addClass"];

                if(classMode){
                    //class defines properties being changed
                    if(options["removeClass"]){
                        jq(this.el).replaceClass(options["removeClass"], options["addClass"]);
                    } else {
                        jq(this.el).addClass(options["addClass"]);
                    }

                } else {
                    //property by property
                    var timeNum = numOnly(options["time"]);
                    if(timeNum==0) options["time"]=0;

                    if (!options["y"]) options["y"] = 0;
                    if (!options["x"]) options["x"] = 0;
                    if (options["previous"]) {
                        var cssMatrix = new $.getCssMatrix(this.el);
                        options.y += numOnly(cssMatrix.f);
                        options.x += numOnly(cssMatrix.e);
                    }
                    if (!options["origin"]) options.origin = "0% 0%";

                    if (!options["scale"]) options.scale = "1";

                    if (!options["rotateY"]) options.rotateY = "0";
                    if (!options["rotateX"]) options.rotateX = "0";
                    if (!options["skewY"]) options.skewY = "0";
                    if (!options["skewX"]) options.skewX = "0";

                    if (!options["timingFunction"]) options["timingFunction"] = "linear";

                    //check for percent or numbers
                    if (typeof (options.x) === "number" || (options.x.indexOf("%") === -1 && options.x.toLowerCase().indexOf("px") === -1 && options.x.toLowerCase().indexOf("deg") === -1)) options.x = parseInt(options.x) + "px";
                    if (typeof (options.y) === "number" || (options.y.indexOf("%") === -1 && options.y.toLowerCase().indexOf("px") === -1 && options.y.toLowerCase().indexOf("deg") === -1)) options.y = parseInt(options.y) + "px";

                    var trans= "translate" + translateOpen + (options.x) + "," + (options.y) + translateClose + " scale(" + parseFloat(options.scale) + ") rotate(" + options.rotateX + ")";
                    if(!$.os.opera)
                        trans+=" rotateY(" + options.rotateY + ")";
                    trans+=" skew(" + options.skewX + "," + options.skewY + ")";
                    this.el.style[$.feat.cssPrefix+"Transform"]=trans;
                    this.el.style[$.feat.cssPrefix+"BackfaceVisibility"] = "hidden";
                    var properties = $.feat.cssPrefix+"Transform";
                    if (options["opacity"]!==undefined) {
                        this.el.style.opacity = options["opacity"];
                        properties+=", opacity";
                    }
                    if (options["width"]) {
                        this.el.style.width = options["width"];
                        properties = "all";
                    }
                    if (options["height"]) {
                        this.el.style.height = options["height"];
                        properties = "all";
                    }
                    this.el.style[$.feat.cssPrefix+"TransitionProperty"] = "all";

                    if((""+options["time"]).indexOf("s") === -1) {
                        var scale = 'ms';
                        var time = options["time"]+scale;
                    } else if(options["time"].indexOf("ms") !== -1){
                        var scale = 'ms';
                        var time = options["time"];
                    } else {
                        var scale = 's';
                        var time = options["time"]+scale;
                    }

                    this.el.style[$.feat.cssPrefix+"TransitionDuration"] = time;
                    this.el.style[$.feat.cssPrefix+"TransitionTimingFunction"] = options["timingFunction"];
                    this.el.style[$.feat.cssPrefix+"TransformOrigin"] = options.origin;

                }

                //add callback to the stack

                this.callbacksStack.push({
                    complete : options["complete"],
                    success : options["success"],
                    failure : options["failure"]
                });
                this.countStack++;

                var that = this;
                var style = window.getComputedStyle(this.el);
                if(classMode){
                    //get the duration
                    var duration = style[$.feat.cssPrefix+"TransitionDuration"];
                    var timeNum = numOnly(duration);
                    options["time"]=timeNum;
                    if(duration.indexOf("ms") !== -1){
                        scale = 'ms';
                    } else {
                        options["time"]*=1000;
                        scale = 's';
                    }
                }

                //finish asap
                if(timeNum==0 || (scale=='ms' && timeNum<5) || style.display=='none'){
                    //the duration is nearly 0 or the element is not displayed, finish immediatly
                    $.asap($.proxy(this.finishAnimation, this, [false]));
                    //this.finishAnimation();
                    //set transitionend event
                } else {
                    //setup the event normally

                   var that=this;
                    this.activeEvent = function(event){
                        clearTimeout(that.timeout);
                        that.finishAnimation(event);
                        that.el.removeEventListener(transitionEnd, that.activeEvent, false);
                    };
                    that.timeout=setTimeout(this.activeEvent, numOnly(options["time"]) + 50);
                    this.el.addEventListener(transitionEnd, this.activeEvent, false);

                }

            },
            addCallbackHook:function(callback){
                if(callback) this.callbacksStack.push(callback);
                this.countStack++;
                return this.linkFinishedProxy_;
            },
            linkFinished:function(canceled){
                if(canceled) this.cancel();
                else this.finishAnimation();
            },
            finishAnimation: function (event) {
                if(event) event.preventDefault();
                if(!this.isActive) return;

                this.countStack--;

                if(this.countStack==0) this.fireCallbacks(false);
            },
            fireCallbacks:function(canceled){
                this.clearEvents();

                //keep callbacks after cleanup
                // (if any of the callbacks overrides this object, callbacks will keep on fire as expected)
                var callbacks = this.callbacksStack;

                //cleanup
                this.cleanup();

                //fire all callbacks
                for(var i=0; i<callbacks.length; i++) {
                    var complete = callbacks[i]['complete'];
                    var success = callbacks[i]['success'];
                    var failure = callbacks[i]['failure'];
                    //fire callbacks
                    if(complete && typeof (complete) === "function") complete(canceled);
                    //success/failure
                    if(canceled && failure && typeof (failure) === "function") failure();
                    else if(success && typeof (success) === "function") success();
                }
            },
            cancel:function(){
                if(!this.isActive) return;
                this.fireCallbacks(true); //fire failure callbacks
            },
            cleanup:function(){
                this.callbacksStack=[];
                this.isActive = false;
                this.countStack = 0;
            },
            clearEvents:function(){
                if(this.activeEvent) {
                    this.el.removeEventListener(transitionEnd, this.activeEvent, false);
                }
                this.activeEvent = null;
            },
            link: function (elID, opts) {
                var callbacks = {complete:opts.complete,success:opts.success,failure:opts.failure};
                opts.complete = this.addCallbackHook(callbacks);
                opts.success = null;
                opts.failure = null;
                //run the animation with the replaced callbacks
                getCSS3Animate(elID, opts);
                //set the old callback back in the obj to avoid strange stuff
                opts.complete = callbacks.complete;
                opts.success = callbacks.success;
                opts.failure = callbacks.failure;
                return this;
            }
        }

        return css3Animate;
    })();

    css3Animate.queue = function () {
        return {
            elements: [],
            push: function (el) {
                this.elements.push(el);
            },
            pop: function () {
                return this.elements.pop();
            },
            run: function () {
                var that = this;
                if (this.elements.length == 0) return;
                if (typeof (this.elements[0]) === "function") {
                    var func = this.shift();
                    func();
                }
                if (this.elements.length == 0) return;
                var params = this.shift();
                if (this.elements.length > 0) params.complete = function (canceled) {
                    if(!canceled) that.run();
                };
                css3Animate(document.getElementById(params.id), params);
            },
            shift: function () {
                return this.elements.shift();
            }
        }
    };
})(jq);
<|endoftext|>