<commit_before>import _ from 'lodash';
import d3 from 'd3';

import * as tile from './tile';
import {tileSize, stockBottomMargin} from './config';
import {bindDrag} from './drag_and_drop';

export class Stock {
  constructor(svg, board) {
    this.svg = svg;
    this.board = board;
  }

  elementCount(level) {
    this.stock = level.initialStock;

    // initialize 0-count stock for non-frozen tiles on board
    level.tileRecipes.forEach((tileRecipe) => {
      if (!tileRecipe.frozen && !_.has(this.stock, tileRecipe.name)) {
        this.stock[tileRecipe.name] = 0;
      }
    });

    this.usedTileNames = _.keys(this.stock);  // add some ordering to the stock?
    this.level = level;
  }

  drawStock() {

    // Reset element
    this.svg.select('.stock').remove();
    this.stockGroup = this.svg
      .append('g')
        .attr('class', 'stock');

    // Create background
    const maxRows = this.level.height - stockBottomMargin;
    const iShift = this.level.width + 1;

    const dataForStockDrawing = _.map(this.usedTileNames, (name, i) => ({
        name: name,
        i: Math.floor(i / maxRows) + iShift,
        j: i % maxRows,
    }));

    this.stockSlots = this.stockGroup
      .selectAll('.stock-slot')
      .data(dataForStockDrawing);

    const stockSlotsEntered = this.stockSlots.enter()
      .append('g')
        .attr('class', 'stock-slot')
        .classed('stock-empty', (d) => this.stock[d.name] <= 0);

    stockSlotsEntered.append('rect')
      .attr('class', 'background-tile')
      .attr('width', tileSize)
      .attr('height', tileSize)
      .attr('transform', (d) => `translate(${d.i * tileSize},${d.j * tileSize})`);

    stockSlotsEntered.append('text')
      .attr('class', 'stock-count')
      .attr('transform', (d) => `translate(${(d.i + 0.9) * tileSize},${(d.j + 0.9) * tileSize})`)
      .text((d) => `x ${this.stock[d.name]}`);

    this.stockTiles = stockSlotsEntered.append('g')
      .datum((d) => new tile.Tile(tile[d.name], 0, false, d.i, d.j))
      .attr('class', 'tile')
      .attr('transform', (d) => `translate(${d.x + tileSize / 2},${d.y + tileSize / 2})`)
      .each(function (tileObj) {
        tileObj.g = d3.select(this);
        tileObj.node = this;
        tileObj.fromStock = true;
        tileObj.draw();
      });

    this.stockTiles.append('rect')
      .attr('class', 'hitbox')
      .attr('x', -tileSize / 2)
      .attr('y', -tileSize / 2)
      .attr('width', tileSize)
      .attr('height', tileSize)
      .on('mouseover', this.board.callbacks.tileMouseover);

    bindDrag(this.stockTiles, this.board, this);

  }

  regenerateTile(stockSlotG) {

    const newTile = stockSlotG.append('g')
      .datum((d) => new tile.Tile(tile[d.name], 0, false, d.i, d.j))
      .attr('class', 'tile')
      .attr('transform', (d) => `translate(${d.x + tileSize / 2},${d.y + tileSize / 2})`)
      .each(function (tileObj) {
        tileObj.g = d3.select(this);
        tileObj.node = this;
        tileObj.fromStock = true;
        tileObj.draw();
      });

    newTile.append('rect')
      .attr('class', 'hitbox')
      .attr('x', -tileSize / 2)
      .attr('y', -tileSize / 2)
      .attr('width', tileSize)
      .attr('height', tileSize)
      .on('mouseover', this.board.callbacks.tileMouseover);

    bindDrag(newTile, this.board, this);

  }

  updateCount(tileName, change) {

    this.stock[tileName] += change;

    this.stockSlots
      .classed('stock-empty', (d) => this.stock[d.name] <= 0);

    this.stockSlots.select('text')
      .text((d) => `x ${this.stock[d.name]}`);
  }

}
<commit_msg>refactor(drag) DRY for tile (re)generation<commit_after>import _ from 'lodash';
import d3 from 'd3';

import * as tile from './tile';
import {tileSize, stockBottomMargin} from './config';
import {bindDrag} from './drag_and_drop';

export class Stock {
  constructor(svg, board) {
    this.svg = svg;
    this.board = board;
  }

  elementCount(level) {
    this.stock = level.initialStock;

    // initialize 0-count stock for non-frozen tiles on board
    level.tileRecipes.forEach((tileRecipe) => {
      if (!tileRecipe.frozen && !_.has(this.stock, tileRecipe.name)) {
        this.stock[tileRecipe.name] = 0;
      }
    });

    this.usedTileNames = _.keys(this.stock);  // add some ordering to the stock?
    this.level = level;
  }

  drawStock() {

    // Reset element
    this.svg.select('.stock').remove();
    this.stockGroup = this.svg
      .append('g')
        .attr('class', 'stock');

    // Create background
    const maxRows = this.level.height - stockBottomMargin;
    const iShift = this.level.width + 1;

    const dataForStockDrawing = _.map(this.usedTileNames, (name, i) => ({
        name: name,
        i: Math.floor(i / maxRows) + iShift,
        j: i % maxRows,
    }));

    this.stockSlots = this.stockGroup
      .selectAll('.stock-slot')
      .data(dataForStockDrawing);

    const stockSlotsEntered = this.stockSlots.enter()
      .append('g')
        .attr('class', 'stock-slot')
        .classed('stock-empty', (d) => this.stock[d.name] <= 0);

    stockSlotsEntered.append('rect')
      .attr('class', 'background-tile')
      .attr('width', tileSize)
      .attr('height', tileSize)
      .attr('transform', (d) => `translate(${d.i * tileSize},${d.j * tileSize})`);

    stockSlotsEntered.append('text')
      .attr('class', 'stock-count')
      .attr('transform', (d) => `translate(${(d.i + 0.9) * tileSize},${(d.j + 0.9) * tileSize})`)
      .text((d) => `x ${this.stock[d.name]}`);

    this.regenerateTile(stockSlotsEntered);
  }

  regenerateTile(stockSlotG) {

    const newTile = stockSlotG.append('g')
      .datum((d) => new tile.Tile(tile[d.name], 0, false, d.i, d.j))
      .attr('class', 'tile')
      .attr('transform', (d) => `translate(${d.x + tileSize / 2},${d.y + tileSize / 2})`)
      .each(function (tileObj) {
        tileObj.g = d3.select(this);
        tileObj.node = this;
        tileObj.fromStock = true;
        tileObj.draw();
      });

    newTile.append('rect')
      .attr('class', 'hitbox')
      .attr('x', -tileSize / 2)
      .attr('y', -tileSize / 2)
      .attr('width', tileSize)
      .attr('height', tileSize)
      .on('mouseover', this.board.callbacks.tileMouseover);

    bindDrag(newTile, this.board, this);

  }

  updateCount(tileName, change) {

    this.stock[tileName] += change;

    this.stockSlots
      .classed('stock-empty', (d) => this.stock[d.name] <= 0);

    this.stockSlots.select('text')
      .text((d) => `x ${this.stock[d.name]}`);
  }

}
<|endoftext|>


<commit_before>import { createAction, handleActions } from 'redux-actions'
import { getChluAPIClient } from 'helpers/chlu'
import { get } from 'lodash'
import { DELETE_WALLET } from './wallet';

// ------------------------------------
// Constants
// ------------------------------------
const READ_REPUTATION_LOADING = 'reviewsaboutvendor/READ_REPUTATION_LOADING'
const READ_REPUTATION_SUCCESS = 'reviewsaboutvendor/READ_REPUTATION_SUCCESS'
const READ_REPUTATION_ERROR = 'reviewsaboutvendor/READ_REPUTATION_ERROR'
const READ_REVIEWRECORD_LOADING = 'reviewsaboutvendor/READ_REVIEWRECORD_LOADING'
const READ_REVIEWRECORD_SUCCESS = 'reviewsaboutvendor/READ_REVIEWRECORD_SUCCESS'
const READ_REVIEWRECORD_ERROR = 'reviewsaboutvendor/READ_REVIEWRECORD_ERROR'

function getInitialState() {
  return {
    loading: false,
    error: null,
    reviews: null
  }
}

// ------------------------------------
// Actions
// ------------------------------------
const readReputationLoading = createAction(READ_REPUTATION_LOADING)
const readReputationSuccess = createAction(READ_REPUTATION_SUCCESS)
const readReputationError = createAction(READ_REPUTATION_ERROR)
const readReviewRecordLoading = createAction(READ_REVIEWRECORD_LOADING)
const readReviewRecordSuccess = createAction(READ_REVIEWRECORD_SUCCESS)
const readReviewRecordError = createAction(READ_REVIEWRECORD_ERROR)

// ------------------------------------
// Thunks
// ------------------------------------

function readReviewRecord(multihash) {
  return async dispatch => {
    try {
      dispatch(readReviewRecordLoading(multihash))
      const chluApiClient = await getChluAPIClient()
      const reviewRecord = await chluApiClient.readReviewRecord(multihash)
      dispatch(readReviewRecordSuccess({ reviewRecord, multihash }))
    } catch (error) {
      dispatch(readReviewRecordError({ multihash, error: error.message || error }))
    }
  }
}

export function readMyReputation () {
  return async (dispatch, getState) => {
    const state = getState()
    const didId = get(state, 'data.wallet.did.publicDidDocument.id', null)
    if (didId) return dispatch(readReputation(didId))
  }
}

export function readReputation (didId) {
  return async (dispatch, getState) => {
    if (didId) {
      dispatch(readReputationLoading(didId))
      try {
        // TODO: improve this and use a loading system per-review
        const chluApiClient = await getChluAPIClient()
        const list = await chluApiClient.getReviewsAboutDID(didId)
        const reviews = {}
        for (const review of list) {
          const multihash = review.multihash
          const content = get(review, 'reviewRecord', {})
          const resolved = get(content, 'resolved', false)
          // TODO: show them as loading and dispatch redux actions to resolve them
          reviews[multihash] = { multihash, loading: !resolved, error: null, ...content }
          // Only read the review if the api client did not return it resolved
          if (!resolved) dispatch(readReviewRecord(multihash))
        }
        dispatch(readReputationSuccess({ reviews, didId }))
      } catch (error) {
        console.log(error)
        dispatch(readReputationError(error.message || error))
      }
    } else {
      dispatch(readReputationError('Not logged in'))
    }
  }
}

function updateReviewRecord (reviews, multihash, data, create = true) {
  if (reviews && multihash && (create || reviews[multihash])) {
    return {
      ...reviews,
      [multihash]: Object.assign(reviews[multihash] || {}, data)
    }
  } else {
    return reviews
  }
}

