<commit_before>//= require jquery-ui/ui/core.js
//= require jquery-ui/ui/widget.js
//= require jquery-ui/ui/mouse.js
//= require jquery-ui/ui/slider.js
//= require accessible.media.player/core/javascript/swfobject/swfobject.js
//= require accessible.media.player/core/javascript/browser.js
//= require accessible.media.player/core/javascript/jquery.player.js
//= require accessible.media.player/core/javascript/youtube_player.js
//= require accessible.media.player/core/javascript/mediaplayer_decorator.js

(function() {
  'use strict';

  class VideoPlayer {
    constructor() {
      this.init();
    }

    init() {
      this.$playButton = $('.js-youtube-play');
      this.$holdingImage = $('.js-youtube-holding');
      this.youtubeId = this.$playButton.data('youtube-id');
      this.transcript = {};
      this.transcript.$toggle = $('.js-video-transcript-toggle');
      this.transcript.$copy = $('.js-video-transcript-copy');
      this.transcript.$content = $('.js-video-transcript');
      this.transcript.$content.attr('aria-hidden', false);

      this.embedLink();
      this.enableTranscriptToggle();
    }

    embedLink() {
      this.$playButton.on('click', this.handlePlayButton.bind(this));
    }

    handlePlayButton() {
      $(`<a href="https://www.youtube.com/watch?v=${this.youtubeId}">Youtube video</a>`)
        .insertAfter(this.$playButton);
      this.$playButton.remove();
      this.$holdingImage.remove();
      this.convertLinksToPlayers();
    }

    convertLinksToPlayers() {
      const $yt_links = $('a[href*="http://www.youtube.com/watch"],a[href*="https://www.youtube.com/watch"]');

      $.each($yt_links, (i, link) => {
        let $holder = $('<span />');

        $(link).replaceWith($holder);

        const $mycaptions = $(this).siblings('.captions'),
          captionsf = $($mycaptions).length > 0 ? $($mycaptions).attr('href') : null,
          videoId = $(link).attr('href').split("=")[1],
          youTubeURL = document.location.protocol + '//www.youtube.com/apiplayer?autoplay=1&enablejsapi=1&version=3&playerapiid=';

        $holder.player({
          id: 'yt' + i,
          media: videoId,
          captions: captionsf,
          url: youTubeURL,
          flashHeight: '252px'
        });

        window.NOMENSA.player.PlayerDaemon.getPlayer('yt' + i).onPlayerReady(function() {
          this.play();
        });
      });
    }

    enableTranscriptToggle() {
      this.handleTranscriptToggle();
      this.transcript.$toggle.removeClass('visually-hidden');
      this.transcript.$content.html(this.transcript.$copy.text());
      this.transcript.$toggle.on('click', this.handleTranscriptToggle.bind(this));
    }

    handleTranscriptToggle(e) {
      if (e) {
        e.preventDefault();
      }

      if (this.transcript.$content.is(':visible')) {
        this.transcript.$content.attr('aria-hidden', true).slideUp();
        this.transcriptToggleTextReplace('Hide', 'Show');
      } else {
        this.transcript.$content
          .attr('aria-hidden', false)
          .slideDown()
          .focus();

        this.transcriptToggleTextReplace('Show', 'Hide');
      }
    }

    transcriptToggleTextReplace(from, to) {
      this.transcript.$toggle.text(this.transcript.$toggle.text().replace(from, to));
    }
  }

  window.PWPG = window.PWPG || {};
  window.PWPG.VideoPlayer = VideoPlayer;

  new VideoPlayer();
})();
<commit_msg>Add video state change to GTM dataLayer<commit_after>//= require jquery-ui/ui/core.js
//= require jquery-ui/ui/widget.js
//= require jquery-ui/ui/mouse.js
//= require jquery-ui/ui/slider.js
//= require accessible.media.player/core/javascript/swfobject/swfobject.js
//= require accessible.media.player/core/javascript/browser.js
//= require accessible.media.player/core/javascript/jquery.player.js
//= require accessible.media.player/core/javascript/youtube_player.js
//= require accessible.media.player/core/javascript/mediaplayer_decorator.js

(function() {
  'use strict';

  class VideoPlayer {
    constructor() {
      this.init();
    }

    init() {
      this.$playButton = $('.js-youtube-play');
      this.$holdingImage = $('.js-youtube-holding');
      this.youtubeId = this.$playButton.data('youtube-id');
      this.transcript = {};
      this.transcript.$toggle = $('.js-video-transcript-toggle');
      this.transcript.$copy = $('.js-video-transcript-copy');
      this.transcript.$content = $('.js-video-transcript');
      this.transcript.$content.attr('aria-hidden', false);

      this.embedLink();
      this.enableTranscriptToggle();
    }

    embedLink() {
      this.$playButton.on('click', this.handlePlayButton.bind(this));
    }

    handlePlayButton() {
      $(`<a href="https://www.youtube.com/watch?v=${this.youtubeId}">Youtube video</a>`)
        .insertAfter(this.$playButton);
      this.$playButton.remove();
      this.$holdingImage.remove();
      this.convertLinksToPlayers();
    }

    convertLinksToPlayers() {
      const $yt_links = $('a[href*="http://www.youtube.com/watch"],a[href*="https://www.youtube.com/watch"]');

      $.each($yt_links, (i, link) => {
        let $holder = $('<span />');

        $(link).replaceWith($holder);

        const $mycaptions = $(this).siblings('.captions'),
          captionsf = $($mycaptions).length > 0 ? $($mycaptions).attr('href') : null,
          videoId = $(link).attr('href').split("=")[1],
          youTubeURL = document.location.protocol + '//www.youtube.com/apiplayer?autoplay=1&enablejsapi=1&version=3&playerapiid=';

        $holder.player({
          id: 'yt' + i,
          media: videoId,
          captions: captionsf,
          url: youTubeURL,
          flashHeight: '252px'
        });

        window.NOMENSA.player.PlayerDaemon.getPlayer('yt' + i).onPlayerReady(function() {
          const originalOnPlayerStateChange = this.onPlayerStateChange;

          this.onPlayerStateChange = function(stateId) {
            dataLayer.push({
              'event': 'onPlayerStateChange',
              'eventValue': stateId
            });

            originalOnPlayerStateChange.apply(this, arguments);
          };

          this.play();
        });
      });
    }

    enableTranscriptToggle() {
      this.handleTranscriptToggle();
      this.transcript.$toggle.removeClass('visually-hidden');
      this.transcript.$content.html(this.transcript.$copy.text());
      this.transcript.$toggle.on('click', this.handleTranscriptToggle.bind(this));
    }

    handleTranscriptToggle(e) {
      if (e) {
        e.preventDefault();
      }

      if (this.transcript.$content.is(':visible')) {
        this.transcript.$content.attr('aria-hidden', true).slideUp();
        this.transcriptToggleTextReplace('Hide', 'Show');
      } else {
        this.transcript.$content
          .attr('aria-hidden', false)
          .slideDown()
          .focus();

        this.transcriptToggleTextReplace('Show', 'Hide');
      }
    }

    transcriptToggleTextReplace(from, to) {
      this.transcript.$toggle.text(this.transcript.$toggle.text().replace(from, to));
    }
  }

  window.PWPG = window.PWPG || {};
  window.PWPG.VideoPlayer = VideoPlayer;

  new VideoPlayer();
})();
<|endoftext|>


<commit_before>import React from 'react';
import { Text, View, StyleSheet } from 'react-native';
import PropTypes from 'prop-types';
import { connect } from 'react-redux';
import { NavigationActions } from 'react-navigation';

import jurisdictionFile from '../data/jurisdiction.json';
import statusFile from '../data/status.json';
import { getItemById, mapToRealStatus } from '../utils';
import { primaryColor, greyDark } from '../styles/colors';

class FoiRequestsListHeader extends React.Component {
  render() {
    const filterJurisdiction = this.props.filter.jurisdiction;
    let filterJurisdictionText = 'ALL';

    if (filterJurisdiction) {
      const jurisdictionName = jurisdictionFile.find(
        getItemById(filterJurisdiction)
      ).name;
      filterJurisdictionText = `${jurisdictionName}`.toUpperCase();
    }

    const filterStatus = this.props.filter.status;
    let filterStatusText = 'ALL';

    if (filterStatus) {
      const statusName = statusFile.find(getItemById(filterStatus)).name;
      filterStatusText = `${statusName}`.toUpperCase();
    }

    const filterCategory = this.props.filter.Category;
    let filterCategoryText = 'ALL';

    if (filterCategory) {
      // const categoryName = CategoryFile.find(getItemById(filterCategory)).name;
      const categoryName = 'Category'; // TODO
      filterCategoryText = `${categoryName}`.toUpperCase();
    }

    return (
      <View style={styles.container}>
        <View
          style={{
            flexDirection: 'row',
            justifyContent: 'space-between',
          }}
        >
          <View style={[styles.item, styles.firstItem]}>
            <Text style={styles.label}>JURISDICTION</Text>
            <Text style={styles.selection}>
              {filterJurisdictionText}
            </Text>
          </View>
          <View style={styles.item}>
            <Text style={styles.label}>STATUS</Text>
            <Text style={styles.selection}>
              {filterStatusText}
            </Text>
          </View>
          <View style={styles.item}>
            <Text style={styles.label}>CATEGORY</Text>
            <Text style={styles.selection}>
              {filterCategoryText}
            </Text>
          </View>
        </View>
      </View>
    );
  }
}

const mapStateToProps = state => {
  return {
    filter: state.foiRequests.filter,
    nResults: state.foiRequests.nResults,
  };
};

const mapDispatchToProps = dispatch => {
  return {
    navigateToFilter: () =>
      dispatch(NavigationActions.navigate({ routeName: 'Filter' })),
  };
};

export default connect(mapStateToProps, mapDispatchToProps)(
  FoiRequestsListHeader
);

