<commit_before>
define( [ 'global', 'class' ], function( aGlobal ) {
	'use strict';

	var GLOBAL = new aGlobal( );

	/**
	 * Class: Soundbank
	 * @param {DOMelement} aElement
	 */

	var Soundbank = Class.extend({
		/**
		 * Method: init
		 * @param {DOMelement} aElement
		 */

		init: function( aElement) {
			var self = this;

			this.sound = aElement;
			this.playing = false;
			this.paused = false;
			this.next = null;

			this.sound.addEventListener( 'ended', function( ) {
				if ( self.sound !== null && self.sound.hasAttribute( 'loop' ) === false ) {
					self.stop( );
				}
			}, true );
		},

		/**
		 * Method: play
		 */

		play: function( ) {
			if ( this.sound !== null ) {
				this.playing = true;
				this.sound.play( );
			}
		},

		/**
		 * Method: stop
		 */

		stop: function( ) {
			if ( this.sound !== null && this.playing === true ) {
				this.sound.pause( );
				this.sound.currentTime = 0;

				this.sound.removeAttribute( 'src' );
				this.sound.removeAttribute( 'volume' );
				this.sound.removeAttribute( 'loop' );

				this.playing = false;
			}
		}
	});

	/**
	 * Class: Audio
	 */

	var Audio = Class.extend({
		/**
		 * Method: init
		 * @param {Object} aSystem
		 */

		init: function( aSystem ) {
			var el = document.getElementById( 'bglAudio' ),
				frag = document.createDocumentFragment( ),
				bank, i;

			this.system = aSystem;

			this.banks = [ ];
			this.lastBank = null;

			bank = document.createElement( 'audio' );
			bank.setAttribute( 'id', 'bglAudioMusic' );
			bank.setAttribute( 'autoplay', 'autoplay' );
			bank.setAttribute( 'loop', 'loop' );
			frag.appendChild( bank );

			this.background = new Soundbank( bank );

			for ( i = 0; i < GLOBAL.audio.numBanks; i++ ) {
				bank = document.createElement( 'audio' );
				bank.setAttribute( 'id', 'bglAudioBank' + i );
				bank.setAttribute( 'autoplay', 'autoplay' );
				frag.appendChild( bank );

				this.addBank( bank );
			}

			el.appendChild( frag );

			this.system.verbose( 'init->audio' );
		},

		/**
		 * Method: addBank
		 * @param {Object} aBank
		 */

		addBank: function( aBank ) {
			var bank = new Soundbank( aBank ),
				len = this.banks.length;

			this.banks.push( bank );

			if ( len === 0 ) {
				this.banks[ 0 ].next = this.banks[ 0 ];
				this.lastBank = this.banks[ 0 ];
			}
			else {
				this.banks[ len ].next = this.banks[ 0 ];
				this.banks[ len - 1 ].next = this.banks[ len ];
			}
		},

		/**
		 * Method: getNextBank
		 * @return {Object/Bool}
		 */

		getNextBank: function( ) {
			var bank,
				i, len;

			if ( this.lastBank === false ) {
				return false;
			}

			i = 0;
			len = this.banks.length;
			bank = this.lastBank;

			while ( i < len && bank.playing === true ) {
				bank = bank.next;
				i++;
			}

			return ( i === len ) ? false : bank;
		},

		/**
		 * Method: playMusic
		 * @param {Object} aSound
		 */

		playMusic: function( aSound ) {
			var sound = {
				fileUrl: aSound.fileUrl,
				volume: aSound.volume || 50,
				effectName: aSound.effectName || false,
				effectDuration: aSound.effectDuration || 0
			};

			this.background.sound.setAttribute( 'src', sound.fileUrl );
			this.background.sound.setAttribute( 'volume', sound.volume );
			this.background.sound.setAttribute( 'loop', '' );
			this.background.sound.load( );

			if ( sound.effectName === 'fadeIn' ) {
				this.effectsFadeIn( this.background, sound.effectDuration );
			}
			else {
				this.background.playing = true;
				this.background.sound.play( );
			}
		},

		/**
		 * Method: pauseMusic
		 */

		pauseMusic: function( ) {
			this.background.sound.pause( );
			this.background.playing = false;
			this.background.paused = true;
		},

		/**
		 * Method: stopMusic
		 */

		stopMusic: function( ) {
			this.background.sound.pause( );
			this.background.sound.currentTime = 0;
			this.background.playing = false;
			this.background.paused = false;
		},

		/**
		 * Method: playSound
		 * @param {Object} aSound
		 * @return {Object/Bool}
		 */

		playSound: function( aSound ) {
			var bank = this.getNextBank( ),
				volume = aSound.volume || 75,
				loop = aSound.loop || false,
				effectName = aSound.effectName || false,
				effectDuration = aSound.effectDuration || 0;

			if ( bank !== false ) {
				this.lastBank = bank;

				bank.sound.setAttribute( 'src', aSound.fileUrl );
				bank.sound.setAttribute( 'volume', volume );

				if ( loop ) {
					bank.sound.setAttribute( 'loop', '' );
				}

				bank.sound.load( );

				if ( effectName === 'fadeIn' ) {
					this.effectFadeIn( bank, effectDuration );
				}
				else {
					bank.play( );
				}
			}

			return bank;
		},

		/**
		 * Method: playRandomSound
		 * @param {Array} aSounds
		 * @return {Object/Bool}
		 */

		playRandomSound: function( aSounds ) {
			var rnd = Math.floor( Math.random( ) * aSounds.files.length ),
				sound = aSounds.files[ rnd ],
				volume = aSounds.volume || sound.volume || 50,
				loop = aSounds.loop || sound.loop || false;

			return this.playSound({
				fileUrl: sound.fileUrl,
				volume: volume,
				loop: loop
			});
		},

		/**
		 * Method: effectsFadeIn
		 * @param {Object} aSoundbank
		 */

		effectsFadeIn: function( aSoundbank, aDuration ) {
			var bank = aSoundbank,
				duration = aDuration,
				volume, max, step,
				self = this;

			if ( bank.playing === false ) {
				max = parseFloat( bank.sound.getAttribute( 'volume' ), 10 );
				duration = duration / 20;
				step = parseFloat( max / duration, 10 );

				bank.sound.setAttribute( 'volume', 0 );
				bank.sound.setAttribute( 'data-volume', max );
				bank.sound.setAttribute( 'data-step', step );

				bank.play( );

				setTimeout(function( ) {
					self.effectsFadeIn( bank, duration );
				});
			}
			else {
				max = parseFloat( bank.sound.getAttribute( 'data-volume' ), 10 );
				step = parseFloat( bank.sound.getAttribute( 'data-step' ), 10 );

				volume = parseFloat( bank.sound.getAttribute( 'volume' ), 10 );
				volume += step;

				if ( volume > max ) {
					volume = max;

					bank.sound.setAttribute( 'volume', volume );
					bank.sound.removeAttribute( 'data-volume' );
					bank.sound.removeAttribute( 'data-step' );
				}
				else {
					bank.sound.setAttribute( 'volume', volume );

					setTimeout(function( ) {
						self.effectsFadeIn( bank, duration );
					});
				}
			}
		}
	});

	return Audio;
});
<commit_msg>audio micro optimization<commit_after>
define( [ 'global', 'class' ], function( aGlobal ) {
	'use strict';

	var GLOBAL = new aGlobal( );

	/**
	 * Class: Soundbank
	 * @param {DOMelement} aElement
	 */

	var Soundbank = Class.extend({
		/**
		 * Method: init
		 * @param {DOMelement} aElement
		 */

		init: function( aElement) {
			var self = this;

			this.sound = aElement;
			this.playing = false;
			this.paused = false;
			this.next = null;

			this.sound.addEventListener( 'ended', function( ) {
				if ( self.sound !== null && self.sound.hasAttribute( 'loop' ) === false ) {
					self.stop( );
				}
			}, true );
		},

		/**
		 * Method: play
		 */

		play: function( ) {
			if ( this.sound !== null ) {
				this.playing = true;
				this.sound.play( );
			}
		},

		/**
		 * Method: stop
		 */

		stop: function( ) {
			if ( this.sound !== null && this.playing === true ) {
				this.sound.pause( );
				this.sound.currentTime = 0;

				this.sound.removeAttribute( 'src' );
				this.sound.removeAttribute( 'volume' );
				this.sound.removeAttribute( 'loop' );

				this.playing = false;
			}
		}
	});

	/**
	 * Class: Audio
	 */

	var Audio = Class.extend({
		/**
		 * Method: init
		 * @param {Object} aSystem
		 */

		init: function( aSystem ) {
			var el = document.getElementById( 'bglAudio' ),
				frag = document.createDocumentFragment( ),
				bank, i;

			this.system = aSystem;

			this.banks = [ ];
			this.lastBank = null;

			bank = document.createElement( 'audio' );
			bank.setAttribute( 'id', 'bglAudioMusic' );
			bank.setAttribute( 'autoplay', 'autoplay' );
			bank.setAttribute( 'loop', 'loop' );
			frag.appendChild( bank );

			this.background = new Soundbank( bank );

			for ( i = 0; i < GLOBAL.audio.numBanks; i++ ) {
				bank = document.createElement( 'audio' );
				bank.setAttribute( 'id', 'bglAudioBank' + i );
				bank.setAttribute( 'autoplay', 'autoplay' );
				frag.appendChild( bank );

				this.addBank( bank );
			}

			el.appendChild( frag );

			this.system.verbose( 'init->audio' );
		},

		/**
		 * Method: addBank
		 * @param {Object} aBank
		 */

		addBank: function( aBank ) {
			var bank = new Soundbank( aBank ),
				len = this.banks.length;

			this.banks.push( bank );

			if ( len === 0 ) {
				this.banks[ 0 ].next = this.banks[ 0 ];
				this.lastBank = this.banks[ 0 ];
			}
			else {
				this.banks[ len ].next = this.banks[ 0 ];
				this.banks[ len - 1 ].next = this.banks[ len ];
			}
		},

		/**
		 * Method: getNextBank
		 * @return {Object/Bool}
		 */

		getNextBank: function( ) {
			var bank, i;

			if ( this.lastBank === false ) {
				return false;
			}

			i = this.banks.length;
			bank = this.lastBank;

			while (i-- && bank.playing === true ) {
				bank = bank.next;
			}

			return ( i === 0 ) ? false : bank;
		},

		/**
		 * Method: playMusic
		 * @param {Object} aSound
		 */

		playMusic: function( aSound ) {
			var sound = {
				fileUrl: aSound.fileUrl,
				volume: aSound.volume || 50,
				effectName: aSound.effectName || false,
				effectDuration: aSound.effectDuration || 0
			};

			this.background.sound.setAttribute( 'src', sound.fileUrl );
			this.background.sound.setAttribute( 'volume', sound.volume );
			this.background.sound.setAttribute( 'loop', '' );
			this.background.sound.load( );

			if ( sound.effectName === 'fadeIn' ) {
				this.effectsFadeIn( this.background, sound.effectDuration );
			}
			else {
				this.background.playing = true;
				this.background.sound.play( );
			}
		},

		/**
		 * Method: pauseMusic
		 */

		pauseMusic: function( ) {
			this.background.sound.pause( );
			this.background.playing = false;
			this.background.paused = true;
		},

		/**
		 * Method: stopMusic
		 */

		stopMusic: function( ) {
			this.background.sound.pause( );
			this.background.sound.currentTime = 0;
			this.background.playing = false;
			this.background.paused = false;
		},

		/**
		 * Method: playSound
		 * @param {Object} aSound
		 * @return {Object/Bool}
		 */

		playSound: function( aSound ) {
			var bank = this.getNextBank( ),
				volume = aSound.volume || 75,
				loop = aSound.loop || false,
				effectName = aSound.effectName || false,
				effectDuration = aSound.effectDuration || 0;

			if ( bank !== false ) {
				this.lastBank = bank;

				bank.sound.setAttribute( 'src', aSound.fileUrl );
				bank.sound.setAttribute( 'volume', volume );

				if ( loop ) {
					bank.sound.setAttribute( 'loop', '' );
				}

				bank.sound.load( );

				if ( effectName === 'fadeIn' ) {
					this.effectFadeIn( bank, effectDuration );
				}
				else {
					bank.play( );
				}
			}

			return bank;
		},

		/**
		 * Method: playRandomSound
		 * @param {Array} aSounds
		 * @return {Object/Bool}
		 */

		playRandomSound: function( aSounds ) {
			var rnd = Math.floor( Math.random( ) * aSounds.files.length ),
				sound = aSounds.files[ rnd ],
				volume = aSounds.volume || sound.volume || 50,
				loop = aSounds.loop || sound.loop || false;

			return this.playSound({
				fileUrl: sound.fileUrl,
				volume: volume,
				loop: loop
			});
		},

		/**
		 * Method: effectsFadeIn
		 * @param {Object} aSoundbank
		 */

		effectsFadeIn: function( aSoundbank, aDuration ) {
			var bank = aSoundbank,
				duration = aDuration,
				volume, max, step,
				self = this;

			if ( bank.playing === false ) {
				max = parseFloat( bank.sound.getAttribute( 'volume' ), 10 );
				duration = duration / 20;
				step = parseFloat( max / duration, 10 );

				bank.sound.setAttribute( 'volume', 0 );
				bank.sound.setAttribute( 'data-volume', max );
				bank.sound.setAttribute( 'data-step', step );

				bank.play( );

				setTimeout(function( ) {
					self.effectsFadeIn( bank, duration );
				});
			}
			else {
				max = parseFloat( bank.sound.getAttribute( 'data-volume' ), 10 );
				step = parseFloat( bank.sound.getAttribute( 'data-step' ), 10 );

				volume = parseFloat( bank.sound.getAttribute( 'volume' ), 10 );
				volume += step;

				if ( volume > max ) {
					volume = max;

					bank.sound.setAttribute( 'volume', volume );
					bank.sound.removeAttribute( 'data-volume' );
					bank.sound.removeAttribute( 'data-step' );
				}
				else {
					bank.sound.setAttribute( 'volume', volume );

					setTimeout(function( ) {
						self.effectsFadeIn( bank, duration );
					});
				}
			}
		}
	});

	return Audio;
});
<|endoftext|>


