<commit_before>// ==UserScript==
// @name                Rabobank Internetbankieren auto-input
// @namespace           FelixAkk
// @description         Quickly select from multiple bank acccounts in the Rabobank login and payment pages
// @include             https://bankieren.rabobank.nl/klanten*
// @include             https://bankieren.rabobank.nl/rib/*
// @include             https://betalen.rabobank.nl/ide/qslo*
// @include             https://betalen.rabobank.nl/ideal-betaling/*
// @grant               GM_setValue
// @grant               GM_getValue
// @grant               GM_listValues
// @grant               GM_deleteValue
// @grant               GM_addStyle
// @grant               GM_registerMenuCommand
// @require             http://ajax.googleapis.com/ajax/libs/jquery/2.0.2/jquery.min.js
// @copyright           2014, Felix Akkermans
// @copyright           2014, Matthijs Kooijman (matthijs@stdin.nl)
// @license             The MIT license; http://opensource.org/licenses/MIT
// @homepageURL         https://github.com/matthijskooijman/greasemonkey-rabobank-autoinput
// @version             2.0.0
// ==/UserScript==

/*jslint undef: true, vars: true, newcap: true, maxerr: 50, maxlen: 200, indent: 4 */

/**
 * The `jslint` comment is an annotation with flags for JSLint.com and alike tools. Some explanation on the options:
 *
 * browser: true        Will make it accept use of document, window, JSON and such without declaration
 * vars: true           Tollerate many seperate variable declarations
 * maxlen: 200          Set the maximum line length to 200 characters
 * undef: true          Tollerate usage of undefined functions. To accept GM_* functions.
 * plusplus: true       Tollerate ++ and -- operators. Just shush already, I just them responsibly.
 */

/**
 * The global annotation is also for JSLint, which will tell it not to whine about the declaration
 */
/*global GM_setValue, GM_getValue, GM_listValues, GM_deleteValue, window, document */