const styles = StyleSheet.create({
  container: {
    backgroundColor: 'white',
    borderBottomWidth: 1,
    borderTopWidth: 1,
    borderBottomColor: greyDark,
    borderTopColor: greyDark,
  },
  item: {
    flexGrow: 1,
    flexBasis: 0,
    borderLeftWidth: 1,
    borderColor: greyDark,
    paddingHorizontal: 10,
    paddingVertical: 5,
  },
  firstItem: {
    borderLeftWidth: 0,
  },
  label: {
    fontSize: 12,
    color: greyDark,
  },
  selection: {
    color: primaryColor,
    fontSize: 12,
  },
});
<commit_msg>add dropdown icons<commit_after>import React from 'react';
import { Text, View, StyleSheet } from 'react-native';
import PropTypes from 'prop-types';
import { connect } from 'react-redux';
import { NavigationActions } from 'react-navigation';
import { Icon } from 'react-native-elements';

import jurisdictionFile from '../data/jurisdiction.json';
import statusFile from '../data/status.json';
import { getItemById, mapToRealStatus } from '../utils';
import { primaryColor, greyDark } from '../styles/colors';

class FoiRequestsListHeader extends React.Component {
  render() {
    const filterJurisdiction = this.props.filter.jurisdiction;
    let filterJurisdictionText = 'ALL';

    if (filterJurisdiction) {
      const jurisdictionName = jurisdictionFile.find(
        getItemById(filterJurisdiction)
      ).name;
      filterJurisdictionText = `${jurisdictionName}`.toUpperCase();
    }

    const filterStatus = this.props.filter.status;
    let filterStatusText = 'ALL';

    if (filterStatus) {
      const statusName = statusFile.find(getItemById(filterStatus)).name;
      filterStatusText = `${statusName}`.toUpperCase();
    }

    const filterCategory = this.props.filter.Category;
    let filterCategoryText = 'ALL';

    if (filterCategory) {
      // const categoryName = CategoryFile.find(getItemById(filterCategory)).name;
      const categoryName = 'Category'; // TODO
      filterCategoryText = `${categoryName}`.toUpperCase();
    }

    return (
      <View style={styles.container}>
        <View
          style={{
            flexDirection: 'row',
            justifyContent: 'space-between',
          }}
        >
          <View style={[styles.item, styles.firstItem]}>
            <View style={styles.align}>
              <Text style={styles.label}>JURISDICTION</Text>
              <Icon
                name="arrow-drop-down"
                color={greyDark}
                height={20}
                width={20}
              />
            </View>
            <Text style={styles.selection}>
              {filterJurisdictionText}
            </Text>
          </View>
          <View style={styles.item}>
            <View style={styles.align}>
              <Text style={styles.label}>STATUS</Text>
              <Icon
                name="arrow-drop-down"
                color={greyDark}
                height={20}
                width={20}
              />
            </View>
            <Text style={styles.selection}>
              {filterStatusText}
            </Text>
          </View>
          <View style={styles.item}>
            <View style={styles.align}>
              <Text style={styles.label}>CATEGORY</Text>
              <Icon
                name="arrow-drop-down"
                color={greyDark}
                height={20}
                width={20}
              />
            </View>
            <Text style={styles.selection}>
              {filterCategoryText}
            </Text>
          </View>
        </View>
      </View>
    );
  }
}

const mapStateToProps = state => {
  return {
    filter: state.foiRequests.filter,
    nResults: state.foiRequests.nResults,
  };
};

const mapDispatchToProps = dispatch => {
  return {
    navigateToFilter: () =>
      dispatch(NavigationActions.navigate({ routeName: 'Filter' })),
  };
};

export default connect(mapStateToProps, mapDispatchToProps)(
  FoiRequestsListHeader
);

const styles = StyleSheet.create({
  container: {
    backgroundColor: 'white',
    borderBottomWidth: 1,
    borderTopWidth: 1,
    borderBottomColor: greyDark,
    borderTopColor: greyDark,
  },
  item: {
    flexGrow: 1,
    flexBasis: 0,
    borderLeftWidth: 1,
    borderColor: greyDark,
    paddingHorizontal: 10,
    paddingBottom: 5,
  },
  firstItem: {
    borderLeftWidth: 0,
  },
  label: {
    fontSize: 12,
    color: greyDark,
  },
  selection: {
    color: primaryColor,
    fontSize: 12,
  },
  align: {
    flexDirection: 'row',
    justifyContent: 'space-between',
    alignItems: 'flex-end',
  },
});
<|endoftext|>


<commit_before>process.argv.slice(4)[0]
var testFile = null;
if(process.argv.length > 4) {
    testFile = process.argv.slice(4)[0];
}

const babelOptions = {
    presets: [
        "react",
        "es2015",
        "stage-0"
    ],
    plugins: ["doc-gen"]
};
/**
 * import common webpack settings
 */
const commonSettings = require("./webpack.config.common.js")("/site", "/build", "__test__", "/src", babelOptions);

/**
 * Json Server
 * @type {config|exports|module.exports}
 */
const JsonServer = require("./server/JsonServer");

/**
 * @link https://webpack.github.io/docs/configuration.html#cache
 * Cache generated modules and chunks to improve performance for multiple incremental builds.
 This is enabled by default in watch mode.
 * @type {boolean}
 */
commonSettings.cache = true;

/**
 * @link https://webpack.github.io/docs/configuration.html#debug
 * Switch loaders to debug mode.
 * @type {boolean}
 */
commonSettings.debug = false;

/**
 * @link https://webpack.github.io/docs/configuration.html#devtool
 * Choose a developer tool to enhance debugging.
 * source-map - A SourceMap is emitted. See also output.sourceMapFilename.
 * @type {string}
 */
/**
 * @link https://webpack.github.io/docs/configuration.html#devtool
 * Choose a developer tool to enhance debugging.
 * source-map - A SourceMap is emitted. See also output.sourceMapFilename.
 * @type {string}
 */
commonSettings.devtool = "eval";
commonSettings.module.preLoaders.push({ test: /.jsx?$/, loader: "eslint", exclude: /node_modules/ });

commonSettings.module.preLoaders.push({ test: /.jsx?$/, loader: "eslint", exclude: /node_modules/ });

const server = new JsonServer(3001, "/application");
server.route("config/data/testdb.json").upload("/files", "config/data/upload", "files").start();

commonSettings.externals = {
    cheerio: "window",
    "react/addons": true, // important!!
    "react/lib/ExecutionEnvironment": true,
    "react/lib/ReactContext": true
};

module.exports = function configure(config) {
    var conf = {
        basePath: "../",
        colors: true,
        captureTimeout: 3000,
        browserDisconnectTimeout: 3000,
        browserDisconnectTolerance: 1,
        browserNoActivityTimeout: 60000,
        browsers: ["Chrome_DEV"],
        singleRun: false,
        frameworks: ["mocha"],
        customLaunchers: {
            Chrome_DEV: {
                base: "Chrome",
                flags: ["--disable-web-security"]
            }
        },
        plugins: [
            "karma-chrome-launcher",
            "karma-chai",
            "karma-mocha",
            "karma-sourcemap-loader",
            "karma-webpack",
            "karma-mocha-reporter"
        ],
        webpack: commonSettings,
        webpackServer: {
            colors: true,
            hash: false,
            version: false,
            timings: false,
            assets: false,
            chunks: false,
            modules: false,
            reasons: false,
            children: false,
            source: false,
            errors: false,
            errorDetails: false,
            warnings: false,
            publicPath: false
        },
        webpackMiddleware: {
            // webpack-dev-middleware configuration
            // i. e.
            stats: "errors-only"
        },
        reporters: ["mocha"],
        client: {
            mocha: {
                timeout: 15000
            }
        }
    };

    let filePattern = "__test__/index.dev.js";
    if(testFile) {
        filePattern = "__test__/**/*/"+testFile+".spec.js";
    }
    conf.files = [
        filePattern
    ];
    conf.preprocessors = {};
    conf.preprocessors[filePattern] = ["webpack"];
    config.set(conf);
};
<commit_msg>## 1.1.3 Developing * added Development Test for Single File * developer can execute one file "npm run testd Wizard"<commit_after>process.argv.slice(4)[0]
var testFile = null;
if(process.argv.length > 4) {
    testFile = process.argv.slice(4)[0];
}

const babelOptions = {
    presets: [
        "react",
        "es2015",
        "stage-0"
    ],
    plugins: ["doc-gen"]
};
/**
 * import common webpack settings
 */
const commonSettings = require("./webpack.config.common.js")("/site", "/build", "__test__", "/src", babelOptions);

/**
 * Json Server
 * @type {config|exports|module.exports}
 */
const JsonServer = require("./server/JsonServer");

/**
 * @link https://webpack.github.io/docs/configuration.html#cache
 * Cache generated modules and chunks to improve performance for multiple incremental builds.
 This is enabled by default in watch mode.
 * @type {boolean}
 */
commonSettings.cache = true;

/**
 * @link https://webpack.github.io/docs/configuration.html#debug
 * Switch loaders to debug mode.
 * @type {boolean}
 */
commonSettings.debug = false;

/**
 * @link https://webpack.github.io/docs/configuration.html#devtool
 * Choose a developer tool to enhance debugging.
 * source-map - A SourceMap is emitted. See also output.sourceMapFilename.
 * @type {string}
 */
/**
 * @link https://webpack.github.io/docs/configuration.html#devtool
 * Choose a developer tool to enhance debugging.
 * source-map - A SourceMap is emitted. See also output.sourceMapFilename.
 * @type {string}
 */
commonSettings.devtool = "eval";
commonSettings.module.preLoaders.push({ test: /.jsx?$/, loader: "eslint", exclude: /node_modules/ });

commonSettings.module.preLoaders.push({ test: /.jsx?$/, loader: "eslint", exclude: /node_modules/ });

const server = new JsonServer(3001, "/application");
server.route("config/data/testdb.json").upload("/files", "config/data/upload", "files").start();