<commit_before>module.exports = function(config) {
  return config.set({
    basePath: "../",
    frameworks: ['jasmine', 'traceur'],
    files: [
      "app/bower_components/traceur-runtime/traceur-runtime.js",
      "app/bower_components/es6-module-loader/dist/es6-module-loader.js",
      "app/bower_components/system.js/dist/system.js",
      "app/bower_components/jquery/dist/jquery.js",
      "app/bower_components/angular/angular.js",
      "app/bower_components/json3/lib/json3.js",
      "app/bower_components/angular-resource/angular-resource.js",
      "app/bower_components/angular-sanitize/angular-sanitize.js",
      "app/bower_components/angular-ui-router/release/angular-ui-router.js",
      "app/bower_components/lodash/dist/lodash.compat.js",
      "app/bower_components/angular-animate/angular-animate.js",
      "app/bower_components/angular-aria/angular-aria.js",
      "app/bower_components/hammerjs/hammer.js",
      "app/bower_components/angular-material/angular-material.js",
      "app/src/app.js",
      "app/src/**/*.js",
      "test/spec/**/*.js",
      "test/test-main.js"
    ],
    preprocessors: {
      "app/src/**/*.js": "traceur",
      "app/src/**/*.html": "ng-html2js" // TODO improve!!!
    },
    reporters: ["mocha"],
    port: 9876,
    colors: true,
    logLevel: config.LOG_INFO,
    autoWatch: true,
    browsers: ["Chrome"],
    captureTimeout: 60000,
    singleRun: false,
    junitReporter: {
      outputFile: "reports/karma/karma-junit.xml",
      suite: "unit"
    },
    ngHtml2JsPreprocessor: {
      stripPrefix: 'app/src/',
      moduleName: 'accounting'
    }
  });
};

<commit_msg>no karma for now<commit_after><|endoftext|>


<commit_before>import { Component } from 'react';
import PropTypes from 'prop-types';
import setDisplayName from 'recompose/setDisplayName';
import wrapDisplayName from 'recompose/wrapDisplayName';
import createEagerFactory from 'recompose/createEagerFactory';

const initStore = initializer => (BaseComponent) => {
  const init = Array.isArray(initializer) ? initializer[0] : initializer;
  const factory = createEagerFactory(BaseComponent);

  const StoreInitializer = class extends Component {
    constructor(props, context) {
      super(props, context);
      this.store = context.store;
    }
    componentWillMount() {
      const store = this.store;
      this.isInitialized(init(store.dispatch, store.getState, this.props));
    }
    componentDidMount() {
      this.mounted = true;
    }
    componentWillUnmount() {
      this.mounted = false;
    }

    componentWillReceiveProps(nextProps) {
      const store = this.store;
      this.isInitialized(init(store.dispatch, store.getState, nextProps, this.props));
    }

    static getStoreInitializer() {
      return initializer;
    }

    isInitialized(initRet) {
      this.shouldUpdate = initRet !== false;
      if (initRet.then) {
        if (typeof window !== 'undefined') {
          this.shouldUpdate = false;
          initRet.then(() => {
            this.shouldUpdate = true;
            if (this.mounted) this.forceUpdate();
          });
        }
      }
    }
    shouldComponentUpdate() {
      return this.shouldUpdate;
    }

    render() {
      return factory(this.props);
    }
  };
  StoreInitializer.contextTypes = {
    store: PropTypes.shape({
      subscribe: PropTypes.func.isRequired,
      dispatch: PropTypes.func.isRequired,
      getState: PropTypes.func.isRequired,
    }),
  };
  if (process.env.NODE_ENV !== 'production') {
    return setDisplayName(wrapDisplayName(BaseComponent, 'initStore'))(
      StoreInitializer
    );
  }
  return StoreInitializer;
};

export default initStore;
<commit_msg>guard against storeInitializer being other than an object<commit_after>import { Component } from 'react';
import PropTypes from 'prop-types';
import setDisplayName from 'recompose/setDisplayName';
import wrapDisplayName from 'recompose/wrapDisplayName';
import createEagerFactory from 'recompose/createEagerFactory';

const initStore = initializer => (BaseComponent) => {
  const init = Array.isArray(initializer) ? initializer[0] : initializer;
  const factory = createEagerFactory(BaseComponent);

  const StoreInitializer = class extends Component {
    constructor(props, context) {
      super(props, context);
      this.store = context.store;
    }
    componentWillMount() {
      const store = this.store;
      this.isInitialized(init(store.dispatch, store.getState, this.props));
    }
    componentDidMount() {
      this.mounted = true;
    }
    componentWillUnmount() {
      this.mounted = false;
    }

    componentWillReceiveProps(nextProps) {
      const store = this.store;
      this.isInitialized(init(store.dispatch, store.getState, nextProps, this.props));
    }

    static getStoreInitializer() {
      return initializer;
    }

    isInitialized(initRet) {
      this.shouldUpdate = initRet !== false;
      if (typeof initRet === 'object' && initRet.then) {
        if (typeof window !== 'undefined') {
          this.shouldUpdate = false;
          initRet.then(() => {
            this.shouldUpdate = true;
            if (this.mounted) this.forceUpdate();
          });
        }
      }
    }
    shouldComponentUpdate() {
      return this.shouldUpdate;
    }

    render() {
      return factory(this.props);
    }
  };
  StoreInitializer.contextTypes = {
    store: PropTypes.shape({
      subscribe: PropTypes.func.isRequired,
      dispatch: PropTypes.func.isRequired,
      getState: PropTypes.func.isRequired,
    }),
  };
  if (process.env.NODE_ENV !== 'production') {
    return setDisplayName(wrapDisplayName(BaseComponent, 'initStore'))(StoreInitializer);
  }
  return StoreInitializer;
};

export default initStore;
<|endoftext|>


<commit_before>import '../common/index'
import globalTest from './global/main'
import empty from './empty/main'
import postmessageTest from './postmessage/main'
import lifecycleTest from './lifecycle/main'
import syncTest from './sync/main'
import result from './result/main'
import init from './init/main'
import env from './env/main'
import summary from './summary/main'
import cache from './cache/main'
import push from './push/main'
import {search2obj, obj2search, uuid, isNumeric} from 'utils'
import store from 'store'
import axios from 'axios'
import './main.css'
import 'vconsole'
import {info, infoKeys} from './helper'
import 'views/common/raven'
window.addEventListener('unhandledrejection', function (event) {
  console.warn('WARNING: Unhandled promise rejection. Shame on you! Reason: ' + event.reason)
})
info.totalSchedule = 8
let uaInfo = {
  info: {}
}
const {step = '0', fr = ''} = search2obj();

(async function main () {

  const id = await store.get('uuid', 'id')
  if (!id) {
    await store.put('uuid', uuid(), 'id')
  }

  // 如若是manifest的测试,直接返回了
  if (fr && fr === 'manifesticon') {
    const ua = await store.get('info', 'ua')
    if (!ua) {
      await env()
    }
    await setUa('info', infoKeys)
    axios({
      method: 'post',
      url: 'http://172.18.18.32:8849/ready/statistic',
      data: {
        id,
        info: uaInfo,
        manifest: {
          addToScreen: 1
        }
      }
    })
    return
  }

  // 如果是step=1刷新，则重定向到step=0，重新走测试流程
  if (step === '1' && localStorage.getItem('from') === 'refresh') {
    const search = search2obj()
    location.search = obj2search(Object.assign(search, {step: '0'}))
  }

  switch (step) {
    case '0':
      await init()
      await env()
      await result()
      await globalTest()
      await result()
      await empty()
      return
    case '1':
      await result()
      await lifecycleTest()
      await result()
      await postmessageTest()
      await result()
      await syncTest()
      await result()
      await cache()
      await result()
      await push()
      await result()
      await summary()
      break
  }
})()

async function setUa(kind, keys) {
  for(let i = 0; i < keys.length; i++) {
    const key = keys[i]
    const score = await store.get(kind, key)
    if(isNumeric(score)) {
      uaInfo[kind][key] = parseFloat(score)
    } else {
      try {
        uaInfo[kind][key] = JSON.parse(score)
      } catch (error) {
        uaInfo[kind][key] = score
      }
    }
  }
}
<commit_msg>小细节修改<commit_after>import '../common/index'
import globalTest from './global/main'
import empty from './empty/main'
import postmessageTest from './postmessage/main'
import lifecycleTest from './lifecycle/main'
import syncTest from './sync/main'
import result from './result/main'
import init from './init/main'
import env from './env/main'
import summary from './summary/main'
import cache from './cache/main'
import push from './push/main'
import {search2obj, obj2search, uuid, isNumeric} from 'utils'
import store from 'store'
import axios from 'axios'
import './main.css'
import 'vconsole'
import {info, infoKeys} from './helper'
import 'views/common/raven'
window.addEventListener('unhandledrejection', function (event) {
  console.warn('WARNING: Unhandled promise rejection. Shame on you! Reason: ' + event.reason)
})
info.totalSchedule = 8
let uaInfo = {
  info: {}
}
const {step = '0', fr = ''} = search2obj();