// ------------------------------------
// Reducer
// ------------------------------------
export default handleActions({
  [READ_REPUTATION_LOADING]: (state, { payload: didId }) => ({
    ...state,
    didId,
    loading: true
  }),
  [READ_REPUTATION_SUCCESS]: (state, { payload: { reviews, didId } }) => ({
    ...state,
    loading: didId === state.didId ? false : state.loading,
    reviews: didId === state.didId ? reviews : state.reviews
  }),
  [READ_REPUTATION_ERROR]: (state, { payload: { error, didId } }) => ({
    ...state,
    loading: didId === state.didId ? false : state.loading,
    error: didId === state.didId ? error : state.error
  }),
  [READ_REVIEWRECORD_LOADING]: (state, { payload: multihash }) => ({
    ...state,
    reviews: {
      ...updateReviewRecord(get(state, 'reviews', {}), multihash, { loading: true, multihash })
    }
  }),
  [READ_REVIEWRECORD_SUCCESS]: (state, { payload: { reviewRecord, multihash } }) => ({
    ...state,
    reviews: {
      ...updateReviewRecord(get(state, 'reviews', {}), multihash, Object.assign({}, reviewRecord, { loading: false }))
    }
  }),
  [READ_REVIEWRECORD_ERROR]: (state, { payload: { error, multihash } }) => ({
    ...state,
    reviews: {
      ...updateReviewRecord(
        get(state, 'reviews', {}),
        multihash,
        { error: error.message || error, loading: false, multihash }
      )
    }
  }),
  [DELETE_WALLET]: state => getInitialState()
}, getInitialState())
<commit_msg>remove dead code<commit_after>import { createAction, handleActions } from 'redux-actions'
import { getChluAPIClient } from 'helpers/chlu'
import { get } from 'lodash'
import { DELETE_WALLET } from './wallet';

// ------------------------------------
// Constants
// ------------------------------------
const READ_REPUTATION_LOADING = 'reviewsaboutvendor/READ_REPUTATION_LOADING'
const READ_REPUTATION_SUCCESS = 'reviewsaboutvendor/READ_REPUTATION_SUCCESS'
const READ_REPUTATION_ERROR = 'reviewsaboutvendor/READ_REPUTATION_ERROR'

function getInitialState() {
  return {
    loading: false,
    error: null,
    reviews: null
  }
}

// ------------------------------------
// Actions
// ------------------------------------
const readReputationLoading = createAction(READ_REPUTATION_LOADING)
const readReputationSuccess = createAction(READ_REPUTATION_SUCCESS)
const readReputationError = createAction(READ_REPUTATION_ERROR)

// ------------------------------------
// Thunks
// ------------------------------------

export function readMyReputation () {
  return async (dispatch, getState) => {
    const state = getState()
    const didId = get(state, 'data.wallet.did.publicDidDocument.id', null)
    if (didId) return dispatch(readReputation(didId))
  }
}

export function readReputation (didId) {
  return async (dispatch, getState) => {
    if (didId) {
      dispatch(readReputationLoading(didId))
      try {
        const myDidId = get(getState(), 'data.wallet.did.publicDidDocument.id', null)
        const chluApiClient = await getChluAPIClient()
        const list = await chluApiClient.getReviewsAboutDID(didId)
        const reviews = {}
        for (const review of list) {
          const multihash = review.multihash
          const content = get(review, 'reviewRecord', {})
          const customerDidId = get(review, 'reviewRecord.customer_signature.creator', null)
          const editable = customerDidId && myDidId && myDidId === customerDidId
          const resolved = get(content, 'resolved', false)
          const preparedContent = { ...content, editable }
          reviews[multihash] = { multihash, loading: !resolved, error: null, ...preparedContent }
        }
        dispatch(readReputationSuccess({ reviews, didId }))
      } catch (error) {
        console.log(error)
        dispatch(readReputationError(error.message || error))
      }
    } else {
      dispatch(readReputationError('Not logged in'))
    }
  }
}

// ------------------------------------
// Reducer
// ------------------------------------
export default handleActions({
  [READ_REPUTATION_LOADING]: (state, { payload: didId }) => ({
    ...state,
    didId,
    loading: true
  }),
  [READ_REPUTATION_SUCCESS]: (state, { payload: { reviews, didId } }) => ({
    ...state,
    loading: didId === state.didId ? false : state.loading,
    reviews: didId === state.didId ? reviews : state.reviews
  }),
  [READ_REPUTATION_ERROR]: (state, { payload: { error, didId } }) => ({
    ...state,
    loading: didId === state.didId ? false : state.loading,
    error: didId === state.didId ? error : state.error
  }),
  [DELETE_WALLET]: state => getInitialState()
}, getInitialState())
<|endoftext|>


<commit_before>/**
* Story model
* Used to get process info about a story such as url, title, and type
*/

import APP_CONSTANTS from './app-constants.js';

export class HNStory{

	constructor(storyInfo){
		this.storyInfo = storyInfo;
	}

	get url(){
		//for ask or show HN stories
		if(this.isLocalHNUrl){
			return APP_CONSTANTS.urls.ask + this.storyInfo['id'];
		}
		return this.storyInfo['url'];
	}

	get isLocalHNUrl(){
		if(!this.storyInfo['url']){
			return true;
		}
		return false;
	}

	/**
	* gets the url root domain for display with story
	* http://www.nytimes.com/story becomes (nytimes.com)
	*/
	get urlRoot() {
		//for ask or show HN stories
		if(this.isLocalHNUrl){
			return '';
		}
		//removes first part of url (http://www.)
		var base_url = this.url;
		base_url =  base_url.replace(/^http(s)?:\/\/(www.)?/, '');
		//removes subfolders from url (/index.html)
		base_url = base_url.replace(/\/.*$/, '');
		//removes get requests from url (?q=something)
		return '(' + base_url.replace(/\?.*$/,'') + ')';
	}

	get title(){
		return this.storyInfo['title'] || '';
	}

	get titleHtml(){
		let title = `<a href="${this.url}"><h3>${this.title}`;
		if(this.urlRoot !== ''){
			title += `<span class='small url_source'>${this.urlRoot}</span>`;
		}
		title += '
';
		return title;
	}

	/**
	* Used for ask pages to display without the link
	* It should have the same style as titleHtml()
	*/
	get askTitle(){
		return `<h3>${this.title}</h3>`;
	}

	get text(){
		return this.storyInfo['text'] || '';
	}

	get author(){
		return this.storyInfo['by'] || '';
	}

	get storyType(){
		if(this.type !== 'story'){
			return false;
		}
		if(this.isLocalHNUrl){
			if(this.title.substring(0,3).toLowerCase() === 'ask'){
				return 'ask';
			}
			return 'show';
		}
		return 'story';
	}

	get type(){
		return this.storyInfo['type'];
	}

	get numComments(){
		if(!this.storyInfo['descendants']){
			return 0;
		}
		return this.storyInfo['descendants'];
	}

	get topLevelCommentsIds(){
		if(!this.storyInfo['kids']){
			return [];
		}
		return this.storyInfo['kids'];
	}

	commentsUrl(commentsUrl){
		// return 'https://news.ycombinator.com/item?id=' + this.storyInfo['id'];
		return commentsUrl + this.storyInfo['id'];
	}
}<commit_msg>Add space between story title and url<commit_after>/**
* Story model
* Used to get process info about a story such as url, title, and type
*/

import APP_CONSTANTS from './app-constants.js';

export class HNStory{

	constructor(storyInfo){
		this.storyInfo = storyInfo;
	}

	get url(){
		//for ask or show HN stories
		if(this.isLocalHNUrl){
			return APP_CONSTANTS.urls.ask + this.storyInfo['id'];
		}
		return this.storyInfo['url'];
	}

	get isLocalHNUrl(){
		if(!this.storyInfo['url']){
			return true;
		}
		return false;
	}

	/**
	* gets the url root domain for display with story
	* http://www.nytimes.com/story becomes (nytimes.com)
	*/
	get urlRoot() {
		//for ask or show HN stories
		if(this.isLocalHNUrl){
			return '';
		}
		//removes first part of url (http://www.)
		var base_url = this.url;
		base_url =  base_url.replace(/^http(s)?:\/\/(www.)?/, '');
		//removes subfolders from url (/index.html)
		base_url = base_url.replace(/\/.*$/, '');
		//removes get requests from url (?q=something)
		return '(' + base_url.replace(/\?.*$/,'') + ')';
	}

	get title(){
		return this.storyInfo['title'] || '';
	}

	get titleHtml(){
		let title = `<a href="${this.url}"><h3>${this.title}`;
		if(this.urlRoot !== ''){
			title += ` <span class='small url_source'>${this.urlRoot}</span>`;
		}
		title += '
';
		return title;
	}

	/**
	* Used for ask pages to display without the link
	* It should have the same style as titleHtml()
	*/
	get askTitle(){
		return `<h3>${this.title}</h3>`;
	}

	get text(){
		return this.storyInfo['text'] || '';
	}

	get author(){
		return this.storyInfo['by'] || '';
	}

	get storyType(){
		if(this.type !== 'story'){
			return false;
		}
		if(this.isLocalHNUrl){
			if(this.title.substring(0,3).toLowerCase() === 'ask'){
				return 'ask';
			}
			return 'show';
		}
		return 'story';
	}

	get type(){
		return this.storyInfo['type'];
	}

	get numComments(){
		if(!this.storyInfo['descendants']){
			return 0;
		}
		return this.storyInfo['descendants'];
	}

	get topLevelCommentsIds(){
		if(!this.storyInfo['kids']){
			return [];
		}
		return this.storyInfo['kids'];
	}

	commentsUrl(commentsUrl){
		// return 'https://news.ycombinator.com/item?id=' + this.storyInfo['id'];
		return commentsUrl + this.storyInfo['id'];
	}
}<|endoftext|>


<commit_before>var story1 = ['In the not-too-distant future, mankind succumbs to the daunting pressures of nuclear conflict, and the Earth is a wasteland.'];
var story2 = ['Humans are GHOSTS now, you know… because everyone’s dead. Seattle is now known as GhosTown, and millions of GHOSTIES call GhosTown their home. They’ve been here all their afterlives.'];
var story3 = ['For most GHOSTS, GhosTown is juuuuuust perfect: it’s boring, uneventful, filled with hipsters, and it rains. A lot... But for a handful of ghosts, this lifeless non-existence is simply not enough.'];
var story4 = ['Three GHOSTS want to know if there is LIFE (or perhaps \'death\') outside of GhosTown! They have questions that need answering! What lies beyond the borders of this afterlife? What hidden force keeps the dead from leaving GhosTown?'];
var story5 = ['There’s only one way to find out -- ESCAPE GhosTown!'];
var story6 = ['YODO: You Only Die Once.'];

// DOGGO pre-encounter
var storyDoggo1 = ['You step outside your front door -- Oh, look, ANOTHER crappy day in GhosTown. :('];
var storyDoggo2 = ['As you begin to wander down the street, headed to wherever (ghosts don’t have jobs, or anything to do in general) you see a small, cute figure approaching. Hey look! it\'s a ghost dog. It looks like its name might be \'Doggo\'.'];
var storyDoggo3 = ['Doggo: “Arf. Boo.”'];
var storyDoggo4 = ['It looks aggressive. If I didn’t know better, I’d say Doggo had hostile intent!'];