commonSettings.externals = {
    cheerio: "window",
    "react/addons": true, // important!!
    "react/lib/ExecutionEnvironment": true,
    "react/lib/ReactContext": true
};

module.exports = function configure(config) {
    var conf = {
        basePath: "../",
        colors: true,
        captureTimeout: 3000,
        browserDisconnectTimeout: 3000,
        browserDisconnectTolerance: 1,
        browserNoActivityTimeout: 60000,
        browsers: ["Chrome_DEV"],
        singleRun: false,
        frameworks: ["mocha"],
        customLaunchers: {
            Chrome_DEV: {
                base: "Chrome",
                flags: ["--disable-web-security"]
            }
        },
        plugins: [
            "karma-chrome-launcher",
            "karma-chai",
            "karma-mocha",
            "karma-sourcemap-loader",
            "karma-webpack",
            "karma-mocha-reporter"
        ],
        webpack: commonSettings,
        webpackServer: {
            colors: true,
            hash: false,
            version: false,
            timings: false,
            assets: false,
            chunks: false,
            modules: false,
            reasons: false,
            children: false,
            source: false,
            errors: false,
            errorDetails: false,
            warnings: false,
            publicPath: false
        },
        webpackMiddleware: {
            // webpack-dev-middleware configuration
            // i. e.
            stats: "errors-only"
        },
        reporters: ["mocha"],
        client: {
            mocha: {
                timeout: 15000
            }
        }
    };

    let filePattern = "__test__/index.dev.js";
    if(testFile) {
        if(!testFile.startsWith("./__test__") && !testFile.startsWith("__test__") && !testFile.startsWith("/")) {
            filePattern = "__test__/**/*/"+testFile+".spec.js";
        } else {
            filePattern = testFile;
        }
    }
    conf.files = [
        filePattern
    ];
    conf.preprocessors = {};
    conf.preprocessors[filePattern] = ["webpack"];
    config.set(conf);
};
<|endoftext|>


<commit_before>var qs = require('querystring');
var Item = require('../models/Item');
var Quantity = require('../models/Quantity');
var Order = require('../models/Order');
var OrderedItem = require('../models/OrderedItem');

var LocalStorage = require('node-localstorage').LocalStorage,
localStorage = new LocalStorage('./scratch');
var myList = new Object();

module.exports = {
	quantity: quantity,
	makeAnOrder: makeAnOrder
}

/*function addToCart(req,res) {
	console.log("in addToCart");
	console.log("get post request in server side");
    var body = '';
        req.on('data', function (data) {
            body += data;
            // 1e6 === 1 * Math.pow(10, 6) === 1 * 1000000 ~~~ 1MB
            if (body.length > 1e6) {
                // FLOOD ATTACK OR FAULTY CLIENT, NUKE REQUEST
                req.connection.destroy();
            }
        });
        req.on('end', function () {
        var POST = qs.parse(body);
		Item.findOne({_id : POST.item_id,'quantities':{name:POST.color}).where(quantities.quantity).gt(POST.sum).exec(function(err, item) {
		if (err) {
            res.status(404);
            res.send('item not found!');
        }
        else{
			cart.push(body);
			console.log("body:" +body+"item: "+item);
        }
	});
});
}*/

function makeAnOrder(req,res) {
	console.log("in makeAnOrder");
	/*// Retrieve the object from storage
	var retrievedObject = localStorage.getItem('myList');
	myList = JSON.parse(retrievedObject);

	item_id = myList._id;
	color = myList.color;
	sum = myList.sum;*/

	console.log("get post request in server side");
    var body = '';
        req.on('data', function (data) {
            body += data;
            // 1e6 === 1 * Math.pow(10, 6) === 1 * 1000000 ~~~ 1MB
            if (body.length > 1e6) {
                // FLOOD ATTACK OR FAULTY CLIENT, NUKE REQUEST
                req.connection.destroy();
            }
        });
        req.on('end', function () {
        var POST = qs.parse(body);
        console.log("body",body)

        console.log("POST",POST)
        var user = JSON.parse(POST.user);
         console.log("user.userName",user.UserName);
        var myList = JSON.parse(POST.myList);
		var colorId=colorConverterId(POST._id,POST.name);
		Quantity.findByIdAndUpdate(colorId, {quantity : POST.sum}).where(quantity ).gt(POST.sum).exec(function(err, doc) {
			if(err){
				throw err;
			}
			console.log("this is the doc variable: "+doc);
			console.log("updated");
		});
		var newOrder = new Order ({userName:POST.userName,email:POST.email,address:POST.address,status:"התקבלה הזמנה",numItems:POST.numItems,payment:POST.payment});
		var newOrderedItem = [];
		var o=JSON.parse(POST.orderedItems);
		for(var i=0; i<o.length;i++)
		{
			newOrderedItem[i] = new OrderedItem({item_id:0[i].item_id,color:o[i].color,sum:o[i].sum});
			newOrderedItem[i].save();
			newOrder.orderedItems.push(newOrderedItem[i]);
		}
		newOrder.save();
		});

}

function colorConverterId(id,color){
	for(var i=0;i<size;i++)
	{
		Item.find({id:id},(err, doc) => {
				if (err) {
					console.log("doc not found");
				}
				console.log("doc"+doc);
				for(var i=0;i<doc[0].quantities.length;i++)
				{
					console.log(doc[0].quantities[i]);
					Quantity.find({_id:doc[0].quantities[i]},(err, result) => {
					if (err) {
						throw err;
					}
					console.log(result[0].name);
					if(result[0].name==color)
					{
						console.log("_id of color "+result[0].name+" is: "+result[0]._id);
						return result[0]._id;
					}
					});
				}
	});
	}
}

//do not delete!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!
/*

function makeAnOrder(req,res) {
	console.log("in makeAnOrder");
	// Retrieve the object from storage
	var retrievedObject = localStorage.getItem('myList');
	myList = JSON.parse(retrievedObject);

	item_id = myList.item_id;
	color = myList.color;
	sum = myList.sum;

	console.log("get post request in server side");
    var body = '';
        req.on('data', function (data) {
            body += data;
            // 1e6 === 1 * Math.pow(10, 6) === 1 * 1000000 ~~~ 1MB
            if (body.length > 1e6) {
                // FLOOD ATTACK OR FAULTY CLIENT, NUKE REQUEST
                req.connection.destroy();
            }
		});
        req.on('end', function () {
        var POST = qs.parse(body);
			for(var i = 0 ; i < item_id.length ; i++)
			{
				Item.find({_id: item_id[i]},function(err,doc){
					if(err){
						throw err;
					}
				console.log(doc);
				var colorsDoc = doc.colors;
				for(var j = 0 ; j < colorsDoc.length ; j++)
					if(color[i]==colorsDoc[j])
					{
						Item.findByIdAndUpdate(item_id[i], {quantities[j] : quantities[j]-sum[i]}).exec(function(err, result) {
						if(err){
							throw err;
						}
						console.log("this is the doc variable: "+result);
						console.log("updated");
						});
					}
				});
			}
		var newOrder = new Order ({userName:POST.userName,email:POST.email,address:POST.address,status:"התקבלה הזמנה",numItems:POST.numItems,payment:POST.payment});
		for(var k=0 ; k < item_id.length ;k++)
		{
			newOrder.item_id.push(item_id[k]);
			newOrder.color.push(color[k]);
			newOrder.sum.push(sum[k]);
		}
		newOrder.save();
		}):
}*/

function quantity(req,res) {
	console.log("in quantity");
	// Retrieve the object from storage
// <<<<<<< HEAD
// 	// var retrievedObject = localStorage.getItem('myList');
// 	// myList = JSON.parse(retrievedObject);
// 	var myList = JSON.parse(localStorage.getItem('myList'));
// 	item_id = myList.item_id;
// =======
	/*var retrievedObject = localStorage.getItem('myList');
	myList = JSON.parse(retrievedObject);*/
	var obj = {
			_id : "",
			color : "",
			quantity : ""
	}
	var problemsDocs = [];

	/*item_id = myList.item_id;
>>>>>>> origin/master
	color = myList.color;
	sum = myList.sum;*/
	//console.log(myList);
	console.log("get post request in server side");
    var body = '';
        req.on('data', function (data) {
            body += data;
            // 1e6 === 1 * Math.pow(10, 6) === 1 * 1000000 ~~~ 1MB
            if (body.length > 1e6) {
                // FLOOD ATTACK OR FAULTY CLIENT, NUKE REQUEST
                req.connection.destroy();
            }
        });
        req.on('end', function () {
        	var l =0;

        var POST = qs.parse(body);
console.log("POST 0",POST);
		myList=JSON.parse(POST.myList);
// console.log("POST 1",myList);
// console.log("POST 2",myList[0]);
		for(var j=0;j<myList.length;j++)
		{console.log("myList[]",myList[j]);
			Item.find({_id: myList[j]._id},(err, doc) => {
				if (err) {
					res.status(404);
					res.send('Item not found!');
				}
				console.log("doc~~~~~~~~~~~"+doc[0].quantities);
				for(var i=0;i<doc[0].quantities.length;i++)
				{
					console.log("~~~~~~~~~~~~~"+i+doc[0].quantities[i]);
					Quantity.find({_id:doc[0].quantities[i]},(err, result) => {
					if (err) {
						throw err;
					}

					if(result[0].name==myList[l].color)
					{

						console.log("~~~~~~~~~~~~~"+myList[l].color);
						console.log("yes");
						console.log("sum "+result[0].quantity);
						if(result[0].quantity < myList[l].quantity)
						{
							obj._id = myList[l]._id;
							obj.color = myList[l].color;
							obj.quantity = result[0].quantity;
							problemsDocs.push(obj);
							console.log("//////////////"+obj._id);
						}
						l++;
						if(l==myList.length)
		{

			res.json(problemsDocs);
		}
						console.log("l"+l);
					}

					});
				}
			});
		}

	});

}
					<commit_msg>aaaaaaaaa<commit_after>var qs = require('querystring');