(async function main () {

  const id = await store.get('uuid', 'id')
  if (!id) {
    await store.put('uuid', uuid(), 'id')
  }

  // 如若是manifest的测试,直接返回了
  if (fr && fr === 'manifesticon') {
    const ua = await store.get('info', 'ua')
    if (!ua) {
      await env()
    }
    await setUa('info', infoKeys)
    axios({
      method: 'post',
      url: 'http://172.18.18.32:8849/ready/statistic',
      data: {
        id,
        info: uaInfo,
        manifest: {
          addToScreen: 1
        }
      }
    })
    return
  }

  // 如果是step=1刷新，则重定向到step=0，重新走测试流程
  if (step === '1' && localStorage.getItem('from') !== 'step0') {
    const search = search2obj()
    location.search = obj2search(Object.assign(search, {step: '0'}))
  }

  switch (step) {
    case '0':
      await init()
      await env()
      await result()
      await globalTest()
      await result()
      await empty()
      return
    case '1':
      await result()
      await lifecycleTest()
      await result()
      await postmessageTest()
      await result()
      await syncTest()
      await result()
      await cache()
      await result()
      await push()
      await result()
      await summary()
      break
  }
})()

async function setUa(kind, keys) {
  for(let i = 0; i < keys.length; i++) {
    const key = keys[i]
    const score = await store.get(kind, key)
    if(isNumeric(score)) {
      uaInfo[kind][key] = parseFloat(score)
    } else {
      try {
        uaInfo[kind][key] = JSON.parse(score)
      } catch (error) {
        uaInfo[kind][key] = score
      }
    }
  }
}
<|endoftext|>


<commit_before>Template.playlist.selected = function () {
  return Session.equals("playing_song", this._id) ? "selected" : '';
};

Template.playlist.events = {
  'click [data-toggle="collapse"]': function (e) {
    var parent = $('.edittoggle');
    var out = parent.find('.collapse.in');
    parent.find('.collapse:not(.in)').collapse('show');
    out.collapse('hide');
  }
};

Template.playlistEntry.isLoved = function() {
	var videoId = this+"";
  var user = Meteor.user();
  if (!user)
    return;
	var i = user.profile.lovedSongs.indexOf(videoId);
	if (i<0)
    return ""; //not loved
	else
    return "loved"; //return classname
};

Template.updatePlaylistForm.editingDoc = function () {
  return Playlists.findOne({_id: this._id});
};

// initialize active_tab
Session.set('active_tab', 'songs');

Template.playlistTabs.helpers({
  isActiveTab: function(route) {
    return Session.equals("active_tab", route) ? "active" : "";
  },
});

Template.playlistTabs.owner = function () {
  return Meteor.users.findOne({_id: this.owner});
};

Template.playlistTabs.events = {
  'click ul.playlist-tabs > li': function (e) {
    var li = $(e.currentTarget);
    var route = li.data('id');
    Session.set("active_tab", route);
  },
  'submit form.youtube-search': function (e) {
    e.preventDefault();
  },
  'input input.youtube-query': function (e) {
    var input = $(e.currentTarget);
    youtubeSearch(input.val());
  },
  'click button[data-toggle="clearResults"]': function(e) {

	$("input.youtube-query").val("");
	searchResults = null;
    searchResultsDependency.changed();
  },
  'click .youtube-result': function (e, template) {
    var videoId = this.id.videoId;
    var playlistId = template.data._id;
    console.log('queue video:', videoId, 'to playlist', playlistId);
    Playlists.update(
      { _id: playlistId},
      { $push: { songs: videoId} }
    );
  },
  //Loved a song!
  'click button#quickLove': function(e) {
	e.stopPropagation();
	console.log("add "+this.snippet.title+" to loved songs");
	var user = Meteor.users; //loved songs are stored in users profile
	user.update(
                    { _id: Meteor.userId()	},
                    { $addToSet : { 'profile.lovedSongs': this.id.videoId }}
                  );
  },
  'click a[rel="external"]': function(e) {
    e.stopPropagation(); // prevent queueing
    e.preventDefault(); // prevent linking in current window
    window.open(e.currentTarget.href, '_blank');
  }
};

Template.songs.events = {
  'click [data-action="play"]' : function(e, template) {
    var row = $(e.currentTarget).parents('div.row');
    var index = $(e.delegateTarget).children('div.row').index(row);
    console.log('playing song at index', index);

    // update the user's profile and the song will automatically play
    var id = Meteor.userId();
    var playlistId = template.data._id;
    if (id) {
      Meteor.users.update({_id: id}, { $set: {
        'profile.playing': {
          'playlist': playlistId,
          'playlistIndex': index,
          'status': 'playing',
          'modified': new Date(),
        }
      }});
    } else {
      console.warn('user not logged in!!!');
    }
  },
  'click [data-action="remove"]' : function(e, template) {
    var row = $(e.currentTarget).parents('div.row');
    var index = $(e.delegateTarget).children('div.row').index(row);
    console.log('removing song at index', index);

    // removing a element at a position is impossible in mongodb,
    // so just set the shole array
    if (index >= 0) {
      var songs = _.clone(template.data.songs); // clone is important!!!
      songs.splice(index, 1); // remove 1 element at position index
      Playlists.update({_id: template.data._id}, { $set : {"songs": songs}});
    }
  },
  'click [data-action="lovesong"]' : function(e) {
	//TODO: should find a way to merge this one with #quicklove from search results..
	var videoId = this+"";
	var user = Meteor.users.findOne({_id: Meteor.userId()});

	//Toggle depending on current state
	if(user.profile.lovedSongs.indexOf(videoId) <0) { //not currently loved
		console.log("add "+videoId+" to loved songs");
		Meteor.users.update(
						{ _id: Meteor.userId()	},
						{ $addToSet : { 'profile.lovedSongs': videoId }}
		      );
	} else { //currently loved, remove it from lovedSongs
		console.log("remove "+videoId+" from loved songs");
		Meteor.users.update(
                    { _id: Meteor.userId()	},
                    { $pull : { 'profile.lovedSongs': videoId }}
                  );
	}
  }
};

// Youtube search results

var searchTimer;
var searchDelay = 250; // ms

function youtubeSearch(value) {
  clearTimeout(searchTimer);
  searchTimer = setTimeout(function() {
    if (!value) {
      searchResults = null;
      searchError = 'Please search for something';
      searchResultsDependency.changed();
      return;
    }
    console.log('youtube search for:', value);
    youtubeSearchQuery({
      part: 'id,snippet',
      type: 'video',
      videoEmbeddable: 'true',
      q: value
    });
  },searchDelay);
}

var searchResults;
var searchError;
var searchResultsDependency = new Deps.Dependency();

youtubeSearchQuery = function(options) {
  options = options || {};

  Meteor.call('youtube_search', options, function(error, data) {
    if (error) {
      console.log('Youtube API error:', error);
    } else {
      console.log('Youtube API result:', data);
    }
    searchError   = error;
    searchResults = data;
    searchResultsDependency.changed();

    // query for more details (needs optimization)
    var ids = _.pluck(_.pluck(data.items, 'id'), 'videoId');
    console.log('load more data for ', ids);

    youtubeVideoQuery({
      'part': 'snippet,contentDetails,statistics',
      'id': ids,
    })
  });
};

youtubeVideoQuery = function(options) {
  options = options || {};

  Meteor.call('youtube_videos_list', options, function(error, data) {
    if (error) {
      console.log('Youtube API error:', error);
    } else {
      console.log('Youtube API result:', data);
    }
  });
};

Template.searchResults.result = function() {
  Deps.depend(searchResultsDependency);
  return searchResults;
};

Template.searchResults.error = function() {
  Deps.depend(searchResultsDependency);
  return searchError;
};

Template.songs.songs = function() {
  // get all users that play a song on this playlist
  var users = Meteor.users.find({'profile.playing.playlist': this._id});
  var indexes = _.groupBy(users.fetch(), function(u) {
    return u.profile.playing.playlistIndex;
  });

  // find all songs for this playlist

  // optimize this later with only 1 query
  // var songs = Songs.find({_id: {$in: ids}});

  var songs = this.songs.map(function (id, i) {
    var song = Songs.findOne({_id: id});

    // all users on this song
    var songUsers = indexes[i];
    song.users = songUsers;

    //var i = users.profile.playing.playlistIndex;
    //console.log(i);
    return song;
  });

  return songs;
};
<commit_msg>fix loved songs<commit_after>Template.playlist.selected = function () {
  return Session.equals("playing_song", this._id) ? "selected" : '';
};

Template.playlist.events = {
  'click [data-toggle="collapse"]': function (e) {
    var parent = $('.edittoggle');
    var out = parent.find('.collapse.in');
    parent.find('.collapse:not(.in)').collapse('show');
    out.collapse('hide');
  }
};

Template.playlistEntry.isLoved = function() {
  var videoId = this._id;
  var user = Meteor.user();
  if (!user)
    return;
  var i = user.profile.lovedSongs.indexOf(videoId);
  if (i<0)
    return ""; //not loved
  else
    return "loved"; //return classname
};

Template.updatePlaylistForm.editingDoc = function () {
  return Playlists.findOne({_id: this._id});
};

// initialize active_tab
Session.set('active_tab', 'songs');

Template.playlistTabs.helpers({
  isActiveTab: function(route) {
    return Session.equals("active_tab", route) ? "active" : "";
  },
});

Template.playlistTabs.owner = function () {
  return Meteor.users.findOne({_id: this.owner});
};

Template.playlistTabs.events = {
  'click ul.playlist-tabs > li': function (e) {
    var li = $(e.currentTarget);
    var route = li.data('id');
    Session.set("active_tab", route);
  },
  'submit form.youtube-search': function (e) {
    e.preventDefault();
  },
  'input input.youtube-query': function (e) {
    var input = $(e.currentTarget);
    youtubeSearch(input.val());
  },
  'click button[data-toggle="clearResults"]': function(e) {

	$("input.youtube-query").val("");
	searchResults = null;
    searchResultsDependency.changed();
  },
  'click .youtube-result': function (e, template) {
    var videoId = this.id.videoId;
    var playlistId = template.data._id;
    console.log('queue video:', videoId, 'to playlist', playlistId);
    Playlists.update(
      { _id: playlistId},
      { $push: { songs: videoId} }
    );
  },
  //Loved a song!
  'click button#quickLove': function(e) {
	e.stopPropagation();
	console.log("add "+this.snippet.title+" to loved songs");
	var user = Meteor.users; //loved songs are stored in users profile
	user.update(
                    { _id: Meteor.userId()	},
                    { $addToSet : { 'profile.lovedSongs': this.id.videoId }}
                  );
  },
  'click a[rel="external"]': function(e) {
    e.stopPropagation(); // prevent queueing
    e.preventDefault(); // prevent linking in current window
    window.open(e.currentTarget.href, '_blank');
  }
};