// DOGGO post-enounter
var storyDoggo5 = ['You have won Doggo over! Doggo is a sweet dog and is now a friend. In times of need, Doggo may just pop up and save the day.'];

// HIPSTER pre-encounter
var storyHipster1 = ['As you continue your aimless wandering, you begin to wonder: what is even beyond the borders of GhosTown? How come nobody has ever been outside this place and come back to tell the tale? Nobody ever talks about these things. What’s the deal with that?'];
var storyHipster2 = ['With just enough time to watch it go down but not enough time to do anything about it, a Hipster Ghost, waist-deep into his cellular ghost-phone, bumps RIGHT INTO YOU!'];
var storyHipster3 = ['Hipster Ghost: “Hey! Why don’t you watch where I’m going?! You totally ruined my Insta-Boo!”'];
var storyHipster4 = ['Oh, what a nice ghostie.'];

// HIPSTER post-encounter
var storyHipster5 = ['Hipster Ghost has retreated, crying. You hurt his feelings. He dropped some crap on the ground as he ran away. You might want to pick one up.'];

// SKULLEX ENVIRONMENTAL encounter
var storySkullex1 = ['Sheesh… what’s wrong with people these days? You’ve GOT to get out of this town. You are floating along as quickly as you can without raising suspicion.'];
var storySkullex2 = ['But hold on -- did you hear that? I think someone’s lurking around somewhere, watching and ready to pounce! Ambush?! What will you do?'];
// envirnomental encounter choices

// SKULLEX pre-encounter
var storySkullex3 = ['Skullex: “Oh, hi there, little ghost. Where do you think you’re going?”'];
var storySkullex4 = ['“You’re not thinking of leaving GhosTown, are you? We would sure miss the pleasure of your company -- HAHAHA!”'];
var storySkullex5 = ['“Well, if you’re DEAD-SET on leaving, I’m just going to have to stop you. Nothing personal -- Boss’ orders.”'];

// SKULLEX post-encounter
var storySkullex6 = ['Skullex collapses in a pile of bones.'];

// GHOSTLY ENVIRONMENTAL encounter
var storyGhostly1 = ['This is weird… skeletons have never been seen inside GhosTown before. There’s definitely something SUSPICIOUS going on. And who is this “BOSS” guy? You’ve got to get out of here!'];
var storyGhostly2 = ['You float your ghostie self as quickly as you possibly can out of G-Town. You are seriously booking it -- like, HARD! Doggo, who has been following you the whole time, senses trouble and growls at something in the shadows.'];
var storyGhostly3 = ['You can’t quite see what’s hiding out there. But then you hear a ghostly voice…'];
var storyGhostly4 = ['Ghostly: “You are not going ANYWHERE! Haaahahahaha!!”'];
var storyGhostly5 = ['A huge, monstrous grin cracks through the shadows along with a pair of glowing eyes. You’ve never seen anything like this before -- it’s a ghost, but it seems to be made out of shadow itself.'];
var storyGhostly6 = ['“You’ve gone quite far enough, my ghostie friend! Hee heee heeeee!”'];
var storyGhostly7 = ['“REEEEEEEEEEEEEEEEEE!!!”'];
var storyGhostly8 = ['What is up with this creepy guy…?'];
// ENVIRONMENTAL encounter choices

// GHOSTLY pre-encounter
var storyGhostly9 = ['Here it comes!'];

// GHOSTLY post-encounter
var storyGhostly10 = ['Ghostly: “He’s coming, Boss…”'];
var storyGhostly11 = ['“Haaaaaaaaaaahhhhhhhhhh………..”'];

// GHO pre-encounter
var storyGho1 = ['Woah! That one was TOUGH! But on a brighter note, it seems like you’re just about out of GhosTown. Woohoo!'];
var storyGho2 = ['As your ghost-body gets further and further past the tall buildings and sprawling suburbs of the city limits into the surrounding countryside, a fog gathers around you and you feel a deepening sense of uneasiness and dread -- which is pretty serious for a ghost!'];
var storyGho3 = ['Gho: “Your mission is impossible… you can never escape… it’s a question of order, not will.”'];
var storyGho4 = ['Gho: “Your mission is impossible… you can never escape… it’s a question of order, not will.”'];
var storyGho5 = ['What the--?! Who WAS that? You aren’t able to pinpoint where the voice is coming from -- it seemed to have come from all over, almost from the fog itself!'];
var storyGho6 = ['Gho: “You must think of me as a jailer or judge or gangster… forcing you to do penance for the crime of dying… but that that is not so.”'];
var storyGho7 = ['Gho: “It is simply the contrast of all things... light and dark… ‘is’ and ‘is-not’… even things themselves are defined by no-things.”'];
var storyGho8 = ['Gho: “You don’t belong outside of GhosTown, little one… the darkness cannot be light… you cannot leave, you cannot live… I will make sure of it.”'];

// GHO post-encounter
var storyGho9 = ['Well… It looks like you’ve defeated Chaos! There is nobody left to stop you now. And on that note, the fog begins to clear away to reveal what’s beyond this grave city.'];
var storyGho10 = ['And what’s beyond the fog? What comes after Chaos is defeated? Well, you see a figure off in the distance. It looks like a mirage, and as you move closer to it, it moves closer to you. Eventually you come face to face and realize that it’s actually a mirror image of yourself.'];
var storyGho11 = ['You reach your little ghostie-arm out and make contact with the figure, who is also reaching out their little arm to you. You make contact, but it’s more like touching your left arm to your right arm, only you apparently absorb into each other.'];
var storyGho12 = ['As you reach further into yourself and out of GhosTown, all the dread and frustration leaves you… there is just light…'];
var storyGho13 = ['THE END! Thanks for playing.'];
<commit_msg>Made some changes to the story.js.<commit_after>var story1 = ['In the not-too-distant future, mankind succumbs to the daunting pressures of nuclear conflict, and the Earth is a wasteland.'];
var story2 = ['Humans are GHOSTS now, you know… because everyone’s dead. Seattle is now known as GhosTown, and millions of GHOSTIES call GhosTown their home. They’ve been here all their afterlives.'];
var story3 = ['For most GHOSTS, GhosTown is juuuuuust perfect: it’s boring, uneventful, filled with hipsters, and it rains. A lot... But for a handful of ghosts, this lifeless non-existence is simply not enough.'];
var story4 = ['Three GHOSTS want to know if there is LIFE (or perhaps \'death\') outside of GhosTown! They have questions that need answering! What lies beyond the borders of this afterlife? What hidden force keeps the dead from leaving GhosTown?'];
var story5 = ['There’s only one way to find out -- ESCAPE GhosTown!'];
var story6 = ['YODO: You Only Die Once.'];

// DOGGO pre-encounter
var storyDoggo1 = ['You step outside your front door -- Oh, look, ANOTHER crappy day in GhosTown. :('];
var storyDoggo2 = ['As you begin to wander down the street, headed to wherever (ghosts don’t have jobs, or anything to do in general) you see a small, cute figure approaching. Hey look! it\'s a ghost dog. It looks like its name might be \'Doggo\'.'];
var storyDoggo3 = ['Doggo: “Arf. Boo.”'];
var storyDoggo4 = ['It looks aggressive. If I didn’t know better, I’d say Doggo had hostile intent!'];

// DOGGO post-enounter
var storyDoggo5 = ['You have won Doggo over! Doggo is a sweet dog and is now a friend. In times of need, Doggo may just pop up and save the day.'];

// HIPSTER pre-encounter
var storyHipster1 = ['As you continue your aimless wandering, you begin to wonder: what is even beyond the borders of GhosTown? How come nobody has ever been outside this place and come back to tell the tale? Nobody ever talks about these things. What’s the deal with that?'];
var storyHipster2 = ['With just enough time to watch it go down but not enough time to do anything about it, a Hipster Ghost, waist-deep into his cellular ghost-phone, bumps RIGHT INTO YOU!'];
var storyHipster3 = ['Hipster Ghost: “Hey! Why don’t you watch where I’m going?! You totally ruined my Insta-Boo!”'];
var storyHipster4 = ['Oh, what a nice ghostie.'];

// HIPSTER post-encounter
var storyHipster5 = ['Hipster Ghost has retreated, crying. You hurt his feelings. He dropped some crap on the ground as he ran away. You might want to pick one up.'];

// SKULLEX ENVIRONMENTAL encounter
var storySkullex1 = ['Sheesh… what’s wrong with people these days? You’ve GOT to get out of this town. You are floating along as quickly as you can without raising suspicion.'];
var storySkullex2 = ['But hold on -- did you hear that? I think someone’s lurking around somewhere, watching and ready to pounce! Ambush?! What will you do?'];
// envirnomental encounter choices

// SKULLEX pre-encounter
var storySkullex3 = ['Skullex: “Oh, hi there, little ghost. Where do you think you’re going?”'];
var storySkullex4 = ['“You’re not thinking of leaving GhosTown, are you? We would sure miss the pleasure of your company -- HAHAHA!”'];
var storySkullex5 = ['“Well, if you’re DEAD-SET on leaving, I’m just going to have to stop you. Nothing personal -- Boss’ orders.”'];

// SKULLEX post-encounter
var storySkullex6 = ['Skullex collapses in a pile of bones.'];

// GHOSTLY ENVIRONMENTAL encounter
var storyGhostly1 = ['This is weird… skeletons have never been seen inside GhosTown before. There’s definitely something SUSPICIOUS going on. And who is this “BOSS” guy? You’ve got to get out of here!'];
var storyGhostly2 = ['You float your ghostie self as quickly as you possibly can out of G-Town. You are seriously booking it -- like, HARD! Doggo, who has been following you the whole time, senses trouble and growls at something in the shadows.'];
var storyGhostly3 = ['You can’t quite see what’s hiding out there. But then you hear a ghostly voice…'];
var storyGhostly4 = ['Ghostly: “You are not going ANYWHERE! Haaahahahaha!!”'];
var storyGhostly5 = ['A huge, monstrous grin cracks through the shadows along with a pair of glowing eyes. You’ve never seen anything like this before -- it’s a ghost, but it seems to be made out of shadow itself.'];
var storyGhostly6 = ['“You’ve gone quite far enough, my ghostie friend! Hee heee heeeee!”'];
var storyGhostly7 = ['“REEEEEEEEEEEEEEEEEE!!!”'];
var storyGhostly8 = ['What is up with this creepy guy…?'];
// ENVIRONMENTAL encounter choices

// GHOSTLY pre-encounter
var storyGhostly9 = ['Here it comes!'];

// GHOSTLY post-encounter
var storyGhostly10 = ['Ghostly: “He’s coming, Boss…”'];
var storyGhostly11 = ['“Haaaaaaaaaaahhhhhhhhhh………..”'];