var Item = require('../models/Item');
var Quantity = require('../models/Quantity');
var Order = require('../models/Order');
var OrderedItem = require('../models/OrderedItem');

var LocalStorage = require('node-localstorage').LocalStorage,
localStorage = new LocalStorage('./scratch');
var myList = new Object();

module.exports = {
	quantity: quantity,
	makeAnOrder: makeAnOrder
}

/*function addToCart(req,res) {
	console.log("in addToCart");
	console.log("get post request in server side");
    var body = '';
        req.on('data', function (data) {
            body += data;
            // 1e6 === 1 * Math.pow(10, 6) === 1 * 1000000 ~~~ 1MB
            if (body.length > 1e6) {
                // FLOOD ATTACK OR FAULTY CLIENT, NUKE REQUEST
                req.connection.destroy();
            }
        });
        req.on('end', function () {
        var POST = qs.parse(body);
		Item.findOne({_id : POST.item_id,'quantities':{name:POST.color}).where(quantities.quantity).gt(POST.sum).exec(function(err, item) {
		if (err) {
            res.status(404);
            res.send('item not found!');
        }
        else{
			cart.push(body);
			console.log("body:" +body+"item: "+item);
        }
	});
});
}*/

function makeAnOrder(req,res) {
	console.log("in makeAnOrder");
	console.log("get post request in server side");
    var body = '';
        req.on('data', function (data) {
            body += data;
            // 1e6 === 1 * Math.pow(10, 6) === 1 * 1000000 ~~~ 1MB
            if (body.length > 1e6) {
                // FLOOD ATTACK OR FAULTY CLIENT, NUKE REQUEST
                req.connection.destroy();
            }
        });
        req.on('end', function () {
        var POST = qs.parse(body);
        console.log("body",body);
        console.log("POST",POST);
        var user = JSON.parse(POST.user);
        console.log("user.userName",user.firstName);
        var myList = JSON.parse(POST.myList);
		myList.forEach(function (value, index) {
			var colorId=colorConverterId(mylist[index]._id,myList.name);
			Quantity.findByIdAndUpdate(colorId, {quantity : POST.sum}).where(quantity ).gt(POST.sum).exec(function(err, doc) {
				if(err){
					throw err;
				}
				console.log("this is the doc variable: "+doc);
				console.log("updated");
			});
			var newOrder = new Order ({userName:POST.userName,email:POST.email,address:POST.address,status:"התקבלה הזמנה",numItems:POST.numItems,payment:POST.payment});
			var newOrderedItem = [];
			var o=JSON.parse(POST.orderedItems);
			for(var i=0; i<o.length;i++)
			{
				newOrderedItem[i] = new OrderedItem({item_id:0[i].item_id,color:o[i].color,sum:o[i].sum});
				newOrderedItem[i].save();
				newOrder.orderedItems.push(newOrderedItem[i]);
			}
			newOrder.save();
			});
		});
}

function colorConverterId(id,color){
	for(var i=0;i<size;i++)
	{
		Item.find({id:id},(err, doc) => {
				if (err) {
					console.log("doc not found");
				}
				console.log("doc"+doc);
				for(var i=0;i<doc[0].quantities.length;i++)
				{
					console.log(doc[0].quantities[i]);
					Quantity.find({_id:doc[0].quantities[i]},(err, result) => {
					if (err) {
						throw err;
					}
					console.log(result[0].name);
					if(result[0].name==color)
					{
						console.log("_id of color "+result[0].name+" is: "+result[0]._id);
						return result[0]._id;
					}
					});
				}
	});
	}
}

//do not delete!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!
/*

function makeAnOrder(req,res) {
	console.log("in makeAnOrder");
	// Retrieve the object from storage
	var retrievedObject = localStorage.getItem('myList');
	myList = JSON.parse(retrievedObject);

	item_id = myList.item_id;
	color = myList.color;
	sum = myList.sum;

	console.log("get post request in server side");
    var body = '';
        req.on('data', function (data) {
            body += data;
            // 1e6 === 1 * Math.pow(10, 6) === 1 * 1000000 ~~~ 1MB
            if (body.length > 1e6) {
                // FLOOD ATTACK OR FAULTY CLIENT, NUKE REQUEST
                req.connection.destroy();
            }
		});
        req.on('end', function () {
        var POST = qs.parse(body);
			for(var i = 0 ; i < item_id.length ; i++)
			{
				Item.find({_id: item_id[i]},function(err,doc){
					if(err){
						throw err;
					}
				console.log(doc);
				var colorsDoc = doc.colors;
				for(var j = 0 ; j < colorsDoc.length ; j++)
					if(color[i]==colorsDoc[j])
					{
						Item.findByIdAndUpdate(item_id[i], {quantities[j] : quantities[j]-sum[i]}).exec(function(err, result) {
						if(err){
							throw err;
						}
						console.log("this is the doc variable: "+result);
						console.log("updated");
						});
					}
				});
			}
		var newOrder = new Order ({userName:POST.userName,email:POST.email,address:POST.address,status:"התקבלה הזמנה",numItems:POST.numItems,payment:POST.payment});
		for(var k=0 ; k < item_id.length ;k++)
		{
			newOrder.item_id.push(item_id[k]);
			newOrder.color.push(color[k]);
			newOrder.sum.push(sum[k]);
		}
		newOrder.save();
		}):
}*/

function quantity(req,res) {
	console.log("in quantity");
	// Retrieve the object from storage
// <<<<<<< HEAD
// 	// var retrievedObject = localStorage.getItem('myList');
// 	// myList = JSON.parse(retrievedObject);
// 	var myList = JSON.parse(localStorage.getItem('myList'));
// 	item_id = myList.item_id;
// =======
	/*var retrievedObject = localStorage.getItem('myList');
	myList = JSON.parse(retrievedObject);*/
	var obj = {
			_id : "",
			color : "",
			quantity : ""
	}
	var problemsDocs = [];

	/*item_id = myList.item_id;
>>>>>>> origin/master
	color = myList.color;
	sum = myList.sum;*/
	//console.log(myList);
	console.log("get post request in server side");
    var body = '';
        req.on('data', function (data) {
            body += data;
            // 1e6 === 1 * Math.pow(10, 6) === 1 * 1000000 ~~~ 1MB
            if (body.length > 1e6) {
                // FLOOD ATTACK OR FAULTY CLIENT, NUKE REQUEST
                req.connection.destroy();
            }
        });
        req.on('end', function () {
        	var l =0;

        var POST = qs.parse(body);
console.log("POST 0",POST);
		myList=JSON.parse(POST.myList);
// console.log("POST 1",myList);
// console.log("POST 2",myList[0]);
		for(var j=0;j<myList.length;j++)
		{console.log("myList[]",myList[j]);
			Item.find({_id: myList[j]._id},(err, doc) => {
				if (err) {
					res.status(404);
					res.send('Item not found!');
				}
				console.log("doc~~~~~~~~~~~"+doc[0].quantities);
				for(var i=0;i<doc[0].quantities.length;i++)
				{
					console.log("~~~~~~~~~~~~~"+i+doc[0].quantities[i]);
					Quantity.find({_id:doc[0].quantities[i]},(err, result) => {
					if (err) {
						throw err;
					}

					if(result[0].name==myList[l].color)
					{

						console.log("~~~~~~~~~~~~~"+myList[l].color);
						console.log("yes");
						console.log("sum "+result[0].quantity);
						if(result[0].quantity < myList[l].quantity)
						{
							obj._id = myList[l]._id;
							obj.color = myList[l].color;
							obj.quantity = result[0].quantity;
							problemsDocs.push(obj);
							console.log("//////////////"+obj._id);
						}
						l++;
						if(l==myList.length)
		{

			res.json(problemsDocs);
		}
						console.log("l"+l);
					}

					});
				}
			});
		}

	});

}
					<|endoftext|>


<commit_before>
var qs = require('querystring');
var Item = require('../models/Item');
var Quantity = require('../models/Quantity');