Template.songs.events = {
  'click [data-action="play"]' : function(e, template) {
    var row = $(e.currentTarget).parents('div.row');
    var index = $(e.delegateTarget).children('div.row').index(row);
    console.log('playing song at index', index);

    // update the user's profile and the song will automatically play
    var id = Meteor.userId();
    var playlistId = template.data._id;
    if (id) {
      Meteor.users.update({_id: id}, { $set: {
        'profile.playing': {
          'playlist': playlistId,
          'playlistIndex': index,
          'status': 'playing',
          'modified': new Date(),
        }
      }});
    } else {
      console.warn('user not logged in!!!');
    }
  },
  'click [data-action="remove"]' : function(e, template) {
    var row = $(e.currentTarget).parents('div.row');
    var index = $(e.delegateTarget).children('div.row').index(row);
    console.log('removing song at index', index);

    // removing a element at a position is impossible in mongodb,
    // so just set the shole array
    if (index >= 0) {
      var songs = _.clone(template.data.songs); // clone is important!!!
      songs.splice(index, 1); // remove 1 element at position index
      Playlists.update({_id: template.data._id}, { $set : {"songs": songs}});
    }
  },
  'click [data-action="lovesong"]' : function(e) {
    //TODO: should find a way to merge this one with #quicklove from search results..
    var videoId = this._id;
    var user = Meteor.user();

    //Toggle depending on current state
    if(user.profile.lovedSongs.indexOf(videoId) <0) { //not currently loved
      console.log("add "+videoId+" to loved songs");
      Meteor.users.update(
        { _id: Meteor.userId() },
        { $addToSet : { 'profile.lovedSongs': videoId }}
      );
    } else { //currently loved, remove it from lovedSongs
      console.log("remove "+videoId+" from loved songs");
      Meteor.users.update(
        { _id: Meteor.userId() },
        { $pull : { 'profile.lovedSongs': videoId }}
      );
    }
  }
};

// Youtube search results

var searchTimer;
var searchDelay = 250; // ms

function youtubeSearch(value) {
  clearTimeout(searchTimer);
  searchTimer = setTimeout(function() {
    if (!value) {
      searchResults = null;
      searchError = 'Please search for something';
      searchResultsDependency.changed();
      return;
    }
    console.log('youtube search for:', value);
    youtubeSearchQuery({
      part: 'id,snippet',
      type: 'video',
      videoEmbeddable: 'true',
      q: value
    });
  },searchDelay);
}

var searchResults;
var searchError;
var searchResultsDependency = new Deps.Dependency();

youtubeSearchQuery = function(options) {
  options = options || {};

  Meteor.call('youtube_search', options, function(error, data) {
    if (error) {
      console.log('Youtube API error:', error);
    } else {
      console.log('Youtube API result:', data);
    }
    searchError   = error;
    searchResults = data;
    searchResultsDependency.changed();

    // query for more details (needs optimization)
    var ids = _.pluck(_.pluck(data.items, 'id'), 'videoId');
    console.log('load more data for ', ids);

    youtubeVideoQuery({
      'part': 'snippet,contentDetails,statistics',
      'id': ids,
    })
  });
};

youtubeVideoQuery = function(options) {
  options = options || {};

  Meteor.call('youtube_videos_list', options, function(error, data) {
    if (error) {
      console.log('Youtube API error:', error);
    } else {
      console.log('Youtube API result:', data);
    }
  });
};

Template.searchResults.result = function() {
  Deps.depend(searchResultsDependency);
  return searchResults;
};

Template.searchResults.error = function() {
  Deps.depend(searchResultsDependency);
  return searchError;
};

Template.songs.songs = function() {
  // get all users that play a song on this playlist
  var users = Meteor.users.find({'profile.playing.playlist': this._id});
  var indexes = _.groupBy(users.fetch(), function(u) {
    return u.profile.playing.playlistIndex;
  });

  // find all songs for this playlist

  // optimize this later with only 1 query
  // var songs = Songs.find({_id: {$in: ids}});

  var songs = this.songs.map(function (id, i) {
    var song = Songs.findOne({_id: id});

    // all users on this song
    var songUsers = indexes[i];
    song.users = songUsers;

    //var i = users.profile.playing.playlistIndex;
    //console.log(i);
    return song;
  });

  return songs;
};
<|endoftext|>


<commit_before>    var player;
    var platforms;
    var cursors;
    var cielo;

    var stars;
    var score = 0;
    var vidas = 5;
    var scoreText;
    var game;

    function crearNivel(nivel){

        switch(nivel) {
        case '0':
            game = new Phaser.Game(800, 600, Phaser.AUTO, 'juegoId', { preload: preload, create: create0, update: update });
            break;
        case '1':
            game = new Phaser.Game(800, 600, Phaser.AUTO, 'juegoId', { preload: preload, create: create1, update: update });
            break;
        case '2':
            game = new Phaser.Game(800, 600, Phaser.AUTO, 'juegoId', { preload: preload, create: create2, update: update });
            break;
        default: noHayNiveles();
            break;
}

    }

    function preload() {

        game.load.image('sky', 'assets/sky.png');
        game.load.image('ground', 'assets/platform.png');
        game.load.image('ground2', 'assets/platform2.png');
        game.load.image('star', 'assets/star.png');
        game.load.image('cielo', 'assets/heaven.png');

        game.load.spritesheet('dude', 'assets/dude.png', 32, 48);

    }

    function create0() {

        //  We're going to be using physics, so enable the Arcade Physics system
        game.physics.startSystem(Phaser.Physics.ARCADE);

        //  A simple background for our game
        game.add.sprite(0, 0, 'sky');

        //  The platforms group contains the ground and the 2 ledges we can jump on
        platforms = game.add.group();
        cielo = game.add.group();
        //  We will enable physics for any object that is created in this group
        platforms.enableBody = true;
        cielo.enableBody = true;

        var fin=cielo.create(0,0,'cielo');
        fin.scale.setTo(2,1);

        // Here we create the ground.
        var ground = platforms.create(0, game.world.height - 64, 'ground');

        //  Scale it to fit the width of the game (the original sprite is 400x32 in size)
        ground.scale.setTo(2, 2);

        //  This stops it from falling away when you jump on it
        ground.body.immovable = true;

        //  Now let's create two ledges
        var ledge = platforms.create(300, 400, 'ground');
        ledge.body.immovable = true;

        ledge = platforms.create(-150, 250, 'ground');
        ledge.body.immovable = true;

        ledge = platforms.create(350, 150, 'ground2');
        ledge.body.immovable = true;

        // The player and its settings
        player = game.add.sprite(32, game.world.height - 150, 'dude');

        //  We need to enable physics on the player
        game.physics.arcade.enable(player);

        //  Player physics properties. Give the little guy a slight bounce.
        player.body.bounce.y = 0.2;
        player.body.gravity.y = 400;
        player.body.collideWorldBounds = true;

        //  Our two animations, walking left and right.
        player.animations.add('left', [0, 1, 2, 3], 10, true);
        player.animations.add('right', [5, 6, 7, 8], 10, true);

        //  Finally some stars to collect
        stars = game.add.group();

        //  We will enable physics for any star that is created in this group
        stars.enableBody = true;

        //  Here we'll create 12 of them evenly spaced apart
        for (var i = 0; i < 12; i++)
        {
            //  Create a star inside of the 'stars' group
            var star = stars.create(i * 70, 0, 'star');

            //  Let gravity do its thing
            star.body.gravity.y = 300;

            //  This just gives each star a slightly random bounce value
            star.body.bounce.y = 0.7 + Math.random() * 0.2;
        }

        //  The score
        scoreText = game.add.text(16, 16, 'score: 0', { fontSize: '32px', fill: '#000' });

        //  Our controls.
        cursors = game.input.keyboard.createCursorKeys();

    }

    function create1() {

        //  We're going to be using physics, so enable the Arcade Physics system
        game.physics.startSystem(Phaser.Physics.ARCADE);

        //  A simple background for our game
        game.add.sprite(0, 0, 'sky');

        //  The platforms group contains the ground and the 2 ledges we can jump on
        platforms = game.add.group();

        //  We will enable physics for any object that is created in this group
        platforms.enableBody = true;

        // Here we create the ground.
        var ground = platforms.create(0, game.world.height - 64, 'ground');

        //  Scale it to fit the width of the game (the original sprite is 400x32 in size)
        ground.scale.setTo(2, 2);

        //  This stops it from falling away when you jump on it
        ground.body.immovable = true;

        //  Now let's create two ledges
        var ledge = platforms.create(300, 400, 'ground');
        ledge.body.immovable = true;

        ledge = platforms.create(-150, 250, 'ground');
        ledge.body.immovable = true;

        ledge = platforms.create(350, 150, 'ground');
        ledge.body.immovable = true;

        // The player and its settings
        player = game.add.sprite(32, game.world.height - 150, 'dude');

        //  We need to enable physics on the player
        game.physics.arcade.enable(player);

        //  Player physics properties. Give the little guy a slight bounce.
        player.body.bounce.y = 0.2;
        player.body.gravity.y = 400;
        player.body.collideWorldBounds = true;

        //  Our two animations, walking left and right.
        player.animations.add('left', [0, 1, 2, 3], 10, true);
        player.animations.add('right', [5, 6, 7, 8], 10, true);

        //  Finally some stars to collect
        stars = game.add.group();

        //  We will enable physics for any star that is created in this group
        stars.enableBody = true;

        //  Here we'll create 12 of them evenly spaced apart
        for (var i = 0; i < 12; i++)
        {
            //  Create a star inside of the 'stars' group
            var star = stars.create(i * 70, 0, 'star');

            //  Let gravity do its thing
            star.body.gravity.y = 300;

            //  This just gives each star a slightly random bounce value
            star.body.bounce.y = 0.7 + Math.random() * 0.2;
        }

        //  The score
        scoreText = game.add.text(16, 16, 'score: 0', { fontSize: '32px', fill: '#000' });

        //  Our controls.
        cursors = game.input.keyboard.createCursorKeys();

    }

    function create2() {

        //  We're going to be using physics, so enable the Arcade Physics system
        game.physics.startSystem(Phaser.Physics.ARCADE);

        //  A simple background for our game
        game.add.sprite(0, 0, 'sky');

        //  The platforms group contains the ground and the 2 ledges we can jump on
        platforms = game.add.group();

        //  We will enable physics for any object that is created in this group
        platforms.enableBody = true;

        // Here we create the ground.
        var ground = platforms.create(0, game.world.height - 64, 'ground');

        //  Scale it to fit the width of the game (the original sprite is 400x32 in size)
        ground.scale.setTo(2, 2);

        //  This stops it from falling away when you jump on it
        ground.body.immovable = true;

        //  Now let's create two ledges
        var ledge = platforms.create(300, 400, 'ground');
        ledge.body.immovable = true;

        ledge = platforms.create(-150, 250, 'ground');
        ledge.body.immovable = true;

        ledge = platforms.create(350, 150, 'ground');
        ledge.body.immovable = true;

        // The player and its settings
        player = game.add.sprite(32, game.world.height - 150, 'dude');

        //  We need to enable physics on the player
        game.physics.arcade.enable(player);

        //  Player physics properties. Give the little guy a slight bounce.
        player.body.bounce.y = 0.2;
        player.body.gravity.y = 400;
        player.body.collideWorldBounds = true;

        //  Our two animations, walking left and right.
        player.animations.add('left', [0, 1, 2, 3], 10, true);
        player.animations.add('right', [5, 6, 7, 8], 10, true);

        //  Finally some stars to collect
        stars = game.add.group();

        //  We will enable physics for any star that is created in this group
        stars.enableBody = true;

        //  Here we'll create 12 of them evenly spaced apart
        for (var i = 0; i < 12; i++)
        {
            //  Create a star inside of the 'stars' group
            var star = stars.create(i * 70, 0, 'star');

            //  Let gravity do its thing
            star.body.gravity.y = 300;

            //  This just gives each star a slightly random bounce value
            star.body.bounce.y = 0.7 + Math.random() * 0.2;
        }

        //  The score
        scoreText = game.add.text(16, 16, 'score: 0', { fontSize: '32px', fill: '#000' });

        //  Our controls.
        cursors = game.input.keyboard.createCursorKeys();

    }

    function update() {

        //  Collide the player and the stars with the platforms
        game.physics.arcade.collide(player, platforms);
        game.physics.arcade.collide(stars, platforms);

        //  Checks to see if the player overlaps with any of the stars, if he does call the collectStar function
        game.physics.arcade.overlap(player, stars, collectStar, null, this);

        game.physics.arcade.overlap(player, cielo, terminaNivel, null, this);

        //  Reset the players velocity (movement)
        player.body.velocity.x = 0;

        if (cursors.left.isDown)
        {
            //  Move to the left
            player.body.velocity.x = -150;

            player.animations.play('left');
        }
        else if (cursors.right.isDown)
        {
            //  Move to the right
            player.body.velocity.x = 150;

            player.animations.play('right');
        }
        else
        {
            //  Stand still
            player.animations.stop();

            player.frame = 4;
        }

        //  Allow the player to jump if they are touching the ground.
        if (cursors.up.isDown && player.body.touching.down)
        {
            player.body.velocity.y = -350;
        }

    }

    function collectStar (player, star) {

        // Removes the star from the screen
        star.kill();

        //  Add and update the score
        player.vidas = player.vidas-1;
        scoreText.text = 'Vidas: ' + player.vidas;

        if(player.vidas<=0){
            scoreText.text = 'Has muerto';
        }

    }

    function terminaNivel (player, final) {

        //Llamar a nivel completado con el tiempo y las vidas
        //Matar al jugador
        console.log("NivelCompletado");

    }