// GHO pre-encounter
var storyGho1 = ['Woah! That one was TOUGH! But on a brighter note, it seems like you’re just about out of GhosTown. Woohoo!'];
var storyGho2 = ['As your ghost-body gets further and further past the tall buildings and sprawling suburbs of the city limits into the surrounding countryside, a fog gathers around you and you feel a deepening sense of uneasiness and dread -- which is pretty serious for a ghost!'];
var storyGho3 = ['Gho: “Your mission is impossible… you can never escape… it’s a question of order, not will.”'];
var storyGho4 = ['Gho: “Your mission is impossible… you can never escape… it’s a question of order, not will.”'];
var storyGho5 = ['What the--?! Who WAS that? You aren’t able to pinpoint where the voice is coming from -- it seemed to have come from all over, almost from the fog itself!'];
var storyGho6 = ['Gho: “You must think of me as a jailer or judge or gangster… forcing you to do penance for the crime of dying… but that that is not so.”'];
var storyGho7 = ['Gho: “It is simply the contrast of all things... light and dark… ‘is’ and ‘is-not’… even things themselves are defined by no-things.”'];
var storyGho8 = ['Gho: “You don’t belong outside of GhosTown, little one… the darkness cannot be light… you cannot leave, you cannot live… I will make sure of it.”'];

// GHO post-encounter
var storyGho9 = ['Well… It looks like you’ve defeated Chaos! There is nobody left to stop you now. And on that note, the fog begins to clear away to reveal what’s beyond this grave city.'];
var storyGho10 = ['And what’s beyond the fog? What comes after Chaos is defeated? Well, you see a figure off in the distance. It looks like a mirage, and as you move closer to it, it moves closer to you. Eventually you come face to face and realize that it’s actually a mirror image of yourself.'];
var storyGho11 = ['You reach your little ghostie-arm out and make contact with the figure, who is also reaching out their little arm to you. You make contact, but it’s more like touching your left arm to your right arm, only you apparently absorb into each other.'];
var storyGho12 = ['As you reach further into yourself and out of GhosTown, all the dread and frustration leaves you… there is just light…'];
var storyGho13 = ['THE END! Thanks for playing!'];
<|endoftext|>


<commit_before>{

options:{
  attribution: 'ベクトルタイル',maxNativeZoom: 2
},
geojsonOptions:{
  pointToLayer: function (feature, latlng) {
    var s = {};
    for(name in feature.properties) {
      if(name.match(/^_/) && !name.match(/_markerType/)){
        if( feature.properties['_markerType']=='Circle' && name =='_radius'){continue;}
        s[name.substr(1)]=feature.properties[name];
      }
    }
    if(feature.properties['_markerType']=='Icon'){
      s['iconUrl']=s['iconUrl'].replace('http://cyberjapandata.gsi.go.jp/','//maps.gsi.go.jp/');
      var myIcon = L.icon(s);
      return L.marker(latlng, {icon: myIcon});
    }
    if(feature.properties['_markerType']=='DivIcon'){
      var myIcon = L.divIcon(s);
      return L.marker(latlng, {icon: myIcon});
    }
    if(feature.properties['_markerType']=='Circle'){
      return L.circle(latlng,feature.properties['_radius'],s);
    }
    if(feature.properties['_markerType']=='CircleMarker'){
      return L.circleMarker(latlng,s);
    }
    return L.marker(latlng);
  },
  style: function (feature) {
    if(!feature.properties['_markerType']){
      var s = {};
      for(name in feature.properties) {
        if(name.match(/^_/) && !name.match(/_markerType/)){
          if( feature.properties['_markerType']=='Circle' && name =='_radius'){continue;}
          s[name.substr(1)]=feature.properties[name];
        }
      }
      return s;
    }
  },
  onEachFeature: function (feature, layer) {
    var s = "
";
    var photoFlg = false;

    for(name in feature.properties) {
      if(!name.match(/^_/)){
        if(name=="name"){
          s += "
" + feature.properties[name] + "
";
        }else if(name=="description"){
          s += "
" + feature.properties[name] + "
";

        // (UAV)動画
        }else if(name=="iframe"){
          s += "
" + feature.properties[name] + "
";

        // 斜め写真・垂直写真
        }else if(name=="写真"){
          photoFlg = true;
          // 写真のURLを取り出す
          var div = document.createElement("div");
          div.innerHTML = feature.properties[name];
          var photoUrl = div.querySelector("a").href;
          s += "
"
               + ""
               + ""
               + "
"
               + "
↑写真クリックで拡大表示
";

        }else{
          s += "
" + name + "	"
               + "" + feature.properties[name] + "
";
        }
      }
    }
    s += "
";
    if(s != "

"){
      if(photoFlg){
        layer.bindPopup(s,{minWidth:300, maxWidth:5000});
      }else{
        layer.bindPopup(s,{maxWidth:5000});
      }
    }
  }
}

}
<commit_msg>Update style.js<commit_after>{

options:{
  attribution: 'ベクトルタイル',maxNativeZoom: 2
},
geojsonOptions:{
  pointToLayer: function (feature, latlng) {
    var s = {};
    for(name in feature.properties) {
      if(name.match(/^_/) && !name.match(/_markerType/)){
        if( feature.properties['_markerType']=='Circle' && name =='_radius'){continue;}
        s[name.substr(1)]=feature.properties[name];
      }
    }
    if(feature.properties['_markerType']=='Icon'){
      s['iconUrl']=s['iconUrl'].replace('http://cyberjapandata.gsi.go.jp/','//maps.gsi.go.jp/');
      var myIcon = L.icon(s);
      return L.marker(latlng, {icon: myIcon});
    }
    if(feature.properties['_markerType']=='DivIcon'){
      var myIcon = L.divIcon(s);
      return L.marker(latlng, {icon: myIcon});
    }
    if(feature.properties['_markerType']=='Circle'){
      return L.circle(latlng,feature.properties['_radius'],s);
    }
    if(feature.properties['_markerType']=='CircleMarker'){
      return L.circleMarker(latlng,s);
    }
    return L.marker(latlng);
  },
  style: function (feature) {
    if(!feature.properties['_markerType']){
      var s = {};
      for(name in feature.properties) {
        if(name.match(/^_/) && !name.match(/_markerType/)){
          if( feature.properties['_markerType']=='Circle' && name =='_radius'){continue;}
          s[name.substr(1)]=feature.properties[name];
        }
      }
      return s;
    }
  },
  onEachFeature: function (feature, layer) {
    var s = "
";
    var photoFlg = false;

    for(name in feature.properties) {
      if(!name.match(/^_/)){
        if(name=="name"){
          s += "
" + feature.properties[name] + "
";
        }else if(name=="description"){
          s += "
" + feature.properties[name] + "
";

        // (UAV)動画
        }else if(name=="iframe"){
          s += "
" + feature.properties[name] + "
";

        // 斜め写真・垂直写真
        }else if(name=="写真"){
          photoFlg = true;
          // 写真のURLを取り出す
          var div = document.createElement("div");
          div.innerHTML = feature.properties[name];
          var photoUrl = div.querySelector("a").href;
          s['photoUrl']=s['photoUrl'].replace('http://saigai.gsi.go.jp/','https://saigai.gsi.go.jp/');
          s += "
"
               + ""
               + ""
               + "
"
               + "
↑写真クリックで拡大表示
";

        }else{
          s += "
" + name + "	"
               + "" + feature.properties[name] + "
";
        }
      }
    }
    s += "
";
    if(s != "

"){
      if(photoFlg){
        layer.bindPopup(s,{minWidth:300, maxWidth:5000});
      }else{
        layer.bindPopup(s,{maxWidth:5000});
      }
    }
  }
}

}
<|endoftext|>


<commit_before>$(function () {
    var t = window.TrelloPowerUp.iframe();
    t.sizeTo('.container');

    if(isMPAutorized()){
        _mpAjax({
            method: 'GET',
            url: 'timer/projects',
            params: {},
            success: function (response) {
                var data = response.data;
                console.log(data);
            }
        });

        _mpAjax({
            method: 'GET',
            url: 'timer/status',
            params: {},
            success: function (response) {
                var data = response.data;
            },
            error: function (data) {
                if (data.status == 401) {
                    localStorage.removeItem('mp_token');
                }
            }
        });
    }
});<commit_msg>trello app<commit_after>$(function () {
    var t = window.TrelloPowerUp.iframe();
    t.sizeTo('.container');

    if(isMPAutorized()){
        _mpAjax({
            method: 'GET',
            url: 'timer/projects',
            params: {},
            success: function (response) {
                var data = response.data;
                var optgroups = {};
                var dd = $('#project_id');
                $.each(data,function (index, project) {
                    if(!optgroups.hasOwnProperty(project.client_name)){
                        optgroups[project.client_name] = $('<optgroup label="'+project.client_name+'">');
                        dd.append(optgroups[project.client_name]);
                    }
                    optgroups[project.client_name].append('<option value="'+project.id+'">'+project.name+'</option>')
                });
            }
        });

        _mpAjax({
            method: 'GET',
            url: 'timer/status',
            params: {},
            success: function (response) {
                var data = response.data;
            },
            error: function (data) {
                if (data.status == 401) {
                    localStorage.removeItem('mp_token');
                }
            }
        });
    }
});<|endoftext|>


<commit_before>$(function(){
    $('#login-btn').on('click',function (e) {
        e.preventDefault();
        var node = $(this);
        var form = node.closest('form');
        var params = form.serialize();
        $.ajax({
            url: 'https://api.moneypenny.me/'+form.find('#tenant_name').val()+'/login',
            data: params,
            method: 'POST',
            error: function (jqXHR, status, error) {
                console.log(jqXHR.responseJSON, status, error);
            },
            success: function (data, status, jqXHR) {
                console.log(data, status, jqXHR);
            }
        });
    });
});
<commit_msg>trello app<commit_after>$(function(){
    $('#login-btn').on('click',function (e) {
        e.preventDefault();
        var node = $(this);
        var form = node.closest('form');
        var params = form.serialize();
        $.ajax({
            url: 'https://api.moneypenny.me/'+form.find('#tenant_name').val()+'/login',
            data: params,
            method: 'POST',
            dataType: 'jsonp',
            error: function (jqXHR, status, error) {
                console.log(jqXHR.responseJSON, status, error);
            },
            success: function (data, status, jqXHR) {
                console.log(data, status, jqXHR);
            }
        });
    });
});
<|endoftext|>


<commit_before>function add_split(){
    if(interval != 0){
        calculate_time();
        get('splits').innerHTML += current_time[0] + ':'
                                 + current_time[1] + ':'
                                 + current_time[2] + '.'
                                 + current_time[3] + '
';
    }
}

function calculate_time(){
    time_ms = new Date().getTime() - start_time;
    current_time = [
        Math.floor(time_ms / 3600000),// hours
        Math.floor(time_ms / 60000) % 60,// minutes
        Math.floor(time_ms / 1000) % 60,// seconds
        time_ms % 1000// milliseconds
    ];

    // extra zero for minutes?
    if(current_time[1] < 10){
        current_time[1] = '0' + current_time[1];
    }

    // extra zero for seconds?
    if(current_time[2] < 10){
        current_time[2] = '0' + current_time[2];
    }

    // extra zeros for milliseconds?
    if(current_time[3] < 10){
        current_time[3] = '00' + current_time[3];
    }else if(current_time[3] < 100){
        current_time[3] = '0' + current_time[3];
    }
}