function addToCart(req,res) {
	console.log("in addToCart");
	console.log("get post request in server side");
    var body = '';
        req.on('data', function (data) {
            body += data;
            // 1e6 === 1 * Math.pow(10, 6) === 1 * 1000000 ~~~ 1MB
            if (body.length > 1e6) {
                // FLOOD ATTACK OR FAULTY CLIENT, NUKE REQUEST
                req.connection.destroy();
            }
        });
        req.on('end', function () {
        var POST = qs.parse(body);
		Item.findOne({_id : POST.item_id,'quantities':{name:POST.color}).where(quantities.quantity).gt(POST.sum).exec(function(err, item) {
		if (err) {
            res.status(404);
            res.send('item not found!');
        }
        else{
			cart.push(body);
			console.log("body:" +body+"item: "+item);
        }
	});
});
}

function makeAnOrder(req,res) {
	console.log("in makeAnOrder");
	// Retrieve the object from storage
	var retrievedObject = localStorage.getItem('addToCart');
	addToCart = JSON.parse(retrievedObject);

	_userName = addToCart.userName;
	_email = addToCart.email;
	_address = addToCart.address;
	_numItems = addToCart.numItems;
	_payment : addToCart.payment;

	_item_id = addToCart._id;
	_color = addToCart.color;
	_sum = addToCart.sum;

	var newOrder = new Order {{userName:_userName,email: _email,address:_address,status:"התקבלה הזמנה",numItems:_numItems,payment:_payment});
	var newOrderedItem = new OrderedItem({item_id:_item_id,color:_color,sum:_sum});
	newOrderedItem.save(function(err, newOrderedItem){
	newOrder.quantities.push(newOrderedItem);
	newOrder.save();
	}):

}<commit_msg>add func quantity in server and fix the makeAnOrder func<commit_after>
var qs = require('querystring');
var Item = require('../models/Item');
var Quantity = require('../models/Quantity');

function addToCart(req,res) {
	console.log("in addToCart");
	console.log("get post request in server side");
    var body = '';
        req.on('data', function (data) {
            body += data;
            // 1e6 === 1 * Math.pow(10, 6) === 1 * 1000000 ~~~ 1MB
            if (body.length > 1e6) {
                // FLOOD ATTACK OR FAULTY CLIENT, NUKE REQUEST
                req.connection.destroy();
            }
        });
        req.on('end', function () {
        var POST = qs.parse(body);
		Item.findOne({_id : POST.item_id,'quantities':{name:POST.color}).where(quantities.quantity).gt(POST.sum).exec(function(err, item) {
		if (err) {
            res.status(404);
            res.send('item not found!');
        }
        else{
			cart.push(body);
			console.log("body:" +body+"item: "+item);
        }
	});
});
}

function makeAnOrder(req,res) {
	console.log("in makeAnOrder");
	// Retrieve the object from storage
	var retrievedObject = localStorage.getItem('addToCart');
	myList = JSON.parse(retrievedObject);

	item_id = myList._id;
	color = myList.color;
	sum = myList.sum;

	console.log("get post request in server side");
    var body = '';
        req.on('data', function (data) {
            body += data;
            // 1e6 === 1 * Math.pow(10, 6) === 1 * 1000000 ~~~ 1MB
            if (body.length > 1e6) {
                // FLOOD ATTACK OR FAULTY CLIENT, NUKE REQUEST
                req.connection.destroy();
            }
        });
        req.on('end', function () {
        var POST = qs.parse(body);
		Item.findByIdAndUpdate(POST._id, {quantities.quantity : quantiy-POST.sum}.where(quantities.quantity ).gt(POST.sum).exec(function(err, doc) {
			if(err){
				throw err;
			}
			console.log("this is the doc variable: "+doc);
			console.log("updated");
		});
		var newOrder = new Order {{userName:POST.userName,email:POST.email,address:POST.address,status:"התקבלה הזמנה",numItems:POST.numItems,payment:POST.payment});
		var newOrderedItem = new OrderedItem({item_id:item_id,color:color,sum:sum});
		newOrderedItem.save(function(err, newOrderedItem){
		newOrder.quantities.push(newOrderedItem);
		newOrder.save();
		}):

}

function quantity(req,res) {
	console.log("in makeAnOrder");
	console.log("get post request in server side");
    var body = '';
        req.on('data', function (data) {
            body += data;
            // 1e6 === 1 * Math.pow(10, 6) === 1 * 1000000 ~~~ 1MB
            if (body.length > 1e6) {
                // FLOOD ATTACK OR FAULTY CLIENT, NUKE REQUEST
                req.connection.destroy();
            }
        });
        req.on('end', function () {
        var POST = qs.parse(body);
		Item.findOne({_id : POST._id,'quantities':{name:POST.color}},{ quantities.quantity:1}).exec(function(err, quantity) {
		//Item.findOne({_id : POST._id,'quantities':{name:POST.color}}).where(quantities.quantity).gt(POST.sum).exec(function(err, item) {
		if (err) {
            res.status(404);
            res.send('item not found!');
        }
        else{
			console.log("quantity: "+quantity);
			res.send(quantity);
        }
		});
	});

}<|endoftext|>


<commit_before><commit_msg>Fixed bug in foonote parser<commit_after><|endoftext|>


<commit_before>Controller = function(){

    this.view = new View();

    this.eventId = 0;
    this.fingerId = [];

    this.init = function(){

        this.device = this.checkDevice();

        if(this.device.iphone||this.device.ipad||this.device.ipod) {
            this.bindTouchEvents();
            //this.bindGestureEvents();
            //this.bindMouseEvents();
        } else {
            this.bindMouseEvents();
        }

        this.bindResizeEvents();

    };

    this.bindMouseEvents = function() {
        $('#touchBox')[0].addEventListener('click',this.clickEvent());
    };

    this.bindTouchEvents = function() {
        $('#touchBox')[0].addEventListener('touchstart',this.touchStart(),false);
        $('#touchBox')[0].addEventListener('touchmove',this.touchMove(),false);
        $('#touchBox')[0].addEventListener('touchend',this.touchEnd(),false);
        //$('body')[0].addEventListener('touchcancel',this.touchCancel(),false);
    };

    this.bindGestureEvents = function() {
        $('#touchBox')[0].addEventListener('gesturestart',this.gestureStart(),false);
        $('#touchBox')[0].addEventListener('gesturechange',this.gestureChange(),false);
        $('#touchBox')[0].addEventListener('gestureend',this.gestureEnd(),false);
    };

    this.touchStart = function(){
        var that = this;
        return function(e){
            e.preventDefault();

            for(var i=0; i < e.changedTouches.length; i++){
                var x = e.changedTouches[i].pageX;
                var y = e.changedTouches[i].pageY;
                var id = that.eventId;
                that.eventId++;
                that.view.startRing(id,x,y);
                that.fingerId[e.changedTouches[i].identifier] = id;
            }

            $('#messageTouchesBox div.info').empty();
            for(var i=0; i < e.touches.length; i++){
                var x = e.touches[i].pageX;
                var y = e.touches[i].pageY;
                var id = that.fingerId[e.touches[i].identifier];
                var col = that.view.rings[id].color;
                $('#messageTouchesBox div.info').append('
'+x+' '+y+'
');
            }

            $('#messageTargetBox div.info').empty();
            for(var i=0; i < e.targetTouches.length; i++){
                var x = e.targetTouches[i].pageX;
                var y = e.targetTouches[i].pageY;
                var id = that.fingerId[e.targetTouches[i].identifier];
                var col = that.view.rings[id].color;
                $('#messageTargetBox div.info').append('
'+x+' '+y+'
');
            }

            $('#messageChangedBox div.info').empty();
            for(var i=0; i < e.changedTouches.length; i++){
                var x = e.changedTouches[i].pageX;
                var y = e.changedTouches[i].pageY;
                var id = that.fingerId[e.changedTouches[i].identifier];
                var col = that.view.rings[id].color;
                $('#messageChangedBox div.info').append('
'+x+' '+y+'
');
            }
        }
    };

    this.touchMove = function(){
        var that = this;
        return function(e){
            e.preventDefault();

            for(var i=0; i < e.changedTouches.length; i++){
                var x = e.changedTouches[i].pageX;
                var y = e.changedTouches[i].pageY;
                var id = that.eventId;
                var prevId = that.fingerId[e.changedTouches[i].identifier];
                that.eventId++;
                that.view.moveRing(id,prevId,x,y);
            }

            $('#messageTouchesBox div.info').empty();
            for(var i=0; i < e.touches.length; i++){
                var x = e.touches[i].pageX;
                var y = e.touches[i].pageY;
                var id = that.fingerId[e.touches[i].identifier];
                var col = that.view.rings[id].color;
                $('#messageTouchesBox div.info').append('
'+x+' '+y+'
');
            }

            $('#messageTargetBox div.info').empty();
            for(var i=0; i < e.targetTouches.length; i++){
                var x = e.targetTouches[i].pageX;
                var y = e.targetTouches[i].pageY;
                var id = that.fingerId[e.targetTouches[i].identifier];
                var col = that.view.rings[id].color;
                $('#messageTargetBox div.info').append('
'+x+' '+y+'
');
            }

            $('#messageChangedBox div.info').empty();
            for(var i=0; i < e.changedTouches.length; i++){
                var x = e.changedTouches[i].pageX;
                var y = e.changedTouches[i].pageY;
                var id = that.fingerId[e.changedTouches[i].identifier];
                var col = that.view.rings[id].color;
                $('#messageChangedBox div.info').append('
'+x+' '+y+'
');
            }
        }
    };

    this.touchEnd = function(){
        var that = this;
        return function(e){
            e.preventDefault();

            for(var i=0; i < e.changedTouches.length; i++){
                var x = e.changedTouches[i].pageX;
                var y = e.changedTouches[i].pageY;
                var id = that.eventId;
                var prevId = that.fingerId[e.changedTouches[i].identifier];
                that.eventId++;
                that.view.endRing(id,prevId,x,y);
            }

            $('#messageTouchesBox div.info').empty();
            for(var i=0; i < e.touches.length; i++){
                var x = e.touches[i].pageX;
                var y = e.touches[i].pageY;
                var id = that.fingerId[e.touches[i].identifier];
                var col = that.view.rings[id].color;
                $('#messageTouchesBox div.info').append('
'+x+' '+y+'
');
            }

            $('#messageTargetBox div.info').empty();
            for(var i=0; i < e.targetTouches.length; i++){
                var x = e.targetTouches[i].pageX;
                var y = e.targetTouches[i].pageY;
                var id = that.fingerId[e.targetTouches[i].identifier];
                var col = that.view.rings[id].color;
                $('#messageTargetBox div.info').append('
'+x+' '+y+'
');
            }

            $('#messageChangedBox div.info').empty();
            for(var i=0; i < e.changedTouches.length; i++){
                var x = e.changedTouches[i].pageX;
                var y = e.changedTouches[i].pageY;
                var id = that.fingerId[e.changedTouches[i].identifier];
                var col = that.view.rings[id].color;
                $('#messageChangedBox div.info').append('
'+x+' '+y+'
');
            }
        }
    };

    this.touchCancel = function(){
        var that = this;
        return function(e){
            e.preventDefault();
        }
    };

    this.gestureStart = function(){
        var that = this;
        return function(e){
            e.preventDefault();
        }
    };

    this.gestureChange = function(){
        var that = this;
        return function(e){
            e.preventDefault();

        }
    };

    this.gestureEnd = function(){
        var that = this;
        return function(e){
            e.preventDefault();
        }
    };

    this.clickEvent = function(){
        var that = this;
        return function(e){
            e.preventDefault();

            var x = e.pageX;
            var y = e.pageY;
            var id = that.eventId;
            that.eventId++;

            that.fingerId[e.identifier] = id;

            that.view.startRing(id,x,y);

            var prevId = that.fingerId[e.identifier];
            var col = that.view.rings[prevId].color;

            $('#messageTouchesBox div.info').empty();
            $('#messageTouchesBox div.info').append('
'+x+' '+y+'
');

            $('#messageTargetBox div.info').empty();
            $('#messageTargetBox div.info').append('
'+x+' '+y+'
');

            $('#messageChangedBox div.info').empty();
            $('#messageChangedBox div.info').append('
'+x+' '+y+'
');

        }
    };

    this.checkDevice = function(){
        var ua = navigator.userAgent;
        var checker = {
            iphone: ua.match(/iPhone/),
            ipod: ua.match(/iPod/),
            ipad: ua.match(/iPad/),
            blackberry: ua.match(/BlackBerry/),
            android: ua.match(/Android/),
            chrome: ua.match(/Chrome/),
            firefox: ua.match(/Firefox/)
        };
        return checker;
    };

    this.bindResizeEvents = function() {
        window.addEventListener('resize', this.checkWindowSize(), false);
        window.addEventListener('orientationchange', this.checkWindowSize(), false);
    };

    this.checkWindowSize = function(){

        var that = this;

        return function(e){
            e.preventDefault();
            that.eventId = 0;
            that.fingerId = [];
            var h = window.innerHeight;
            var w = window.innerWidth;
            that.view.resizeLayout(h,w);
            that.init();
        }

    };

    this.init();

};
<commit_msg>proba rozwiazania problemu z 'resize'<commit_after>Controller = function(){

    this.view = new View();

    this.eventId = 0;
    this.fingerId = [];

    this.init = function(){

        this.device = this.checkDevice();

        if(this.device.iphone||this.device.ipad||this.device.ipod) {
            this.bindTouchEvents();
            //this.bindGestureEvents();
            //this.bindMouseEvents();
        } else {
            this.bindMouseEvents();
        }

        this.bindResizeEvents();

    };

    this.bindMouseEvents = function() {
        $('#touchBox')[0].addEventListener('click',this.clickEvent());
    };

    this.bindTouchEvents = function() {
        $('#touchBox')[0].addEventListener('touchstart',this.touchStart(),false);
        $('#touchBox')[0].addEventListener('touchmove',this.touchMove(),false);
        $('#touchBox')[0].addEventListener('touchend',this.touchEnd(),false);
        //$('body')[0].addEventListener('touchcancel',this.touchCancel(),false);
    };

    this.bindGestureEvents = function() {
        $('#touchBox')[0].addEventListener('gesturestart',this.gestureStart(),false);
        $('#touchBox')[0].addEventListener('gesturechange',this.gestureChange(),false);
        $('#touchBox')[0].addEventListener('gestureend',this.gestureEnd(),false);
    };

    this.touchStart = function(){
        var that = this;
        return function(e){
            e.preventDefault();

            for(var i=0; i < e.changedTouches.length; i++){
                var x = e.changedTouches[i].pageX;
                var y = e.changedTouches[i].pageY;
                var id = that.eventId;
                that.eventId++;
                that.view.startRing(id,x,y);
                that.fingerId[e.changedTouches[i].identifier] = id;
            }

            $('#messageTouchesBox div.info').empty();
            for(var i=0; i < e.touches.length; i++){
                var x = e.touches[i].pageX;
                var y = e.touches[i].pageY;
                var id = that.fingerId[e.touches[i].identifier];
                var col = that.view.rings[id].color;
                $('#messageTouchesBox div.info').append('
'+x+' '+y+'
');
            }

            $('#messageTargetBox div.info').empty();
            for(var i=0; i < e.targetTouches.length; i++){
                var x = e.targetTouches[i].pageX;
                var y = e.targetTouches[i].pageY;
                var id = that.fingerId[e.targetTouches[i].identifier];
                var col = that.view.rings[id].color;
                $('#messageTargetBox div.info').append('
'+x+' '+y+'
');
            }

            $('#messageChangedBox div.info').empty();
            for(var i=0; i < e.changedTouches.length; i++){
                var x = e.changedTouches[i].pageX;
                var y = e.changedTouches[i].pageY;
                var id = that.fingerId[e.changedTouches[i].identifier];
                var col = that.view.rings[id].color;
                $('#messageChangedBox div.info').append('
'+x+' '+y+'
');
            }
        }
    };

    this.touchMove = function(){
        var that = this;
        return function(e){
            e.preventDefault();

            for(var i=0; i < e.changedTouches.length; i++){
                var x = e.changedTouches[i].pageX;
                var y = e.changedTouches[i].pageY;
                var id = that.eventId;
                var prevId = that.fingerId[e.changedTouches[i].identifier];
                that.eventId++;
                that.view.moveRing(id,prevId,x,y);
            }

            $('#messageTouchesBox div.info').empty();
            for(var i=0; i < e.touches.length; i++){
                var x = e.touches[i].pageX;
                var y = e.touches[i].pageY;
                var id = that.fingerId[e.touches[i].identifier];
                var col = that.view.rings[id].color;
                $('#messageTouchesBox div.info').append('
'+x+' '+y+'
');
            }

            $('#messageTargetBox div.info').empty();
            for(var i=0; i < e.targetTouches.length; i++){
                var x = e.targetTouches[i].pageX;
                var y = e.targetTouches[i].pageY;
                var id = that.fingerId[e.targetTouches[i].identifier];
                var col = that.view.rings[id].color;
                $('#messageTargetBox div.info').append('
'+x+' '+y+'
');
            }

            $('#messageChangedBox div.info').empty();
            for(var i=0; i < e.changedTouches.length; i++){
                var x = e.changedTouches[i].pageX;
                var y = e.changedTouches[i].pageY;
                var id = that.fingerId[e.changedTouches[i].identifier];
                var col = that.view.rings[id].color;
                $('#messageChangedBox div.info').append('
'+x+' '+y+'
');
            }
        }
    };

    this.touchEnd = function(){
        var that = this;
        return function(e){
            e.preventDefault();

            for(var i=0; i < e.changedTouches.length; i++){
                var x = e.changedTouches[i].pageX;
                var y = e.changedTouches[i].pageY;
                var id = that.eventId;
                var prevId = that.fingerId[e.changedTouches[i].identifier];
                that.eventId++;
                that.view.endRing(id,prevId,x,y);
            }

            $('#messageTouchesBox div.info').empty();
            for(var i=0; i < e.touches.length; i++){
                var x = e.touches[i].pageX;
                var y = e.touches[i].pageY;
                var id = that.fingerId[e.touches[i].identifier];
                var col = that.view.rings[id].color;
                $('#messageTouchesBox div.info').append('
'+x+' '+y+'
');
            }

            $('#messageTargetBox div.info').empty();
            for(var i=0; i < e.targetTouches.length; i++){
                var x = e.targetTouches[i].pageX;
                var y = e.targetTouches[i].pageY;
                var id = that.fingerId[e.targetTouches[i].identifier];
                var col = that.view.rings[id].color;
                $('#messageTargetBox div.info').append('
'+x+' '+y+'
');
            }

            $('#messageChangedBox div.info').empty();
            for(var i=0; i < e.changedTouches.length; i++){
                var x = e.changedTouches[i].pageX;
                var y = e.changedTouches[i].pageY;
                var id = that.fingerId[e.changedTouches[i].identifier];
                var col = that.view.rings[id].color;
                $('#messageChangedBox div.info').append('
'+x+' '+y+'
');
            }
        }
    };

    this.touchCancel = function(){
        var that = this;
        return function(e){
            e.preventDefault();
        }
    };

    this.gestureStart = function(){
        var that = this;
        return function(e){
            e.preventDefault();
        }
    };

    this.gestureChange = function(){
        var that = this;
        return function(e){
            e.preventDefault();

        }
    };

    this.gestureEnd = function(){
        var that = this;
        return function(e){
            e.preventDefault();
        }
    };

    this.clickEvent = function(){
        var that = this;
        return function(e){
            e.preventDefault();

            var x = e.pageX;
            var y = e.pageY;
            var id = that.eventId;
            that.eventId++;

            that.fingerId[e.identifier] = id;

            that.view.startRing(id,x,y);

            var prevId = that.fingerId[e.identifier];
            var col = that.view.rings[prevId].color;

            $('#messageTouchesBox div.info').empty();
            $('#messageTouchesBox div.info').append('
'+x+' '+y+'
');

            $('#messageTargetBox div.info').empty();
            $('#messageTargetBox div.info').append('
'+x+' '+y+'
');

            $('#messageChangedBox div.info').empty();
            $('#messageChangedBox div.info').append('
'+x+' '+y+'
');

        }
    };

    this.checkDevice = function(){
        var ua = navigator.userAgent;
        var checker = {
            iphone: ua.match(/iPhone/),
            ipod: ua.match(/iPod/),
            ipad: ua.match(/iPad/),
            blackberry: ua.match(/BlackBerry/),
            android: ua.match(/Android/),
            chrome: ua.match(/Chrome/),
            firefox: ua.match(/Firefox/)
        };
        return checker;
    };

    this.bindResizeEvents = function() {
        window.addEventListener('resize', this.checkWindowSize(), false);
        window.addEventListener('orientationchange', this.checkWindowSize(), false);
    };

    this.checkWindowSize = function(){

        var that = this;

        return function(e){
            e.preventDefault();
            $('#touchBox')[0].removeEventListener('touchstart',arguments.callee,false);
            $('#touchBox')[0].removeEventListener('touchmove',arguments.callee,false);
            $('#touchBox')[0].removeEventListener('touchend',arguments.callee,false);
            window.removeEventListener('resize', arguments.callee, false);
            window.removeEventListener('orientationchange', arguments.callee, false);
            that.eventId = 0;
            that.fingerId = [];
            var h = window.innerHeight;
            var w = window.innerWidth;
            that.view.resizeLayout(h,w);
            that.init();
        }

    };

    this.init();

};
<|endoftext|>


<commit_before>import ModalComponent from 'ghost-admin/components/modal-base';
import {computed} from '@ember/object';
import {inject as service} from '@ember/service';

export default ModalComponent.extend({
    router: service(),

    upgradeMessage: computed('details', function () {
        const {limit, total} = this.model.details;
        const message = this.model.message;

        return {limit, total, message};
    }),

    actions: {
        upgrade() {
            this.router.transitionTo('pro');
        },

        confirm() {
            this.send('upgrade');
        }
    }
});
<commit_msg>Fixed limit error parsing when there are no details<commit_after>import ModalComponent from 'ghost-admin/components/modal-base';
import {computed} from '@ember/object';
import {inject as service} from '@ember/service';

export default ModalComponent.extend({
    router: service(),

    upgradeMessage: computed('details', function () {
        const {limit, total} = this.model.details || {};
        const message = this.model.message;

        return {limit, total, message};
    }),

    actions: {
        upgrade() {
            this.router.transitionTo('pro');
        },

        confirm() {
            this.send('upgrade');
        }
    }
});
<|endoftext|>


<commit_before>// Copyright 2018, University of Colorado Boulder

/**
 * Tests for Enumeration
 *
 * @author Jonathan Olson <jonathan.olson@colorado.edu>
 */
define( function( require ) {
  'use strict';

  // modules
  const Enumeration = require( 'PHET_CORE/Enumeration' );

  QUnit.module( 'Enumeration' );

  QUnit.test( 'Basic enumeration', function( assert ) {
    const CardinalDirection = new Enumeration( [ 'NORTH', 'SOUTH', 'EAST', 'WEST' ] );

    assert.equal( CardinalDirection.NORTH, 'NORTH', 'Equality for NORTH' );
    assert.equal( CardinalDirection.SOUTH, 'SOUTH', 'Equality for SOUTH' );
    assert.equal( CardinalDirection.EAST, 'EAST', 'Equality for EAST' );
    assert.equal( CardinalDirection.WEST, 'WEST', 'Equality for WEST' );

    assert.equal( CardinalDirection.includes( CardinalDirection.NORTH ), true, 'NORTH is in the enumeration' );
    assert.equal( CardinalDirection.includes( 'NORTH' ), false, 'Strings shouln\'t match' );
    assert.equal( CardinalDirection.includes( 'YORKSHIRE_TERRIER_WITH_THE_CANDLE_STICK_IN_THE_BALLROOM' ), false,
      'Not in the enumeration' );
    assert.equal( CardinalDirection.includes( { name: 'NORTH' } ), false, 'Should not be able to synthesize Enumeration values' );

    // Test toString
    var object = {};
    object[ CardinalDirection.NORTH ] = 'exit';
    assert.equal( object.NORTH, 'exit', 'toString should work seamlessly' );

    window.assert && assert.throws( function() {
      CardinalDirection.SOMETHING_AFTER_THE_FREEZE = 5;
    }, 'Should not be able to set things after initialization' );

    window.assert && assert.throws( function() {
      const x = new Enumeration( [ 'lowercase', 'should', 'fail' ] );
      assert.ok( !!x, 'fake assertion so x is used' );
    }, 'Enumeration should fail for lowercase values' );
  } );

  QUnit.test( 'Before freeze test', function( assert ) {
    const E = new Enumeration( [ 'A', 'B' ], E => {
      E.opposite = e => {
        window.assert && window.assert( E.includes( e ) );
        return e === E.A ? E.B : E.A;
      };
    } );

    assert.equal( E.A, 'A', 'Equality for A' );
    assert.equal( E.B, 'B', 'Equality for B' );
    assert.equal( E.opposite( E.A ), E.B, 'Custom function check 1' );
    assert.equal( E.opposite( E.B ), E.A, 'Custom function check 2' );

    window.assert && assert.throws( function() {
      E.SOMETHING_AFTER_THE_FREEZE = 5;
    }, 'Should not be able to set things after initialization' );
  } );
} );
<commit_msg>Added unit test for mutating VALUES, see https://github.com/phetsims/phet-core/issues/46<commit_after>// Copyright 2018, University of Colorado Boulder

/**
 * Tests for Enumeration
 *
 * @author Jonathan Olson <jonathan.olson@colorado.edu>
 */
define( function( require ) {
  'use strict';

  // modules
  const Enumeration = require( 'PHET_CORE/Enumeration' );

  QUnit.module( 'Enumeration' );

  QUnit.test( 'Basic enumeration', function( assert ) {
    const CardinalDirection = new Enumeration( [ 'NORTH', 'SOUTH', 'EAST', 'WEST' ] );

    assert.equal( CardinalDirection.NORTH, 'NORTH', 'Equality for NORTH' );
    assert.equal( CardinalDirection.SOUTH, 'SOUTH', 'Equality for SOUTH' );
    assert.equal( CardinalDirection.EAST, 'EAST', 'Equality for EAST' );
    assert.equal( CardinalDirection.WEST, 'WEST', 'Equality for WEST' );

    assert.equal( CardinalDirection.includes( CardinalDirection.NORTH ), true, 'NORTH is in the enumeration' );
    assert.equal( CardinalDirection.includes( 'NORTH' ), false, 'Strings shouln\'t match' );
    assert.equal( CardinalDirection.includes( 'YORKSHIRE_TERRIER_WITH_THE_CANDLE_STICK_IN_THE_BALLROOM' ), false,
      'Not in the enumeration' );
    assert.equal( CardinalDirection.includes( { name: 'NORTH' } ), false, 'Should not be able to synthesize Enumeration values' );

    // Test toString
    var object = {};
    object[ CardinalDirection.NORTH ] = 'exit';
    assert.equal( object.NORTH, 'exit', 'toString should work seamlessly' );

    window.assert && assert.throws( function() {
      CardinalDirection.SOMETHING_AFTER_THE_FREEZE = 5;
    }, 'Should not be able to set things after initialization' );

    window.assert && assert.throws( function() {
      const x = new Enumeration( [ 'lowercase', 'should', 'fail' ] );
      assert.ok( !!x, 'fake assertion so x is used' );
    }, 'Enumeration should fail for lowercase values' );
  } );

  QUnit.test( 'Before freeze test', function( assert ) {
    const E = new Enumeration( [ 'A', 'B' ], E => {
      E.opposite = e => {
        window.assert && window.assert( E.includes( e ) );
        return e === E.A ? E.B : E.A;
      };
    } );

    assert.equal( E.A, 'A', 'Equality for A' );
    assert.equal( E.B, 'B', 'Equality for B' );
    assert.equal( E.opposite( E.A ), E.B, 'Custom function check 1' );
    assert.equal( E.opposite( E.B ), E.A, 'Custom function check 2' );

    window.assert && assert.throws( function() {
      E.SOMETHING_AFTER_THE_FREEZE = 5;
    }, 'Should not be able to set things after initialization' );
  } );

  QUnit.test( 'VALUES', function( assert ) {
    const People = new Enumeration( [ 'ALICE', 'BOB' ] );
    window.assert && assert.throws( () => {
      People.VALUES = 'something else';
    }, 'Setting values after initialization should throw an error.' );
  } );
} );
<|endoftext|>


<commit_before>/**
 * Created by kribh03 on 17-Jun-16.
 */
<commit_msg>Delete spinnerDirective.js<commit_after><|endoftext|>


<commit_before>// Copyright 2017, University of Colorado Boulder

/**
 *
 *
 * @author Sam Reid (PhET Interactive Simulations)
 * @author Denzell Barnett (PhET Interactive Simulations)
 *
 */
define( function( require ) {
  'use strict';

  // modules
  var ArrowNode = require( 'SCENERY_PHET/ArrowNode' );
  var ClearThermalButton = require( 'SCENERY_PHET/ClearThermalButton' );
  var griddle = require( 'GRIDDLE/griddle' );
  var inherit = require( 'PHET_CORE/inherit' );
  var Line = require( 'SCENERY/nodes/Line' );
  var Panel = require( 'SUN/Panel' );
  var Color = require( 'SCENERY/util/Color' );
  var Node = require( 'SCENERY/nodes/Node' );
  var Rectangle = require( 'SCENERY/nodes/Rectangle' );

  // constants
  var LINE_WIDTH = 0.8; // Empirically determined
  var STROKE_COLOR = 'gray';

  /**
   * @constructor
   */
  function VerticalBarChart( barNodes, options ) {
    // TODO: we may want to create the barNodes in the chart because the chart is aware of how much space we are working with.
    options = _.extend( {
      width: 100,
      height: 375,
      backgroundFill: 'white',
      title: null,
      titleFill: 'black',
      xAxisLabels: null,
      thermalEnergyProperty: null,
      thermalEnergyIndex: null, // {number} Index of the thermal energy property to be monitored. Used for ClearThermalButton positioning.
      thermalEnergyListener: null,
      visible: true
    }, options );

    var self = this;

    // Background for bar graph
    this.background = new Rectangle( 0, 200, options.width, 0, {
      fill: options.backgroundFill,
      stroke: STROKE_COLOR,
      lineWidth: LINE_WIDTH,
      cornerRadius: 7
    } );
    this.background.setRectHeight( options.height );

    // Creation of xAxis
    var xAxis = new Line( 0, 0, options.width - 20, 0, {
      stroke: 'black'
    } );

    // Creation of yAxis in respect to the xAxis
    var yAxisHeight = -options.height + 20;
    var yAxis = new ArrowNode( xAxis.getX1(), xAxis.getY1(), 0, yAxisHeight, {
      headHeight: 10,
      headWidth: 10,
      tailWidth: 1,
      fill: 'black',
      stroke: null
    } );

    // Layer for all bars added/removed from chart
    // TODO: Use clipArea, ask JO
    this.barLayer = new Node( {
      visible: options.visible
    } );

    // Layer for the x-axis labels
    this.labelLayer = new Node( {
      visible: options.visible
    } );

    // TODO: add x-axis labels that correspond to the placement of the bar nodes
    // Layer that refers to the chart starting with an origin at 0,0
    var chartNode = new Node( {
      children: [
        this.barLayer,
        this.labelLayer,
        xAxis,
        yAxis
      ],
      center: this.background.center
    } );

    this.barNodes = barNodes;

    //TODO: Find an appropriate derivation for the label spacing
    // Empirically determined spacing for the labels.
    var labelSpacing = options.height * 0.11;

    // TODO: Make sure to unlink and remove listeners for memory leaks.

    this.positionBar = function( barNode, index ) {
      var centerX = (index + 1) / (barNodes.length + 1) * options.width - 10;

      // Determine the placement for the labels if they exist. There must be the same amount of labels as barNodes.
      // TODO: Add assert so that labels.length === barNodes.length;
      if ( options.xAxisLabels !== null && (barNodes.length === options.xAxisLabels.length) ) {

        // The valueNode is a transparent background for each label. Used to make the label standout against bar if the bar falls beneath the x-Axis.
        var valueNode = new Panel( options.xAxisLabels[ index ], {
          stroke: null,
          fill: new Color( 255, 255, 255, 0.6 ),// put transparency in the color so that the children aren't transparent
          cornerRadius: 0,
          xMargin: 3,
          yMargin: 7
        } );
        self.labelLayer.addChild( valueNode );

        //Realign the axises
        yAxis.setTailAndTip( xAxis.getX1(), xAxis.getY1(), 0, -options.height + 20 );
        xAxis.setY1( -labelSpacing );
        xAxis.setY2( -labelSpacing );
        valueNode.centerX = centerX;
        valueNode.top = xAxis.centerY;
        options.xAxisLabels.forEach( function( label ) {
          label.maxWidth = labelSpacing * .5;
        } );
      }

      // Center of the bar determined based on the amount of bars present in the graph and the width of the graph
      barNode.centerX = centerX;
      barNode.bottom = xAxis.getY1();
      barNode.bottom = xAxis.getY1();
      barNode.visible = options.visible;
      self.barLayer.addChild( barNode );
    };

    // Adding barNodes to the chart with proper centering
    this.barNodes.forEach( function( barNode, index ) {
      self.positionBar( barNode, index );
    } );

    if ( options.thermalEnergyProperty ) {
      // var buttonCenter = (xAxis.width / barNodes.length) * options.thermalEnergyIndex;
      var buttonCenter = barNodes[ options.thermalEnergyIndex ].centerX;

      var clearThermalButton = new ClearThermalButton( {
        listener: options.thermalEnergyListener,
        centerX: buttonCenter,
        top: xAxis.centerY + this.labelLayer.height - 3, //TODO: This -3 number is a slight offset. Can we find a work around for this?
        scale: 0.7
      } );
      options.thermalEnergyProperty.lazyLink( function( value ) {
        clearThermalButton.enabled = !(value === 0);
      } );
      chartNode.addChild( clearThermalButton );

    }

    // TODO: Max Height of bar should adjust to height of chart area.
    Node.call( this, {
      children: [
        this.background, chartNode
      ]
    } );

    // Title added to the top of the chart area
    if ( options.title !== null ) {
      options.title.centerX = this.background.centerX;
      options.title.top = this.background.top + 4;
      options.title.fill = options.titleFill;
      options.title.visible = options.visible;
      this.addChild( options.title );
    }
  }

  griddle.register( 'VerticalBarChart', VerticalBarChart );

  return inherit( Node, VerticalBarChart, {

    // TODO: Methods to be added  ( removeBars, addOneBars, addBarGroup,)
    removeAllBars: function() {
      this.barLayer.removeAllChildren();
    },

    setBarNode: function( newBarNode, index ) {
      this.positionBar( newBarNode, index );
    }
  } );
} );
<commit_msg>More positional changes to energy graph regarding the x-axis.<commit_after>// Copyright 2017, University of Colorado Boulder

/**
 *
 *
 * @author Sam Reid (PhET Interactive Simulations)
 * @author Denzell Barnett (PhET Interactive Simulations)
 *
 */
define( function( require ) {
  'use strict';

  // modules
  var ArrowNode = require( 'SCENERY_PHET/ArrowNode' );
  var ClearThermalButton = require( 'SCENERY_PHET/ClearThermalButton' );
  var griddle = require( 'GRIDDLE/griddle' );
  var inherit = require( 'PHET_CORE/inherit' );
  var Line = require( 'SCENERY/nodes/Line' );
  var Panel = require( 'SUN/Panel' );
  var Color = require( 'SCENERY/util/Color' );
  var Node = require( 'SCENERY/nodes/Node' );
  var Rectangle = require( 'SCENERY/nodes/Rectangle' );

  // constants
  var LINE_WIDTH = 0.8; // Empirically determined
  var STROKE_COLOR = 'gray';

  /**
   * @constructor
   */
  function VerticalBarChart( barNodes, options ) {
    // TODO: we may want to create the barNodes in the chart because the chart is aware of how much space we are working with.
    options = _.extend( {
      width: 100,
      height: 375,
      backgroundFill: 'white',
      title: null,
      titleFill: 'black',
      xAxisLabels: null,
      thermalEnergyProperty: null,
      thermalEnergyIndex: null, // {number} Index of the thermal energy property to be monitored. Used for ClearThermalButton positioning.
      thermalEnergyListener: null,
      visible: true
    }, options );

    var self = this;

    // Background for bar graph
    this.background = new Rectangle( 0, 200, options.width, 0, {
      fill: options.backgroundFill,
      stroke: STROKE_COLOR,
      lineWidth: LINE_WIDTH,
      cornerRadius: 7
    } );
    this.background.setRectHeight( options.height );

    // Creation of xAxis
    var xAxis = new Line( 0, 0, options.width - 20, 0, {
      stroke: 'black'
    } );

    // Creation of yAxis in respect to the xAxis
    var yAxisHeight = -options.height + 20;
    var yAxis = new ArrowNode( xAxis.getX1(), xAxis.getY1(), 0, yAxisHeight, {
      headHeight: 10,
      headWidth: 10,
      tailWidth: 1,
      fill: 'black',
      stroke: null
    } );

    // Layer for all bars added/removed from chart
    // TODO: Use clipArea, ask JO
    this.barLayer = new Node( {
      visible: options.visible
    } );

    // Layer for the x-axis labels
    this.labelLayer = new Node( {
      visible: options.visible
    } );

    // TODO: add x-axis labels that correspond to the placement of the bar nodes
    // Layer that refers to the chart starting with an origin at 0,0
    var chartNode = new Node( {
      children: [
        this.barLayer,
        this.labelLayer,
        xAxis,
        yAxis
      ],
      center: this.background.center
    } );

    this.barNodes = barNodes;

    //TODO: Find an appropriate derivation for the label spacing
    // Empirically determined spacing for the labels.
    var labelSpacing = options.height * 0.14;

    // TODO: Make sure to unlink and remove listeners for memory leaks.

    this.positionBar = function( barNode, index ) {
      var centerX = (index + 1) / (barNodes.length + 1) * options.width - 10;

      // Determine the placement for the labels if they exist. There must be the same amount of labels as barNodes.
      // TODO: Add assert so that labels.length === barNodes.length;
      if ( options.xAxisLabels !== null && (barNodes.length === options.xAxisLabels.length) ) {

        // The valueNode is a transparent background for each label. Used to make the label standout against bar if the bar falls beneath the x-Axis.
        var valueNode = new Panel( options.xAxisLabels[ index ], {
          stroke: null,
          fill: new Color( 255, 255, 255, 0.6 ),// put transparency in the color so that the children aren't transparent
          cornerRadius: 0,
          xMargin: 3,
          yMargin: 7
        } );
        self.labelLayer.addChild( valueNode );

        //Realign the axises
        yAxis.setTailAndTip( xAxis.getX1(), xAxis.getY1(), 0, -options.height + 20 );
        xAxis.setY1( -labelSpacing );
        xAxis.setY2( -labelSpacing );
        valueNode.centerX = centerX;
        valueNode.top = xAxis.centerY;
        options.xAxisLabels.forEach( function( label ) {
          label.maxWidth = labelSpacing * .5;
        } );
      }

      // Center of the bar determined based on the amount of bars present in the graph and the width of the graph
      barNode.centerX = centerX;
      barNode.bottom = xAxis.getY1();
      barNode.bottom = xAxis.getY1();
      barNode.visible = options.visible;
      self.barLayer.addChild( barNode );
    };

    // Adding barNodes to the chart with proper centering
    this.barNodes.forEach( function( barNode, index ) {
      self.positionBar( barNode, index );
    } );

    if ( options.thermalEnergyProperty ) {
      // var buttonCenter = (xAxis.width / barNodes.length) * options.thermalEnergyIndex;
      var buttonCenter = barNodes[ options.thermalEnergyIndex ].centerX;

      var clearThermalButton = new ClearThermalButton( {
        listener: options.thermalEnergyListener,
        centerX: buttonCenter,
        top: xAxis.centerY + this.labelLayer.height,
        scale: 0.7
      } );
      options.thermalEnergyProperty.lazyLink( function( value ) {
        clearThermalButton.enabled = !(value === 0);
      } );
      chartNode.addChild( clearThermalButton );

    }

    // TODO: Max Height of bar should adjust to height of chart area.
    Node.call( this, {
      children: [
        this.background, chartNode
      ]
    } );

    // Title added to the top of the chart area
    if ( options.title !== null ) {
      options.title.centerX = this.background.centerX;
      options.title.top = this.background.top + 4;
      options.title.fill = options.titleFill;
      options.title.visible = options.visible;
      this.addChild( options.title );
    }
  }

  griddle.register( 'VerticalBarChart', VerticalBarChart );

  return inherit( Node, VerticalBarChart, {

    // TODO: Methods to be added  ( removeBars, addOneBars, addBarGroup,)
    removeAllBars: function() {
      this.barLayer.removeAllChildren();
    },

    setBarNode: function( newBarNode, index ) {
      this.positionBar( newBarNode, index );
    }
  } );
} );
<|endoftext|>