<commit_msg>clase 13/10/2016 v2<commit_after>    var player;
    var platforms;
    var cursors;
    var cielo;

    var stars;
    var vidas = 5;
    var vidasText;
    var finText;
    var game;

    function crearNivel(nivel){

        switch(nivel) {
        case '0':
            game = new Phaser.Game(800, 600, Phaser.AUTO, 'juegoId', { preload: preload, create: create0, update: update });
            break;
        case '1':
            game = new Phaser.Game(800, 600, Phaser.AUTO, 'juegoId', { preload: preload, create: create1, update: update });
            break;
        case '2':
            game = new Phaser.Game(800, 600, Phaser.AUTO, 'juegoId', { preload: preload, create: create2, update: update });
            break;
        default: noHayNiveles();
            break;
}

    }

    function preload() {

        game.load.image('sky', 'assets/sky.png');
        game.load.image('ground', 'assets/platform.png');
        game.load.image('ground2', 'assets/platform2.png');
        game.load.image('star', 'assets/star.png');
        game.load.image('cielo', 'assets/heaven.png');

        game.load.spritesheet('dude', 'assets/dude.png', 32, 48);

    }

    function create0() {

        //  We're going to be using physics, so enable the Arcade Physics system
        game.physics.startSystem(Phaser.Physics.ARCADE);

        //  A simple background for our game
        game.add.sprite(0, 0, 'sky');

        //  The platforms group contains the ground and the 2 ledges we can jump on
        platforms = game.add.group();
        cielo = game.add.group();
        //  We will enable physics for any object that is created in this group
        platforms.enableBody = true;
        cielo.enableBody = true;

        var fin=cielo.create(0,0,'cielo');
        fin.scale.setTo(2,1);

        // Here we create the ground.
        var ground = platforms.create(0, game.world.height - 64, 'ground');

        //  Scale it to fit the width of the game (the original sprite is 400x32 in size)
        ground.scale.setTo(2, 2);

        //  This stops it from falling away when you jump on it
        ground.body.immovable = true;

        //  Now let's create two ledges
        var ledge = platforms.create(300, 400, 'ground');
        ledge.body.immovable = true;

        ledge = platforms.create(-150, 250, 'ground');
        ledge.body.immovable = true;

        ledge = platforms.create(350, 150, 'ground2');
        ledge.body.immovable = true;

        // The player and its settings
        player = game.add.sprite(32, game.world.height - 150, 'dude');

        //  We need to enable physics on the player
        game.physics.arcade.enable(player);

        //  Player physics properties. Give the little guy a slight bounce.
        player.body.bounce.y = 0.2;
        player.body.gravity.y = 400;
        player.body.collideWorldBounds = true;

        //  Our two animations, walking left and right.
        player.animations.add('left', [0, 1, 2, 3], 10, true);
        player.animations.add('right', [5, 6, 7, 8], 10, true);

        //  Finally some stars to collect
        stars = game.add.group();

        //  We will enable physics for any star that is created in this group
        stars.enableBody = true;

        //  Here we'll create 12 of them evenly spaced apart
        for (var i = 0; i < 12; i++)
        {
            //  Create a star inside of the 'stars' group
            var star = stars.create(i * 70, 0, 'star');

            //  Let gravity do its thing
            star.body.gravity.y = 300;

            //  This just gives each star a slightly random bounce value
            star.body.bounce.y = 0.7 + Math.random() * 0.2;
        }

        //  The vidas
        vidasText = game.add.text(16, 16, 'vidas: ' +vidas, { fontSize: '32px', fill: '#fff' });
        finText = game.add.text(200, 200, '', { fontSize: '60px', fill: '#fff'});

        //  Our controls.
        cursors = game.input.keyboard.createCursorKeys();

    }

    function update() {

        //  Collide the player and the stars with the platforms
        game.physics.arcade.collide(player, platforms);
        game.physics.arcade.collide(stars, platforms);

        //  Checks to see if the player overlaps with any of the stars, if he does call the collectStar function
        game.physics.arcade.overlap(player, stars, collectStar, null, this);

        game.physics.arcade.overlap(player, cielo, terminaNivel, null, this);

        //  Reset the players velocity (movement)
        player.body.velocity.x = 0;

        if (cursors.left.isDown)
        {
            //  Move to the left
            player.body.velocity.x = -150;

            player.animations.play('left');
        }
        else if (cursors.right.isDown)
        {
            //  Move to the right
            player.body.velocity.x = 150;

            player.animations.play('right');
        }
        else
        {
            //  Stand still
            player.animations.stop();

            player.frame = 4;
        }

        //  Allow the player to jump if they are touching the ground.
        if (cursors.up.isDown && player.body.touching.down)
        {
            player.body.velocity.y = -350;
        }

    }

    function collectStar (player, star) {

        // Removes the star from the screen
        star.kill();

        //  Add and update the vidas
        vidas = vidas-1;
        vidasText.text = 'vidas: ' + vidas;

        if(vidas<=0){
            vidasText.text ='';
            finText.text = '¡¡Has muerto!!';
        }

    }

    function terminaNivel (player, final) {

        //Llamar a nivel completado con el tiempo y las vidas
        //Matar al jugador
        console.log("NivelCompletado");

    }
<|endoftext|>


<commit_before>'use strict';

var gulp = require('gulp'),
    gutil = require('gulp-util'),
    config = require('../config').sass,
    stylelint = require('gulp-stylelint');

gulp.task('stylelint', function() {
  return gulp
    .src(config.src)
    .on('error', gutil.log)
    .pipe(stylelint({
      failAfterError: false,
      reporters: [{
        formatter: 'string',
        console: true
      }]
    }));
});
<commit_msg>Fail the build if stylelint errors<commit_after>'use strict';

var gulp = require('gulp'),
    gulpif = require('gulp-if'),
    gutil = require('gulp-util'),
    config = require('../config').sass,
    plumber = require('gulp-plumber'),
    stylelint = require('gulp-stylelint');

gulp.task('stylelint', function() {
  var env   = global.runmode,
      isDev = (env === 'dev');

  return gulp
    .src(config.src)
    .pipe(gulpif(isDev, plumber(function(error) {
      gutil.log(gutil.colors.red(error.message));
      this.emit('end');
    })))
    .pipe(stylelint({
      failAfterError: !isDev,
      reporters: [{
        formatter: 'string',
        console: true
      }]
    }));
});
<|endoftext|>


<commit_before>/// <binding BeforeBuild='moveToLibs, sass, typescript' Clean='clean' ProjectOpened='sass:watch, watch:ts' />
var gulp = require('gulp'),
    ts = require('gulp-typescript'),
    dest = require('gulp-dest'),
    sass = require('gulp-sass'),
    merge = require('merge2'),
    del = require('del'),
    tsProject = ts.createProject('tsconfig.json'),
    paths = {
        target: {
            webroot: 'wwwroot',
            js: 'wwwroot/js',
            css: 'wwwroot/css',
            lib: 'wwwroot/lib'
        },
        source: {
            typescript: 'App/**/*.ts',
            packages: [
                '@angular/core/bundles',
                '@angular/compiler/bundles',
                '@angular/common/bundles',
                '@angular/platform-browser/bundles',
                '@angular/forms/bundles',
                '@angular/http/bundles',
                '@angular/router/bundles',
                '@angular/platform-browser-dynamic/bundles',
                'systemjs',
                'reflect-metadata',
                'rxjs',
                'zone.js'
            ],
            sass: [
                'CSS/home.scss'
            ]
        }
    };

gulp.task('typescript', function () {
    var result = gulp.src(paths.source.typescript)
        .pipe(tsProject());

    return result.js.pipe(gulp.dest(paths.target.js));
});
gulp.task('watch:ts', ['typescript'], function () {
    gulp.watch(paths.source.typescript, ['typescript']);
});

gulp.task('sass', function () {
    return gulp.src(paths.source.sass)
        .pipe(sass().on('error', sass.logError))
        .pipe(gulp.dest(paths.target.css));
});
gulp.task('sass:watch', function () {
    gulp.watch(paths.sass, ['sass']);
});

gulp.task('moveToLibs', function () {
    var merges = [];
    for (var i = 0; i < paths.source.packages.length; i++) {
        var to = paths.source.packages[i].replace('@', '');
        merges.push(gulp.src('node_modules/' + paths.source.packages[i] + '/**/*.js').pipe(gulp.dest(paths.target.lib + '/' + to)));
        merges.push(gulp.src('node_modules/' + paths.source.packages[i] + '/**/*.min.js').pipe(gulp.dest(paths.target.lib + '/' + to)));
    }
    return merge(merges);
});

gulp.task('clean', function () {
    return del([paths.target.lib + '/*', paths.target.js + '/*', paths.target.css + '/*']);
})<commit_msg>Fix issue where gulp watch sass was not looking at correct files.<commit_after>/// <binding BeforeBuild='moveToLibs, sass, typescript' Clean='clean' ProjectOpened='sass:watch, watch:ts' />
var gulp = require('gulp'),
    ts = require('gulp-typescript'),
    dest = require('gulp-dest'),
    sass = require('gulp-sass'),
    merge = require('merge2'),
    del = require('del'),
    tsProject = ts.createProject('tsconfig.json'),
    paths = {
        target: {
            webroot: 'wwwroot',
            js: 'wwwroot/js',
            css: 'wwwroot/css',
            lib: 'wwwroot/lib'
        },
        source: {
            typescript: 'App/**/*.ts',
            packages: [
                '@angular/core/bundles',
                '@angular/compiler/bundles',
                '@angular/common/bundles',
                '@angular/platform-browser/bundles',
                '@angular/forms/bundles',
                '@angular/http/bundles',
                '@angular/router/bundles',
                '@angular/platform-browser-dynamic/bundles',
                'systemjs',
                'reflect-metadata',
                'rxjs',
                'zone.js'
            ],
            sass: [
                'CSS/home.scss'
            ]
        }
    };