function draw(){
    calculate_time();
    get(0).innerHTML = current_time[0];
    get(1).innerHTML = current_time[1];
    get(2).innerHTML = current_time[2];
    get(3).innerHTML = current_time[3];
}

function get(i){
    return document.getElementById(i);
}

function reset_timer(){
    if(confirm('Clear splits and reset timer?')){
        stop();
        start_time = -1;
        get(0).innerHTML = 0;
        get(1).innerHTML = '00';
        get(2).innerHTML = '00';
        get(3).innerHTML = '000';
        get('splits').innerHTML = '';
    }
}

function reset_settings(){
    if(confirm('Reset settings?')){
        get('start-key').value = 'H';
        get('start-key-display').innerHTML = 'H';

        get('reset-key').value = 'T';
        get('reset-key-display').innerHTML = 'T';

        save();
    }
}

function save(){
    i = 1;
    do{
        if(get(['start-key','reset-key'][i]).value == ['H', 'T'][i]){
            ls.removeItem('timer' + i);

        }else{
            ls.setItem(
                'timer' + i,
                get(['start-key','reset-key'][i]).value
            );
        }
    }while(i--);

    get('reset-key-display').innerHTML = get('reset-key').value;
    get('start-key-display').innerHTML = get('start-key').value;
}

function showhide(){
    get('controls').style.display = get('controls').style.display === 'none' ? 'inline' : 'none';
    get('settings').style.display = get('controls').style.display === 'none' ? 'inline' : 'none';
}

function start(){
    stop();
    start_time = new Date().getTime() - (start_time === -1 ? 0 : time_ms);
    interval = setInterval('draw()', 20);
}

function stop(){
    clearInterval(interval);
    interval = 0;
}

var current_time = 0;
var i = 0;
var interval = 0;
var ls = window.localStorage;
var start_time = -1;
var time_ms = 0;

// fetch start key from localStorage
if(ls.getItem('timer0')){
    get('start-key').value = ls.getItem('timer0');
    get('start-key-display').innerHTML = ls.getItem('timer0');

}else{
    get('start-key').value = 'H';
}

// fetch reset key from localStorage
if(ls.getItem('timer1')){
    get('reset-key').value = ls.getItem('timer1');
    get('reset-key-display').innerHTML = ls.getItem('timer1');

}else{
    get('reset-key').value = 'T';
}

window.onbeforeunload = function(){
    if(start_time > -1){
        return 'Timer and splits not yet saveable. Leave?';
    }
};

window.onkeydown = function(e){
    i = window.event ? event : e;
    i = i.charCode ? i.charCode : i.keyCode;

    if(i === 32){// Space
        e.preventDefault();
        add_split();

    }else if(i === 27){// ESC
        stop();

    }else if(String.fromCharCode(i) === get('start-key').value){
        start();

    }else if(String.fromCharCode(i) === get('reset-key').value){
        reset_timer();
    }
}
<commit_msg>removed get() function, fixed showhide(), improved formatting<commit_after>function add_split(){
    if(interval != 0){
        calculate_time();
        document.getElementById('splits').innerHTML += current_time[0] + ':'
          + current_time[1] + ':'
          + current_time[2] + '.'
          + current_time[3] + '
';
    }
}

function calculate_time(){
    time_ms = new Date().getTime() - start_time;
    current_time = [
      Math.floor(time_ms / 3600000),// hours
      Math.floor(time_ms / 60000) % 60,// minutes
      Math.floor(time_ms / 1000) % 60,// seconds
      time_ms % 1000// milliseconds
    ];

    // extra zero for minutes?
    if(current_time[1] < 10){
        current_time[1] = '0' + current_time[1];
    }

    // extra zero for seconds?
    if(current_time[2] < 10){
        current_time[2] = '0' + current_time[2];
    }

    // extra zeros for milliseconds?
    if(current_time[3] < 10){
        current_time[3] = '00' + current_time[3];
    }else if(current_time[3] < 100){
        current_time[3] = '0' + current_time[3];
    }
}

function draw(){
    calculate_time();
    document.getElementById(0).innerHTML = current_time[0];
    document.getElementById(1).innerHTML = current_time[1];
    document.getElementById(2).innerHTML = current_time[2];
    document.getElementById(3).innerHTML = current_time[3];
}

function reset_timer(){
    if(confirm('Clear splits and reset timer?')){
        stop();
        start_time = -1;
        document.getElementById(0).innerHTML = 0;
        document.getElementById(1).innerHTML = '00';
        document.getElementById(2).innerHTML = '00';
        document.getElementById(3).innerHTML = '000';
        document.getElementById('splits').innerHTML = '';
    }
}

function reset_settings(){
    if(confirm('Reset settings?')){
        document.getElementById('start-key').value = 'H';
        document.getElementById('start-key-display').innerHTML = 'H';

        document.getElementById('reset-key').value = 'T';
        document.getElementById('reset-key-display').innerHTML = 'T';

        save();
    }
}

function save(){
    i = 1;
    do{
        if(document.getElementById(['start-key','reset-key'][i]).value == ['H', 'T'][i]){
            window.localStorage.removeItem('timer' + i);

        }else{
            window.localStorage.setItem(
              'timer' + i,
              document.getElementById(['start-key','reset-key'][i]).value
            );
        }
    }while(i--);

    document.getElementById('reset-key-display').innerHTML = document.getElementById('reset-key').value;
    document.getElementById('start-key-display').innerHTML = document.getElementById('start-key').value;
}

function showhide(){
    document.getElementById('controls').style.display = document.getElementById('controls').style.display === 'none'
      ? 'inline'
      : 'none';
    document.getElementById('settings').style.display = document.getElementById('settings').style.display === 'none'
      ? 'inline'
      : 'none';
}

function start(){
    stop();
    start_time = new Date().getTime() - (start_time === -1 ? 0 : time_ms);
    interval = setInterval('draw()', 20);
}

function stop(){
    clearInterval(interval);
    interval = 0;
}

var current_time = 0;
var i = 0;
var interval = 0;
var start_time = -1;
var time_ms = 0;

// fetch start key from localStorage
if(window.localStorage.getItem('timer0')){
    document.getElementById('start-key').value = window.localStorage.getItem('timer0');
    document.getElementById('start-key-display').innerHTML = window.localStorage.getItem('timer0');

}else{
    document.getElementById('start-key').value = 'H';
}

// fetch reset key from localStorage
if(window.localStorage.getItem('timer1')){
    document.getElementById('reset-key').value = window.localStorage.getItem('timer1');
    document.getElementById('reset-key-display').innerHTML = window.localStorage.getItem('timer1');

}else{
    document.getElementById('reset-key').value = 'T';
}

window.onbeforeunload = function(){
    if(start_time > -1){
        return 'Timer and splits not yet saveable. Leave?';
    }
};

window.onkeydown = function(e){
    i = window.event ? event : e;
    i = i.charCode ? i.charCode : i.keyCode;

    if(i === 32){// Space
        e.preventDefault();
        add_split();

    }else if(i === 27){// ESC
        stop();

    }else if(String.fromCharCode(i) === document.getElementById('start-key').value){
        start();

    }else if(String.fromCharCode(i) === document.getElementById('reset-key').value){
        reset_timer();
    }
}
<|endoftext|>


<commit_before>// var myTime = new Date();
// console.log(myTime);
// var startDate = new Date(2015, 6, 13);
// console.log(startDate);
// var timeleft = myTime - startDate;
// var countdown = new Date(timeleft)
// console.log(countdown.getUTCHours(), countdown.getMinutes(), countdown.getSeconds());

function countdown(){
  var myTime = new Date();
  var end = new Date(2015, 7, 3);
  console.log(end);
  var count = end - myTime;
  console.log(count);
  var timeleft = new Date(count);
  console.log(timeleft.getDate());

  document.getElementById('timer').innerHTML = (timeleft.getDate(), ":", timeleft.getUTCHours(), ":", timeleft.getMinutes(),":", timeleft.getSeconds());

};
<commit_msg>Add timer<commit_after>// var myTime = new Date();
// console.log(myTime);
// var startDate = new Date(2015, 6, 13);
// console.log(startDate);
// var timeleft = myTime - startDate;
// var countdown = new Date(timeleft)
// console.log(countdown.getUTCHours(), countdown.getMinutes(), countdown.getSeconds());

function countdown(){
  var myTime = new Date();
  var end = new Date(2015, 7, 3);
  console.log(end);
  var count = end - myTime;
  console.log(count);
  var timeleft = new Date(count);
  console.log(timeleft.getDate());

  document.getElementById('timer').innerHTML = (timeleft.getDate(), ":", timeleft.getUTCHours(), ":", timeleft.getMinutes(),":", timeleft.getSeconds());

};

window.setTimeout(countdown () , 6000);
<|endoftext|>


<commit_before>// Following function takes a numebrs and returns a rounded off number
function toInteger(number) {
  // Making float to show 2 decimal places
  return parseFloat(number).toFixed(2);
};

// Following function calculates slope between two points a certain distance
function slopeCalc() {
  // Taking input
  var a = document.getElementById('pointA').valueAsNumber;
  var b = document.getElementById('pointB').valueAsNumber;
  var distance = document.getElementById('distance').valueAsNumber;
  // Calculating slope
  var result = toInteger(distance / (b - a));

  document.getElementById('slopeResult').innerHTML = "The slope is 1: " + result;
}

// following function calculates the level of the second point based on the level of the first point, slope to be maintained, and the distance of the second point from the first point
function levelOfSecond() {
  // Taking inputs
  var a = document.getElementById('firstPoint').valueAsNumber;
  var distance = document.getElementById('distanceToSecond').valueAsNumber;
  var slope = document.getElementById('slope').valueAsNumber;

  // If "up" is selected, provide point higher than the first point
  if (document.getElementById('up').checked == true) {
    var result = toInteger(a + (distance / slope));
    output = "The level of second point is " + result;
  }

  // If "down" is selected, provide point lower than the first point
  if (document.getElementById('down').checked == true) {
    var result = toInteger(a - (distance / slope));
    output = "The level of second point is " + result;
  }

  // If neither "up" or "down" is selected, give a message
  if (document.getElementById('up').checked != true && document.getElementById('down').checked != true) {
    output = "Please select either \"up\" or \"Down\""
  }
  // Send output back to HTML
  document.getElementById('levelOfSecond').innerHTML = output;
}

// following function calculates the coplanar distance between two points based on the location of the first point, second point & provided slope

window.onload = function() {

  $('#this').on('change', function() {
    //  alert( this.value ); // or $(this).val()
    if (this.value == "arcLength") {
      $('#div1').show();
      $('#div2,#div3,#selectionMsg').hide();
    } else if (this.value == "arcRadius") {
      $('#div2').show();
      $('#div1,#div3,#selectionMsg').hide();
    } else if (this.value == "centreAngle") {
      $('#div3').show();
      $('#div1,#div2,#selectionMsg').hide();
    } else {
      $('#selectionMsg').show();
      $('#div1,#div2,#div3').hide();
      document.getElementById('selectionMsg').innerHTML = "Please select any of options";
    }
  });
};