// http://stackoverflow.com/questions/1335851/what-does-use-strict-do-in-javascript-and-what-is-the-reasoning-behind-it
(function () {
	"use strict";
	// --------------- General settings -------------------
	// tweak it to your own likings (script may malfunction on bad values)

	// Want me to fill in your default/primary account automatically as a page loads?
	var autoFillDefault = true,
		// Change to the account you want to select from the accountsArray (start counting from zero).
		defaultAccount = 0,
		// Time in miliseconds to wait for Rabobank's native JavaScript that's ran on DOM-ready to finish.
		// Increase this if you see your account selected but not filled in.
		autoFillDelay = 1000,
		// Optionally you can also choose your account through the GreaseMonkey command menu (off by default)
		GMMenu = false,
		// Want me to remove that puny original Rabobank 'remember my card' checkbox?
		// It's bugged, and I just made it obsolete... Yeah, that's what I though :)
		removeOriginalRemember = true;

	// ---------------- CSS/Stylesheet --------------------

	var stylesheet =
	'div#account_selection {'+
	'    margin-bottom: 20px;'+
	'    margin-left: 196px;'+
	'    margin-right: 196px;'+
	'    width: 528px;'+
	'}'+
	'div#account_selection table#accounts {'+
	'    background: none repeat scroll 0 0 White;'+
	'    border: 1px solid #CCCCCC;'+
	'    margin: 10px;'+
	'    padding: 5px;'+
	'    width: 96%;'+
	'}'+
	'table#accounts th {'+
	'    text-align: left;'+
	'}'+
	'table#accounts td.account_name label {'+
	'    display: inline-block;'+
	'    max-width: 200px;'+
	'    overflow: hidden;'+
	'    text-overflow: ellipsis;'+
	'    vertical-align: middle;'+
	'    white-space: nowrap;'+
	'    word-wrap: normal;'+
	'}'+
	'table#accounts td.account_name label {'+
	'}'+
	'a.edit {'+
	'    background: no-repeat scroll 0 0 transparent;'+
	'    display: block;'+
	'    margin: 10px;'+
	'    padding-left: 25px;'+
	'}'+
	'a.edit.enter {'+
	'    background-image: url("http://www.famfamfam.com/lab/icons/silk/icons/page_white_edit.png");'+
	'}'+
	'a.edit.exit {'+
	'    background-image: url("http://www.famfamfam.com/lab/icons/silk/icons/page_white_put.png");'+
	'}'+
	'a.account.add, a.account.delete {'+
	'    background: no-repeat scroll 0 0 transparent;'+
	'    display: inline-block;'+
	'    height: 16px;'+
	'    opacity: 0.3;'+
	'    vertical-align: text-bottom;'+
	'    width: 16px;'+
	'}'+
	'a.account.add:hover, a.account.delete:hover {'+
	'    opacity: 1;'+
	'}'+
	'a.account.add {'+
	'    background-image: url("http://www.famfamfam.com/lab/icons/silk/icons/add.png");'+
	'}'+
	'a.account.delete {'+
	'    background-image: url("http://www.famfamfam.com/lab/icons/silk/icons/delete.png");'+
	'}';

	// Construct selection panel DOM
	var selectionPanel =
	// I'll employ the styles of the Rabobank CSS classes .imgstripe, .newpanel to make it look identical.
	'
'+
	'  <form>'+
	'
'+
	// Static table header
	'
'+
	'
'+
	'          Selecteer uw Rabobank rekening	'+
	'          Rekening nummer	'+
	'          Kaart nummer	'+
	'
'+
	'
'+
	'

'+
	'
'+
	'  <form>'+
	// The edit button
	'  Rekeningen instellen...'+
	'  Veranderingen opslaan'+
	'
'
	selectionPanel = $(selectionPanel);

	// Account object
	function Account(descr, acc, card) {
		this.description = descr;
		this.number = acc;
		this.cardNumber = card;
	}

	// Define whether the page is in the editing stage
	var editing = false;
	// Example accounts
	var examples = [
		new Account("Bijv. Privé coulante rekening", 123456789, 1234),
		new Account("Bijv. Spaar rekening", 123456789, 1234),
		new Account("Bijv. Zakelijke rekening", 123456789, 1234)
	];

	// Prefetch storage
	var accountsJSON = GM_getValue('accountsJSON');
	// Actual accounts
	var accountsArray;
	// If we have no values stored yet (first run), initialize the storage with example values
	if (accountsJSON === undefined) {
		GM_setValue('accountsJSON', JSON.stringify(examples));
		accountsArray = examples;
	} else {
		// Else load the bank accounts
		accountsArray = JSON.parse(accountsJSON);
	}

	// Utility function that takes a bank account number and returns it seperated by points like on the Rabobank cards
	function numberFormat(account) {
		var nr = String(account);
		return nr.substring(0, 4) + '.' + nr.substring(4, 6) + '.' + nr.substring(6);
	}

	// Build accounts table contents (the rows), depending on whether we're editing (true) or selecting (false)
	function constructTable() {
		var t = $('#accounts tbody');
		t.empty();
		for (var idx = 0; idx < accountsArray.length; idx++) {
			if (editing)
				t.append(constructEditableRow(accountsArray[idx]));
			else
				t.append(constructSelectableRow(idx, accountsArray[idx]));
		}
		if (editing)
			$('

').on('click', addAccount).appendTo(t);
	}

	function constructSelectableRow(idx, acc) {
		return $('
').append(
			$('').append(
				$('<input type="radio" name="account" />'),
				$('').text(acc.description)
			),
			$('').append($('').text(acc.number)),
			$('').append($('').text(acc.cardNumber))
		).on('click', function() { selectAccount(idx); });
	}

	function constructEditableRow(acc) {
		return $('
').append(
			$('').append($('<input type="text" />').attr('value', acc.description)),
			$('').append($('<input type="text" size="9" maxlength="9"/>').attr('value', acc.number)),
			$('').append($('<input type="text" size="4" maxlength="4"/>').attr('value', acc.cardNumber)),
			$('').append($('').on('click', deleteAccount))
		);
	}

	function accountFromRow(row) {
		var inputs = $('input', row);
		return new Account(inputs[0].value, inputs[1].value, inputs[2].value);
	}

	// Define event handling function for selecting an account; fills in the account details
	function selectAccount(idx) {
		var d = document;
		$('#AuthIdv4').attr('value', accountsArray[idx].number);
		$('#AuthBpasNrv4').attr('value', accountsArray[idx].cardNumber);
		// Login pages have AuthCdv4, sign pages have SignCdv4.
		// Focuse whatever one is available.
		$('#AuthCdv4, #SignCdv4').focus();
		$('#accounts input[type="radio"]')[idx].checked = true;
	}

	// Define event handling function for deleting an account/row in the accounts table when editing accounts
	function deleteAccount() {
		$(this).closest('tr').remove();
	}

	// Define event handling function for inserting an account/row in the accounts table after a given index (when editing accounts)
	function addAccount(accountIdx) {
		var row = constructEditableRow(new Account());
		row.insertBefore($('#accounts tbody tr').last());
	}

	// Event handler for the save changes button
	function saveChanges() {
		accountsArray = []; // new array, clean slate
		// Fill array
		$('#accounts tbody tr').slice(0, -1).each(function(idx, row) {
			accountsArray.push(accountFromRow(row));
		});
		// Save it all
		GM_setValue('accountsJSON', JSON.stringify(accountsArray));
		setEditMode(false);
	}

	// Function to add an menu item to the GreaseMonkey command item to select your account.
	// This function is necessary to get 'idx' to be a seperate variable at runtime instead of the end value of the 'idx' variable of the insertPanel function.
	function addGMMenuItem(idx) {
		// Format caption like '1. Account description (12345689 : 1234)'
		var caption = (idx + 1) + '. ' + accountsArray[idx].description + '  (' + numberFormat(accountsArray[idx].number) + ' : ' + accountsArray[idx].cardNumber + ')';
		// Have to wrap the select account function in an anonymous function to create a closure with the index parameter bound
		var handler = function () { selectAccount(idx); };
		GM_registerMenuCommand(caption, handler);
	}

	function setEditMode(value) {
		// Update edit/save links
		$("a.edit.enter", selectionPanel).toggle(!value);
		$("a.edit.exit", selectionPanel).toggle(value);
		// Remember new edit mode
		editing = value;
		// Reconstruct table
		constructTable();
	}

	function initAccountsPanel() {
		$("a.edit.enter", selectionPanel).on("click", function() { setEditMode(true)});
		$("a.edit.exit", selectionPanel).on("click", function() { saveChanges()});
		setEditMode(false);
	}

	function initialize() {
		// Load the defined custom styles
		GM_addStyle(stylesheet);

		// Insert and fill the custom account selection panel
		$("#brt_content-section").prepend(selectionPanel);
		initAccountsPanel(editing);

		if (GMMenu) {
			for (var idx = 0; idx < accountsArray.length; idx++) {
				addGMMenuItem(idx);
			}
		}

		// Want me to remove that puny original Rabobank 'remember my card' checkbox? It's bugged, and I just made it obsolete... Yeah, that's what I though :)
		if (removeOriginalRemember) {
			$('input[type="checkbox"]#brtcheck01').parent().hide();
		}

		// And for good measure, we may select the default/primary straight away.
		// This basically just fires the event listener function without setting the it's this.id attribute.
		if (autoFillDefault) {
			// We have to wait a little while to avoid conflict with Rabobank's native JavaScript ran on DOM-ready
			window.setTimeout(function() { selectAccount(defaultAccount); }, autoFillDelay);
		}
	}
	/**
	/* Run only when script is of use, i.e.;
	/* if we're on a Rabobank page where we have the kind of form we can input something usefull into.
	 */
	if(
		$('#brt_form').length != 0 &&
		$('#AuthIdv4').length != 0 &&
		$('#AuthBpasNrv4').length != 0
	) {
		initialize();
	}

}());

<commit_msg>Remove unused variable<commit_after>// ==UserScript==
// @name                Rabobank Internetbankieren auto-input
// @namespace           FelixAkk
// @description         Quickly select from multiple bank acccounts in the Rabobank login and payment pages
// @include             https://bankieren.rabobank.nl/klanten*
// @include             https://bankieren.rabobank.nl/rib/*
// @include             https://betalen.rabobank.nl/ide/qslo*
// @include             https://betalen.rabobank.nl/ideal-betaling/*
// @grant               GM_setValue
// @grant               GM_getValue
// @grant               GM_listValues
// @grant               GM_deleteValue
// @grant               GM_addStyle
// @grant               GM_registerMenuCommand
// @require             http://ajax.googleapis.com/ajax/libs/jquery/2.0.2/jquery.min.js
// @copyright           2014, Felix Akkermans
// @copyright           2014, Matthijs Kooijman (matthijs@stdin.nl)
// @license             The MIT license; http://opensource.org/licenses/MIT
// @homepageURL         https://github.com/matthijskooijman/greasemonkey-rabobank-autoinput
// @version             2.0.0
// ==/UserScript==

/*jslint undef: true, vars: true, newcap: true, maxerr: 50, maxlen: 200, indent: 4 */

/**
 * The `jslint` comment is an annotation with flags for JSLint.com and alike tools. Some explanation on the options:
 *
 * browser: true        Will make it accept use of document, window, JSON and such without declaration
 * vars: true           Tollerate many seperate variable declarations
 * maxlen: 200          Set the maximum line length to 200 characters
 * undef: true          Tollerate usage of undefined functions. To accept GM_* functions.
 * plusplus: true       Tollerate ++ and -- operators. Just shush already, I just them responsibly.
 */

/**
 * The global annotation is also for JSLint, which will tell it not to whine about the declaration
 */
/*global GM_setValue, GM_getValue, GM_listValues, GM_deleteValue, window, document */

// http://stackoverflow.com/questions/1335851/what-does-use-strict-do-in-javascript-and-what-is-the-reasoning-behind-it
(function () {
	"use strict";
	// --------------- General settings -------------------
	// tweak it to your own likings (script may malfunction on bad values)

	// Want me to fill in your default/primary account automatically as a page loads?
	var autoFillDefault = true,
		// Change to the account you want to select from the accountsArray (start counting from zero).
		defaultAccount = 0,
		// Time in miliseconds to wait for Rabobank's native JavaScript that's ran on DOM-ready to finish.
		// Increase this if you see your account selected but not filled in.
		autoFillDelay = 1000,
		// Optionally you can also choose your account through the GreaseMonkey command menu (off by default)
		GMMenu = false,
		// Want me to remove that puny original Rabobank 'remember my card' checkbox?
		// It's bugged, and I just made it obsolete... Yeah, that's what I though :)
		removeOriginalRemember = true;

	// ---------------- CSS/Stylesheet --------------------

	var stylesheet =
	'div#account_selection {'+
	'    margin-bottom: 20px;'+
	'    margin-left: 196px;'+
	'    margin-right: 196px;'+
	'    width: 528px;'+
	'}'+
	'div#account_selection table#accounts {'+
	'    background: none repeat scroll 0 0 White;'+
	'    border: 1px solid #CCCCCC;'+
	'    margin: 10px;'+
	'    padding: 5px;'+
	'    width: 96%;'+
	'}'+
	'table#accounts th {'+
	'    text-align: left;'+
	'}'+
	'table#accounts td.account_name label {'+
	'    display: inline-block;'+
	'    max-width: 200px;'+
	'    overflow: hidden;'+
	'    text-overflow: ellipsis;'+
	'    vertical-align: middle;'+
	'    white-space: nowrap;'+
	'    word-wrap: normal;'+
	'}'+
	'table#accounts td.account_name label {'+
	'}'+
	'a.edit {'+
	'    background: no-repeat scroll 0 0 transparent;'+
	'    display: block;'+
	'    margin: 10px;'+
	'    padding-left: 25px;'+
	'}'+
	'a.edit.enter {'+
	'    background-image: url("http://www.famfamfam.com/lab/icons/silk/icons/page_white_edit.png");'+
	'}'+
	'a.edit.exit {'+
	'    background-image: url("http://www.famfamfam.com/lab/icons/silk/icons/page_white_put.png");'+
	'}'+
	'a.account.add, a.account.delete {'+
	'    background: no-repeat scroll 0 0 transparent;'+
	'    display: inline-block;'+
	'    height: 16px;'+
	'    opacity: 0.3;'+
	'    vertical-align: text-bottom;'+
	'    width: 16px;'+
	'}'+
	'a.account.add:hover, a.account.delete:hover {'+
	'    opacity: 1;'+
	'}'+
	'a.account.add {'+
	'    background-image: url("http://www.famfamfam.com/lab/icons/silk/icons/add.png");'+
	'}'+
	'a.account.delete {'+
	'    background-image: url("http://www.famfamfam.com/lab/icons/silk/icons/delete.png");'+
	'}';

	// Construct selection panel DOM
	var selectionPanel =
	// I'll employ the styles of the Rabobank CSS classes .imgstripe, .newpanel to make it look identical.
	'
'+
	'  <form>'+
	'
'+
	// Static table header
	'
'+
	'
'+
	'          Selecteer uw Rabobank rekening	'+
	'          Rekening nummer	'+
	'          Kaart nummer	'+
	'
'+
	'
'+
	'

'+
	'
'+
	'  <form>'+
	// The edit button
	'  Rekeningen instellen...'+
	'  Veranderingen opslaan'+
	'
'
	selectionPanel = $(selectionPanel);

	// Account object
	function Account(descr, acc, card) {
		this.description = descr;
		this.number = acc;
		this.cardNumber = card;
	}

	// Define whether the page is in the editing stage
	var editing = false;
	// Example accounts
	var examples = [
		new Account("Bijv. Privé coulante rekening", 123456789, 1234),
		new Account("Bijv. Spaar rekening", 123456789, 1234),
		new Account("Bijv. Zakelijke rekening", 123456789, 1234)
	];

	// Prefetch storage
	var accountsJSON = GM_getValue('accountsJSON');
	// Actual accounts
	var accountsArray;
	// If we have no values stored yet (first run), initialize the storage with example values
	if (accountsJSON === undefined) {
		GM_setValue('accountsJSON', JSON.stringify(examples));
		accountsArray = examples;
	} else {
		// Else load the bank accounts
		accountsArray = JSON.parse(accountsJSON);
	}

	// Utility function that takes a bank account number and returns it seperated by points like on the Rabobank cards
	function numberFormat(account) {
		var nr = String(account);
		return nr.substring(0, 4) + '.' + nr.substring(4, 6) + '.' + nr.substring(6);
	}

	// Build accounts table contents (the rows), depending on whether we're editing (true) or selecting (false)
	function constructTable() {
		var t = $('#accounts tbody');
		t.empty();
		for (var idx = 0; idx < accountsArray.length; idx++) {
			if (editing)
				t.append(constructEditableRow(accountsArray[idx]));
			else
				t.append(constructSelectableRow(idx, accountsArray[idx]));
		}
		if (editing)
			$('

').on('click', addAccount).appendTo(t);
	}

	function constructSelectableRow(idx, acc) {
		return $('
').append(
			$('').append(
				$('<input type="radio" name="account" />'),
				$('').text(acc.description)
			),
			$('').append($('').text(acc.number)),
			$('').append($('').text(acc.cardNumber))
		).on('click', function() { selectAccount(idx); });
	}

	function constructEditableRow(acc) {
		return $('
').append(
			$('').append($('<input type="text" />').attr('value', acc.description)),
			$('').append($('<input type="text" size="9" maxlength="9"/>').attr('value', acc.number)),
			$('').append($('<input type="text" size="4" maxlength="4"/>').attr('value', acc.cardNumber)),
			$('').append($('').on('click', deleteAccount))
		);
	}

	function accountFromRow(row) {
		var inputs = $('input', row);
		return new Account(inputs[0].value, inputs[1].value, inputs[2].value);
	}

	// Define event handling function for selecting an account; fills in the account details
	function selectAccount(idx) {
		$('#AuthIdv4').attr('value', accountsArray[idx].number);
		$('#AuthBpasNrv4').attr('value', accountsArray[idx].cardNumber);
		// Login pages have AuthCdv4, sign pages have SignCdv4.
		// Focuse whatever one is available.
		$('#AuthCdv4, #SignCdv4').focus();
		$('#accounts input[type="radio"]')[idx].checked = true;
	}

	// Define event handling function for deleting an account/row in the accounts table when editing accounts
	function deleteAccount() {
		$(this).closest('tr').remove();
	}

	// Define event handling function for inserting an account/row in the accounts table after a given index (when editing accounts)
	function addAccount(accountIdx) {
		var row = constructEditableRow(new Account());
		row.insertBefore($('#accounts tbody tr').last());
	}

	// Event handler for the save changes button
	function saveChanges() {
		accountsArray = []; // new array, clean slate
		// Fill array
		$('#accounts tbody tr').slice(0, -1).each(function(idx, row) {
			accountsArray.push(accountFromRow(row));
		});
		// Save it all
		GM_setValue('accountsJSON', JSON.stringify(accountsArray));
		setEditMode(false);
	}

	// Function to add an menu item to the GreaseMonkey command item to select your account.
	// This function is necessary to get 'idx' to be a seperate variable at runtime instead of the end value of the 'idx' variable of the insertPanel function.
	function addGMMenuItem(idx) {
		// Format caption like '1. Account description (12345689 : 1234)'
		var caption = (idx + 1) + '. ' + accountsArray[idx].description + '  (' + numberFormat(accountsArray[idx].number) + ' : ' + accountsArray[idx].cardNumber + ')';
		// Have to wrap the select account function in an anonymous function to create a closure with the index parameter bound
		var handler = function () { selectAccount(idx); };
		GM_registerMenuCommand(caption, handler);
	}

	function setEditMode(value) {
		// Update edit/save links
		$("a.edit.enter", selectionPanel).toggle(!value);
		$("a.edit.exit", selectionPanel).toggle(value);
		// Remember new edit mode
		editing = value;
		// Reconstruct table
		constructTable();
	}

	function initAccountsPanel() {
		$("a.edit.enter", selectionPanel).on("click", function() { setEditMode(true)});
		$("a.edit.exit", selectionPanel).on("click", function() { saveChanges()});
		setEditMode(false);
	}

	function initialize() {
		// Load the defined custom styles
		GM_addStyle(stylesheet);

		// Insert and fill the custom account selection panel
		$("#brt_content-section").prepend(selectionPanel);
		initAccountsPanel(editing);

		if (GMMenu) {
			for (var idx = 0; idx < accountsArray.length; idx++) {
				addGMMenuItem(idx);
			}
		}

		// Want me to remove that puny original Rabobank 'remember my card' checkbox? It's bugged, and I just made it obsolete... Yeah, that's what I though :)
		if (removeOriginalRemember) {
			$('input[type="checkbox"]#brtcheck01').parent().hide();
		}

		// And for good measure, we may select the default/primary straight away.
		// This basically just fires the event listener function without setting the it's this.id attribute.
		if (autoFillDefault) {
			// We have to wait a little while to avoid conflict with Rabobank's native JavaScript ran on DOM-ready
			window.setTimeout(function() { selectAccount(defaultAccount); }, autoFillDelay);
		}
	}
	/**
	/* Run only when script is of use, i.e.;
	/* if we're on a Rabobank page where we have the kind of form we can input something usefull into.
	 */
	if(
		$('#brt_form').length != 0 &&
		$('#AuthIdv4').length != 0 &&
		$('#AuthBpasNrv4').length != 0
	) {
		initialize();
	}

}());

<|endoftext|>


<commit_before>import atkPlugin from 'plugins/atkPlugin';
import apiService from '../services/ApiService';

export default class serverEvent extends atkPlugin {

  main() {

    if (typeof(EventSource) !== "undefined") {
      let source = new EventSource(`${this.settings.uri}?${this.settings.name}=sse`);
      source.onmessage = function (e) {
        apiService.atkSuccessTest(JSON.parse(e.data));
      };
      source.onerror = function (e) {
          if (e.eventPhase === EventSource.CLOSED) {
            source.close();
          }
      };
      source.addEventListener("jsAction", function(e) {
        apiService.atkSuccessTest(JSON.parse(e.data));
      }, false);
    } else {
      console.log('server side event not supported fallback to atkAjaxec');
      this.$el.atkReloadView({
        uri: this.settings.uri,
        uri_options: {[this.settings.name]:'callback'},
      });
    }
  }
}

serverEvent.DEFAULTS = {
  uri: null,
  uri_options: {},
  name: '',
};<commit_msg>fix typo in console log.<commit_after>import atkPlugin from 'plugins/atkPlugin';
import apiService from '../services/ApiService';

export default class serverEvent extends atkPlugin {

  main() {

    if (typeof(EventSource) !== "undefined") {
      let source = new EventSource(`${this.settings.uri}?${this.settings.name}=sse`);
      source.onmessage = function (e) {
        apiService.atkSuccessTest(JSON.parse(e.data));
      };
      source.onerror = function (e) {
          if (e.eventPhase === EventSource.CLOSED) {
            source.close();
          }
      };
      source.addEventListener("jsAction", function(e) {
        apiService.atkSuccessTest(JSON.parse(e.data));
      }, false);
    } else {
      console.log('server side event not supported fallback to atkReloadView');
      this.$el.atkReloadView({
        uri: this.settings.uri,
        uri_options: {[this.settings.name]:'callback'},
      });
    }
  }
}

serverEvent.DEFAULTS = {
  uri: null,
  uri_options: {},
  name: '',
};<|endoftext|>


<commit_before>// $(document).ready(function(){

var playerTurn = "red";

var changePlayerTurn = function () {
  if ( playerTurn != "red" ) {
    playerTurn = "red";
  } else {
    playerTurn = "black";
  }
}

var changePlayerMenu = function () {
  var newPlayerTurn

  if ( playerTurn != "red" ) {
    newPlayerTurn = "red";
  } else {
    newPlayerTurn = "black";
  }

  $( ".player" ).attr('data-color',newPlayerTurn);
  $('.player_name').text(newPlayerTurn.charAt(0).toUpperCase() + newPlayerTurn.slice(1) + " Player's Turn")
}

var animateTurn = function (empty_cells) {
  animation_from_cell = empty_cells.children().first();
  animation_to_cell = empty_cells.children().last();

  // console.log("from",animation_from_cell,"to",animation_to_cell)
  cell_played = empty_cells.last();

  if (empty_cells.length == 1) {
    animation_from_cell = $(".board");
  }

  animation_from_cell.attr("id","animate_from_cell");
  animation_to_cell.attr("id","animate_to_cell");
  cell_played.attr("id","cell_played");

  $(".player").hide({effect: "slide", direction:"left", duration: 150, complete: animatePlacePiece});

}

var animatePlacePiece = function() {
  changePlayerMenu();
  $("#animate_from_cell").effect("transfer", {to:"#animate_to_cell", duration:500, className:playerTurn, easing:"easeOutBounce", complete: afterPiecePlaced});
  $(".player").show("slide",{direction:"right"}, 150);
}

var afterPiecePlaced = function() {
  $("#cell_played").attr('data-color',playerTurn);
  $("#cell_played").css("background-color","");
  $("#cell_played").css("opacity","");

  // clear out temp ids
  $("#cell_played").attr("id","");
  $("#animate_from_cell").attr("id","");
  $("#animate_to_cell").attr("id","");

  changePlayerTurn();

  if (winner(cell_played[0])) {
    $( ".column" ).unbind();  //FREEZES THE GAME
    $(".row").css("opacity","");
    $(".board").css("background-color","green");
    playerTurn = "none";
  } else {
    setEvents();
  }
}

var removePlayer = function() {
  // $(".player").hide(0);
  $(".player").toggle("slide",{direction:"right"},500);
  $(".player").toggle("slide",{direction:"left"},500);

}

var placePiece = function() {
  $( ".column" ).unbind();
  var empty_cells = $( this ).children("[data-color=empty]");
  var cell_played = empty_cells.last();

  animateTurn(empty_cells);
}

var startGame = function () {
  $(".column").unbind();
  $(".restart").unbind();

  playerTurn = "black";

  changePlayerMenu();
  changePlayerTurn();

  $(".row").attr('data-color',"empty");
  // $(".row").css("background-color","");
  $(".board").css("background-color","");
  setEvents();

}

var setEvents = function () {
  $( ".column:has([data-color=empty])" ).click(placePiece);
  $( ".restart" ).click( startGame );

  // if playerTurn

  $( ".column" ).hover( function () {
    $( this ).children("[data-color=empty]").last().css({"background-color":playerTurn,"opacity":"0.4"});
    }, function () {
      $( this ).children().css({"background-color":"","opacity":""});
    }
  );
}

startGame();

// $( ".img" ).click(placePiece);
// var placePiece = function(){
//   console.log("test")
// }
// $(".board").on("click",'.column.c0', function(e){
//   console.log("test")
// })
// });
<commit_msg>saving progress in order to merge<commit_after>// $(document).ready(function(){

var playerTurn = "red";

var changePlayerTurn = function () {
  if ( playerTurn != "red" ) {
    playerTurn = "red";
  } else {
    playerTurn = "black";
  }
}

var changePlayerMenu = function () {
  var newPlayerTurn

  if ( playerTurn != "red" ) {
    newPlayerTurn = "red";
  } else {
    newPlayerTurn = "black";
  }

  $( ".player" ).attr('data-color',newPlayerTurn);
  $('.player_name').text(newPlayerTurn.charAt(0).toUpperCase() + newPlayerTurn.slice(1) + " Player's Turn")
}

var animateTurn = function (empty_cells) {
  animation_from_cell = empty_cells.children().first();
  animation_to_cell = empty_cells.children().last();

  // console.log("from",animation_from_cell,"to",animation_to_cell)
  cell_played = empty_cells.last();

  if (empty_cells.length == 1) {
    animation_from_cell = $(".board");
  }

  animation_from_cell.attr("id","animate_from_cell");
  animation_to_cell.attr("id","animate_to_cell");
  cell_played.attr("id","cell_played");

  $(".player").hide({effect: "slide", direction:"left", duration: 150, complete: animatePlacePiece});

}

var animatePlacePiece = function() {
  changePlayerMenu();
  $("#animate_from_cell").effect("transfer", {to:"#animate_to_cell", duration:500, className:playerTurn, easing:"easeOutBounce", complete: afterPiecePlaced});
  $(".player").show("slide",{direction:"right"}, 150);
}

var afterPiecePlaced = function() {
  $("#cell_played").attr('data-color',playerTurn);
  $("#cell_played").css("background-color","");
  $("#cell_played").css("opacity","");

  // clear out temp ids
  $("#cell_played").attr("id","");
  $("#animate_from_cell").attr("id","");
  $("#animate_to_cell").attr("id","");

  changePlayerTurn();

  if (winner(cell_played[0])) {
    $( ".column" ).unbind();  //FREEZES THE GAME
    $(".row").css("opacity","");
    $(".board").css("background-color","green");
    playerTurn = "none";
  } else {
    setEvents();
  }
}

var removePlayer = function() {
  // $(".player").hide(0);
  $(".player").toggle("slide",{direction:"right"},500);
  $(".player").toggle("slide",{direction:"left"},500);

}

var autoPlace = function(column) {
  $( ".column" ).unbind();
  var empty_cells = $( column ).children("[data-color=empty]");
  var cell_played = empty_cells.last();

  animateTurn(empty_cells);
}

var placePiece = function() {
  $( ".column" ).unbind();
  var empty_cells = $( this ).children("[data-color=empty]");
  var cell_played = empty_cells.last();

  animateTurn(empty_cells);
}

var startGame = function () {
  $(".column").unbind();
  $(".restart").unbind();

  playerTurn = "black";

  changePlayerMenu();
  changePlayerTurn();

  $(".row").attr('data-color',"empty");
  // $(".row").css("background-color","");
  $(".board").css("background-color","");
  setEvents();

}

var setEvents = function () {
  $( ".column:has([data-color=empty])" ).click(placePiece);
  $( ".restart" ).click( startGame );

  // if playerTurn

  $( ".column" ).hover( function () {
    $( this ).children("[data-color=empty]").last().css({"background-color":playerTurn,"opacity":"0.4"});
    }, function () {
      $( this ).children().css({"background-color":"","opacity":""});
    }
  );
}

startGame();

// $( ".img" ).click(placePiece);
// var placePiece = function(){
//   console.log("test")
// }
// $(".board").on("click",'.column.c0', function(e){
//   console.log("test")
// })
// });
<|endoftext|>


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

/**
 * a type representing the steam-generating tea kettle in the model.
 *
 * @author John Blanco
 * @author  Andrew Adare
 */
define( function( require ) {
  'use strict';

  // modules
  var EFACA11yStrings = require( 'ENERGY_FORMS_AND_CHANGES/EFACA11yStrings' );
  var EFACConstants = require( 'ENERGY_FORMS_AND_CHANGES/common/EFACConstants' );
  var Energy = require( 'ENERGY_FORMS_AND_CHANGES/systems/model/Energy' );
  var EnergyChunk = require( 'ENERGY_FORMS_AND_CHANGES/common/model/EnergyChunk' );
  var EnergyChunkPathMover = require( 'ENERGY_FORMS_AND_CHANGES/systems/model/EnergyChunkPathMover' );
  var energyFormsAndChanges = require( 'ENERGY_FORMS_AND_CHANGES/energyFormsAndChanges' );
  var EnergySource = require( 'ENERGY_FORMS_AND_CHANGES/systems/model/EnergySource' );
  var EnergyType = require( 'ENERGY_FORMS_AND_CHANGES/common/model/EnergyType' );
  var Image = require( 'SCENERY/nodes/Image' );
  var inherit = require( 'PHET_CORE/inherit' );
  var Property = require( 'AXON/Property' );
  var Range = require( 'DOT/Range' );
  var Vector2 = require( 'DOT/Vector2' );

  // images
  var TEAPOT_ICON = require( 'image!ENERGY_FORMS_AND_CHANGES/tea_kettle_icon.png' );

  // constants

  // Offsets and other constants used for energy paths.  These are mostly
  // empirically determined and coordinated with the image.
  var SPOUT_BOTTOM_OFFSET = new Vector2( 0.03, 0.02 );
  var SPOUT_EXIT_ANGLE = 0.876; // in radians
  var WATER_SURFACE_HEIGHT_OFFSET = 0; // From tea kettle position, in meters.
  var THERMAL_ENERGY_CHUNK_Y_ORIGIN = -0.05; // Meters. Coordinated with heater position.
  var THERMAL_ENERGY_CHUNK_X_ORIGIN_RANGE = new Range( -0.015, 0.015 ); // Meters. Coordinated with heater position.

  // Miscellaneous other constants.
  var MAX_ENERGY_CHANGE_RATE = EFACConstants.MAX_ENERGY_PRODUCTION_RATE / 5; // In joules/second
  var COOLING_CONSTANT = 0.1; // Controls rate at which tea kettle cools down, empirically determined.
  var COOL_DOWN_COMPLETE_THRESHOLD = 30; // In joules/second
  var ENERGY_CHUNK_TRANSFER_DISTANCE_RANGE = new Range( 0.12, 0.15 );
  var ENERGY_CHUNK_WATER_TO_SPOUT_TIME = 0.7; // Used to keep chunks evenly spaced.

  /**
   * @param {Property.<boolean>} energyChunksVisibleProperty
   * @param {Property.<boolean>} steamPowerableElementInPlaceProperty
   * @constructor
   */
  function TeaKettle( energyChunksVisibleProperty, steamPowerableElementInPlaceProperty ) {

    EnergySource.call( this, new Image( TEAPOT_ICON ) );

    // @public {string} - a11y name
    this.a11yName = EFACA11yStrings.teaKettle.value;

    this.heatCoolAmountProperty = new Property( 0 );
    this.energyProductionRateProperty = new Property( 0 );

    this.energyChunksVisibleProperty = energyChunksVisibleProperty;
    this.steamPowerableElementInPlaceProperty = steamPowerableElementInPlaceProperty;
    this.heatEnergyProducedSinceLastChunk = EFACConstants.ENERGY_PER_CHUNK / 2;
    this.energyChunkMovers = [];

    // List of chunks that are not being transferred to the next energy system
    // element.
    this.exemptFromTransferEnergyChunks = [];

    // Flag for whether next chunk should be transferred or kept, used to
    // alternate transfer with non-transfer.
    this.transferNextAvailableChunk = true;
  }

  energyFormsAndChanges.register( 'TeaKettle', TeaKettle );

  return inherit( EnergySource, TeaKettle, {

    /**
     * Animation for tea kettle and energy chunks
     *
     * @param  {number} dt timestep
     *
     * @returns {Energy}
     * @public
     * @override
     */
    step: function( dt ) {

      if ( this.activeProperty.value ) {

        if ( this.heatCoolAmountProperty.value > 0 || this.energyProductionRateProperty.value > COOL_DOWN_COMPLETE_THRESHOLD ) {

          // Calculate the energy production rate.

          // Analogous to acceleration.
          var increase = this.heatCoolAmountProperty.value * MAX_ENERGY_CHANGE_RATE;

          // Analogous to friction.
          var decrease = this.energyProductionRateProperty.value * COOLING_CONSTANT;

          // Analogous to velocity.
          var rate = this.energyProductionRateProperty.value + increase * dt - decrease * dt;
          rate = Math.min( rate, EFACConstants.MAX_ENERGY_PRODUCTION_RATE );

          this.energyProductionRateProperty.set( rate );
        }
        else {
          // Clamp the energy production rate to zero so that it doesn't
          // trickle on forever.
          this.energyProductionRateProperty.set( 0 );
        }

        // See if it's time to emit a new energy chunk from the heater.
        this.heatEnergyProducedSinceLastChunk +=
          Math.max( this.heatCoolAmountProperty.value, 0 ) * EFACConstants.MAX_ENERGY_PRODUCTION_RATE * dt;

        if ( this.heatEnergyProducedSinceLastChunk >= EFACConstants.ENERGY_PER_CHUNK ) {

          // Emit a new thermal energy chunk.
          var xRange = THERMAL_ENERGY_CHUNK_X_ORIGIN_RANGE;
          var x0 = this.positionProperty.value.x + xRange.min + phet.joist.random.nextDouble() * xRange.getLength();
          var y0 = this.positionProperty.value.y + THERMAL_ENERGY_CHUNK_Y_ORIGIN;
          var initialPosition = new Vector2( x0, y0 );

          var energyChunk = new EnergyChunk(
            EnergyType.THERMAL,
            initialPosition,
            Vector2.ZERO,
            this.energyChunksVisibleProperty
          );

          this.energyChunkList.push( energyChunk );

          this.heatEnergyProducedSinceLastChunk -= EFACConstants.ENERGY_PER_CHUNK;

          this.energyChunkMovers.push( new EnergyChunkPathMover( energyChunk,
            this.createThermalEnergyChunkPath( initialPosition, this.positionProperty.value ),
            EFACConstants.ENERGY_CHUNK_VELOCITY ) );
        }

        // Move all energy chunks that are under this element's control.
        this.moveEnergyChunks( dt );
      }
      return new Energy( EnergyType.MECHANICAL, this.energyProductionRateProperty.value * dt, Math.PI / 2 );
    },

    /**
     * @param  {number} dt time step
     * @private
     */
    moveEnergyChunks: function( dt ) {
      var self = this;
      var chunkMovers = _.clone( this.energyChunkMovers );

      chunkMovers.forEach( function( mover ) {
        mover.moveAlongPath( dt );
        var chunk = mover.energyChunk;

        if ( mover.pathFullyTraversed ) {

          _.pull( self.energyChunkMovers, mover );

          // This is a thermal chunk that is coming out of the water.
          if ( chunk.energyTypeProperty.get() === EnergyType.THERMAL &&
               chunk.positionProperty.get().y === self.positionProperty.value.y + WATER_SURFACE_HEIGHT_OFFSET ) {
            if ( phet.joist.random.nextDouble() > 0.2 ) {

              // Turn the chunk into mechanical energy.
              chunk.energyTypeProperty.set( EnergyType.MECHANICAL );
            }

            // Set this chunk on a path to the base of the spout.
            var travelDistance = chunk.positionProperty.get().distance( self.positionProperty.value.plus( SPOUT_BOTTOM_OFFSET ) );

            self.energyChunkMovers.push( new EnergyChunkPathMover( chunk,
              self.createPathToSpoutBottom( self.positionProperty.value ),
              travelDistance / ENERGY_CHUNK_WATER_TO_SPOUT_TIME ) );
          }

          // This chunk is moving out of the spout.
          else if ( chunk.positionProperty.get().equals( self.positionProperty.value.plus( SPOUT_BOTTOM_OFFSET ) ) ) {
            self.energyChunkMovers.push( new EnergyChunkPathMover( chunk,
              self.createSpoutExitPath( self.positionProperty.value ),
              EFACConstants.ENERGY_CHUNK_VELOCITY /* This is a speed (scalar) */ ) );
          }

          // This chunk is out of view, and we are done with it.
          else {
            self.energyChunkList.remove( chunk );
          }
        }

        // Path not fully traversed
        else {

          // See if this energy chunks should be transferred to the
          // next energy system.
          if ( chunk.energyTypeProperty.get() === EnergyType.MECHANICAL &&
               self.steamPowerableElementInPlaceProperty.get() &&
               ENERGY_CHUNK_TRANSFER_DISTANCE_RANGE.contains( self.positionProperty.value.distance( chunk.positionProperty.get() ) ) &&
               !_.includes( self.exemptFromTransferEnergyChunks, chunk ) ) {

            // Send this chunk to the next energy system.
            if ( self.transferNextAvailableChunk ) {
              self.outgoingEnergyChunks.push( chunk );

              _.pull( self.energyChunkMovers, mover );

              // Alternate sending or keeping chunks.
              self.transferNextAvailableChunk = false;
            }

            // Don't transfer this chunk.
            // Set up to transfer the next one.
            else {
              self.exemptFromTransferEnergyChunks.push( chunk );

              self.transferNextAvailableChunk = true;
            }
          }

          // if a chunk has reached the position where it should transfer to the next system, but no steam powerable
          // element is in place, add the chunk to the list of non transfers
          else if ( !self.steamPowerableElementInPlaceProperty.get() &&
                    ENERGY_CHUNK_TRANSFER_DISTANCE_RANGE.contains(
                      self.positionProperty.value.distance( chunk.positionProperty.get() )
                    ) &&
                    !_.includes( self.exemptFromTransferEnergyChunks, chunk ) ) {
            self.exemptFromTransferEnergyChunks.push( chunk );
          }
        }

      } );
    },

    /**
     * @param  {Vector2}  startPosition
     * @param  {Vector2}  teaKettlePosition
     *
     * @returns {Vector2[]}
     * @private
     */
    createThermalEnergyChunkPath: function( startPosition, teaKettlePosition ) {
      var path = [];

      path.push( new Vector2( startPosition.x, teaKettlePosition.y + WATER_SURFACE_HEIGHT_OFFSET ) );

      return path;
    },

    /**
     * @param  {Vector2} parentElementPosition
     *
     * @returns {Vector2[]}
     * @private
     */
    createPathToSpoutBottom: function( parentElementPosition ) {
      var path = [];

      path.push( parentElementPosition.plus( SPOUT_BOTTOM_OFFSET ) );

      return path;
    },

    /**
     * @param  {Vector2} parentElementPosition
     *
     * @returns {Vector2[]}
     * @private
     */
    createSpoutExitPath: function( parentElementPosition ) {
      var path = [];

      // calculate the travel vector based on how high the chunks should gp
      var yDistance = EFACConstants.ENERGY_CHUNK_MAX_TRAVEL_HEIGHT - parentElementPosition.y;
      var xDistance = yDistance / Math.tan( SPOUT_EXIT_ANGLE ) + parentElementPosition.x;
      var distantTargetLocation = new Vector2( xDistance, yDistance );
      path.push( distantTargetLocation );

      return path;
    },

    /**
     * @public
     * @override
     */
    preloadEnergyChunks: function() {
      this.clearEnergyChunks();

      // Return if no chunks to add.
      if ( this.energyProductionRateProperty.get() === 0 ) {
        return;
      }

      var preloadComplete = false;
      var dt = 1 / EFACConstants.FRAMES_PER_SECOND;
      var energySinceLastChunk = EFACConstants.ENERGY_PER_CHUNK * 0.99;

      // Simulate energy chunks moving through the system.
      while ( !preloadComplete ) {
        energySinceLastChunk += this.energyProductionRateProperty.get() * dt;

        if ( energySinceLastChunk >= EFACConstants.ENERGY_PER_CHUNK ) {

          // Create a chunk inside the tea kettle (at the water surface).
          var initialPosition = new Vector2( this.positionProperty.value.x,
            this.positionProperty.value.y + WATER_SURFACE_HEIGHT_OFFSET );

          var energyType = phet.joist.random.nextDouble() > 0.2 ? EnergyType.MECHANICAL : EnergyType.THERMAL;

          var newEnergyChunk = new EnergyChunk(
            energyType,
            initialPosition,
            Vector2.ZERO,
            this.energyChunksVisibleProperty
          );
          this.energyChunkList.push( newEnergyChunk );

          var travelDistance = newEnergyChunk.positionProperty.get().distance(
            this.positionProperty.value.plus( SPOUT_BOTTOM_OFFSET ) );

          this.energyChunkMovers.push( new EnergyChunkPathMover( newEnergyChunk,
            this.createPathToSpoutBottom( this.positionProperty.value ),
            travelDistance / ENERGY_CHUNK_WATER_TO_SPOUT_TIME ) );

          energySinceLastChunk -= EFACConstants.ENERGY_PER_CHUNK;
        }

        // Update energy chunk positions.
        this.moveEnergyChunks( dt );

        if ( this.outgoingEnergyChunks.length > 0 || this.exemptFromTransferEnergyChunks.length > 0 ) {

          // An energy chunk has traversed to the output of this system, or passed the point of moving to the next system.
          preloadComplete = true;
        }
      }
    },

    /**
     * @returns {Energy}
     * @public
     * @override
     */
    getEnergyOutputRate: function() {
      return new Energy( EnergyType.MECHANICAL, this.energyProductionRateProperty.value, Math.PI / 2 );
    },

    /**
     * Deactivate the tea kettle
     * @public
     * @override
     */
    deactivate: function() {
      EnergySource.prototype.deactivate.call( this );
      this.heatCoolAmountProperty.reset();
      this.energyProductionRateProperty.reset();
    },

    /**
     * @public
     * @override
     */
    clearEnergyChunks: function() {
      EnergySource.prototype.clearEnergyChunks.call( this );
      this.exemptFromTransferEnergyChunks.length = 0;
      this.energyChunkMovers.length = 0;
    }

  } );
} );

<commit_msg>Update tea kettle path creator usages, see https://github.com/phetsims/energy-forms-and-changes/issues/159<commit_after>// Copyright 2016-2018, University of Colorado Boulder

/**
 * a type representing the steam-generating tea kettle in the model.
 *
 * @author John Blanco
 * @author  Andrew Adare
 */
define( function( require ) {
  'use strict';

  // modules
  var EFACA11yStrings = require( 'ENERGY_FORMS_AND_CHANGES/EFACA11yStrings' );
  var EFACConstants = require( 'ENERGY_FORMS_AND_CHANGES/common/EFACConstants' );
  var Energy = require( 'ENERGY_FORMS_AND_CHANGES/systems/model/Energy' );
  var EnergyChunk = require( 'ENERGY_FORMS_AND_CHANGES/common/model/EnergyChunk' );
  var EnergyChunkPathMover = require( 'ENERGY_FORMS_AND_CHANGES/systems/model/EnergyChunkPathMover' );
  var energyFormsAndChanges = require( 'ENERGY_FORMS_AND_CHANGES/energyFormsAndChanges' );
  var EnergySource = require( 'ENERGY_FORMS_AND_CHANGES/systems/model/EnergySource' );
  var EnergyType = require( 'ENERGY_FORMS_AND_CHANGES/common/model/EnergyType' );
  var Image = require( 'SCENERY/nodes/Image' );
  var inherit = require( 'PHET_CORE/inherit' );
  var Property = require( 'AXON/Property' );
  var Range = require( 'DOT/Range' );
  var Vector2 = require( 'DOT/Vector2' );

  // images
  var TEAPOT_ICON = require( 'image!ENERGY_FORMS_AND_CHANGES/tea_kettle_icon.png' );

  // constants

  // Offsets and other constants used for energy paths.  These are mostly
  // empirically determined and coordinated with the image.
  var SPOUT_BOTTOM_OFFSET = new Vector2( 0.03, 0.02 );
  var SPOUT_EXIT_ANGLE = 0.876; // in radians
  var WATER_SURFACE_HEIGHT_OFFSET = 0; // From tea kettle position, in meters.
  var THERMAL_ENERGY_CHUNK_Y_ORIGIN = -0.05; // Meters. Coordinated with heater position.
  var THERMAL_ENERGY_CHUNK_X_ORIGIN_RANGE = new Range( -0.015, 0.015 ); // Meters. Coordinated with heater position.

  // Miscellaneous other constants.
  var MAX_ENERGY_CHANGE_RATE = EFACConstants.MAX_ENERGY_PRODUCTION_RATE / 5; // In joules/second
  var COOLING_CONSTANT = 0.1; // Controls rate at which tea kettle cools down, empirically determined.
  var COOL_DOWN_COMPLETE_THRESHOLD = 30; // In joules/second
  var ENERGY_CHUNK_TRANSFER_DISTANCE_RANGE = new Range( 0.12, 0.15 );
  var ENERGY_CHUNK_WATER_TO_SPOUT_TIME = 0.7; // Used to keep chunks evenly spaced.

  /**
   * @param {Property.<boolean>} energyChunksVisibleProperty
   * @param {Property.<boolean>} steamPowerableElementInPlaceProperty
   * @constructor
   */
  function TeaKettle( energyChunksVisibleProperty, steamPowerableElementInPlaceProperty ) {

    EnergySource.call( this, new Image( TEAPOT_ICON ) );

    // @public {string} - a11y name
    this.a11yName = EFACA11yStrings.teaKettle.value;

    this.heatCoolAmountProperty = new Property( 0 );
    this.energyProductionRateProperty = new Property( 0 );

    this.energyChunksVisibleProperty = energyChunksVisibleProperty;
    this.steamPowerableElementInPlaceProperty = steamPowerableElementInPlaceProperty;
    this.heatEnergyProducedSinceLastChunk = EFACConstants.ENERGY_PER_CHUNK / 2;
    this.energyChunkMovers = [];

    // List of chunks that are not being transferred to the next energy system
    // element.
    this.exemptFromTransferEnergyChunks = [];

    // Flag for whether next chunk should be transferred or kept, used to
    // alternate transfer with non-transfer.
    this.transferNextAvailableChunk = true;
  }

  energyFormsAndChanges.register( 'TeaKettle', TeaKettle );

  return inherit( EnergySource, TeaKettle, {

    /**
     * Animation for tea kettle and energy chunks
     *
     * @param  {number} dt timestep
     *
     * @returns {Energy}
     * @public
     * @override
     */
    step: function( dt ) {

      if ( this.activeProperty.value ) {

        if ( this.heatCoolAmountProperty.value > 0 || this.energyProductionRateProperty.value > COOL_DOWN_COMPLETE_THRESHOLD ) {

          // Calculate the energy production rate.

          // Analogous to acceleration.
          var increase = this.heatCoolAmountProperty.value * MAX_ENERGY_CHANGE_RATE;

          // Analogous to friction.
          var decrease = this.energyProductionRateProperty.value * COOLING_CONSTANT;

          // Analogous to velocity.
          var rate = this.energyProductionRateProperty.value + increase * dt - decrease * dt;
          rate = Math.min( rate, EFACConstants.MAX_ENERGY_PRODUCTION_RATE );

          this.energyProductionRateProperty.set( rate );
        }
        else {
          // Clamp the energy production rate to zero so that it doesn't
          // trickle on forever.
          this.energyProductionRateProperty.set( 0 );
        }

        // See if it's time to emit a new energy chunk from the heater.
        this.heatEnergyProducedSinceLastChunk +=
          Math.max( this.heatCoolAmountProperty.value, 0 ) * EFACConstants.MAX_ENERGY_PRODUCTION_RATE * dt;

        if ( this.heatEnergyProducedSinceLastChunk >= EFACConstants.ENERGY_PER_CHUNK ) {

          // Emit a new thermal energy chunk.
          var xRange = THERMAL_ENERGY_CHUNK_X_ORIGIN_RANGE;
          var x0 = this.positionProperty.value.x + xRange.min + phet.joist.random.nextDouble() * xRange.getLength();
          var y0 = this.positionProperty.value.y + THERMAL_ENERGY_CHUNK_Y_ORIGIN;
          var initialPosition = new Vector2( x0, y0 );

          var energyChunk = new EnergyChunk(
            EnergyType.THERMAL,
            initialPosition,
            Vector2.ZERO,
            this.energyChunksVisibleProperty
          );

          this.energyChunkList.push( energyChunk );

          this.heatEnergyProducedSinceLastChunk -= EFACConstants.ENERGY_PER_CHUNK;

          this.energyChunkMovers.push( new EnergyChunkPathMover( energyChunk,
            this.createThermalEnergyChunkPath( initialPosition, this.positionProperty.value ),
            EFACConstants.ENERGY_CHUNK_VELOCITY ) );
        }

        // Move all energy chunks that are under this element's control.
        this.moveEnergyChunks( dt );
      }
      return new Energy( EnergyType.MECHANICAL, this.energyProductionRateProperty.value * dt, Math.PI / 2 );
    },

    /**
     * @param  {number} dt time step
     * @private
     */
    moveEnergyChunks: function( dt ) {
      var self = this;
      var chunkMovers = _.clone( this.energyChunkMovers );

      chunkMovers.forEach( function( mover ) {
        mover.moveAlongPath( dt );
        var chunk = mover.energyChunk;

        if ( mover.pathFullyTraversed ) {

          _.pull( self.energyChunkMovers, mover );

          // This is a thermal chunk that is coming out of the water.
          if ( chunk.energyTypeProperty.get() === EnergyType.THERMAL &&
               chunk.positionProperty.get().y === self.positionProperty.value.y + WATER_SURFACE_HEIGHT_OFFSET ) {
            if ( phet.joist.random.nextDouble() > 0.2 ) {

              // Turn the chunk into mechanical energy.
              chunk.energyTypeProperty.set( EnergyType.MECHANICAL );
            }

            // Set this chunk on a path to the base of the spout.
            var travelDistance = chunk.positionProperty.get().distance( self.positionProperty.value.plus( SPOUT_BOTTOM_OFFSET ) );

            // create path mover to spout bottom
            self.energyChunkMovers.push( new EnergyChunkPathMover( chunk,
              EnergyChunkPathMover.createPathFromOffsets( self.positionProperty.value, [ SPOUT_BOTTOM_OFFSET ] ),
              travelDistance / ENERGY_CHUNK_WATER_TO_SPOUT_TIME ) );
          }

          // This chunk is moving out of the spout.
          else if ( chunk.positionProperty.get().equals( self.positionProperty.value.plus( SPOUT_BOTTOM_OFFSET ) ) ) {
            self.energyChunkMovers.push( new EnergyChunkPathMover( chunk,
              EnergyChunkPathMover.createStraightPath( self.positionProperty.value, SPOUT_EXIT_ANGLE ),
              EFACConstants.ENERGY_CHUNK_VELOCITY /* This is a speed (scalar) */ ) );
          }

          // This chunk is out of view, and we are done with it.
          else {
            self.energyChunkList.remove( chunk );
          }
        }

        // Path not fully traversed
        else {

          // See if this energy chunks should be transferred to the
          // next energy system.
          if ( chunk.energyTypeProperty.get() === EnergyType.MECHANICAL &&
               self.steamPowerableElementInPlaceProperty.get() &&
               ENERGY_CHUNK_TRANSFER_DISTANCE_RANGE.contains( self.positionProperty.value.distance( chunk.positionProperty.get() ) ) &&
               !_.includes( self.exemptFromTransferEnergyChunks, chunk ) ) {

            // Send this chunk to the next energy system.
            if ( self.transferNextAvailableChunk ) {
              self.outgoingEnergyChunks.push( chunk );

              _.pull( self.energyChunkMovers, mover );

              // Alternate sending or keeping chunks.
              self.transferNextAvailableChunk = false;
            }

            // Don't transfer this chunk.
            // Set up to transfer the next one.
            else {
              self.exemptFromTransferEnergyChunks.push( chunk );

              self.transferNextAvailableChunk = true;
            }
          }

          // if a chunk has reached the position where it should transfer to the next system, but no steam powerable
          // element is in place, add the chunk to the list of non transfers
          else if ( !self.steamPowerableElementInPlaceProperty.get() &&
                    ENERGY_CHUNK_TRANSFER_DISTANCE_RANGE.contains(
                      self.positionProperty.value.distance( chunk.positionProperty.get() )
                    ) &&
                    !_.includes( self.exemptFromTransferEnergyChunks, chunk ) ) {
            self.exemptFromTransferEnergyChunks.push( chunk );
          }
        }

      } );
    },

    /**
     * @param  {Vector2}  startPosition
     * @param  {Vector2}  teaKettlePosition
     *
     * @returns {Vector2[]}
     * @private
     */
    createThermalEnergyChunkPath: function( startPosition, teaKettlePosition ) {
      var path = [];

      path.push( new Vector2( startPosition.x, teaKettlePosition.y + WATER_SURFACE_HEIGHT_OFFSET ) );

      return path;
    },

    /**
     * @public
     * @override
     */
    preloadEnergyChunks: function() {
      this.clearEnergyChunks();

      // Return if no chunks to add.
      if ( this.energyProductionRateProperty.get() === 0 ) {
        return;
      }

      var preloadComplete = false;
      var dt = 1 / EFACConstants.FRAMES_PER_SECOND;
      var energySinceLastChunk = EFACConstants.ENERGY_PER_CHUNK * 0.99;

      // Simulate energy chunks moving through the system.
      while ( !preloadComplete ) {
        energySinceLastChunk += this.energyProductionRateProperty.get() * dt;

        if ( energySinceLastChunk >= EFACConstants.ENERGY_PER_CHUNK ) {

          // Create a chunk inside the tea kettle (at the water surface).
          var initialPosition = new Vector2( this.positionProperty.value.x,
            this.positionProperty.value.y + WATER_SURFACE_HEIGHT_OFFSET );

          var energyType = phet.joist.random.nextDouble() > 0.2 ? EnergyType.MECHANICAL : EnergyType.THERMAL;

          var newEnergyChunk = new EnergyChunk(
            energyType,
            initialPosition,
            Vector2.ZERO,
            this.energyChunksVisibleProperty
          );
          this.energyChunkList.push( newEnergyChunk );

          var travelDistance = newEnergyChunk.positionProperty.get().distance(
            this.positionProperty.value.plus( SPOUT_BOTTOM_OFFSET ) );

          // create path mover to spout bottom
          this.energyChunkMovers.push( new EnergyChunkPathMover( newEnergyChunk,
            EnergyChunkPathMover.createPathFromOffsets( this.positionProperty.value, [ SPOUT_BOTTOM_OFFSET ] ),
            travelDistance / ENERGY_CHUNK_WATER_TO_SPOUT_TIME ) );

          energySinceLastChunk -= EFACConstants.ENERGY_PER_CHUNK;
        }

        // Update energy chunk positions.
        this.moveEnergyChunks( dt );

        if ( this.outgoingEnergyChunks.length > 0 || this.exemptFromTransferEnergyChunks.length > 0 ) {

          // An energy chunk has traversed to the output of this system, or passed the point of moving to the next system.
          preloadComplete = true;
        }
      }
    },

    /**
     * @returns {Energy}
     * @public
     * @override
     */
    getEnergyOutputRate: function() {
      return new Energy( EnergyType.MECHANICAL, this.energyProductionRateProperty.value, Math.PI / 2 );
    },

    /**
     * Deactivate the tea kettle
     * @public
     * @override
     */
    deactivate: function() {
      EnergySource.prototype.deactivate.call( this );
      this.heatCoolAmountProperty.reset();
      this.energyProductionRateProperty.reset();
    },

    /**
     * @public
     * @override
     */
    clearEnergyChunks: function() {
      EnergySource.prototype.clearEnergyChunks.call( this );
      this.exemptFromTransferEnergyChunks.length = 0;
      this.energyChunkMovers.length = 0;
    }

  } );
} );

<|endoftext|>


<commit_before>define("ace/snippets/pascal",["require","exports","module"], function(require, exports, module) {
"use strict";

exports.snippetText =undefined;
exports.scope = "pascal";

});
<commit_msg>Update tmp/bower_components/ace-builds/src/snippets/pascal.js<commit_after><|endoftext|>


<commit_before>// check if the redis native extension is available
//if (typeof redis !== "undefined" || typeof redis.RedisAccess !== "undefined") {

redis.RedisDocStore = function (settings) {

  // reference to this for use within instance methods
  var self = this;

  this.redis = redis.RedisAccess.Create(0);

  // default settings for redis db
  var host = "127.0.0.1";
  var port = 6379;
  var scope = "substance";

  // use the settings object to override the default settings
  if (arguments.length == 1) {
    if (typeof settings.host != "undefined") {
      host = settings.host;
    }
    if (typeof settings.port != "undefined") {
      port = settings.port;
    }
    if (typeof settings.scope != "undefined") {
      scope = settings.scope;
    }
  }

  this.redis.setHost(host);
  this.redis.setPort(port);
  this.redis.connect();

  // the scope is useful to keep parts of the redis db separated
  // e.g. tests would use its own, or one could separate user spaces
  this.redis.setScope(scope);

  /**
   *  Checks if a document exists
   *  @param id the document's id
   *  @param cb callback
   */
  this.exists = function (id, cb) {
    var result = self.redis.exists(id);

    if (cb) cb({err: 0, result: result});

    return result;
  };

  /**
   * Creates a new document with the provided id
   * @param cb callback
   */
  this.create = function (id, cb) {
    if(self.exists(id) && cb) {
      return cb({err: -1, msg: "Document already exists."});
    }

    // TODO: more initial fields?
    // initial id field
    self.redis.set(id, {"id": id});

    // TODO create initial list for commits
    if (cb) cb({err: 0});

    return true;
  };

  /**
   *  Deletes a document
   *  @param cb callback
   */
  this.delete = function (id, cb) {
    self.redis.remove(id);

    if (arguments.length === 2)
      cb({err: 0});

    return true;
  }

  /**
   *  Stores a sequence of commits for a given document id.
   *
   *  @param newCommits an array of commit objects
   *  @param cb callback
   */
  this.update = function(id, newCommits, cb) {
    var commitsKey = id + ":commits";
    var commits = self.redis.asList(commitsKey);

    var lastSha = undefined;
    if(commits.size() > 0)
      lastSha = commits.get();

    self.redis.beginTransaction();
    for(var idx=0; idx<newCommits.length; idx++) {

      // commit must be in proper order
      if (typeof lastSha !== undefined && newCommits[idx].parent != lastSha) {
        self.redis.cancelTransaction();
        var err = {err: -1, msg: "Invalid commit chain."};
        // TODO: maybe give more details about the problem
        if (typeof cb !== "undefined")
          cb(err);
        else
          console.log(err.msg);
        return false;
      }

      // note: these commands will be executed when executeTransaction is called
      //       if something is wrong, e.g., invalid sha sequence, then the transaction is cancelled.
      commits.add(newCommits[idx].sha);

      // store the commit's data into an own field
      self.redis.set(commitsKey + ":" + newCommits[idx].sha, newCommits[idx]);

      lastSha = newCommits[idx].sha;
    }

    self.redis.executeTransaction();

    if(arguments.length == 3)
      cb({err: 0});
    else
      return true;
  };

  /**
   * Retrieves a document
   *
   * @param id the document's id
   * @param cb callback
   */
  this.get = function(id, cb) {

    if(!self.exists(id) && typeof cb !== "undefined") {
      if(arguments.length == 2) {
        cb({err: -1, msg: "Document does not exist."}, undefined);
      } else {
        throw new RedisError("Document does not exist.")
      }
    }

    var doc = self.redis.getJSON(id);
    doc.commits = {};

    var commits = self.redis.asList(id + ":commits");
    var shas = commits.asArray();
    for (var idx=0; idx<shas.length; ++idx) {
      var commit = self.redis.getJSON( id + ":commits:" + shas[idx]);
      doc.commits[shas[idx]] = commit;
    }

    // TODO: more about that refs
    var lastSha;
    if(shas.length > 0) {
      lastSha = commits.get();
    } else {
      lastSha = undefined;
    }
    doc.refs = {
      master: lastSha
    }

    if(arguments.length == 2)
      cb(0, doc);

    return doc;
  };
};

var redisstore = new redis.RedisDocStore();

//}
<commit_msg>Use hash for document data in redis docstore.<commit_after>// check if the redis native extension is available
//if (typeof redis !== "undefined" || typeof redis.RedisAccess !== "undefined") {

redis.RedisDocStore = function (settings) {

  // reference to this for use within instance methods
  var self = this;

  this.redis = redis.RedisAccess.Create(0);

  // default settings for redis db
  var host = "127.0.0.1";
  var port = 6379;
  var scope = "substance";

  // use the settings object to override the default settings
  if (arguments.length == 1) {
    if (typeof settings.host != "undefined") {
      host = settings.host;
    }
    if (typeof settings.port != "undefined") {
      port = settings.port;
    }
    if (typeof settings.scope != "undefined") {
      scope = settings.scope;
    }
  }

  this.redis.setHost(host);
  this.redis.setPort(port);
  this.redis.connect();

  // the scope is useful to keep parts of the redis db separated
  // e.g. tests would use its own, or one could separate user spaces
  this.redis.setScope(scope);

  self.documents = self.redis.asHash("documents");

  /**
   *  Checks if a document exists
   *  @param id the document's id
   *  @param cb callback
   */
  this.exists = function (id, cb) {
    var result = self.documents.contains(id);

    if (cb) cb({err: 0, result: result});

    return result;
  };

  /**
   * Creates a new document with the provided id
   * @param cb callback
   */
  this.create = function (id, cb) {
    if(self.exists(id) && cb) {
      return cb({err: -1, msg: "Document already exists."});
    }

    var doc = {"id": id};
    // TODO: more initial fields?
    // initial id field
    self.documents.set(id, JSON.stringify(doc));

    // TODO create initial list for commits
    if (cb) cb({err: 0});

    return true;
  };

  /**
   *  Deletes a document
   *  @param cb callback
   */
  this.delete = function (id, cb) {
    self.documents.remove(id);
    self.redis.remove(id);

    if (arguments.length === 2)
      cb({err: 0});

    return true;
  }

  /**
   *  Stores a sequence of commits for a given document id.
   *
   *  @param newCommits an array of commit objects
   *  @param cb callback
   */
  this.update = function(id, newCommits, cb) {
    var commitsKey = id + ":commits";
    var commits = self.redis.asList(commitsKey);

    var lastSha = undefined;
    if(commits.size() > 0)
      lastSha = commits.get();

    self.redis.beginTransaction();
    for(var idx=0; idx<newCommits.length; idx++) {

      // commit must be in proper order
      if (typeof lastSha !== undefined && newCommits[idx].parent != lastSha) {
        self.redis.cancelTransaction();
        var err = {err: -1, msg: "Invalid commit chain."};
        // TODO: maybe give more details about the problem
        if (typeof cb !== "undefined")
          cb(err);
        else
          console.log(err.msg);
        return false;
      }

      // note: these commands will be executed when executeTransaction is called
      //       if something is wrong, e.g., invalid sha sequence, then the transaction is cancelled.
      commits.add(newCommits[idx].sha);

      // store the commit's data into an own field
      self.redis.set(commitsKey + ":" + newCommits[idx].sha, newCommits[idx]);

      lastSha = newCommits[idx].sha;
    }

    self.redis.executeTransaction();

    if(arguments.length == 3)
      cb({err: 0});
    else
      return true;
  };

  /**
   * Retrieves a document
   *
   * @param id the document's id
   * @param cb callback
   */
  this.get = function(id, cb) {

    if(!self.exists(id) && typeof cb !== "undefined") {
      if(arguments.length == 2) {
        cb({err: -1, msg: "Document does not exist."}, undefined);
      } else {
        throw new RedisError("Document does not exist.")
      }
    }

    var docData = self.documents.get(id);
    var doc = JSON.parse(docData);
    doc.commits = {};

    var commits = self.redis.asList(id + ":commits");
    var shas = commits.asArray();
    for (var idx=0; idx<shas.length; ++idx) {
      var commit = self.redis.getJSON( id + ":commits:" + shas[idx]);
      doc.commits[shas[idx]] = commit;
    }

    // TODO: more about that refs
    var lastSha;
    if(shas.length > 0) {
      lastSha = commits.get();
    } else {
      lastSha = undefined;
    }
    doc.refs = {
      master: lastSha
    }

    if(arguments.length == 2)
      cb(0, doc);

    return doc;
  };
};

var redisstore = new redis.RedisDocStore();

//}
<|endoftext|>


<commit_before>jQuery(document).ready(function ($) {
    $('#error_repost_show').die().live('click', function () {
        $('#importReportModal').modal('toggle');

        return false;
    });

    //--
    //In the form when Paiement Date changes and Mois de TVA not set, the field Mois de TVA should take the corresponding YearMonth of Paiement Date
    //http://redmine.testenm.com/issues/1376
    symfony_ajax.behaviors.PaiementDateCloneMoisdeTVA = {
        attach:function (context) {
            var _uniqid = symfony_ajax.get_uniqid();

            //-- V01-TVA || A02-TVA
            if ($('#' + _uniqid + '_paiement_date', context).size() && $('#' + _uniqid + '_mois_mois', context).size()) {
                $('#' + _uniqid + '_paiement_date', context).change(function () {

                    if ($(this).val() && !$('#' + _uniqid + '_mois_mois :selected', context).val()) {
                        var date_arr = $(this).val().split('/');
                        var year_month = date_arr[2] + '-' + Number(date_arr[1]);

                        $('#' + _uniqid + '_mois_mois option', context).each(function () {
                            $(this).removeAttr('selected');
                        });

                        $('#' + _uniqid + '_mois_mois option', context).each(function () {
                            if ($(this).val() == year_month) {
                                $(this).attr('selected', 'selected').trigger('change');
                            }
                        })
                    }
                });
            }
        }
    };

    //-- get Devises money value
    //http://redmine.testenm.com/issues/1364#note-9
    symfony_ajax.behaviors.rDevises = {
        attach:function (context) {
            var _uniqid = symfony_ajax.get_uniqid();
            if (_uniqid) {
                $('#' + _uniqid + '_paiement_devise, #' + _uniqid + '_paiement_date', context).change(function () {
                    var _uniqid = symfony_ajax.get_uniqid();

                    var devise = $('#' + _uniqid + '_paiement_devise :selected').val();
                    var paiement_date = $('#' + _uniqid + '_paiement_date').val();
                    var paiement_montant = $('#' + _uniqid + '_paiement_montant').val();
                    var $taux_de_change = $('#' + _uniqid + '_taux_de_change');

                    if (devise && paiement_date && paiement_montant && !$taux_de_change.val()) {
                        $.ajax({
                            url:Sonata.url.rdevises,
                            type:'POST',
                            data:{
                                devise:devise,
                                date:paiement_date
                            },
                            dataType:'json',
                            async:false,
                            success:function (i) {
                                $taux_de_change.val(i.value ? i.value : '');
                            }
                        })
                    }
                });
            }
        }
    };

    //-- Calc MontantTVAfrancaiseAndMontantTTC
    symfony_ajax.behaviors.calcMontantTVAfrancaiseAndMontantTTC = {
        attach:function (context) {
            var _uniqid = symfony_ajax.get_uniqid();
            if (_uniqid) {
                $('#' + _uniqid + '_montant_HT_en_devise, #' + _uniqid + '_taux_de_TVA', context)
                    //state procurement
                    .change(this.calc)
                    .keyup(this.calc)
                    .trigger('change');
            }
        },
        number_limit:function (e) {
            var chr = String.fromCharCode(e.charCode == undefined ? e.keyCode : e.charCode);
            return (chr < ' ' || (chr >= '0' && chr <= '9') || chr == ',' || chr == '.');
        },
        calc:function (e) {
            var _uniqid = symfony_ajax.get_uniqid();

            var $montant_HT_en_devise = $('#' + _uniqid + '_montant_HT_en_devise');
            var $taux_de_TVA = $('#' + _uniqid + '_taux_de_TVA');

            substr_replace($montant_HT_en_devise, 2);
            substr_replace($taux_de_TVA, 3);

            var montant_HT_en_devise = $montant_HT_en_devise.val().replace(',', '.').replace(/\s+/, '');
            var taux_de_TVA = $taux_de_TVA.val().replace(',', '.').replace(/\s+/, '');

            var montant_TVA_francaise = parseFloat(parseFloat(montant_HT_en_devise) * parseFloat(taux_de_TVA));

            //If method validate from file Validate/ErrorElements.php function round $precision = 2, $mode = PHP_ROUND_HALF_DOWN
            montant_TVA_francaise = montant_TVA_francaise ? montant_TVA_francaise.toFixed(2) : '';

            var montant_TTC = parseFloat(parseFloat(montant_HT_en_devise) + parseFloat(montant_TVA_francaise));

            montant_TVA_francaise = montant_TVA_francaise ? montant_TVA_francaise.replace('.', ',') : '';
            montant_TTC = montant_TTC ? montant_TTC.toFixed(2).replace('.', ',') : '';

            $('#' + _uniqid + '_montant_TVA_francaise').val(montant_TVA_francaise);
            $('#' + _uniqid + '_montant_TTC').val(montant_TTC);
        }
    };

});

function substr_replace($object, limit) {

    var result = $object.val().split(',');
    var result2 = $object.val().split('.');
    if ((result[1] && result[1].length > limit) || result2[1] && result2[1].length > limit) {
        $object.val($object.val().substr(0, $object.val().length - 1));
    }
}

function init_clientoperations_buttons(o) {

    var btn_client_alert_click = false;
    $('#btn_client_alert').live('click', function (event) {

        symfony_ajax.behaviors.alert_popo = {
            attach:function (context) {
                $('.modal-body .table td').removeAttr('objectid');
            }
        }

        field_dialog_form_add__id(event, o.alert.link, {title:o.alert.title });
        return false;
    });

    if (o.blocking.permit) {
        $("#btn_locking").click(function () {
            if (o.blocking.isBlocked && o.blocking.hasBlocking) {
                $('#btn_client_alert').click();
            }
            else {
                if (confirm(o.blocking.text)) {
                    location.href = o.blocking.link;
                }
            }
        });
    }

    $('input[id=inputFile]').change(function () {
        $('#inputFileCover').val($(this).val());
    });

    $('#deleteImport').click(function () {
        $.ajax({
            url:o.import.link,
            dataType:'json',
            success:function (json) {
                var $table = $('

');
                $('
')
                    .append('N°	')
                    .append('Date	')
                    .append('Utilisateur	')
                    .append('Action	')
                    .appendTo($table.children('thead'));

                var $tbody = $('
');
                for (i in json.imports) {
                    var import_id = json.imports[i].id;
                    var deleteUrl = o.import.delete.replace("__id__", import_id);
                    $('
')
                        .append('' + import_id + '	')
                        .append('' + json.imports[i].date.date + '	')
                        .append('' + json.imports[i].username + '	')
                        .append('Supprimer	')
                        .appendTo($tbody);
                }
                $table.append($tbody);

                // populate the popup container
                field_dialog__id.find('.popup-body').html('').append($table);
                field_dialog__id.find('.title').html(json.title);
                field_dialog__id.modal('toggle');

                $table.find('a.import_del').click(function () {
                    return confirm(o.import.confirm);
                });
            }
        });
    });
}

function init_rapprochement_sums() {
    var ECARTsumm = 0;

    var $plus = $('.rapprochement_content_no_deb .rapprochement_content_input table.table tr.totals_row div b :first');
    $plus = $plus.length ? $plus.html() : '0';
    var $minus = $('.rapprochement_content_deb .rapprochement_content_input table.table tr.totals_row div b :first');
    $minus = $minus.length ? $minus.html() : '0';
    var diff = Number($plus.replace(',', '.')) - Number($minus.replace(',', '.'));
    ECARTsumm += diff;
    $('#totals_input_v1').html(
        (Math.round((diff) * 100) / 100).toFixed(2).toString().replace('.', ',')
    );

    var $plus = $('.rapprochement_content_no_deb .rapprochement_content_input table.table tr.totals_row div b :last');
    $plus = $plus.length ? $plus.html() : '0';
    var $minus = $('.rapprochement_content_deb .rapprochement_content_input table.table tr.totals_row div b :last');
    $minus = $minus.length ? $minus.html() : '0';
    var diff = Number($plus.replace(',', '.')) - Number($minus.replace(',', '.'));
    ECARTsumm += diff;
    $('#totals_input_v2').html(
        (Math.round((diff) * 100) / 100).toFixed(2).toString().replace('.', ',')
    );

    var $plus = $('.rapprochement_content_no_deb .rapprochement_content_output table.table tr.totals_row div b :first');
    $plus = $plus.length ? $plus.html() : '0';
    var $minus = $('.rapprochement_content_deb .rapprochement_content_output table.table tr.totals_row div b :first');
    $minus = $minus.length ? $minus.html() : '0';
    var diff = Number($plus.replace(',', '.')) - Number($minus.replace(',', '.'));
    ECARTsumm += diff;
    $('#totals_output_v1').html(
        (Math.round((diff) * 100) / 100).toFixed(2).toString().replace('.', ',')
    );

    var $plus = $('.rapprochement_content_no_deb .rapprochement_content_output table.table tr.totals_row div b :last');
    $plus = $plus.length ? $plus.html() : '0';
    var $minus = $('.rapprochement_content_deb .rapprochement_content_output table.table tr.totals_row div b :last');
    $minus = $minus.length ? $minus.html() : '0';
    var diff = Number($plus.replace(',', '.')) - Number($minus.replace(',', '.'));
    ECARTsumm += diff;
    $('#totals_output_v2').html(
        (Math.round((diff) * 100) / 100).toFixed(2).toString().replace('.', ',')
    );

    if (ECARTsumm == 0) {
        $("#rapprochement_validation").show();
    }
}

function init_tabs_filters_sticky_header() {
    var $thead = $('.sonata-ba-list .table thead:first');
    if ($thead.length == 0) {
        var $table = $('
').prependTo('.sonata-ba-list:first');
        $thead = $('
').appendTo($table);
    }

    var $tr = $('
').prependTo($thead);
    var $th = $('')
        .attr('colspan', $thead.children(':last').children().length)
        .append($('.clientoperations_tabs_types_block'))
        .appendTo($tr);

    $('.clientoperations_tabs_types_block #client-topinfo').after($('#block_actions'));

    var depth = 0;
    $thead.children().addClass('sticky_header').each(function () {
        $(this).attr('depth', depth++);
    });
    $('.sonata-ba-list .table').stickyHeader({
        'headerClassName':'sticky_header',
        'depth':[1, 1, 1]
    });
    $('.sticky_header_clone ._filterText').keyup(function () {
        var id = $(this).attr('id').replace("clone_", "_");
        $('#' + id).val($(this).val()).keyup();
    }).each(function () {
            $(this).attr('id', 'clone' + $(this).attr('id'));
        });
    $('.sticky_header_orig ._filterText').keyup(function () {
        $('#clone' + $(this).attr('id')).val($(this).val());
    });
    $('.sticky_header_clone a').click(function () {
        var href = $(this).attr('href');
        $('.sticky_header_orig a[href="' + href + '"]').click();

        return false;
    });

    $('.emptyColumnFilters').tooltip();
    $(".emptyColumnFilters").click(function () {
        $(this).parent().parent().find("._filterText").val("").keyup();

        return false;
    });
}<commit_msg>Bug #1420 :: Client Operations - Operations not opening<commit_after>jQuery(document).ready(function ($) {
    $('#error_repost_show').die().live('click', function () {
        $('#importReportModal').modal('toggle');

        return false;
    });

    //--
    //In the form when Paiement Date changes and Mois de TVA not set, the field Mois de TVA should take the corresponding YearMonth of Paiement Date
    //http://redmine.testenm.com/issues/1376
    symfony_ajax.behaviors.PaiementDateCloneMoisdeTVA = {
        attach:function (context) {
            var _uniqid = symfony_ajax.get_uniqid();

            //-- V01-TVA || A02-TVA
            if ($('#' + _uniqid + '_paiement_date', context).size() && $('#' + _uniqid + '_mois_mois', context).size()) {
                $('#' + _uniqid + '_paiement_date', context).change(function () {

                    if ($(this).val() && !$('#' + _uniqid + '_mois_mois :selected', context).val()) {
                        var date_arr = $(this).val().split('/');
                        var year_month = date_arr[2] + '-' + Number(date_arr[1]);

                        $('#' + _uniqid + '_mois_mois option', context).each(function () {
                            $(this).removeAttr('selected');
                        });

                        $('#' + _uniqid + '_mois_mois option', context).each(function () {
                            if ($(this).val() == year_month) {
                                $(this).attr('selected', 'selected').trigger('change');
                            }
                        })
                    }
                });
            }
        }
    };

    //-- get Devises money value
    //http://redmine.testenm.com/issues/1364#note-9
    symfony_ajax.behaviors.rDevises = {
        attach:function (context) {
            var _uniqid = symfony_ajax.get_uniqid();
            if (_uniqid) {
                $('#' + _uniqid + '_paiement_devise, #' + _uniqid + '_paiement_date', context).change(function () {
                    var _uniqid = symfony_ajax.get_uniqid();

                    var devise = $('#' + _uniqid + '_paiement_devise :selected').val();
                    var paiement_date = $('#' + _uniqid + '_paiement_date').val();
                    var paiement_montant = $('#' + _uniqid + '_paiement_montant').val();
                    var $taux_de_change = $('#' + _uniqid + '_taux_de_change');

                    if (devise && paiement_date && paiement_montant && !$taux_de_change.val()) {
                        $.ajax({
                            url:Sonata.url.rdevises,
                            type:'POST',
                            data:{
                                devise:devise,
                                date:paiement_date
                            },
                            dataType:'json',
                            async:false,
                            success:function (i) {
                                $taux_de_change.val(i.value ? i.value : '');
                            }
                        })
                    }
                });
            }
        }
    };

    //-- Calc MontantTVAfrancaiseAndMontantTTC
    symfony_ajax.behaviors.calcMontantTVAfrancaiseAndMontantTTC = {
        attach:function (context) {
            var _uniqid = symfony_ajax.get_uniqid();
            if (_uniqid) {
                var $montant_HT_en_devise = $('#' + _uniqid + '_montant_HT_en_devise', context);
                var $taux_de_TVA = $('#' + _uniqid + '_taux_de_TVA', context);
                if ($montant_HT_en_devise.length && $taux_de_TVA.length){
                    $montant_HT_en_devise.change(this.calc).keyup(this.calc);
                    $taux_de_TVA.change(this.calc).trigger('change');
                }
            }
        },
        number_limit:function (e) {
            var chr = String.fromCharCode(e.charCode == undefined ? e.keyCode : e.charCode);
            return (chr < ' ' || (chr >= '0' && chr <= '9') || chr == ',' || chr == '.');
        },
        calc:function (e) {
            var _uniqid = symfony_ajax.get_uniqid();

            var $montant_HT_en_devise = $('#' + _uniqid + '_montant_HT_en_devise');
            var $taux_de_TVA = $('#' + _uniqid + '_taux_de_TVA');

            substr_replace($montant_HT_en_devise, 2);
            substr_replace($taux_de_TVA, 3);

            var montant_HT_en_devise = $montant_HT_en_devise.val().replace(',', '.').replace(/\s+/, '');
            var taux_de_TVA = $taux_de_TVA.val().replace(',', '.').replace(/\s+/, '');

            var montant_TVA_francaise = parseFloat(parseFloat(montant_HT_en_devise) * parseFloat(taux_de_TVA));

            //If method validate from file Validate/ErrorElements.php function round $precision = 2, $mode = PHP_ROUND_HALF_DOWN
            montant_TVA_francaise = montant_TVA_francaise ? montant_TVA_francaise.toFixed(2) : '';

            var montant_TTC = parseFloat(parseFloat(montant_HT_en_devise) + parseFloat(montant_TVA_francaise));

            montant_TVA_francaise = montant_TVA_francaise ? montant_TVA_francaise.replace('.', ',') : '';
            montant_TTC = montant_TTC ? montant_TTC.toFixed(2).replace('.', ',') : '';

            $('#' + _uniqid + '_montant_TVA_francaise').val(montant_TVA_francaise);
            $('#' + _uniqid + '_montant_TTC').val(montant_TTC);
        }
    };

});

function substr_replace($object, limit) {
    if ($object && $object.length){
        var result = $object.val().split(',');
        var result2 = $object.val().split('.');
        if ((result[1] && result[1].length > limit) || result2[1] && result2[1].length > limit) {
            $object.val($object.val().substr(0, $object.val().length - 1));
        }
    }
}

function init_clientoperations_buttons(o) {

    var btn_client_alert_click = false;
    $('#btn_client_alert').live('click', function (event) {

        symfony_ajax.behaviors.alert_popo = {
            attach:function (context) {
                $('.modal-body .table td').removeAttr('objectid');
            }
        }

        field_dialog_form_add__id(event, o.alert.link, {title:o.alert.title });
        return false;
    });

    if (o.blocking.permit) {
        $("#btn_locking").click(function () {
            if (o.blocking.isBlocked && o.blocking.hasBlocking) {
                $('#btn_client_alert').click();
            }
            else {
                if (confirm(o.blocking.text)) {
                    location.href = o.blocking.link;
                }
            }
        });
    }

    $('input[id=inputFile]').change(function () {
        $('#inputFileCover').val($(this).val());
    });

    $('#deleteImport').click(function () {
        $.ajax({
            url:o.import.link,
            dataType:'json',
            success:function (json) {
                var $table = $('

');
                $('
')
                    .append('N°	')
                    .append('Date	')
                    .append('Utilisateur	')
                    .append('Action	')
                    .appendTo($table.children('thead'));

                var $tbody = $('
');
                for (i in json.imports) {
                    var import_id = json.imports[i].id;
                    var deleteUrl = o.import.delete.replace("__id__", import_id);
                    $('
')
                        .append('' + import_id + '	')
                        .append('' + json.imports[i].date.date + '	')
                        .append('' + json.imports[i].username + '	')
                        .append('Supprimer	')
                        .appendTo($tbody);
                }
                $table.append($tbody);

                // populate the popup container
                field_dialog__id.find('.popup-body').html('').append($table);
                field_dialog__id.find('.title').html(json.title);
                field_dialog__id.modal('toggle');

                $table.find('a.import_del').click(function () {
                    return confirm(o.import.confirm);
                });
            }
        });
    });
}

function init_rapprochement_sums() {
    var ECARTsumm = 0;

    var $plus = $('.rapprochement_content_no_deb .rapprochement_content_input table.table tr.totals_row div b :first');
    $plus = $plus.length ? $plus.html() : '0';
    var $minus = $('.rapprochement_content_deb .rapprochement_content_input table.table tr.totals_row div b :first');
    $minus = $minus.length ? $minus.html() : '0';
    var diff = Number($plus.replace(',', '.')) - Number($minus.replace(',', '.'));
    ECARTsumm += diff;
    $('#totals_input_v1').html(
        (Math.round((diff) * 100) / 100).toFixed(2).toString().replace('.', ',')
    );

    var $plus = $('.rapprochement_content_no_deb .rapprochement_content_input table.table tr.totals_row div b :last');
    $plus = $plus.length ? $plus.html() : '0';
    var $minus = $('.rapprochement_content_deb .rapprochement_content_input table.table tr.totals_row div b :last');
    $minus = $minus.length ? $minus.html() : '0';
    var diff = Number($plus.replace(',', '.')) - Number($minus.replace(',', '.'));
    ECARTsumm += diff;
    $('#totals_input_v2').html(
        (Math.round((diff) * 100) / 100).toFixed(2).toString().replace('.', ',')
    );

    var $plus = $('.rapprochement_content_no_deb .rapprochement_content_output table.table tr.totals_row div b :first');
    $plus = $plus.length ? $plus.html() : '0';
    var $minus = $('.rapprochement_content_deb .rapprochement_content_output table.table tr.totals_row div b :first');
    $minus = $minus.length ? $minus.html() : '0';
    var diff = Number($plus.replace(',', '.')) - Number($minus.replace(',', '.'));
    ECARTsumm += diff;
    $('#totals_output_v1').html(
        (Math.round((diff) * 100) / 100).toFixed(2).toString().replace('.', ',')
    );

    var $plus = $('.rapprochement_content_no_deb .rapprochement_content_output table.table tr.totals_row div b :last');
    $plus = $plus.length ? $plus.html() : '0';
    var $minus = $('.rapprochement_content_deb .rapprochement_content_output table.table tr.totals_row div b :last');
    $minus = $minus.length ? $minus.html() : '0';
    var diff = Number($plus.replace(',', '.')) - Number($minus.replace(',', '.'));
    ECARTsumm += diff;
    $('#totals_output_v2').html(
        (Math.round((diff) * 100) / 100).toFixed(2).toString().replace('.', ',')
    );

    if (ECARTsumm == 0) {
        $("#rapprochement_validation").show();
    }
}

function init_tabs_filters_sticky_header() {
    var $thead = $('.sonata-ba-list .table thead:first');
    if ($thead.length == 0) {
        var $table = $('
').prependTo('.sonata-ba-list:first');
        $thead = $('
').appendTo($table);
    }

    var $tr = $('
').prependTo($thead);
    var $th = $('')
        .attr('colspan', $thead.children(':last').children().length)
        .append($('.clientoperations_tabs_types_block'))
        .appendTo($tr);

    $('.clientoperations_tabs_types_block #client-topinfo').after($('#block_actions'));

    var depth = 0;
    $thead.children().addClass('sticky_header').each(function () {
        $(this).attr('depth', depth++);
    });
    $('.sonata-ba-list .table').stickyHeader({
        'headerClassName':'sticky_header',
        'depth':[1, 1, 1]
    });
    $('.sticky_header_clone ._filterText').keyup(function () {
        var id = $(this).attr('id').replace("clone_", "_");
        $('#' + id).val($(this).val()).keyup();
    }).each(function () {
            $(this).attr('id', 'clone' + $(this).attr('id'));
        });
    $('.sticky_header_orig ._filterText').keyup(function () {
        $('#clone' + $(this).attr('id')).val($(this).val());
    });
    $('.sticky_header_clone a').click(function () {
        var href = $(this).attr('href');
        $('.sticky_header_orig a[href="' + href + '"]').click();

        return false;
    });

    $('.emptyColumnFilters').tooltip();
    $(".emptyColumnFilters").click(function () {
        $(this).parent().parent().find("._filterText").val("").keyup();

        return false;
    });
}<|endoftext|>