gulp.task('typescript', function () {
    var result = gulp.src(paths.source.typescript)
        .pipe(tsProject());

    return result.js.pipe(gulp.dest(paths.target.js));
});
gulp.task('watch:ts', ['typescript'], function () {
    gulp.watch(paths.source.typescript, ['typescript']);
});

gulp.task('sass', function () {
    return gulp.src(paths.source.sass)
        .pipe(sass().on('error', sass.logError))
        .pipe(gulp.dest(paths.target.css));
});
gulp.task('sass:watch', function () {
    gulp.watch(paths.source.sass, ['sass']);
});

gulp.task('moveToLibs', function () {
    var merges = [];
    for (var i = 0; i < paths.source.packages.length; i++) {
        var to = paths.source.packages[i].replace('@', '');
        merges.push(gulp.src('node_modules/' + paths.source.packages[i] + '/**/*.js').pipe(gulp.dest(paths.target.lib + '/' + to)));
        merges.push(gulp.src('node_modules/' + paths.source.packages[i] + '/**/*.min.js').pipe(gulp.dest(paths.target.lib + '/' + to)));
    }
    return merge(merges);
});

gulp.task('clean', function () {
    return del([paths.target.lib + '/*', paths.target.js + '/*', paths.target.css + '/*']);
})<|endoftext|>


<commit_before>  var down = function () {
    $("#plane").animate({
      top: "-=10",
    }, 3000)
  };

  var up = function () {
    $("#plane").animate({
      top: "+=10",
    }, 3000)
  };

  var turbulance = function () {
    up();
    down();
    console.log("called method ")
  };

$(document).ready(function(){

  // when page loads plane flys in from the right of the page and then images will appear in the windows

  //top right corner of the image going to be x, y 0
  $("#plane").animate({
    right: "+=800",
  }, 3000, function(){
    // setInterval(turbulance, 1000);
  })

});
<commit_msg>Uncomment turbulance method and add animation to windows<commit_after>  var down = function () {
    $("#plane").animate({
      top: "-=10",
    }, 3000)
  };

  var up = function () {
    $("#plane").animate({
      top: "+=10",
    }, 3000)
  };

  var turbulance = function () {
    up();
    down();
    console.log("called method ")
  };

$(document).ready(function(){

  // when page loads plane flys in from the right of the page and then images will appear in the windows

  //top right corner of the image going to be x, y 0
  $("#plane").animate({
    right: "+=800",
  }, 3000, function(){
    setInterval(turbulance, 1000);
  })

  $("#window-container").animate({
    right: "+=900",
  }, 3000, function(){
    // setInterval(turbulance, 1000);
  })

});
<|endoftext|>


<commit_before>/*
 * flipsnap.js
 *
 * @version  0.1.0
 *
 */

(function(window) {

var d = window.document,
	support = {
		transform3d: ('WebKitCSSMatrix' in window && 'm11' in new WebKitCSSMatrix()),
		touch: ('ontouchstart' in window)
	},
	touchStartEvent =  support.touch ? 'touchstart' : 'mousedown',
	touchMoveEvent =  support.touch ? 'touchmove' : 'mousemove',
	touchEndEvent =  support.touch ? 'touchend' : 'mouseup';

var Flipsnap = function(element, conf) {
	return (this instanceof Flipsnap)
		? this.init(element, conf)
		: new Flipsnap(element, conf);
};

Flipsnap.prototype = {
	init: function(element, conf) {
		var self = this;

		self.element = element;
		if (typeof element === 'string') {
			self.element = d.querySelector(element);
		}
		self.element.style.webkitTransitionProperty = '-webkit-transform';
		self.element.style.webkitTransitionTimingFunction = 'cubic-bezier(0,0,0.25,1)';
		self.element.style.webkitTransitionDuration = '0';
		self.element.style.webkitTransform = getTranslate(0);

		self.conf = conf || {};
		self.ontouchend = self.conf.ontouchend || function() {};
		self.enabled = true;
		self.currentPoint = 0;
		self.currentX = 0;

		self.refresh();

		self.element.addEventListener(touchStartEvent, self, false);
		self.element.addEventListener(touchMoveEvent, self, false);
		self.element.addEventListener(touchEndEvent, self, false);

		return self;
	},
	handleEvent: function(event) {
		var self = this;

		switch (event.type) {
			case touchStartEvent:
				self._touchStart(event);
				break;
			case touchMoveEvent:
				self._touchMove(event);
				break;
			case touchEndEvent:
				self._touchEnd(event);
				break;
		}
	},
	refresh: function() {
		var self = this;

		var conf = self.conf;

		// setting max point
		self.maxPoint = conf.point ? conf.point : (function() {
			var childNodes = self.element.childNodes,
				itemLength = 0,
				i = 0,
				len = childNodes.length,
				node;
			for(; i < len; i++) {
				node = childNodes[i];
				if (node.nodeType === 1) {
					itemLength++;
				}
			}

			return itemLength - 1;
		})();
		if (self.maxPoint < 0) {
			self.maxPoint = 0;
		}

		// setting distance
		self.distance = conf.distance ? conf.distance : (function() {
			return self.element.scrollWidth / (self.maxPoint + 1);
		})();

		// setting
		self.maxX = conf.maxX ? - conf.maxX : (function() {
			return - self.distance * self.maxPoint;
		})();

		if (self.currentX < self.maxX) {
			self._setX(self.maxX);
		}
	},
	_setX: function(x) {
		var self = this;

		self.currentX = x;
		self.element.style.webkitTransform = getTranslate(x);
	},
	_touchStart: function(event) {
		var self = this;

		if (!self.enabled) {
			return;
		}

		if (!support.touch) {
			event.preventDefault();
		}

		self.element.style.webkitTransitionDuration = '0';
		self.scrolling = true;
		self.moveReady = false;
		self.startPageX = getPage(event, 'pageX');
		self.startPageY = getPage(event, 'pageY');
		self.basePageX = self.startPageX;
		self.directionX = 0;
	},
	_touchMove: function(event) {
		var self = this;

		if (!self.scrolling) {
			return;
		}

		var pageX = getPage(event, 'pageX'),
			pageY = getPage(event, 'pageY'),
			distX,
			newX,
			deltaX,
			deltaY;

		if (self.moveReady) {
			event.preventDefault();
			event.stopPropagation();

			distX = pageX - self.basePageX;
			newX = self.currentX + distX;
			if (newX >= 0 || newX < self.maxX) {
				newX = Math.round(self.currentX + distX / 3);
			}
			self._setX(newX);

			self.directionX = distX > 0 ? -1 : 1;
		}
		else {
			deltaX = Math.abs(pageX - self.startPageX);
			deltaY = Math.abs(pageY - self.startPageY);
			if (deltaY > 5) {
				self.scrolling = false;
			}
			else if (deltaX > 5) {
				self.moveReady = true;
			}
		}

		self.basePageX = pageX;
	},
	_touchEnd: function(event) {
		var self = this;

		if (!this.scrolling) {
			return;
		}

		self.scrolling = false;

		var newPoint = -self.currentX / self.distance,
			newX;

		// to int
		newPoint =
			(self.directionX > 0) ? Math.ceil(newPoint) :
			(self.directionX < 0) ? Math.floor(newPoint) :
			Math.round(newPoint);

		self.currentPoint = -newPoint;
		newX = -newPoint * self.distance;

		if (newX > 0) {
			newX = self.currentPoint = 0;
		} else if (newX < self.maxX) {
			self.currentPoint = self.maxPoint;
			newX = self.maxX;
		}

		self.element.style.webkitTransitionDuration = '350ms';
		self._setX(newX);

		self.ontouchend();
	},
	destroy: function() {
		var self = this;

		self.element.removeEventListener(touchStartEvent, self);
		self.element.removeEventListener(touchMoveEvent, self);
		self.element.removeEventListener(touchEndEvent, self);
	}
};

function getTranslate(x) {
	return support.transform3d
		? 'translate3d(' + x + 'px, 0, 0)'
		: 'translate(' + x + 'px, 0)';
}

function getPage(event, page) {
	return support.touch ? event.changedTouches[0][page] : event[page];
}

window.Flipsnap = Flipsnap;

})(this);
<commit_msg>fix, currentPoint sign<commit_after>/*
 * flipsnap.js
 *
 * @version  0.1.0
 *
 */

(function(window) {

var d = window.document,
	support = {
		transform3d: ('WebKitCSSMatrix' in window && 'm11' in new WebKitCSSMatrix()),
		touch: ('ontouchstart' in window)
	},
	touchStartEvent =  support.touch ? 'touchstart' : 'mousedown',
	touchMoveEvent =  support.touch ? 'touchmove' : 'mousemove',
	touchEndEvent =  support.touch ? 'touchend' : 'mouseup';

var Flipsnap = function(element, conf) {
	return (this instanceof Flipsnap)
		? this.init(element, conf)
		: new Flipsnap(element, conf);
};

Flipsnap.prototype = {
	init: function(element, conf) {
		var self = this;

		self.element = element;
		if (typeof element === 'string') {
			self.element = d.querySelector(element);
		}
		self.element.style.webkitTransitionProperty = '-webkit-transform';
		self.element.style.webkitTransitionTimingFunction = 'cubic-bezier(0,0,0.25,1)';
		self.element.style.webkitTransitionDuration = '0';
		self.element.style.webkitTransform = getTranslate(0);

		self.conf = conf || {};
		self.ontouchend = self.conf.ontouchend || function() {};
		self.enabled = true;
		self.currentPoint = 0;
		self.currentX = 0;

		self.refresh();

		self.element.addEventListener(touchStartEvent, self, false);
		self.element.addEventListener(touchMoveEvent, self, false);
		self.element.addEventListener(touchEndEvent, self, false);

		return self;
	},
	handleEvent: function(event) {
		var self = this;

		switch (event.type) {
			case touchStartEvent:
				self._touchStart(event);
				break;
			case touchMoveEvent:
				self._touchMove(event);
				break;
			case touchEndEvent:
				self._touchEnd(event);
				break;
		}
	},
	refresh: function() {
		var self = this;

		var conf = self.conf;

		// setting max point
		self.maxPoint = conf.point ? conf.point : (function() {
			var childNodes = self.element.childNodes,
				itemLength = 0,
				i = 0,
				len = childNodes.length,
				node;
			for(; i < len; i++) {
				node = childNodes[i];
				if (node.nodeType === 1) {
					itemLength++;
				}
			}

			return itemLength - 1;
		})();
		if (self.maxPoint < 0) {
			self.maxPoint = 0;
		}

		// setting distance
		self.distance = conf.distance ? conf.distance : (function() {
			return self.element.scrollWidth / (self.maxPoint + 1);
		})();

		// setting
		self.maxX = conf.maxX ? - conf.maxX : (function() {
			return - self.distance * self.maxPoint;
		})();

		if (self.currentX < self.maxX) {
			self._setX(self.maxX);
		}
	},
	_setX: function(x) {
		var self = this;

		self.currentX = x;
		self.element.style.webkitTransform = getTranslate(x);
	},
	_touchStart: function(event) {
		var self = this;

		if (!self.enabled) {
			return;
		}

		if (!support.touch) {
			event.preventDefault();
		}

		self.element.style.webkitTransitionDuration = '0';
		self.scrolling = true;
		self.moveReady = false;
		self.startPageX = getPage(event, 'pageX');
		self.startPageY = getPage(event, 'pageY');
		self.basePageX = self.startPageX;
		self.directionX = 0;
	},
	_touchMove: function(event) {
		var self = this;

		if (!self.scrolling) {
			return;
		}

		var pageX = getPage(event, 'pageX'),
			pageY = getPage(event, 'pageY'),
			distX,
			newX,
			deltaX,
			deltaY;

		if (self.moveReady) {
			event.preventDefault();
			event.stopPropagation();

			distX = pageX - self.basePageX;
			newX = self.currentX + distX;
			if (newX >= 0 || newX < self.maxX) {
				newX = Math.round(self.currentX + distX / 3);
			}
			self._setX(newX);

			self.directionX = distX > 0 ? -1 : 1;
		}
		else {
			deltaX = Math.abs(pageX - self.startPageX);
			deltaY = Math.abs(pageY - self.startPageY);
			if (deltaY > 5) {
				self.scrolling = false;
			}
			else if (deltaX > 5) {
				self.moveReady = true;
			}
		}

		self.basePageX = pageX;
	},
	_touchEnd: function(event) {
		var self = this;

		if (!this.scrolling) {
			return;
		}

		self.scrolling = false;

		var newPoint = -self.currentX / self.distance,
			newX;

		// to int
		newPoint =
			(self.directionX > 0) ? Math.ceil(newPoint) :
			(self.directionX < 0) ? Math.floor(newPoint) :
			Math.round(newPoint);

		self.currentPoint = newPoint;
		newX = -newPoint * self.distance;

		if (newX > 0) {
			newX = self.currentPoint = 0;
		} else if (newX < self.maxX) {
			self.currentPoint = self.maxPoint;
			newX = self.maxX;
		}

		self.element.style.webkitTransitionDuration = '350ms';
		self._setX(newX);

		self.ontouchend();
	},
	destroy: function() {
		var self = this;

		self.element.removeEventListener(touchStartEvent, self);
		self.element.removeEventListener(touchMoveEvent, self);
		self.element.removeEventListener(touchEndEvent, self);
	}
};

function getTranslate(x) {
	return support.transform3d
		? 'translate3d(' + x + 'px, 0, 0)'
		: 'translate(' + x + 'px, 0)';
}

function getPage(event, page) {
	return support.touch ? event.changedTouches[0][page] : event[page];
}

window.Flipsnap = Flipsnap;

})(this);
<|endoftext|>