function resultArcLength() {
  // Taking input
  var a = document.getElementById('inputRadius').valueAsNumber;
  var b = document.getElementById('inputAngle').valueAsNumber;
  // Calculating Arc Length
  var result = 2 * Math.PI * a * (b / 360);
  var positiveResult = Math.abs(result);

  document.getElementById('arcValue').innerHTML = "The result is: " + positiveResult;
}

function resultArcRadius() {
  // Taking input
  var a = document.getElementById('inputArcLength').valueAsNumber;
  var b = document.getElementById('inputAngle2').valueAsNumber;
  // Calculating Arc Length
  var result = (a * 360) / (2 * Math.PI * b);
  var positiveResult = Math.abs(result);

  document.getElementById('arcValue').innerHTML = "The result is: " + positiveResult;
}

function resultCentreAngle() {
  // Taking input
  var a = document.getElementById('inputArcLength2').valueAsNumber;
  var b = document.getElementById('inputRadius2').valueAsNumber;
  // Calculating Arc Length
  var result = (a * 360) / (2 * Math.PI * b);
  var positiveResult = Math.abs(result);

  document.getElementById('arcValue').innerHTML = "The result is: " + positiveResult;
}
<commit_msg>Add notes, Add distance calculator<commit_after>// Following function takes a numebrs and returns a rounded off number
function toInteger(number) {
  // Making float to show 2 decimal places
  return parseFloat(number).toFixed(2);
};

// Following function calculates slope between two points a certain distance
function slopeCalc() {
  // Taking input
  var a = document.getElementById('pointA').valueAsNumber;
  var b = document.getElementById('pointB').valueAsNumber;
  var distance = document.getElementById('distance').valueAsNumber;
  // Calculating slope
  var result = toInteger(distance / (b - a));

  document.getElementById('slopeResult').innerHTML = "The slope is 1: " + result;
}

// following function calculates the level of the second point based on the level of the first point, slope to be maintained, and the distance of the second point from the first point
function levelOfSecond() {
  // Taking inputs
  var a = document.getElementById('firstPoint').valueAsNumber;
  var distance = document.getElementById('distanceToSecond').valueAsNumber;
  var slope = document.getElementById('slope').valueAsNumber;

  // If "up" is selected, provide point higher than the first point
  if (document.getElementById('up').checked == true) {
    var result = toInteger(a + (distance / slope));
    output = "The level of second point is " + result;
  }

  // If "down" is selected, provide point lower than the first point
  if (document.getElementById('down').checked == true) {
    var result = toInteger(a - (distance / slope));
    output = "The level of second point is " + result;
  }

  // If neither "up" or "down" is selected, give a message
  if (document.getElementById('up').checked != true && document.getElementById('down').checked != true) {
    output = "Please select either \"up\" or \"Down\""
  }
  // Send output back to HTML
  document.getElementById('levelOfSecond').innerHTML = output;
}

// Following function calculates the coplanar distance between two points based on the location of the first point, second point & provided slope

function distanceBwPoints() {
  // Taking input
  var a = document.getElementById('levelA').valueAsNumber;
  var b = document.getElementById('levelB').valueAsNumber;
  var slope = document.getElementById('givenSlope').valueAsNumber;
  // Calculating distance
  var result = toInteger(slope * (b - a));
  var positiveResult = Math.abs(result);

  document.getElementById('distanceBwPoints').innerHTML = "The distance is: " + positiveResult;
}

// Following functions calculate the arc length / arc raduis / centre angle of an arc

// Run script on page load
window.onload = function() {

  // Following are the loops for hiding / showing particular divisitions on option selection
  $('#this').on('change', function() {
    if (this.value == "arcLength") {
      $('#div1').show();
      $('#div2,#div3,#selectionMsg').hide();
    } else if (this.value == "arcRadius") {
      $('#div2').show();
      $('#div1,#div3,#selectionMsg').hide();
    } else if (this.value == "centreAngle") {
      $('#div3').show();
      $('#div1,#div2,#selectionMsg').hide();
    } else {
      $('#selectionMsg').show();
      $('#div1,#div2,#div3').hide();
      document.getElementById('selectionMsg').innerHTML = "Please select any of options";
    }
  });
};

// Function for calculating arc length
function resultArcLength() {
  // Taking input
  var a = document.getElementById('inputRadius').valueAsNumber;
  var b = document.getElementById('inputAngle').valueAsNumber;
  // Calculating Arc Length
  var result = 2 * Math.PI * a * (b / 360);
  var positiveResult = Math.abs(result);
  // Appending result
  document.getElementById('arcValue').innerHTML = "The result is: " + positiveResult;
}

// Function for calculating arc radius
function resultArcRadius() {
  // Taking input
  var a = document.getElementById('inputArcLength').valueAsNumber;
  var b = document.getElementById('inputAngle2').valueAsNumber;
  // Calculating Arc Radius
  var result = (a * 360) / (2 * Math.PI * b);
  var positiveResult = Math.abs(result);
  // Appending result
  document.getElementById('arcValue').innerHTML = "The result is: " + positiveResult;
}

// Function for calculating arc radius
function resultCentreAngle() {
  // Taking input
  var a = document.getElementById('inputArcLength2').valueAsNumber;
  var b = document.getElementById('inputRadius2').valueAsNumber;
  // Calculating Centre Angle
  var result = (a * 360) / (2 * Math.PI * b);
  var positiveResult = Math.abs(result);
  // Appending result
  document.getElementById('arcValue').innerHTML = "The result is: " + positiveResult;
}
<|endoftext|>


<commit_before>Parse.initialize("eXa6XCYsez7lkZpf2ytbtRinq0STc1w9NvJkkf4p", "H4gpX9rYLfaYccdgjxP6OH48bPfK2jHeM8e1dr8Z");

var from = "";
var to = "";
// 出發地點預設值

var now = new Date();
var y = now.getFullYear();
var m = now.getMonth() + 1;
var d = now.getDate();
set_date(y, m, d);
// 時間預設值（當天）

var time_choose = 0;
var type_choose = 0;
var time = "00:00";
time = cal_time(time);
// 客人選擇預設為『出發時間』、『全部類型』

var train_date = [];
var train_info = [];
var station = [];
var tr_type = ["太魯閣號", "新自強", "自強", "莒光", "復興", "區間快", "區間車", "電車", "兩鐵", "單機迴送", "客迴", "普快車", "普通貨車", "普通車", "柴客", "柴快車", "柴油車" ,"柴迴", "特種", "臨時客迴", "行包專車", "試轉運", "調車列車"];
var tr_diration = ["去程", "返程", "順行", "逆行" ,"南下", "北上"];
var tr_line = ["不經山海線", "山線", "海線"];
var show_data = [];
var from_id;
var to_id;
get_cost(from,to);
document.getElementById("date").value = date;

var station_api = "http://210.59.250.227:80/MOTC/v1/Rail/TRA/Station?%24format=json";
get_info(station_api, 0);
var train_info_api = "http://210.59.250.227:80/MOTC/v1/Rail/TRA/TrainInfo/" + date + "?%24format=json";
var train_date_api = "http://210.59.250.227:80/MOTC/v1/Rail/TRA/DailyTimetable/" + date + "?%24format=json";

var cost_1;
var cost_2;
var cost_3;

function set_date(y, m, d){
     year = y;
     month = m;
     day = d;
     date = (y + "-" + m + "-" + d);
           document.getElementById("date").value = date;

} // 取得理想格式的時間

function get_info(url,index){
     var httpRequest;
     if (window.XMLHttpRequest) { // Mozilla, Safari, ...
          httpRequest = new XMLHttpRequest();
     } else if (window.ActiveXObject) { // IE
          httpRequest = new ActiveXObject("Microsoft.XMLHTTP");
     }
     httpRequest.open('GET', url, true);
     httpRequest.send(null);
     httpRequest.onreadystatechange = function() {
          Contents(httpRequest);
     };
     function Contents (httpRequest) {
          if (httpRequest.readyState == 4) {
               if (httpRequest.status == 200) {
                    switch(index){
                         case 0:
                              station = JSON.parse(httpRequest.responseText);
                              get_info(train_date_api, 1);
                              break;
                         case 1:
                              train_date[day] = JSON.parse(httpRequest.responseText);
                              show_data.length = 0;
                              from_id = changeID(from);
                              to_id = changeID(to);

                              get_info(train_info_api, 2);
                              // console.log("from : " + from);
                              // console.log("To : " + to);
                              // console.log("date : " + date);
                              break;
                         case 2:
                              train_info[day] = JSON.parse(httpRequest.responseText);
                              find_train_time(from_id, to_id, train_date[day], train_info[day], type_choose, time_choose);
                              show_data.sort(function(a,b){
                                   return a.order > b.order ? 1 : -1;;
                              });
                              var test3="";
                              var title="

	" + from +" -> " + to +"	By	Spend	Cost
";
                              var tail="
";
                              for(var n=0;n<show_data.length;n++){
                              test3 = test3 + "
<input type= checkbox value= Travel " + "id = train_" + n + " name=interest onclick=trainCheck(this) >	" + show_data[n].Arrival_t +" -> "+show_data[n].departure_t + "	" + show_data[n].Type + show_data[n].ID + "	" + show_data[n].during_t +"	" + show_data[n].cost +"
";
                              }
                              test3 = title + test3 + tail;

							  if(show_data!="")
							  {
                              setTimeout(function(){$("#S1").html(test3);},1000);
                              }

                              // console.log(show_data);
                              break;
                         default:
                              alert ("伺服器處理錯誤");
                              break;
                    }
          }
          }
     }
} // 連API去取得資訊回來

function changeID (id) {
     for (var i = 0; i < station.length; i++)
     {
          if (id == station[i].StationName.Zh_tw)
          {
               return station[i].StationID;
          }
     }
} // 將中文站名換成代碼