<commit_before>/* global MainGame */

// shows FirstName, LastName, Health, Edu, Shelter
var PeopleRightView={
	style: {font:"30px myKaiti", fill:"black"},
	createNew: function(data){
		var v=MainGame.game.make.sprite(0,0,"peopleViewRightBg");
		// name, health, edu, shelter
		v.data=JSON.parse(JSON.stringify(data));
		// ListView: 10 items (slots)
			// createNew(textures, margin, itemSize, itemCallback, isHorizontal)
		v.listView=DListView.createNew(
			{},
			{},
			{w:400, h:45},
			function(index){PeopleRightView.onPersonSelected(v,index)}
		);
		v.addChild(v.listView);
		// PageIndicator: N pages
		var pageCount=Math.ceil(data.length/10);
		v.pageIndicator=DPageIndicator.createNew(
			pageCount,
			{width:400,textPos:{x:200,y:0}},
			function(index){PeopleRightView.onPageChanged(v,index)}
		);
		v.pageIndicator.y=440;
		v.addChild(v.pageIndicator);
		// setup the init page
		PeopleRightView._setupPage_(v,0);
		return v;
	},
	onPersonSelected: function(view,index){
		console.log("PeopleRightView: person selected:",index);
		// TODO: center the person's housing unit
	},
	onPageChanged: function(view,index){
		console.log("PeoplePageChanged: ",index);
		PeopleRightView._setupPage_(view,index);
	},
	_makeEntry_: function(oneEntryData){
		var entrySprite=MainGame.game.make.sprite(0,0);
		var entryString=""+oneEntryData.name+" | Hth:"+oneEntryData.health+" | Edu:"
			+oneEntryData.edu+" | Sht:"+oneEntryData.shelter;
		var entryText=MainGame.game.make.text(0,0,entryString,PeopleRightView.style);
		entrySprite.addChild(entryText);
		return entrySprite;
	},
	_setupPage_: function(view,pageIndex){
		view.listView.removeAll();
		var startIndex=pageIndex*10;
		var endIndex=Math.min(startIndex+10,view.data.length);
		for(var i=startIndex;i<endIndex;i++)
			view.listView.add(PeopleRightView._makeEntry_(view.data[i]));
	},
};

var PeopleView={
	createNew: function(){
		var pv=MainGame.game.add.sprite(0,0,'peopleViewBg');
		pv.x=100, pv.y=100;

		// create low people view (right)
			// create low people data
		var lowData=[
		{name:"Sam Reha",health:50,edu:50,shelter:50},
		{name:"A Math",health:20,edu:50,shelter:50},
		{name:"B Dee",health:30,edu:50,shelter:50},
		{name:"C Eee",health:40,edu:50,shelter:50},
		{name:"D FFF",health:50,edu:50,shelter:50},
		{name:"Sam2",health:50,edu:50,shelter:50},
		{name:"A2 Math",health:20,edu:50,shelter:50},
		{name:"B2 Dee",health:30,edu:50,shelter:50},
		{name:"C2 Eee",health:40,edu:50,shelter:50},
		{name:"D2 FFF",health:50,edu:50,shelter:50},
		{name:"Sam3Reha",health:50,edu:50,shelter:50},
		{name:"A3Math",health:20,edu:50,shelter:50},
		{name:"B Dee",health:30,edu:50,shelter:50},
		{name:"C3 ee",health:40,edu:50,shelter:50},
		{name:"D3FFF",health:50,edu:50,shelter:50},
		{name:"Sa4 Reha",health:50,edu:50,shelter:50},
		{name:"A4Math",health:20,edu:50,shelter:50},
		{name:"B4Dee",health:30,edu:50,shelter:50},
		{name:"C4Eee",health:40,edu:50,shelter:50},
		{name:"D4FFF",health:50,edu:50,shelter:50},
		];

		pv.right=PeopleRightView.createNew(lowData);
		pv.right.x=450, pv.right.y=0;
		// TBD: set a precise x
		pv.addChild(pv.right);

		// Class funcs
		pv.setVisible=function(value){pv.visible=value};

		return pv;
	},
};
<commit_msg>use itemsPerPage in PeopleView.js<commit_after>/* global MainGame */

// change item per page here!
var itemsPerPage=10;

// shows FirstName, LastName, Health, Edu, Shelter
var PeopleRightView={
	style: {font:"30px myKaiti", fill:"black"},
	createNew: function(data){
		var v=MainGame.game.make.sprite(0,0,"peopleViewRightBg");
		// name, health, edu, shelter
		v.data=JSON.parse(JSON.stringify(data));
		// ListView: [itemsPerPage] items (slots)
			// createNew(textures, margin, itemSize, itemCallback, isHorizontal)
		v.listView=DListView.createNew(
			{},
			{},
			{w:400, h:45},
			function(index){PeopleRightView.onPersonSelected(v,index)}
		);
		v.addChild(v.listView);
		// PageIndicator: N pages
		var pageCount=Math.ceil(data.length/itemsPerPage);
		v.pageIndicator=DPageIndicator.createNew(
			pageCount,
			{width:400,textPos:{x:200,y:0}},
			function(index){PeopleRightView.onPageChanged(v,index)}
		);
		v.pageIndicator.y=440;
		v.addChild(v.pageIndicator);
		// setup the init page
		PeopleRightView._setupPage_(v,0);
		return v;
	},
	onPersonSelected: function(view,index){
		var globalIndex=view.pageIndicator.curPage*itemsPerPage+index;
		console.log("PeopleRightView: person selected:",globalIndex);
		// TODO: center the person's housing unit
	},
	onPageChanged: function(view,index){
		console.log("PeoplePageChanged: ",index);
		PeopleRightView._setupPage_(view,index);
	},
	_makeEntry_: function(oneEntryData){
		var entrySprite=MainGame.game.make.sprite(0,0);
		var entryString=""+oneEntryData.name+" | Hth:"+oneEntryData.health+" | Edu:"
			+oneEntryData.edu+" | Sht:"+oneEntryData.shelter;
		var entryText=MainGame.game.make.text(0,0,entryString,PeopleRightView.style);
		entrySprite.addChild(entryText);
		return entrySprite;
	},
	_setupPage_: function(view,pageIndex){
		view.listView.removeAll();
		var startIndex=pageIndex*itemsPerPage;
		var endIndex=Math.min(startIndex+itemsPerPage,view.data.length);
		for(var i=startIndex;i<endIndex;i++)
			view.listView.add(PeopleRightView._makeEntry_(view.data[i]));
	},
};

var PeopleView={
	createNew: function(){
		var pv=MainGame.game.add.sprite(0,0,'peopleViewBg');
		pv.x=100, pv.y=100;

		// create low people view (right)
			// create low people data
		var lowData=[
		{name:"Sam Reha",health:50,edu:50,shelter:50},
		{name:"A Math",health:20,edu:50,shelter:50},
		{name:"B Dee",health:30,edu:50,shelter:50},
		{name:"C Eee",health:40,edu:50,shelter:50},
		{name:"D FFF",health:50,edu:50,shelter:50},
		{name:"Sam2",health:50,edu:50,shelter:50},
		{name:"A2 Math",health:20,edu:50,shelter:50},
		{name:"B2 Dee",health:30,edu:50,shelter:50},
		{name:"C2 Eee",health:40,edu:50,shelter:50},
		{name:"D2 FFF",health:50,edu:50,shelter:50},
		{name:"Sam3Reha",health:50,edu:50,shelter:50},
		{name:"A3Math",health:20,edu:50,shelter:50},
		{name:"B Dee",health:30,edu:50,shelter:50},
		{name:"C3 ee",health:40,edu:50,shelter:50},
		{name:"D3FFF",health:50,edu:50,shelter:50},
		{name:"Sa4 Reha",health:50,edu:50,shelter:50},
		{name:"A4Math",health:20,edu:50,shelter:50},
		{name:"B4Dee",health:30,edu:50,shelter:50},
		{name:"C4Eee",health:40,edu:50,shelter:50},
		{name:"D4FFF",health:50,edu:50,shelter:50},
		{name:"Json File",health:50,edu:50,shelter:10},
		];

		pv.right=PeopleRightView.createNew(lowData);
		pv.right.x=450, pv.right.y=0;
		// TBD: set a precise x
		pv.addChild(pv.right);

		// Class funcs
		pv.setVisible=function(value){pv.visible=value};

		return pv;
	},
};
<|endoftext|>


<commit_before>$(function() {

  var ACE_FILES_PATH = '/assets/ace/';
  var THEME = 'ace/theme/textmate';

  var active_file = undefined;

  var showFirstFile = function() {
    var frame = $('.frame[data-role="main_file"]').isPresent() ? $('.frame[data-role="main_file"]') : $('.frame').first();
    var file_id = frame.find('.editor').data('file-id');
    $('#files').jstree().select_node(file_id);
    showFrame(frame);
  };

  var showFrame = function(frame) {
    $('.frame').hide();
    frame.show();
  };

  var initializeFileTree = function() {
    $('#files').jstree($('#files').data('entries'));
    $('#files').on('click', 'li.jstree-leaf', function() {
      active_file = {
        filename: $(this).text(),
        id: parseInt($(this).attr('id'))
      };
      var frame = $('[data-file-id="' + active_file.id + '"]').parent();
      showFrame(frame);
    });
  };

  if ($.isController('exercises') && $('#timeline').isPresent()) {

    _.each(['modePath', 'themePath', 'workerPath'], function(attribute) {
      ace.config.set(attribute, ACE_FILES_PATH);
    });

    var editors = $('.editor');
    var slider = $('#slider>input');
    var submissions = $('#data').data('submissions');
    var files = $('#data').data('files');

    editors.each(function(index, element) {
      currentEditor = ace.edit(element);

      var file_id = $(element).data('file-id');
      var content = $('.editor-content[data-file-id=' + file_id + ']');

      currentEditor.setShowPrintMargin(false);
      currentEditor.setTheme(THEME);
      currentEditor.$blockScrolling = Infinity;
      currentEditor.setReadOnly(true);

      var session = currentEditor.getSession();
      session.setMode($(element).data('mode'));
      session.setTabSize($(element).data('indent-size'));
      session.setUseSoftTabs(true);
      session.setUseWrapMode(true);
      session.setValue(content.text());
    });

    slider.on('change', function(event) {
      var currentSubmission = slider.val();
      var currentFiles = files[currentSubmission];

      editors.each(function(index, editor) {
        currentEditor = ace.edit(editor);
        fileContent = "";
        if (currentFiles[index]) {
          fileContent = currentFiles[index].content
        }
        currentEditor.getSession().setValue(fileContent);
      });
    });

    initializeFileTree();
    showFirstFile();
  }

});
<commit_msg>Change file tree when changing submission<commit_after>$(function() {

  var ACE_FILES_PATH = '/assets/ace/';
  var THEME = 'ace/theme/textmate';

  var currentSubmission = 0;
  var active_file = undefined;
  var fileTrees = []

  var showFirstFile = function() {
    var frame = $('.frame[data-role="main_file"]').isPresent() ? $('.frame[data-role="main_file"]') : $('.frame').first();
    var file_id = frame.find('.editor').data('file-id');
    $(fileTrees[currentSubmission]).jstree().select_node(file_id);
    showFrame(frame);
    showFileTree(currentSubmission);
  };

  var showFrame = function(frame) {
    $('.frame').hide();
    frame.show();
  };

  var initializeFileTree = function() {
    $('.files').each(function(index, element) {
      fileTree = $(element).jstree($(element).data('entries'));
      fileTree.on('click', 'li.jstree-leaf', function() {
        active_file = {
          filename: $(this).text(),
          id: parseInt($(this).attr('id'))
        };
        var frame = $('[data-file-id="' + active_file.id + '"]').parent();
        showFrame(frame);
      });
      fileTrees.push(fileTree);
    });
  };

  var showFileTree = function(index) {
    $('.files').hide();
    $(fileTrees[index].context).show();
  }

  if ($.isController('exercises') && $('#timeline').isPresent()) {

    _.each(['modePath', 'themePath', 'workerPath'], function(attribute) {
      ace.config.set(attribute, ACE_FILES_PATH);
    });

    var editors = $('.editor');
    var slider = $('#slider>input');
    var submissions = $('#data').data('submissions');
    var files = $('#data').data('files');

    editors.each(function(index, element) {
      currentEditor = ace.edit(element);

      var file_id = $(element).data('file-id');
      var content = $('.editor-content[data-file-id=' + file_id + ']');

      currentEditor.setShowPrintMargin(false);
      currentEditor.setTheme(THEME);
      currentEditor.$blockScrolling = Infinity;
      currentEditor.setReadOnly(true);

      var session = currentEditor.getSession();
      session.setMode($(element).data('mode'));
      session.setTabSize($(element).data('indent-size'));
      session.setUseSoftTabs(true);
      session.setUseWrapMode(true);
      session.setValue(content.text());
    });

    slider.on('change', function(event) {
      currentSubmission = slider.val();
      showFileTree(currentSubmission);
      var currentFiles = files[currentSubmission];

      editors.each(function(index, editor) {
        currentEditor = ace.edit(editor);
        fileContent = "";
        if (currentFiles[index]) {
          fileContent = currentFiles[index].content
        }
        currentEditor.getSession().setValue(fileContent);
      });
    });

    initializeFileTree();
    showFirstFile();
  }

});
<|endoftext|>


<commit_before>import React from 'react';
import { Navbar, NavItem, Nav, Jumbotron, Button, Input} from 'react-bootstrap';

import {
    BrowserRouter as Router,
    Route,
    Link,
    Redirect,
    Switch,
    NavLink
} from 'react-router-dom';
import IssueReports from './IssueReports.js';

class  IssueTrackerNav extends React.Component {
    constructor(props) {
        super(props);

     this.state = {
      redirectToMenu: false,
    };
  }

render(){

  return (

         <Navbar>

          <NavItem>
            <NavLink activeClassName='active' to='/menu/BugTracking'>Issue</NavLink>
          </NavItem>
          <NavItem>
            <NavLink activeClassName='active' to='/menu/IssueReports'>Reports</NavLink>
          </NavItem>
          <NavItem>
            <NavLink activeClassName='active' to='/menu/NewIssue'>Create New Issue</NavLink>
          </NavItem>

        </Navbar>

 );
}
}

export default IssueTrackerNav;
<commit_msg>fixing redirect<commit_after>import React from 'react';
import { Navbar, NavItem, Nav, Jumbotron, Button, Input} from 'react-bootstrap';

import {
    BrowserRouter as Router,
    Route,
    Link,
    Redirect,
    Switch,
    NavLink
} from 'react-router-dom';
import IssueReports from './IssueReports.js';

class  IssueTrackerNav extends React.Component {
    constructor(props) {
        super(props);

     this.state = {
      redirectToMenu: false,
    };
  }

render(){

  return (

         <Navbar>

          <NavItem>
            <NavLink activeClassName='active' to='/menu/IssueTracker'>Issue</NavLink>
          </NavItem>
          <NavItem>
            <NavLink activeClassName='active' to='/menu/IssueReports'>Reports</NavLink>
          </NavItem>
          <NavItem>
            <NavLink activeClassName='active' to='/menu/NewIssue'>Create New Issue</NavLink>
          </NavItem>

        </Navbar>

 );
}
}

export default IssueTrackerNav;
<|endoftext|>


<commit_before>var pull = require('pull-stream')
var Level = require('level')
var bytewise = require('bytewise')
var Write = require('pull-write')
var pl = require('pull-level')
var defer = require('pull-defer')

function create(path) {
  return Level(path, {keyEncoding: bytewise, valueEncoding: 'json'})
}

module.exports = function (_db, path, version, map) {
  var db = create(path)

  var META = '\x00', since

  db.get(META, {keyEncoding: 'utf8'}, function (err, value) {
    since = value && value.since || 0
    if(err) // new database
      next()
    else if (value.version !== version) {
      db.close(function () {
        Level.destroy(path, function (err) {
          if(err) throw err //just die?
          db = create(path)
          since = 0
          next()
        })
      })
    }
    else
      next()
  })

  var written = 0, waiting = []

  function await(ready) {
    _db.seen.await(function () {
      if(_db.seen.get() === since) return ready()
      waiting.push({ts: _db.seen.get(), cb: ready})
    })
  }

  var reader, closed

  function next () {
    while(waiting.length && waiting[0].ts <= since) {
      waiting.shift().cb()
    }

    pull(
      reader = _db.createLogStream({gt: since, live: true, sync: false}),
      Write(function (batch, cb) {
        if(closed) return cb(new Error('database closed while index was building'))
        db.batch(batch, function (err) {
          if(err) return cb(err)
          since = batch[0].value.since
          //callback to anyone waiting for this point.
          while(waiting.length && waiting[0].ts <= since) {
            waiting.shift().cb()
          }
          cb()
        })
      }, function reduce (batch, data) {
        if(data.sync) return batch
        var ts = data.ts || data.timestamp

        if(!batch)
          batch = [{
            key: META,
            value: {version: version, since: ts},
            valueEncoding: 'json', keyEncoding:'utf8', type: 'put'
          }]

        batch = batch.concat(map(data))
        batch[0].value.since = Math.max(batch[0].value.since, ts)
        return batch
      }, 512, function (err) {
        //probably a fatal database error
        if(err) console.error(err.stack)
      })
    )
  }

  return {
    get: function (key, cb) {
      //wait until the log has been processed up to the current point.
      await(function () {
        db.get(key, cb)
      })
    },
    read: function (opts) {
      opts = opts || {}
      if(since === _db.seen.get()) return pl.read(db, opts)

      var source = defer.source()
      await(function () {
        source.resolve(pl.read(db, opts))
      })
      return source
    },
    close: function (cb) {
      closed = true
      //todo: move this bit into pull-write
      if(reader)
        reader(true, function () {
          db.close(cb)
        })
      else db.close(cb)
    }
    //put, del, batch - leave these out for now, since the indexes just map.
  }
}

<commit_msg>expose rebuild<commit_after>var pull = require('pull-stream')
var Level = require('level')
var bytewise = require('bytewise')
var Write = require('pull-write')
var pl = require('pull-level')
var defer = require('pull-defer')

module.exports = function (_db, path, version, map) {
  var db = create(path), writer

  var META = '\x00', since

  var written = 0, waiting = [], closed

  function create(path) {
    closed = false
    return Level(path, {keyEncoding: bytewise, valueEncoding: 'json'})
  }

  function await(ready) {
    _db.seen.await(function () {
      if(_db.seen.get() === since) return ready()
      waiting.push({ts: _db.seen.get(), cb: ready})
    })
  }

  function close (cb) {
    closed = true
    //todo: move this bit into pull-write
    if(writer)
      writer.abort(function () {
        db.close(cb)
      })
    else db.close(cb)
  }

  function build (rebuild, cb) {
    since = null
    if(rebuild)
      destroy()
    else
      db.get(META, {keyEncoding: 'utf8'}, function (err, value) {
        since = value && value.since || 0
        if(err) // new database
          next()
        else if (value.version !== version) destroy()
        else
          next()
      })

    function destroy () {
      close(function () {
        Level.destroy(path, function (err) {
          if(err) throw err //just die?
          db = create(path)
          since = 0
          next()
        })
      })
    }

    function next () {
      while(waiting.length && waiting[0].ts <= since) {
        waiting.shift().cb()
      }

      if(closed) return

      pull(
        _db.createLogStream({gt: since, live: true, sync: false}),
        writer = Write(function (batch, cb) {
          if(closed) return cb(new Error('database closed while index was building'))
          db.batch(batch, function (err) {
            if(err) return cb(err)
            since = batch[0].value.since
            //callback to anyone waiting for this point.
            while(waiting.length && waiting[0].ts <= since) {
              waiting.shift().cb()
            }
            cb()
          })
        }, function reduce (batch, data) {
          if(data.sync) return batch
          var ts = data.ts || data.timestamp

          if(!batch)
            batch = [{
              key: META,
              value: {version: version, since: ts},
              valueEncoding: 'json', keyEncoding:'utf8', type: 'put'
            }]

          batch = batch.concat(map(data))
          batch[0].value.since = Math.max(batch[0].value.since, ts)
          return batch
        }, 512, cb)
      )
    }
  }

  build(null, function (err) {
    //console.error(err)
  })

  return {
    get: function (key, cb) {
      //wait until the log has been processed up to the current point.
      await(function () {
        db.get(key, cb)
      })
    },
    await: await,
    read: function (opts) {
      opts = opts || {}
      if(since === _db.seen.get()) return pl.read(db, opts)

      var source = defer.source()
      await(function () {
        source.resolve(pl.read(db, opts))
      })
      return source
    },
    rebuild: function (cb) {
      build(true, cb)
    },
    close: close,
    //put, del, batch - leave these out for now, since the indexes just map.
  }

}

<|endoftext|>