function find_train_time(f_id, t_id, traindate, trainInfo, type_choose, time_choose){

     for (var i = 0; i < traindate.length; i ++)
     {
          type = tr_type[trainInfo[i].TrainClassification];
          if (type_choose == 2 && (type != "區間車" && type != "區間快")){
                    continue;
          }
          else if (type_choose == 1 && (type == "區間車" || type == "區間快")){
                    continue;
          }    // 篩選車型

          var buffer = 0;
          for (var j = 0; j < traindate[i].StoppingTimeElement.length; j++){

               if (f_id == traindate[i].StoppingTimeElement[j].StationID){
                    var train = new Object();
                    train.Arrival_t = traindate[i].StoppingTimeElement[j].ArrivalTime;
                    buffer = traindate[i].StoppingTimeElement[j].StopSequence;
               }
               else if (t_id == traindate[i].StoppingTimeElement[j].StationID && buffer > 0){

                    train.departure_t = traindate[i].StoppingTimeElement[j].DepartureTime;
                    train.ID = traindate[i].TrainNo;
                    train.Type = type;
                    train.order = cal_time(train.Arrival_t);
                    train.during_t = cal_during_t(train);
                         // 將資訊放入名為train的object

                    if (time_choose == 0 && train.order < time){
                         continue;
                    }
                    else if (time_choose == 1 && cal_time(train.departure_t) > time){
                         continue;
                    }    // 篩選條件『出發、抵達』時間

                    if(trainInfo[i].TrainClassification==0||trainInfo[i].TrainClassification==1||trainInfo[i].TrainClassification==2)
                              {
                                   train.cost = cost_3;
                              }
                              if(trainInfo[i].TrainClassification==3)
                              {
                                   train.cost = cost_2;
                              }
                              if(trainInfo[i].TrainClassification==4||trainInfo[i].TrainClassification==5||trainInfo[i].TrainClassification==6)
                              {
                                   train.cost = cost_1;
                              }  // 計算票價

					//console.log(train.cost);

                    show_data.push(train);

                    break;
               }
          }

     }
} // 從API載下來的資料中去挑選想要車次

function cal_time(t){
     var time;
     time = parseInt(t[0]+t[1]) * 60 + parseInt(t[3]+t[4]);
     return time;
} // 計算總秒數->幫助排列從早到晚的車次

function cal_during_t(train){
     var during = cal_time(train.departure_t) - cal_time(train.Arrival_t);
     if(during>=0){
          ;
     }
     else{
     during =  1440 - cal_time(train.Arrival_t) + cal_time(train.departure_t);
     }
     var hour = parseInt(during / 60);
     var minute = during - hour*60;
     return (hour + "小時" + minute + "分");
} // 計算車程所耗費的時間

function search(a,b,c,d,e,f){

     from = a;
     to = b;

     if (from == to){
          return alert("上下車地點相同喔～請重新選擇");
     }    // 避免相同地點

     time_choose = c;
          // console.log(time_choose);
          // 『出發時間』的值會等於 0;
          // 『抵達時間』的值會等於 1;

     time = d;      // 『出發or抵達』時間值
     time = cal_time(time);

     type_choose = e;
          //『全部類型』的值等於 0;
          //『對號』的值等於 1;
          //『非對號』的值等於 2;

           //console.log(c.date);
     date =document.getElementById("date").value;
     get_cost(from,to);
           //console.log(d);
     //set_date(c.date.getFullYear(), c.date.getMonth() + 1, c.date.getDate());
          // 取得固定格式的時間 -> 以利放入api的網址中
     from_id = changeID(from);
     to_id = changeID(to);         // 轉換中文成ID

     get_info(train_date_api, 1);  // 取得api中的資料（這裡會連鎖開始跑程式去篩選）

	 if(f==0)
	 {
	 loadTab("台鐵",1,0);
	 $('#tabsC').modal();
	 }

          /* jQuery("html,body").animate({
                                             scrollTop:$("#tabsC").offset().top
                                             },800);*/
} // 按鈕按下後所跑的程式

function get_cost(from,to){
     var cost;

     var query = new Parse.Query("cost_west");
     query.limit(200);
     query.find({
          success: function(results) {
          //console.log("1");
          //alert("Successfully retrieved " + results.length + " scores.");
          // Do something with the returned Parse.Object values
          for (var i = 0; i < results.length; i++) {
               var object = results[i];

               if(object.get('station')==from)
               {
                    var from_distance = object.get('distance');
               }
               else if(object.get('station')==to)
               {

                    var to_distance = object.get('distance');
               }

               //alert(object.id + ' - ' + object.get('distance'));
          }
          sub = Math.abs(to_distance - from_distance);
          if(sub<10)
          {
               cost_1=15;
               cost_2=18;
               cost_3=23;
          }
          else
          {
               cost_1=Math.ceil(1.46*sub);
               cost_2=Math.ceil(1.75*sub);
               cost_3=Math.ceil(2.27*sub);
          }
          /*console.log(cost_1);
          console.log(cost_2);
          console.log(cost_3);*/
          /*console.log(sub);
          console.log(type);
          console.log(dir);
          console.log(cost);*/
          //return cost;

          //alert(to_distance);
          },
          error: function(error) {
               alert("Error: " + error.code + " " + error.message);
          }
     });
}// 取的票價

function trainCheck(buffer){
     var cloneNode = buffer.parentNode.parentNode.cloneNode(true); // 複製一個新的node
     if(buffer.checked == true){
          if(Choose_Train.children.length == 0){
               Choose_Train.innerHTML = "

台鐵	" + from +" -> " + to +"	By	Spend	Cost
";
               t5.children[0].appendChild(cloneNode);

          } // 建立首欄＆新增喜好時刻
          else{
               t5.children[0].appendChild(cloneNode);
          }
     }
     else{
          for (var i = 1; i < t5.childNodes[0].children.length; i++){
               var node = t5.childNodes[0].childNodes[i];
               var id = node.childNodes[0].childNodes[0].id;
               if (id == buffer.id){
                    document.getElementById(id).checked = false;
                    t5.childNodes[0].removeChild(t5.childNodes[0].childNodes[i]);
               } // 刪除喜好時刻 & 取消勾選
               if(t5.childNodes[0].children.length == 1){
                    Choose_Train.removeChild(Choose_Train.firstChild);
                    break;
               } // 刪除首欄
          }
     }
}// 選取喜好的火車時段
<commit_msg>buy ticket v1<commit_after>Parse.initialize("eXa6XCYsez7lkZpf2ytbtRinq0STc1w9NvJkkf4p", "H4gpX9rYLfaYccdgjxP6OH48bPfK2jHeM8e1dr8Z");

var from = "";
var to = "";
// 出發地點預設值

var now = new Date();
var y = now.getFullYear();
var m = now.getMonth() + 1;
var d = now.getDate();
set_date(y, m, d);
// 時間預設值（當天）

var time_choose = 0;
var type_choose = 0;
var time = "00:00";
time = cal_time(time);
// 客人選擇預設為『出發時間』、『全部類型』

var buy;
var train_date = [];
var train_info = [];
var station = [];
var tr_type = ["太魯閣號", "新自強", "自強", "莒光", "復興", "區間快", "區間車", "電車", "兩鐵", "單機迴送", "客迴", "普快車", "普通貨車", "普通車", "柴客", "柴快車", "柴油車" ,"柴迴", "特種", "臨時客迴", "行包專車", "試轉運", "調車列車"];
var tr_diration = ["去程", "返程", "順行", "逆行" ,"南下", "北上"];
var tr_line = ["不經山海線", "山線", "海線"];
var show_data = [];
var from_id;
var to_id;
get_cost(from,to);
document.getElementById("date").value = date;

var station_api = "http://210.59.250.227:80/MOTC/v1/Rail/TRA/Station?%24format=json";
get_info(station_api, 0);
var train_info_api = "http://210.59.250.227:80/MOTC/v1/Rail/TRA/TrainInfo/" + date + "?%24format=json";
var train_date_api = "http://210.59.250.227:80/MOTC/v1/Rail/TRA/DailyTimetable/" + date + "?%24format=json";

var cost_1;
var cost_2;
var cost_3;

function set_date(y, m, d){
     year = y;
     month = m;
     day = d;
     date = (y + "-" + m + "-" + d);
     data2= (y + "/" + m + "/" + d);
           document.getElementById("date").value = date;

} // 取得理想格式的時間

function get_info(url,index){
     var httpRequest;
     if (window.XMLHttpRequest) { // Mozilla, Safari, ...
          httpRequest = new XMLHttpRequest();
     } else if (window.ActiveXObject) { // IE
          httpRequest = new ActiveXObject("Microsoft.XMLHTTP");
     }
     httpRequest.open('GET', url, true);
     httpRequest.send(null);
     httpRequest.onreadystatechange = function() {
          Contents(httpRequest);
     };
     function Contents (httpRequest) {
          if (httpRequest.readyState == 4) {
               if (httpRequest.status == 200) {
                    switch(index){
                         case 0:
                              station = JSON.parse(httpRequest.responseText);
                              get_info(train_date_api, 1);
                              break;
                         case 1:
                              train_date[day] = JSON.parse(httpRequest.responseText);
                              show_data.length = 0;
                              from_id = changeID(from);
                              to_id = changeID(to);

                              get_info(train_info_api, 2);
                              // console.log("from : " + from);
                              // console.log("To : " + to);
                              // console.log("date : " + date);
                              break;
                         case 2:
                              train_info[day] = JSON.parse(httpRequest.responseText);
                              find_train_time(from_id, to_id, train_date[day], train_info[day], type_choose, time_choose);
                              show_data.sort(function(a,b){
                                   return a.order > b.order ? 1 : -1;;
                              });
                              var test3="";
                              var title="

	" + from +" -> " + to +"	By	Spend	Cost
";
                              var tail="
";
                              for(var n=0;n<show_data.length;n++){
			      buy_ticket(n);
                              test3 = test3 + "
<input type= checkbox value= Travel " + "id = train_" + n + " name=interest onclick=trainCheck(this) >	" + show_data[n].Arrival_t +" -> "+show_data[n].departure_t + "	" + show_data[n].Type + show_data[n].ID + "	" + show_data[n].during_t +"	" + show_data[n].cost +"buy"+"
";
                              }
                              test3 = title + test3 + tail;

							  if(show_data!="")
							  {
                              setTimeout(function(){$("#S1").html(test3);},1000);
                              }

                              // console.log(show_data);
                              break;
                         default:
                              alert ("伺服器處理錯誤");
                              break;
                    }
          }
          }
     }
} // 連API去取得資訊回來

function changeID (id) {
     for (var i = 0; i < station.length; i++)
     {
          if (id == station[i].StationName.Zh_tw)
          {
               return station[i].StationID;
          }
     }
} // 將中文站名換成代碼

function find_train_time(f_id, t_id, traindate, trainInfo, type_choose, time_choose){

     for (var i = 0; i < traindate.length; i ++)
     {
          type = tr_type[trainInfo[i].TrainClassification];
          if (type_choose == 2 && (type != "區間車" && type != "區間快")){
                    continue;
          }
          else if (type_choose == 1 && (type == "區間車" || type == "區間快")){
                    continue;
          }    // 篩選車型

          var buffer = 0;
          for (var j = 0; j < traindate[i].StoppingTimeElement.length; j++){

               if (f_id == traindate[i].StoppingTimeElement[j].StationID){
                    var train = new Object();
                    train.Arrival_t = traindate[i].StoppingTimeElement[j].ArrivalTime;
                    buffer = traindate[i].StoppingTimeElement[j].StopSequence;
               }
               else if (t_id == traindate[i].StoppingTimeElement[j].StationID && buffer > 0){

                    train.departure_t = traindate[i].StoppingTimeElement[j].DepartureTime;
                    train.ID = traindate[i].TrainNo;
                    train.Type = type;
                    train.order = cal_time(train.Arrival_t);
                    train.during_t = cal_during_t(train);
                         // 將資訊放入名為train的object

                    if (time_choose == 0 && train.order < time){
                         continue;
                    }
                    else if (time_choose == 1 && cal_time(train.departure_t) > time){
                         continue;
                    }    // 篩選條件『出發、抵達』時間

                    if(trainInfo[i].TrainClassification==0||trainInfo[i].TrainClassification==1||trainInfo[i].TrainClassification==2)
                              {
                                   train.cost = cost_3;
                              }
                              if(trainInfo[i].TrainClassification==3)
                              {
                                   train.cost = cost_2;
                              }
                              if(trainInfo[i].TrainClassification==4||trainInfo[i].TrainClassification==5||trainInfo[i].TrainClassification==6)
                              {
                                   train.cost = cost_1;
                              }  // 計算票價

					//console.log(train.cost);

                    show_data.push(train);

                    break;
               }
          }

     }
} // 從API載下來的資料中去挑選想要車次

function cal_time(t){
     var time;
     time = parseInt(t[0]+t[1]) * 60 + parseInt(t[3]+t[4]);
     return time;
} // 計算總秒數->幫助排列從早到晚的車次

function cal_during_t(train){
     var during = cal_time(train.departure_t) - cal_time(train.Arrival_t);
     if(during>=0){
          ;
     }
     else{
     during =  1440 - cal_time(train.Arrival_t) + cal_time(train.departure_t);
     }
     var hour = parseInt(during / 60);
     var minute = during - hour*60;
     return (hour + "小時" + minute + "分");
} // 計算車程所耗費的時間

function search(a,b,c,d,e,f){

     from = a;
     to = b;

     if (from == to){
          return alert("上下車地點相同喔～請重新選擇");
     }    // 避免相同地點

     time_choose = c;
          // console.log(time_choose);
          // 『出發時間』的值會等於 0;
          // 『抵達時間』的值會等於 1;

     time = d;      // 『出發or抵達』時間值
     time = cal_time(time);

     type_choose = e;
          //『全部類型』的值等於 0;
          //『對號』的值等於 1;
          //『非對號』的值等於 2;

           //console.log(c.date);
     date =document.getElementById("date").value;
     get_cost(from,to);
           //console.log(d);
     //set_date(c.date.getFullYear(), c.date.getMonth() + 1, c.date.getDate());
          // 取得固定格式的時間 -> 以利放入api的網址中
     from_id = changeID(from);
     to_id = changeID(to);         // 轉換中文成ID

     get_info(train_date_api, 1);  // 取得api中的資料（這裡會連鎖開始跑程式去篩選）

	 if(f==0)
	 {
	 loadTab("台鐵",1,0);
	 $('#tabsC').modal();
	 }

          /* jQuery("html,body").animate({
                                             scrollTop:$("#tabsC").offset().top
                                             },800);*/
} // 按鈕按下後所跑的程式

function get_cost(from,to){
     var cost;

     var query = new Parse.Query("cost_west");
     query.limit(200);
     query.find({
          success: function(results) {
          //console.log("1");
          //alert("Successfully retrieved " + results.length + " scores.");
          // Do something with the returned Parse.Object values
          for (var i = 0; i < results.length; i++) {
               var object = results[i];

               if(object.get('station')==from)
               {
                    var from_distance = object.get('distance');
               }
               else if(object.get('station')==to)
               {

                    var to_distance = object.get('distance');
               }

               //alert(object.id + ' - ' + object.get('distance'));
          }
          sub = Math.abs(to_distance - from_distance);
          if(sub<10)
          {
               cost_1=15;
               cost_2=18;
               cost_3=23;
          }
          else
          {
               cost_1=Math.ceil(1.46*sub);
               cost_2=Math.ceil(1.75*sub);
               cost_3=Math.ceil(2.27*sub);
          }
          /*console.log(cost_1);
          console.log(cost_2);
          console.log(cost_3);*/
          /*console.log(sub);
          console.log(type);
          console.log(dir);
          console.log(cost);*/
          //return cost;

          //alert(to_distance);
          },
          error: function(error) {
               alert("Error: " + error.code + " " + error.message);
          }
     });
}// 取的票價

function trainCheck(buffer){
     var cloneNode = buffer.parentNode.parentNode.cloneNode(true); // 複製一個新的node
     if(buffer.checked == true){
          if(Choose_Train.children.length == 0){
               Choose_Train.innerHTML = "

台鐵	" + from +" -> " + to +"	By	Spend	Cost
";
               t5.children[0].appendChild(cloneNode);

          } // 建立首欄＆新增喜好時刻
          else{
               t5.children[0].appendChild(cloneNode);
          }
     }
     else{
          for (var i = 1; i < t5.childNodes[0].children.length; i++){
               var node = t5.childNodes[0].childNodes[i];
               var id = node.childNodes[0].childNodes[0].id;
               if (id == buffer.id){
                    document.getElementById(id).checked = false;
                    t5.childNodes[0].removeChild(t5.childNodes[0].childNodes[i]);
               } // 刪除喜好時刻 & 取消勾選
               if(t5.childNodes[0].children.length == 1){
                    Choose_Train.removeChild(Choose_Train.firstChild);
                    break;
               } // 刪除首欄
          }
     }
}// 選取喜好的火車時段

function buy_ticket(n){
buy="http://railway.hinet.net/ctno1.htm?from_station=";
var  x1=from;
var x2=to;
var x3=show_data[n].ID.
buy=buy+x1+"&to_station="+x2+"&getin_date="+data2+"&train_no="+x3;
}

<|endoftext|>


<commit_before>// -*- coding: utf-8 -*-
/*
 (c) 2014 Andreas Motl, Elmyra UG <andreas.motl@elmyra.de>
 derived from https://github.com/tavendo/AutobahnPython/blob/master/examples/twisted/wamp/pubsub/simple/example2/index.html
 */

// WAMP session object
var sess;
var wsuri;

window.onload = function() {

    if (window.location.protocol === "file:") {
        wsuri = "ws://localhost:9000";
    } else {
        wsuri = "ws://" + window.location.hostname + ":9000";
    }

    //ab.debug(true, true, true);

    // connect to WAMP server
    ab.connect(wsuri,

        // WAMP session was established
        function(session) {

            sess = session;
            console.log("Connected!");

            sess.prefix("registry", "http://ilaundry.useeds.de/registry#");
            sess.prefix("broadcast", "http://ilaundry.useeds.de/broadcast#");
            sess.prefix("dashboard", "http://ilaundry.useeds.de/dashboard#");

            sess.subscribe("broadcast:node-heartbeat", node_heartbeat);
            sess.subscribe("broadcast:node-activity", dump_event);
            sess.subscribe("broadcast:node-activity", node_activity);
            sess.subscribe("broadcast:node-privacy", dump_event);
            sess.subscribe("dashboard:update", dashboard_update);

            // trigger dashboard update
            sess.publish("dashboard:update", null, false);

        },

        // WAMP session is gone
        function(code, reason) {
            sess = null;
            //alert(reason);
        }
    );
};

function dump_event(topic, event) {
    console.log({'topic': topic, 'event': event});
}

function node_heartbeat(topic, node_id) {
    console.log({'topic': topic, 'node_id': node_id});
}

function node_activity(topic, event) {
    var node_id = event.node_id;
    var state = event.state;
    console.log({'topic': topic, 'node_id': node_id, 'state': state});
}

function dashboard_update(topic, event) {
    sess.call("registry:get_nodelist").then(function(nodelist) {
        ab.log('nodelist: ' + nodelist);
        var node_select = document.getElementById("node_id");
        node_select.options.length = 0;
        for (index in nodelist) {
            var node_id = nodelist[index];
            node_select.options[node_select.options.length] = new Option(node_id, node_id);
        }
    });
}

function sayText(node_id, message) {
    /*
    evt = {};
    evt.node_id = node_id;
    evt.message = message;
    evt.date = new Date();
    */

    if (!sess) {
        console.error('ERROR: No WAMP session with iLaundry master service');
        return;
    }

    var node_topic = 'http://ilaundry.useeds.de/node/' + node_id + '#';
    sess.prefix(node_id, node_topic);
    //sess.subscribe(node_topic, dump_event);
    var event_topic = node_id + ':say';
    sess.publish(event_topic, message);
}
<commit_msg>ui: better debugging<commit_after>// -*- coding: utf-8 -*-
/*
 (c) 2014 Andreas Motl, Elmyra UG <andreas.motl@elmyra.de>
 derived from https://github.com/tavendo/AutobahnPython/blob/master/examples/twisted/wamp/pubsub/simple/example2/index.html
 */

// WAMP session object
var sess;
var wsuri;

window.onload = function() {

    if (window.location.protocol === "file:") {
        wsuri = "ws://localhost:9000";
    } else {
        wsuri = "ws://" + window.location.hostname + ":9000";
    }

    //ab.debug(true, true, true);

    // connect to WAMP server
    ab.connect(wsuri,

        // WAMP session was established
        function(session) {

            sess = session;
            console.log("Connected!");

            sess.prefix("registry", "http://ilaundry.useeds.de/registry#");
            sess.prefix("broadcast", "http://ilaundry.useeds.de/broadcast#");
            sess.prefix("dashboard", "http://ilaundry.useeds.de/dashboard#");

            sess.subscribe("broadcast:node-heartbeat", node_heartbeat);
            //sess.subscribe("broadcast:node-activity", dump_event);
            sess.subscribe("broadcast:node-activity", node_state);
            sess.subscribe("broadcast:node-privacy", node_state);
            sess.subscribe("dashboard:update", dashboard_update);

            // trigger dashboard update
            sess.publish("dashboard:update", null, false);

        },

        // WAMP session is gone
        function(code, reason) {
            sess = null;
            //alert(reason);
        }
    );
};

function dump_event(topic, event) {
    console.log({'topic': topic, 'event': event});
}

function node_heartbeat(topic, node_id) {
    console.log({'topic': topic, 'node_id': node_id});
}

function node_state(topic, event) {
    var node_id = event.node_id;
    var state = event.state;
    console.log({'topic': topic, 'node_id': node_id, 'state': state});
}

function dashboard_update(topic, event) {
    sess.call("registry:get_nodelist").then(function(nodelist) {
        ab.log('nodelist: ' + nodelist);
        var node_select = document.getElementById("node_id");
        node_select.options.length = 0;
        for (index in nodelist) {
            var node_id = nodelist[index];
            node_select.options[node_select.options.length] = new Option(node_id, node_id);
        }
    });
}

function sayText(node_id, message) {
    /*
    evt = {};
    evt.node_id = node_id;
    evt.message = message;
    evt.date = new Date();
    */

    if (!sess) {
        console.error('ERROR: No WAMP session with iLaundry master service');
        return;
    }

    var node_topic = 'http://ilaundry.useeds.de/node/' + node_id + '#';
    sess.prefix(node_id, node_topic);
    //sess.subscribe(node_topic, dump_event);
    var event_topic = node_id + ':say';
    sess.publish(event_topic, message);
}
<|endoftext|>