<commit_before>// This [jQuery](http://jquery.com/) plugin implements an `<iframe>`
// [transport](http://api.jquery.com/extending-ajax/#Transports) so that
// `$.ajax()` calls support the uploading of files using standard HTML file
// input fields. This is done by switching the exchange from `XMLHttpRequest`
// to a hidden `iframe` element containing a form that is submitted.

// The [source for the plugin](http://github.com/cmlenz/jquery-iframe-transport)
// is available on [Github](http://github.com/) and dual licensed under the MIT
// or GPL Version 2 licenses.

// ## Usage

// To use this plugin, you simply add an `iframe` option with the value `true`
// to the Ajax settings an `$.ajax()` call, and specify the file fields to
// include in the submssion using the `files` option, which can be a selector,
// jQuery object, or a list of DOM elements containing one or more
// `<input type="file">` elements:

//     $("#myform").submit(function() {
//         $.ajax(this.action, {
//             files: $(":file", this),
//             iframe: true
//         }).complete(function(data) {
//             console.log(data);
//         });
//     });

// The plugin will construct hidden `<iframe>` and `<form>` elements, add the
// file field(s) to that form, submit the form, and process the response.

// If you want to include other form fields in the form submission, include
// them in the `data` option, and set the `processData` option to `false`:

//     $("#myform").submit(function() {
//         $.ajax(this.action, {
//             data: $(":text", this).serializeArray(),
//             files: $(":file", this),
//             iframe: true,
//             processData: false
//         }).complete(function(data) {
//             console.log(data);
//         });
//     });

// ### Response Data Types

// As the transport does not have access to the HTTP headers of the server
// response, it is not as simple to make use of the automatic content type
// detection provided by jQuery as with regular XHR. If you can't set the
// expected response data type (for example because it may vary depending on
// the outcome of processing by the server), you will need to employ a
// workaround on the server side: Send back an HTML document containing just a
// `<textarea>` element with a `data-type` attribute that specifies the MIME
// type, and put the actual payload in the textarea:

//     <textarea data-type="application/json">
//       {"ok": true, "message": "Thanks so much"}
//     </textarea>

// The iframe transport plugin will detect this and pass the value of the
// `data-type` attribute on to jQuery as if it was the "Content-Type" response
// header, thereby enabling the same kind of conversions that jQuery applies
// to regular responses. For the example above you should get a Javascript
// object as the `data` parameter of the `complete` callback, with the
// properties `ok: true` and `message: "Thanks so much"`.

// ### Handling Server Errors

// Another problem with using an `iframe` for file uploads is that it is
// impossible for the javascript code to determine the HTTP status code of the
// servers response. Effectively, all of the calls you make will look like they
// are getting successful responses, and thus invoke the `done()` or
// `complete()` callbacks. You can only determine communicate problems using
// the content of the response payload. For example, consider using a JSON
// response such as the following to indicate a problem with an uploaded file:

//     <textarea data-type="application/json">
//       {"ok": false, "message": "Please only upload reasonably sized files."}
//     </textarea>

// ### Compatibility

// This plugin has primarily been tested on Safari 5 (or later), Firefox 4 (or
// later), and Internet Explorer (all the way back to version 6). While I
// haven't found any issues with it so far, I'm fairly sure it still doesn't
// work around all the quirks in all different browsers. But the code is still
// pretty simple overall, so you should be able to fix it and contribute a
// patch :)

// ## Annotated Source

(function($, undefined) {
  "use strict";

  // Register a prefilter that checks whether the `iframe` option is set, and
  // switches to the "iframe" data type if it is `true`.
  $.ajaxPrefilter(function(options, origOptions, jqXHR) {
    if (options.iframe) {
      return "iframe";
    }
  });

  // Register a transport for the "iframe" data type. It will only activate
  // when the "files" option has been set to a non-empty list of enabled file
  // inputs.
  $.ajaxTransport("iframe", function(options, origOptions, jqXHR) {
    var form = null,
        iframe = null,
        name = "iframe-" + $.now(),
        files = $(options.files).filter(":file:enabled"),
        markers = null,
        accepts;

    // This function gets called after a successful submission or an abortion
    // and should revert all changes made to the page to enable the
    // submission via this transport.
    function cleanUp() {
      markers.prop('disabled', false);
      form.remove();
      iframe.one("load", function() { iframe.remove(); });
      iframe.attr("src", "javascript:false;");
    }

    // Remove "iframe" from the data types list so that further processing is
    // based on the content type returned by the server, without attempting an
    // (unsupported) conversion from "iframe" to the actual type.
    options.dataTypes.shift();

    if (files.length) {
      form = $("<form enctype='multipart/form-data' method='post'></form>").
        hide().attr({action: options.url, target: name});

      // If there is any additional data specified via the `data` option,
      // we add it as hidden fields to the form. This (currently) requires
      // the `processData` option to be set to false so that the data doesn't
      // get serialized to a string.
      if (typeof(options.data) === "string" && options.data.length > 0) {
        $.error("data must not be serialized");
      }
      $.each(options.data || {}, function(name, value) {
        if ($.isPlainObject(value)) {
          name = value.name;
          value = value.value;
        }
        $("<input type='hidden' />").attr({name:  name, value: value}).
          appendTo(form);
      });

      // Add a hidden `X-Requested-With` field with the value `IFrame` to the
      // field, to help server-side code to determine that the upload happened
      // through this transport.
      $("<input type='hidden' value='IFrame' name='X-Requested-With' />").
        appendTo(form);

      // Borrowed straight from the JQuery source
      // Provides a way of specifying the accepted data type similar to HTTP_ACCEPTS
      accepts = options.dataTypes[ 0 ] && options.accepts[ options.dataTypes[0] ] ?
        options.accepts[ options.dataTypes[0] ] + ( options.dataTypes[ 0 ] !== "*" ? ", */*; q=0.01" : "" ) :
        options.accepts[ "*" ]

      $("<input type='hidden' name='X-Http-Accept'>")
        .attr("value", accepts).appendTo(form);

      // Move the file fields into the hidden form, but first remember their
      // original locations in the document by replacing them with disabled
      // clones. This should also avoid introducing unwanted changes to the
      // page layout during submission.
      markers = files.after(function(idx) {
        return $(this).clone().prop("disabled", true);
      }).next();
      files.appendTo(form);

      return {

        // The `send` function is called by jQuery when the request should be
        // sent.
        send: function(headers, completeCallback) {
          iframe = $("");

          // The first load event gets fired after the iframe has been injected
          // into the DOM, and is used to prepare the actual submission.
          iframe.one("load", function() {

            // The second load event gets fired when the response to the form
            // submission is received. The implementation detects whether the
            // actual payload is embedded in a `<textarea>` element, and
            // prepares the required conversions to be made in that case.
            iframe.one("load", function() {
              var doc = this.contentWindow ? this.contentWindow.document :
                (this.contentDocument ? this.contentDocument : this.document),
                root = doc.documentElement ? doc.documentElement : doc.body,
                textarea = root.getElementsByTagName("textarea")[0],
                type = textarea && textarea.getAttribute("data-type") || null,
                status = textarea && textarea.getAttribute("data-status") || 200,
                statusText = textarea && textarea.getAttribute("data-statusText") || "OK",
                content = {
                  html: root.innerHTML,
                  text: type ?
                    textarea.value :
                    root ? (root.textContent || root.innerText) : null
                };
              cleanUp();
              completeCallback(status, statusText, content, type ?
                ("Content-Type: " + type) :
                null);
            });

            // Now that the load handler has been set up, submit the form.
            form[0].submit();
          });

          // After everything has been set up correctly, the form and iframe
          // get injected into the DOM so that the submission can be
          // initiated.
          $("body").append(form, iframe);
        },

        // The `abort` function is called by jQuery when the request should be
        // aborted.
        abort: function() {
          if (iframe !== null) {
            iframe.unbind("load").attr("src", "javascript:false;");
            cleanUp();
          }
        }

      };
    }
  });

})(jQuery);
<commit_msg>Some formatting changes for a more consistent style.<commit_after>// This [jQuery](http://jquery.com/) plugin implements an `<iframe>`
// [transport](http://api.jquery.com/extending-ajax/#Transports) so that
// `$.ajax()` calls support the uploading of files using standard HTML file
// input fields. This is done by switching the exchange from `XMLHttpRequest`
// to a hidden `iframe` element containing a form that is submitted.

// The [source for the plugin](http://github.com/cmlenz/jquery-iframe-transport)
// is available on [Github](http://github.com/) and dual licensed under the MIT
// or GPL Version 2 licenses.

// ## Usage

// To use this plugin, you simply add an `iframe` option with the value `true`
// to the Ajax settings an `$.ajax()` call, and specify the file fields to
// include in the submssion using the `files` option, which can be a selector,
// jQuery object, or a list of DOM elements containing one or more
// `<input type="file">` elements:

//     $("#myform").submit(function() {
//         $.ajax(this.action, {
//             files: $(":file", this),
//             iframe: true
//         }).complete(function(data) {
//             console.log(data);
//         });
//     });

// The plugin will construct hidden `<iframe>` and `<form>` elements, add the
// file field(s) to that form, submit the form, and process the response.

// If you want to include other form fields in the form submission, include
// them in the `data` option, and set the `processData` option to `false`:

//     $("#myform").submit(function() {
//         $.ajax(this.action, {
//             data: $(":text", this).serializeArray(),
//             files: $(":file", this),
//             iframe: true,
//             processData: false
//         }).complete(function(data) {
//             console.log(data);
//         });
//     });

// ### Response Data Types

// As the transport does not have access to the HTTP headers of the server
// response, it is not as simple to make use of the automatic content type
// detection provided by jQuery as with regular XHR. If you can't set the
// expected response data type (for example because it may vary depending on
// the outcome of processing by the server), you will need to employ a
// workaround on the server side: Send back an HTML document containing just a
// `<textarea>` element with a `data-type` attribute that specifies the MIME
// type, and put the actual payload in the textarea:

//     <textarea data-type="application/json">
//       {"ok": true, "message": "Thanks so much"}
//     </textarea>

// The iframe transport plugin will detect this and pass the value of the
// `data-type` attribute on to jQuery as if it was the "Content-Type" response
// header, thereby enabling the same kind of conversions that jQuery applies
// to regular responses. For the example above you should get a Javascript
// object as the `data` parameter of the `complete` callback, with the
// properties `ok: true` and `message: "Thanks so much"`.

// ### Handling Server Errors

// Another problem with using an `iframe` for file uploads is that it is
// impossible for the javascript code to determine the HTTP status code of the
// servers response. Effectively, all of the calls you make will look like they
// are getting successful responses, and thus invoke the `done()` or
// `complete()` callbacks. You can only determine communicate problems using
// the content of the response payload. For example, consider using a JSON
// response such as the following to indicate a problem with an uploaded file:

//     <textarea data-type="application/json">
//       {"ok": false, "message": "Please only upload reasonably sized files."}
//     </textarea>

// ### Compatibility

// This plugin has primarily been tested on Safari 5 (or later), Firefox 4 (or
// later), and Internet Explorer (all the way back to version 6). While I
// haven't found any issues with it so far, I'm fairly sure it still doesn't
// work around all the quirks in all different browsers. But the code is still
// pretty simple overall, so you should be able to fix it and contribute a
// patch :)

// ## Annotated Source

(function($, undefined) {
  "use strict";

  // Register a prefilter that checks whether the `iframe` option is set, and
  // switches to the "iframe" data type if it is `true`.
  $.ajaxPrefilter(function(options, origOptions, jqXHR) {
    if (options.iframe) {
      return "iframe";
    }
  });

  // Register a transport for the "iframe" data type. It will only activate
  // when the "files" option has been set to a non-empty list of enabled file
  // inputs.
  $.ajaxTransport("iframe", function(options, origOptions, jqXHR) {
    var form = null,
        iframe = null,
        name = "iframe-" + $.now(),
        files = $(options.files).filter(":file:enabled"),
        markers = null,
        accepts = null;

    // This function gets called after a successful submission or an abortion
    // and should revert all changes made to the page to enable the
    // submission via this transport.
    function cleanUp() {
      markers.prop("disabled", false);
      form.remove();
      iframe.one("load", function() { iframe.remove(); });
      iframe.attr("src", "javascript:false;");
    }

    // Remove "iframe" from the data types list so that further processing is
    // based on the content type returned by the server, without attempting an
    // (unsupported) conversion from "iframe" to the actual type.
    options.dataTypes.shift();

    if (files.length) {
      form = $("<form enctype='multipart/form-data' method='post'></form>").
        hide().attr({action: options.url, target: name});

      // If there is any additional data specified via the `data` option,
      // we add it as hidden fields to the form. This (currently) requires
      // the `processData` option to be set to false so that the data doesn't
      // get serialized to a string.
      if (typeof(options.data) === "string" && options.data.length > 0) {
        $.error("data must not be serialized");
      }
      $.each(options.data || {}, function(name, value) {
        if ($.isPlainObject(value)) {
          name = value.name;
          value = value.value;
        }
        $("<input type='hidden' />").attr({name:  name, value: value}).
          appendTo(form);
      });

      // Add a hidden `X-Requested-With` field with the value `IFrame` to the
      // field, to help server-side code to determine that the upload happened
      // through this transport.
      $("<input type='hidden' value='IFrame' name='X-Requested-With' />").
        appendTo(form);

      // Borrowed straight from the JQuery source.
      // Provides a way of specifying the accepted data type similar to the
      // HTTP "Accept" header
      if (options.dataTypes[0] && options.accepts[options.dataTypes[0]]) {
        accepts = options.accepts[options.dataTypes[0]] +
                  (options.dataTypes[0] !== "*" ? ", */*; q=0.01" : "");
      } else {
        accepts = options.accepts["*"];
      }
      $("<input type='hidden' name='X-HTTP-Accept'>").
        attr("value", accepts).appendTo(form);

      // Move the file fields into the hidden form, but first remember their
      // original locations in the document by replacing them with disabled
      // clones. This should also avoid introducing unwanted changes to the
      // page layout during submission.
      markers = files.after(function(idx) {
        return $(this).clone().prop("disabled", true);
      }).next();
      files.appendTo(form);

      return {

        // The `send` function is called by jQuery when the request should be
        // sent.
        send: function(headers, completeCallback) {
          iframe = $("");

          // The first load event gets fired after the iframe has been injected
          // into the DOM, and is used to prepare the actual submission.
          iframe.one("load", function() {

            // The second load event gets fired when the response to the form
            // submission is received. The implementation detects whether the
            // actual payload is embedded in a `<textarea>` element, and
            // prepares the required conversions to be made in that case.
            iframe.one("load", function() {
              var doc = this.contentWindow ? this.contentWindow.document :
                (this.contentDocument ? this.contentDocument : this.document),
                root = doc.documentElement ? doc.documentElement : doc.body,
                textarea = root.getElementsByTagName("textarea")[0],
                type = textarea && textarea.getAttribute("data-type") || null,
                status = textarea && textarea.getAttribute("data-status") || 200,
                statusText = textarea && textarea.getAttribute("data-statusText") || "OK",
                content = {
                  html: root.innerHTML,
                  text: type ?
                    textarea.value :
                    root ? (root.textContent || root.innerText) : null
                };
              cleanUp();
              completeCallback(status, statusText, content, type ?
                ("Content-Type: " + type) :
                null);
            });

            // Now that the load handler has been set up, submit the form.
            form[0].submit();
          });

          // After everything has been set up correctly, the form and iframe
          // get injected into the DOM so that the submission can be
          // initiated.
          $("body").append(form, iframe);
        },

        // The `abort` function is called by jQuery when the request should be
        // aborted.
        abort: function() {
          if (iframe !== null) {
            iframe.unbind("load").attr("src", "javascript:false;");
            cleanUp();
          }
        }

      };
    }
  });

})(jQuery);
<|endoftext|>


<commit_before><commit_msg>Add minimified plugin file<commit_after><|endoftext|>


<commit_before>// Copyright 2002-2013, University of Colorado Boulder

//TODO reimplement as a RectangleButton subtype
//TODO add button color change for 'over' and 'down'
//TODO add enabled/disabled, probably via options.enabledProperty
/**
 * Button for expanding/collapsing something.
 *
 * @author Chris Malley (PixelZoom, Inc.)
 */
define( function( require ) {
  'use strict';

  // imports
  var ButtonListener = require( 'SCENERY/input/ButtonListener' );
  var inherit = require( 'PHET_CORE/inherit' );
  var Node = require( 'SCENERY/nodes/Node' );
  var Path = require( 'SCENERY/nodes/Path' );
  var Shape = require( 'KITE/Shape' );

  /**
   * @param {Number} sideLength length of one side of the square button
   * @param {Property<Boolean>} expandedProperty
   * @param {*} options
   * @constructor
   */
  function ExpandCollapseButton( sideLength, expandedProperty, options ) {

    options = _.extend( {}, options );

    var thisButton = this;
    Node.call( thisButton );

    // configure the button shape
    var cornerRadius = 0.1 * sideLength;
    var buttonShape = Shape.roundRectangle( 0, 0, sideLength, sideLength, cornerRadius, cornerRadius );

    // configure the +/- symbol on the button
    var symbolLength = 0.6 * sideLength;
    var symbolLineWidth = 0.15 * sideLength;
    var symbolOptions = {
      lineWidth: symbolLineWidth,
      stroke: 'white',
      centerX: sideLength / 2,
      centerY: sideLength / 2
    };

    // Expand '+' button
    var expandButton = new Path( buttonShape, { fill: 'rgb(0, 179, 0 )', stroke: 'black', lineWidth: 0.5 } );
    var plusSymbolShape = new Shape()
      .moveTo( symbolLength / 2, 0 )
      .lineTo( symbolLength / 2, symbolLength )
      .moveTo( 0, symbolLength / 2 )
      .lineTo( symbolLength, symbolLength / 2 );
    expandButton.addChild( new Path( plusSymbolShape, symbolOptions ) );

    // Collapse '-' button
    var collapseButton = new Path( buttonShape, { fill: 'rgb( 255, 85, 0 )', stroke: 'black', lineWidth: 0.5 } );
    var minusSymbolShape = new Shape()
      .moveTo( -symbolLength / 2, 0 )
      .lineTo( symbolLength / 2, 0 );
    collapseButton.addChild( new Path( minusSymbolShape, symbolOptions ) );

    // rendering order
    thisButton.addChild( expandButton );
    thisButton.addChild( collapseButton );

    // click to toggle
    thisButton.cursor = 'pointer';
    thisButton.addInputListener( new ButtonListener( {
      fire: function() {
        expandedProperty.set( !expandedProperty.get() );
      }
    } ) );

    // sync with property
    expandedProperty.link( function( expanded ) {
      expandButton.visible = !expanded;
      collapseButton.visible = expanded;
    } );

    thisButton.mutate( options );
  }

  return inherit( Node, ExpandCollapseButton );
} );
<commit_msg> #94 note that ExpandCollapseButton needs to be reimplemented using RectangularPushButton<commit_after>// Copyright 2002-2013, University of Colorado Boulder

//TODO reimplement as a subtype of sun.buttons.RectangularPushButton
/**
 * Button for expanding/collapsing something.
 *
 * @author Chris Malley (PixelZoom, Inc.)
 */
define( function( require ) {
  'use strict';

  // imports
  var ButtonListener = require( 'SCENERY/input/ButtonListener' );
  var inherit = require( 'PHET_CORE/inherit' );
  var Node = require( 'SCENERY/nodes/Node' );
  var Path = require( 'SCENERY/nodes/Path' );
  var Shape = require( 'KITE/Shape' );

  /**
   * @param {Number} sideLength length of one side of the square button
   * @param {Property<Boolean>} expandedProperty
   * @param {*} options
   * @constructor
   */
  function ExpandCollapseButton( sideLength, expandedProperty, options ) {

    options = _.extend( {}, options );

    var thisButton = this;
    Node.call( thisButton );

    // configure the button shape
    var cornerRadius = 0.1 * sideLength;
    var buttonShape = Shape.roundRectangle( 0, 0, sideLength, sideLength, cornerRadius, cornerRadius );

    // configure the +/- symbol on the button
    var symbolLength = 0.6 * sideLength;
    var symbolLineWidth = 0.15 * sideLength;
    var symbolOptions = {
      lineWidth: symbolLineWidth,
      stroke: 'white',
      centerX: sideLength / 2,
      centerY: sideLength / 2
    };

    // Expand '+' button
    var expandButton = new Path( buttonShape, { fill: 'rgb(0, 179, 0 )', stroke: 'black', lineWidth: 0.5 } );
    var plusSymbolShape = new Shape()
      .moveTo( symbolLength / 2, 0 )
      .lineTo( symbolLength / 2, symbolLength )
      .moveTo( 0, symbolLength / 2 )
      .lineTo( symbolLength, symbolLength / 2 );
    expandButton.addChild( new Path( plusSymbolShape, symbolOptions ) );

    // Collapse '-' button
    var collapseButton = new Path( buttonShape, { fill: 'rgb( 255, 85, 0 )', stroke: 'black', lineWidth: 0.5 } );
    var minusSymbolShape = new Shape()
      .moveTo( -symbolLength / 2, 0 )
      .lineTo( symbolLength / 2, 0 );
    collapseButton.addChild( new Path( minusSymbolShape, symbolOptions ) );

    // rendering order
    thisButton.addChild( expandButton );
    thisButton.addChild( collapseButton );

    // click to toggle
    thisButton.cursor = 'pointer';
    thisButton.addInputListener( new ButtonListener( {
      fire: function() {
        expandedProperty.set( !expandedProperty.get() );
      }
    } ) );

    // sync with property
    expandedProperty.link( function( expanded ) {
      expandButton.visible = !expanded;
      collapseButton.visible = expanded;
    } );

    thisButton.mutate( options );
  }

  return inherit( Node, ExpandCollapseButton );
} );
<|endoftext|>


<commit_before>//removes the player and resets him if he dies
//adds gold
//manages creeps
game.GameTimerManager = Object.extend({
	init: function(x, y, settings){
		this.now = new Date().getTime();
		this.lastCreep = new Date().getTime();
		//creepe cannot pause at all
		this.paused = false;
		this.alwaysUpdate = true;
	},

	update: function(){
		this.now = new Date().getTime();
		this.goldTimerCheck();
		this.creepTimerCheck();

		return true;
	},
	//organizes code above
	goldTimerCheck: function(){
		//controls when the creep spons
		if(Math.round(this.now/1000)%20 ===0 && (this.now - this.lastCreep >= 1000)){
			game.data.gold += (game.data.exp1+1);
			console.log("Current gold: " + game.data.gold);

		}
	},
	creepTimerCheck: function(){
		//controls when the creep spons
		if(Math.round(this.now/1000)%10 ===0 && (this.now - this.lastCreep >= 1000)){
			//controls when the creep spons
			this.lastCreep = this.now;
			//bulids a creep and puts it into the world
			var creepe = me.pool.pull("EnemyCreep", 1000, 0, {});
			me.game.world.addChild(creepe, 5);

			//var creepe1 = me.pool.pull("Player2", 1000, 0, {});
			//me.game.world.addChild(creepe, 5);

		}
	}
});

//manages the players death
//oragnizes the code
game.HeroDeathManager = Object.extend({
	init: function(x, y, settings){
		this.alwaysUpdate = true;

	},

	update: function(){
		//dead function in game manager
		if(game.data.player.dead){
			me.game.world.removeChild(game.data.player);
			me.state.current().resetPlayer(10, 0);
		}
		return true;
	}
});

//gains the player expeience if they win
game.ExperienceManager = Object.extend({
	init: function (x, y, settings) {
		this.alwaysUpdate = true;
		this.gameover = false;
	},

	update: function(){
		if(game.data.win === true && !this.gameover){
			//the game is over when the player dies
			this.gameOver(true);
		}else if(game.data.win === false && !this.gameover){
			this.gameOver(false);
			//this.gameOver = true;
			//saves current game variable
			//me.save.exp = game.data.exp;
		}
		console.log(game.data.exp);

		return true;
	},
	//organizes update function
	//game over function
	gameOver: function(win){
		if(win){
			game.data.exp += 10;
		}else{
			game.data.exp += 1;
		}
		    console.log(game.data.exp);
			this.gameover = true;
			//saves the 5 exp variables in game.js
			me.save.exp = game.data.exp;

	}
});

game.SpendGold = Object.extend({
	init: function (x, y, settings){
		this.now = new Date().getTime();
		this.lastBuy = new Date().getTime();
		//creepe cannot pause at all
		this.paused = false;
		this.alwaysUpdate = true;
		this.updateWhenPaused = true;
		this.buying = false;
	},

	update: function(){
		this.now = new Date().getTime();

		if(me.input.isKeyPressed("buy") && this.now-this.lastBuy >=1000){
			this.lastBuy = this.now;
			if(!this.buying){
				this.startBuying();
			}else{
				this.stopBuying();
			}
		}

		return true;

	},

//enables player to buy certain level ups by pussing f keys
	startBuying: function(){
		this.buying = true;
		me.state.pause(me.state.PLAY);
		game.data.pausePos = me.game.viewport.localToWorld(0, 0);
		game.data.buyscreen = new me.Sprite(game.data.pausePos.x, game.data.pausePos.y, me.loader.getImage('gold-screen'));
		game.data.buyscreen.updateWhenPaused = true;
		game.data.buyscreen.setOpacity(0.8);
		me.game.world.addChild(game.data.buyscreen, 34);
		game.data.player.body.setVelocity(0, 0);
		me.state.pause(me.state.PLAY);
		me.input.bindKey(me.input.KEY.F1, "F1", true);
		me.input.bindKey(me.input.KEY.F2, "F2", true);
		me.input.bindKey(me.input.KEY.F3, "F3", true);
		me.input.bindKey(me.input.KEY.F4, "F4", true);
		me.input.bindKey(me.input.KEY.F5, "F5", true);
		me.input.bindKey(me.input.KEY.F6, "F6", true);
		this.setBuyText();
	},

	setBuyText: function(){
		//adds the word awesomenauts to the game
		game.data.buytext = new (me.Renderable.extend({
			init: function(){
				this._super(me.Renderable, 'init', [game.data.pausePos.x, game.data.pausePos.y, 300, 50]);
				this.font = new me.Font("Arial", 26, "white");
				this.updateWhenPaused = true;
				this.alwaysUpdate = true;
				//me.input.registerPointerEvent('pointerdown', this, this.newGame.bind(this), true);
			},

			//function renderer tells the font size of the words in quotations
			draw: function(renderer){
				this.font.draw(renderer.getContext(), "PRESS F1-F6 TO BUY, B TO EXIT. Current Gold: " + game.data.gold, this.pos.x, this.pos.y);
				this.font.draw(renderer.getContext(), "Skill 1: Increase Damage. Current Level: " + game.data.skill1 + " Cost: " + ((game.data.exp1+1)*10);
				this.font.draw(renderer.getContext(), "Skill 2: Run Faster! Current Level: " + game.data.skill2 + " Cost: " + ((game.data.exp2+1)*10), this.pos.x, this.pos.y);
				this.font.draw(renderer.getContext(), "Skill 3: Increase Health. Current Level:  " + game.data.skill3 + " Cost: " + ((game.data.exp1+1)*10), this.pos.x, this.pos.y);
				this.font.draw(renderer.getContext(), "O Ability: Speed Burst. Current Level: " + game.data.ability1 + " Cost: " + ((game.data.ability4+1)*10), this.pos.y);
				this.font.draw(renderer.getContext(), "W Ability: Eat Your Creep for Health: " + game.data.ability2 + " Cost: " + ((game.data.ability5+1)*10), this.pos.y);
				this.font.draw(renderer.getContext(), "E Ability: Throw Your Spear: " + game.data.ability3 + " Cost: " + ((game.data.ability6+1)*10), this.pos.y);

			}

		})));
		me.game.world.addChild(game.data.buytext, 35);
	},

//reverse function. enables the player to not buy or undo the buy
	stopBuying: function(){
		this.buying = false;
		me.state.resume(me.state.PLAY);
		game.data.player.body.setVelocity(game.data.playerMoveSpeed, 20);
		me.game.world.removeChild(game.data.buyscreen);
		me.input.unbindKey(me.input.KEY.F1, "F1", true);
		me.input.unbindKey(me.input.KEY.F2, "F2", true);
		me.input.unbindKey(me.input.KEY.F3, "F3", true);
		me.input.unbindKey(me.input.KEY.F4, "F4", true);
		me.input.unbindKey(me.input.KEY.F5, "F5", true);
		me.input.unbindKey(me.input.KEY.F6, "F6", true);
		me.game.world.removeChild(game.data.buytext);
	}

});
// 6:06
<commit_msg>video 50 almost done<commit_after>//removes the player and resets him if he dies
//adds gold
//manages creeps
game.GameTimerManager = Object.extend({
	init: function(x, y, settings){
		this.now = new Date().getTime();
		this.lastCreep = new Date().getTime();
		//creepe cannot pause at all
		this.paused = false;
		this.alwaysUpdate = true;
	},

	update: function(){
		this.now = new Date().getTime();
		this.goldTimerCheck();
		this.creepTimerCheck();

		return true;
	},
	//organizes code above
	goldTimerCheck: function(){
		//controls when the creep spons
		if(Math.round(this.now/1000)%20 ===0 && (this.now - this.lastCreep >= 1000)){
			game.data.gold += (game.data.exp1+1);
			console.log("Current gold: " + game.data.gold);

		}
	},
	creepTimerCheck: function(){
		//controls when the creep spons
		if(Math.round(this.now/1000)%10 ===0 && (this.now - this.lastCreep >= 1000)){
			//controls when the creep spons
			this.lastCreep = this.now;
			//bulids a creep and puts it into the world
			var creepe = me.pool.pull("EnemyCreep", 1000, 0, {});
			me.game.world.addChild(creepe, 5);

			//var creepe1 = me.pool.pull("Player2", 1000, 0, {});
			//me.game.world.addChild(creepe, 5);

		}
	}
});

//manages the players death
//oragnizes the code
game.HeroDeathManager = Object.extend({
	init: function(x, y, settings){
		this.alwaysUpdate = true;

	},

	update: function(){
		//dead function in game manager
		if(game.data.player.dead){
			me.game.world.removeChild(game.data.player);
			me.state.current().resetPlayer(10, 0);
		}
		return true;
	}
});

//gains the player expeience if they win
game.ExperienceManager = Object.extend({
	init: function (x, y, settings) {
		this.alwaysUpdate = true;
		this.gameover = false;
	},

	update: function(){
		if(game.data.win === true && !this.gameover){
			//the game is over when the player dies
			this.gameOver(true);
		}else if(game.data.win === false && !this.gameover){
			this.gameOver(false);
			//this.gameOver = true;
			//saves current game variable
			//me.save.exp = game.data.exp;
		}
		console.log(game.data.exp);

		return true;
	},
	//organizes update function
	//game over function
	gameOver: function(win){
		if(win){
			game.data.exp += 10;
		}else{
			game.data.exp += 1;
		}
		    console.log(game.data.exp);
			this.gameover = true;
			//saves the 5 exp variables in game.js
			me.save.exp = game.data.exp;

	}
});

game.SpendGold = Object.extend({
	init: function (x, y, settings){
		this.now = new Date().getTime();
		this.lastBuy = new Date().getTime();
		//creepe cannot pause at all
		this.paused = false;
		this.alwaysUpdate = true;
		this.updateWhenPaused = true;
		this.buying = false;
	},

	update: function(){
		this.now = new Date().getTime();

		if(me.input.isKeyPressed("buy") && this.now-this.lastBuy >=1000){
			this.lastBuy = this.now;
			if(!this.buying){
				this.startBuying();
			}else{
				this.stopBuying();
			}
		}

		//checks the buy keys below
		this.checkBuyKeys();

		return true;

	},

//enables player to buy certain level ups by pussing f keys
	startBuying: function(){
		this.buying = true;
		me.state.pause(me.state.PLAY);
		game.data.pausePos = me.game.viewport.localToWorld(0, 0);
		game.data.buyscreen = new me.Sprite(game.data.pausePos.x, game.data.pausePos.y, me.loader.getImage('gold-screen'));
		game.data.buyscreen.updateWhenPaused = true;
		game.data.buyscreen.setOpacity(0.8);
		me.game.world.addChild(game.data.buyscreen, 34);
		game.data.player.body.setVelocity(0, 0);
		me.state.pause(me.state.PLAY);
		me.input.bindKey(me.input.KEY.F1, "F1", true);
		me.input.bindKey(me.input.KEY.F2, "F2", true);
		me.input.bindKey(me.input.KEY.F3, "F3", true);
		me.input.bindKey(me.input.KEY.F4, "F4", true);
		me.input.bindKey(me.input.KEY.F5, "F5", true);
		me.input.bindKey(me.input.KEY.F6, "F6", true);
		this.setBuyText();
	},

	setBuyText: function(){
		//adds the word awesomenauts to the game
		game.data.buytext = new (me.Renderable.extend({
			init: function(){
				this._super(me.Renderable, 'init', [game.data.pausePos.x, game.data.pausePos.y, 300, 50]);
				this.font = new me.Font("Arial", 26, "white");
				this.updateWhenPaused = true;
				this.alwaysUpdate = true;
				//me.input.registerPointerEvent('pointerdown', this, this.newGame.bind(this), true);
			},

			//function renderer tells the font size of the words in quotations
			draw: function(renderer){
				this.font.draw(renderer.getContext(), "PRESS F1-F6 TO BUY, B TO EXIT. Current Gold: " + game.data.gold, this.pos.x, this.pos.y);
				this.font.draw(renderer.getContext(), "Skill 1: Increase Damage. Current Level: " + game.data.skill1 + " Cost: " + ((game.data.exp1+1)*10);
				this.font.draw(renderer.getContext(), "Skill 2: Run Faster! Current Level: " + game.data.skill2 + " Cost: " + ((game.data.exp2+1)*10), this.pos.x, this.pos.y);
				this.font.draw(renderer.getContext(), "Skill 3: Increase Health. Current Level:  " + game.data.skill3 + " Cost: " + ((game.data.exp1+1)*10), this.pos.x, this.pos.y);
				this.font.draw(renderer.getContext(), "O Ability: Speed Burst. Current Level: " + game.data.ability1 + " Cost: " + ((game.data.ability4+1)*10), this.pos.y);
				this.font.draw(renderer.getContext(), "W Ability: Eat Your Creep for Health: " + game.data.ability2 + " Cost: " + ((game.data.ability5+1)*10), this.pos.y);
				this.font.draw(renderer.getContext(), "E Ability: Throw Your Spear: " + game.data.ability3 + " Cost: " + ((game.data.ability6+1)*10), this.pos.y);

			}

		})));
		me.game.world.addChild(game.data.buytext, 35);
	},

//reverse function. enables the player to not buy or undo the buy
	stopBuying: function(){
		this.buying = false;
		me.state.resume(me.state.PLAY);
		game.data.player.body.setVelocity(game.data.playerMoveSpeed, 20);
		me.game.world.removeChild(game.data.buyscreen);
		me.input.unbindKey(me.input.KEY.F1, "F1", true);
		me.input.unbindKey(me.input.KEY.F2, "F2", true);
		me.input.unbindKey(me.input.KEY.F3, "F3", true);
		me.input.unbindKey(me.input.KEY.F4, "F4", true);
		me.input.unbindKey(me.input.KEY.F5, "F5", true);
		me.input.unbindKey(me.input.KEY.F6, "F6", true);
		me.game.world.removeChild(game.data.buytext);
	}

//check that the buy keys are working
checkBuyKeys: function(){
	if(me.input.isKeyPressed("F1")){
		//checks the cost of the key pressed
		if(this.checkCost(1)){

		}
	}else if(me.input.isKeyPressed("F2")){

	}else if(me.input.isKeyPressed("F3")){

	}else if(me.input.isKeyPressed("F4")){

	}else if(me.input.isKeyPressed("F5")){

	}else if(me.input.isKeyPressed("F6")){

	}
},
//checks the cost of the key pressed
checkCost: function(){

}

});
// video 50,
<|endoftext|>


<commit_before>/**
 * @license
 * Copyright 2015 Google Inc. All Rights Reserved.
 *
 * Licensed under the Apache License, Version 2.0 (the "License");
 * you may not use this file except in compliance with the License.
 * You may obtain a copy of the License at
 *
 *     http://www.apache.org/licenses/LICENSE-2.0
 *
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS,
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 * See the License for the specific language governing permissions and
 * limitations under the License.
 */

CLASS({
  name: 'PopupView',
  package: 'foam.ui.md',
  extendsModel: 'foam.ui.SimpleView',

  exports: [ 'as popup' ],

  properties: [
    {
      model_: 'ViewFactoryProperty',
      name: 'delegate',
      documentation: function() {/* The inner view to pop up.
        This should be created in the context of this popup,
        so that X.viewContainerController is available to the inner
        view to control the popup.

The ViewContainerController interface includes methods to control
        your containing view, including .accept() and .reject()
        for standard dialogs. */}
    },
    {
      name: 'delegateView',
      defaultValue: null
    },
    {
      name: '$content',
      getter: function() {
        return this.X.document.getElementById(this.id+'Content');
      }
    },
    {
      name: '$blocker',
      getter: function() {
        return this.X.document.getElementById(this.id+'Blocker');
      }
    },
    {
      name: 'className',
      defaultValue: "popup-view-container"
    },
    {
      name: 'state',
      defaultValue: 'closed'
    },
  ],

  methods: {
    open: function(sourceElement) {
      if ( this.state == 'closed' ) {
        this.delegateView = this.delegate();
        if ( this.data ) this.delegateView.data = this.data;

        if ( this.$ ) this.$.outerHTML = '';  // clean up old copy, in case of rapid re-activation
        this.X.document.body.insertAdjacentHTML('beforeend', this.toHTML());
        this.initializePosition();
        this.X.setTimeout(function() {  this.animateToExpanded(); }.bind(this), 100);
        this.initHTML();
        this.state = 'open';
      }
    },
    initializePosition: function() {
      this.$content.style.zIndex = "1010";
      //this.$content.style.transform = "translateY("+this.viewportSize().height+"px)";
      this.$content.style.opacity = "0";
      this.$blocker.style.opacity = "0";
    },
    animateToExpanded: function() {
      //this.$content.style.transition = "transform cubic-bezier(0.0, 0.0, 0.2, 1) .1s";
      //this.$content.style.transform = "translateY(0)";
      this.$content.style.transition = "opacity cubic-bezier(0.0, 0.0, 0.2, 1) .1s";
      this.$content.style.opacity = "1";

      this.$blocker.style.transition = "opacity cubic-bezier(0.0, 0.0, 0.2, 1) .1s";
      this.$blocker.style.opacity = "0.4";

      this.isHidden = false;
    },
    animateToHidden: function() {
      this.isHidden = true;
      if ( this.$content ) {
        this.$content.style.transition = "opacity cubic-bezier(0.4, 0.0, 1, 1) .1s"
        this.$content.style.opacity = "0";
        this.$content.style.pointerEvents = "none";
      }
      if ( this.$blocker ) {
        this.$blocker.style.transition = "opacity cubic-bezier(0.4, 0.0, 1, 1) .1s"
        this.$blocker.style.opacity = "0";
        this.$blocker.style.pointerEvents = "none";
      }
    },
    close: function() {
      this.animateToHidden();
      this.X.setTimeout(function() { this.destroy(); }.bind(this), 300);
    },
    destroy: function(p) {
      if ( this.$ ) this.$.outerHTML = '';
      this.delegateView = null;
      this.state = 'closed';
      this.SUPER(p);
    },

  },

  templates: [
    function toInnerHTML() {/*
      <div id="<%= this.id %>Blocker" class='popup-view-modal-blocker'>

      <div id="<%= this.id %>Content"class='popup-view-content md-card'>
        %%delegateView

    */},
    function CSS() {/*
      .popup-view-modal-blocker {
        position: fixed;
        top: 0px;
        left: 0px;
        bottom: 0px;
        right: 0px;
        background: black;
        opacity: 0;
      }
      .popup-view-container {
        display: flex;
        align-items: center;
        justify-content: center;
        position: fixed;
        top: 0px;
        left: 0px;
        bottom: 0px;
        right: 0px;
        z-index: 1000;
      }
    */}
  ]
});
<commit_msg>Fix md.PopupView to work if you call .open() .close() and .open() in rapid succession.<commit_after>/**
 * @license
 * Copyright 2015 Google Inc. All Rights Reserved.
 *
 * Licensed under the Apache License, Version 2.0 (the "License");
 * you may not use this file except in compliance with the License.
 * You may obtain a copy of the License at
 *
 *     http://www.apache.org/licenses/LICENSE-2.0
 *
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS,
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 * See the License for the specific language governing permissions and
 * limitations under the License.
 */

CLASS({
  name: 'PopupView',
  package: 'foam.ui.md',
  extendsModel: 'foam.ui.SimpleView',

  exports: [ 'as popup' ],
  imports: [
    'clearTimeout',
    'setTimeout',
    'document'
  ],

  properties: [
    {
      model_: 'ViewFactoryProperty',
      name: 'delegate',
      documentation: function() {/* The inner view to pop up.
        This should be created in the context of this popup,
        so that X.viewContainerController is available to the inner
        view to control the popup.

The ViewContainerController interface includes methods to control
        your containing view, including .accept() and .reject()
        for standard dialogs. */}
    },
    {
      name: 'delegateView',
      defaultValue: null
    },
    {
      name: '$content',
      getter: function() {
        return this.document.getElementById(this.id+'Content');
      }
    },
    {
      name: '$blocker',
      getter: function() {
        return this.document.getElementById(this.id+'Blocker');
      }
    },
    {
      name: 'className',
      defaultValue: "popup-view-container"
    },
    {
      name: 'state',
      defaultValue: 'closed'
    },
    {
      name: 'closeLatch_'
    }
  ],

  methods: {
    open: function(sourceElement) {
      if ( this.closeLatch_ ) this.closeLatch_();

      if ( this.state == 'closed' ) {
        this.delegateView = this.delegate();
        if ( this.data ) this.delegateView.data = this.data;

        if ( this.$ ) this.$.outerHTML = '';  // clean up old copy, in case of rapid re-activation
        this.document.body.insertAdjacentHTML('beforeend', this.toHTML());
        this.initializePosition();
        this.setTimeout(function() {  this.animateToExpanded(); }.bind(this), 100);
        this.initHTML();
        this.state = 'open';
      }
    },
    initializePosition: function() {
      this.$content.style.zIndex = "1010";
      //this.$content.style.transform = "translateY("+this.viewportSize().height+"px)";
      this.$content.style.opacity = "0";
      this.$blocker.style.opacity = "0";
    },
    animateToExpanded: function() {
      //this.$content.style.transition = "transform cubic-bezier(0.0, 0.0, 0.2, 1) .1s";
      //this.$content.style.transform = "translateY(0)";
      this.$content.style.transition = "opacity cubic-bezier(0.0, 0.0, 0.2, 1) .1s";
      this.$content.style.opacity = "1";

      this.$blocker.style.transition = "opacity cubic-bezier(0.0, 0.0, 0.2, 1) .1s";
      this.$blocker.style.opacity = "0.4";

      this.isHidden = false;
    },
    animateToHidden: function() {
      this.isHidden = true;
      if ( this.$content ) {
        this.$content.style.transition = "opacity cubic-bezier(0.4, 0.0, 1, 1) .1s"
        this.$content.style.opacity = "0";
        this.$content.style.pointerEvents = "none";
      }
      if ( this.$blocker ) {
        this.$blocker.style.transition = "opacity cubic-bezier(0.4, 0.0, 1, 1) .1s"
        this.$blocker.style.opacity = "0";
        this.$blocker.style.pointerEvents = "none";
      }
    },
    close: function() {
      this.state = 'closing';

      this.animateToHidden();
      var id = this.setTimeout(function() { this.destroy(); }.bind(this), 300);
      this.closeLatch_ = function() {
        this.clearTimeout(id);
        this.closeLatch_ = '';
        this.destroy();
      }.bind(this);
    },
    destroy: function(p) {
      if ( this.$ ) this.$.outerHTML = '';
      this.delegateView = null;
      this.state = 'closed';
      this.SUPER(p);
    },

  },

  templates: [
    function toInnerHTML() {/*
      <div id="<%= this.id %>Blocker" class='popup-view-modal-blocker'>

      <div id="<%= this.id %>Content"class='popup-view-content md-card'>
        %%delegateView

    */},
    function CSS() {/*
      .popup-view-modal-blocker {
        position: fixed;
        top: 0px;
        left: 0px;
        bottom: 0px;
        right: 0px;
        background: black;
        opacity: 0;
      }
      .popup-view-container {
        display: flex;
        align-items: center;
        justify-content: center;
        position: fixed;
        top: 0px;
        left: 0px;
        bottom: 0px;
        right: 0px;
        z-index: 1000;
      }
    */}
  ]
});
<|endoftext|>


<commit_before>ui.language({
	//List Headers
	focus: "Keskity",
	lists: "Listat",
	today: "Tämänpäiväiset",
	next: "Seuraavat",
	scheduled: "Ajastetut",
	logbook: "Logbook",
	all: "Kaikki tehtävät",

	//Default Names
	nlist: "Uusi lista",
	ntask: "Uusi tehtävä",

	//Buttons
	addbtn: "Lisää",
	deletebtn: "Muokkaa",
	sortbtn: "Poista",

	// Sort
	sortMagic: "Magic",
	sortDefault: "by Hand",
	sortPriority: "Priority",
	sortDate: "Date",

	//Placeholder Text
	search: "Hae",
	notes: "Huomautukset",

	//Priority
	none: "Ei mitään",
	low: "Matala",
	medium: "Keski",
	high: "Tärkeä",

	//Date Labels
	dueDate: "Due Date",
	schedule: "Schedule",

	// Delete Modals
	deleteMore: "Do you really want to delete these %s tasks?",
	deleteMoreYes: "Yes, Delete them",
	deleteMoreNo: "No, Keep them",
	deleteOne: "Do you really want to delete this task?",
	deleteOneYes: "Yes, Delete it",
	deleteOneNo: "No, Keep it",
	deleteList: "Are you sure you want to delete that list?",
	warning: "Warning!",

	"recurring": "Toistuva",
	"reviewNo": "Käy läpi:",
	"recurType": "Luodaan:",
	"daily": "päivittäin",
	"weekly": "viikoittain",
	"monthly": "kuukausittain",
	"recurNext": "Seuraava: ",
	"recurEnds": "Päättyy: ",
	"reviewAction": "ja sijoita kohteeseen: ",
	"create": "Luo",
	"cancel": "Peruuta",

	hideWarnings: "Piilota poistovaroitukset",
	nextNoLists: "Älä näytä mitään",
	nextEverything:	"Näytä kaikki tehtävät",

	general: "Yleiset",
	nextDescription: "Näytä muut listat seuraavissa: ",
	deleteWarningsDescription: "Tämä piilottaa varmistuslaatikon, joka ilmaantuu poistettaessa tehtäviä tai listoja.",

	language: "Language",
	authortext: "Author",

	about: "About",
	theme: "Teema",
	pickTheme: "Valitse teema: ",
	themeDescription: "Teemat mahdollistavat Nitron ulkoasun muuttamisen. CSS:llä voit jopa luoda oman teeman!",
	replaceDefault: "Vaihda tausta: ",
	useDefault: "Käytä oletustaustaa: ",
	removeBG: "Poista tausta",
	bgSize: "Taustan koko: ",
	fill: "Täytä ruutu",
	center:	"Keskitä",
	tile: "Vierekkäin",
	bgDescription: "Vaihda tekstin väriä vastaamaan paremmin valitsemaasi taustaa.",
	headingColor: "Otsikkoväri",
	default: "Oletus",
	light: "Vaalea",
	dark:"Tumma",
	headingDescription:	"Vaihda tekstin väriä vastaamaan paremmin valitsemaasi taustaa.",
	sync: "Sync",
	donateText:	"Sync is beta. If Nitro breaks, explodes or melts your computer - we warned you. It is pretty stable but if anything does break, you can contact @GeorgeCzabania or @consindo",
	syncLabel: "Run sync: ",
	syncDescription:"Sync allows you to access your tasks from other computers and smartphones.",
	syncNever: "Never (No notifications)",
	syncManual:	"Manually",
	syncTimer: "Every 30 seconds",
	syncAuto: "Every time a change is made",
	syncLoggedIn: "Logged in as: ",
	syncService:"Service: ",
	syncLogout: "Logout",
	syncAuthenticate: "Waiting for Nitro to be authenticated...",
	syncError: "Could not sync with server...",
	cancel: "Cancel"
})
<commit_msg>Updated Finnish<commit_after>ui.language({
	//List Headers
	focus: "Keskity",
	lists: "Listat",
	today: "Tämänpäiväiset",
	next: "Seuraavat",
	scheduled: "Ajastetut",
	logbook: "Lokikirja",
	all: "Kaikki tehtävät",

	//Default Names
	nlist: "Uusi lista",
	ntask: "Uusi tehtävä",

	//Buttons
	addbtn: "Lisää",
	deletebtn: "Muokkaa",
	sortbtn: "Poista",

	// Sort
	sortMagic: "Taikuudella",
	sortDefault: "Käsin",
	sortPriority: "Tärkeys",
	sortDate: "Päiväys",

	//Placeholder Text
	search: "Hae",
	notes: "Huomautukset",

	//Priority
	none: "Ei mitään",
	low: "Matala",
	medium: "Keski",
	high: "Tärkeä",

	//Date Labels
	dueDate: "Eräpäivä",
	schedule: "Ajasta",

	// Delete Modals
	deleteMore: "Haluatko varmasti poistaa nämä &s tehtävää?",
	deleteMoreYes: "Kyllä, poista ne",
	deleteMoreNo: "Ei, säilytä ne",
	deleteOne: "Haluatko varmasti poistaa tämän tehtävän?",
	deleteOneYes: "Kyllä, poista se",
	deleteOneNo: "Ei, säilytä se",
	deleteList: "Haluatko varmasti poistaa tämän listan?",
	warning: "Varoitus!",

	recurring: "Toistuva",
	reviewNo: "Käy läpi:",
	recurType: "Luodaan:",
	daily: "päivittäin",
	weekly: "viikoittain",
	monthly: "kuukausittain",
	recurNext: "Seuraava: ",
	recurEnds: "Päättyy: ",
	reviewAction: "ja sijoita kohteeseen: ",
	create: "Luo",
	cancel: "Peruuta",

	hideWarnings: "Piilota poistovaroitukset",
	nextNoLists: "Älä näytä mitään",
	nextEverything:	"Näytä kaikki tehtävät",

	general: "Yleiset",
	nextDescription: "Näytä muut listat seuraavissa: ",
	deleteWarningsDescription: "Tämä piilottaa varmistuslaatikon, joka ilmaantuu poistettaessa tehtäviä tai listoja.",

	language: "Kieli",
	authortext: "Kääntäjä",

	about: "Tietoa",
	theme: "Teema",
	pickTheme: "Valitse teema: ",
	themeDescription: "Teemat mahdollistavat Nitron ulkoasun muuttamisen. CSS:llä voit jopa luoda oman teeman!",
	replaceDefault: "Vaihda tausta: ",
	useDefault: "Käytä oletustaustaa: ",
	removeBG: "Poista tausta",
	bgSize: "Taustan koko: ",
	fill: "Täytä ruutu",
	center:	"Keskitä",
	tile: "Vierekkäin",
	bgDescription: "Vaihda tekstin väriä vastaamaan paremmin valitsemaasi taustaa.",
	headingColor: "Otsikkoväri",
	default: "Oletus",
	light: "Vaalea",
	dark:"Tumma",
	headingDescription:	"Vaihda tekstin väriä vastaamaan paremmin valitsemaasi taustaa.",
	sync: "Synkronointi",
	donateText:	"Synkronointi on beeta. Jos Nitro hajottaa, räjäyttää tai sulattaa tietokoneesi - me varoitimme sinua. Se toimii melko vakaasti, mutta jos jokin rikkoontuu, voit ottaa yhteyttä @GeorgeCzabania tai @consindo",
	syncLabel: "Synkronoi: ",
	syncDescription:"Synkronoinnin avulla pääset käsiksi tehtäviisi muilta tietokoneilta ja älypuhelimista.",
	syncNever: "Ei koskaan (Ei ilmoituksia)",
	syncManual:	"Manuaalisesti",
	syncTimer: "30 sekunnin välein",
	syncAuto: "Jokaisen muutoksen jälkeen",
	syncLoggedIn: "Kirjauduttu nimellä: ",
	syncService:"Palvelu: ",
	syncLogout: "Kirjaudu ulos",
	syncAuthenticate: "Odotetaan Nitron todentamista...",
	syncError: "Synkronointi epäonnistui palvelimen kanssa...",
	cancel: "Peruuta"
})
<|endoftext|>


<commit_before>/** MIT License (c) copyright B Cavalier & J Hann */

/**
 * curl debug plugin
 *
 * Licensed under the MIT License at:
 * 		http://www.opensource.org/licenses/mit-license.php
 *
 */

/**
 * usage:
 *  curl({ debug: true }, ['curl/debug']).next(['other/modules'], function (otherModules) {
 * 		// do stuff while logging debug messages
 * 	});
 *
 * The debug module must be used in conjunction with the debug: true config param!
 *
 */
define(['require', 'curl/_privileged'], function (require, priv) {
"use strict";

	var cache, totalWaiting, prevTotal, origDefine;

	if (typeof console == 'undefined') {
		throw new Error('`console` object must be defined to use debug module.');
	}

	priv._curl['undefine'] = function (moduleId) { delete cache[moduleId]; };

	cache = priv['cache'];

	// add logging to core functions
	for (var p in priv['core']) (function (name, orig) {
		priv['core'][name] = function () {
			var result;
			console.log('curl ' + name + ' arguments:', arguments);
			result = orig.apply(this, arguments);
			console.log('curl ' + name + ' return:', result);
			return result;
		};
	}(p, priv['core'][p]));

	// add logging to define
	origDefine = priv._define;
	priv._define = function () {
		console.log('curl define:', arguments);
		return origDefine.apply(this, arguments);
	};

	// log cache stats periodically
	totalWaiting = 0;

	function count () {
		totalWaiting = 0;
		for (var p in cache) {
			if (cache[p] instanceof priv['ResourceDef']) totalWaiting++;
		}
	}
	count();

	function periodicLogger () {
		count();
		if (prevTotal != totalWaiting) {
			console.log('curl: ********** modules waiting: ' + totalWaiting);
			for (var p in cache) {
				if (cache[p] instanceof priv['ResourceDef']) {
					console.log('curl: ********** module waiting: ' + p);
				}
			}
		}
		prevTotal = totalWaiting;
		setTimeout(periodicLogger, 500);
	}
	periodicLogger();

	return true;

});
<commit_msg>debug module now reflects new privileged API<commit_after>/** MIT License (c) copyright B Cavalier & J Hann */

/**
 * curl debug plugin
 *
 * Licensed under the MIT License at:
 * 		http://www.opensource.org/licenses/mit-license.php
 *
 */

/**
 * usage:
 *  curl({ debug: true }, ['curl/debug']).next(['other/modules'], function (otherModules) {
 * 		// do stuff while logging debug messages
 * 	});
 *
 * The debug module must be used in conjunction with the debug: true config param!
 *
 */
define(['require', 'curl/_privileged'], function (require, priv) {
"use strict";

	var cache, totalWaiting, prevTotal, origDefine;

	if (typeof console == 'undefined') {
		throw new Error('`console` object must be defined to use debug module.');
	}

	priv._curl['undefine'] = function (moduleId) { delete cache[moduleId]; };

	cache = priv['cache'];

	// add logging to core functions
	for (var p in priv['core']) (function (name, orig) {
		priv['core'][name] = function () {
			var result;
			console.log('curl ' + name + ' arguments:', arguments);
			result = orig.apply(this, arguments);
			console.log('curl ' + name + ' return:', result);
			return result;
		};
	}(p, priv['core'][p]));

	// add logging to define
	origDefine = priv._define;
	priv._define = function () {
		console.log('curl define:', arguments);
		return origDefine.apply(this, arguments);
	};

	// log cache stats periodically
	totalWaiting = 0;

	function count () {
		totalWaiting = 0;
		for (var p in cache) {
			if (cache[p] instanceof priv['Promise']) totalWaiting++;
		}
	}
	count();

	function periodicLogger () {
		count();
		if (prevTotal != totalWaiting) {
			console.log('curl: ********** modules waiting: ' + totalWaiting);
			for (var p in cache) {
				if (cache[p] instanceof priv['Promise']) {
					console.log('curl: ********** module waiting: ' + p);
				}
			}
		}
		prevTotal = totalWaiting;
		setTimeout(periodicLogger, 500);
	}
	periodicLogger();

	return true;

});
<|endoftext|>


<commit_before>/*
  Body condition score, mobilization and body weight.

  REFERENCES

  Metzner, M, Heuwieser, W. und W. Klee, 1993. Die Beurteilung der Körperkondition (body condition scoring) im
  Herdenmanagement. Der praktische Tierarzt 11, 991–998

  Friggens NC, Ingvartsen KL and Emmans GC 2004. Prediction of body lipid change in pregnancy and lactation.
  Journal of Dairy Science 87, 988–1000.

  Johnson IR (2008). Biophysical pasture model documentation: model documentation for DairyMod, EcoMod and the SGS
  Pasture Model. (IMJ Consultants: Dorrigo, NSW) (http://imj.com.au/gmdocs/)

  Wright, Russel 1984. Estimation in vivo of the chemical composition of the bodies of mature cows.

  LICENSE

  Copyright 2014 Jan Vaillant   <jan.vaillant@zalf.de>
  Copyright 2014 Lisa Baldinger <lisa.baldinger@boku.ac.at>

  Distributed under the MIT License. See accompanying file LICENSE or copy at http://opensource.org/licenses/MIT

  Any publication for which this file or a derived work is used must include an a reference to at least one source:

  Vaillant, J. and Baldinger, L. 2014.
  dairy.js - an open-source JavaScript library for simulation of dairy cow herds and rapid model prototyping.
  Poster presentation at the International Livestock Modelling and Research Colloquium, 14-16 October, Bilbao, Spain.

  Baldinger, L., Vaillant, J., Zollitsch, W. and Rinne, M. 2014.
  Making a decision support system for dairy farmers usable throughout Europe - the challenge of feed evaluation.
  Oral presentation at the International Livestock Modelling and Research Colloquium, 14-16 October, Bilbao, Spain.

  TODO:
  - reference for "DAYS_ZERO_MOBILIZATION_AFTER_MILK_PEAK"
  - improve BCS function
  - implement either "full" Friggens approach or investigate how to "reasonably" relate mobilization, day max milk, day
    min milk solids, day of conception ...
*/

var dairy = dairy || {};

dairy.body = (function () {

var pow = Math.pow
  , log = Math.log
  , exp = Math.exp
  , DAYS_IN_MONTH = 30.5
  , DAYS_ZERO_MOBILIZATION_AFTER_MILK_PEAK = 55
  ;

/*
  Metzner et. al. (1993)

  We assume BCS of BCS_max during dry period and a minimum BCS at day d_mx + 55.
  BCS is everywhere expressed on a six point scale.

  BCS     [-]     body condition score
  DIM     [day]   days in milk
  CI      [month] calving interval in month
  DP      [day]   dry period in days
  d_mx    [day]   day milk peaks
*/

var BCS = function (DIM, CI, DP, d_mx) {

      /* BCS maximum */
  var BCS_max = 3.5
      /* BCS minimum */
    , BCS_min = 3.0
      /* calving interval in days */
    , CI_d = CI * DAYS_IN_MONTH
    , BCS = BCS_max
    , BWC_0 = DAYS_ZERO_MOBILIZATION_AFTER_MILK_PEAK + d_mx
    ;

  if (DIM <= BWC_0)
    BCS = BCS_max - ((BCS_max - BCS_min) / BWC_0) * DIM;
  else if (DIM <= CI_d - DP)
    BCS = BCS_min +  ((BCS_max - BCS_min) / (CI_d - DP - BWC_0)) * (DIM - BWC_0);

  return BCS;

};

/*
  Johnson (2008) eq. 7.8a

  W       [kg]      weight of cow or young stock at day age
  age     [day]     age in days
  age_c1  [month]   age first calving
  W_b     [kg]      weight of calf at birth
  W_c1    [kg kg-1] fraction (recommended) of mature body weight at first calving
  W_m     [kg]      weight of mature cow
*/

var W = function (age, age_c1, W_b, W_c1, W_m) {

  var W = 0;

  /* make sure W_c1 < 1 */
  W_c1 = (W_c1 >= 1) ? 0.99 : W_c1;

  /* growth parameter (solve W_m * W_c1 = W_m - (W_m - W_b) * exp(-k * age) for k) */
  var k = log((W_b - W_m) / (W_m * (W_c1 - 1))) / (age_c1 * DAYS_IN_MONTH);

  W = W_m - (W_m - W_b) * exp(-k * age);

  /* make sure mature body weight is reached at some point (W_m is an asymptote) */
  // W = (W >= W_m - 1) ? W_m : W; // TODO: round ?

  return W;

};

/*
  Johnson IR (2005 & 2008), eq. 7.6

  Calf birth weight.

  W_b [kg]  weight of calf at birth
  W_m [kg]  weight of mature cow
*/

var W_b = function (W_m) {

  var W_b = 0
      /* parameters for cattle, table 7.3 */
    , c_b = -2
    , m_b = 0.066
    ;

  W_b = c_b + m_b * W_m;

  return W_b;

};

/*
  Wright, Russel (1984b) table 2, Wright, Russel (1984a) table 1

  Mobilization of body fat in early lactation.

  TODO:
    - body lipid change to body weight change conversion?

  W_mob [kg]    mobilized body fat
  W_m   [kg]    mature body weight
  type  [enum]  cow type (milk or dual)
*/

var W_mob = function (W_m, type) {

  var W_mob = 0
    , b_1 = (type === 'dual' ? 52.3 : 84.2)
    , BCS_mx = 3.5
    , BCS_mn = 3.0
    , W_ref = (type === 'dual' ? 542 : 560)
    ;

  W_mob = b_1 * (BCS_mx - BCS_mn) * W_m / W_ref;

  return W_mob;

};

/*
  Friggens et. al. (2004)

  Body weight change of young stock and cows (dry or lactating). Simplified version of Friggens' approach.

  We assume that..

  * the day of zero mobilization is 55 days after milk peaks (d_0).
  * either the cow mobilizes or gains weight, there is no longer period w/o weight change.
  * a mature cow gains after d_0 the same amout of body weight she lost till day d_0.
  * a growing cow will additionally gain the total body weight she should gain according to growth (W) function within
    the total lactaion after d_0 (i.e. she will not grow during mobilization but compensate those "losses", "non-gains").

  TODO:
  - fat vs body weight (tissue). fat === body weight ?

  BWC     [kg d-1]  body weight change
  DPP     [day]     days post partum
  d_mx    [day]     day milk peaks
  age     [day]     cow's age in days
  CI      [m]       calving interval in month
  W_m     [kg]      mature body weight
  age_c1  [month]   age first calving
  W_b     [kg]      weight of calf at birth
  W_c1    [kg kg-1] fraction (recommended) of mature body weight at first calving
  type    [enum]    cow type (milk or dual)
*/

var BWC = function (DPP, d_mx, age, CI, W_m, age_c1, W_b, W_c1, type) {

  var BWC = 0;

  /* month to days */
  CI = CI * DAYS_IN_MONTH;

  /* day of zero mobilization */
  var d_0 = d_mx + DAYS_ZERO_MOBILIZATION_AFTER_MILK_PEAK;

  if (age < age_c1 * DAYS_IN_MONTH) { /* young stock */

    BWC = W(age, age_c1, W_b, W_c1, W_m) - W(age - 1, age_c1, W_b, W_c1, W_m);

  } else { /* cows */

    /* body weight mobilized [kg] */
    var mob = W_mob(W(age - DPP, age_c1, W_b, W_c1, W_m), type);

    if (DPP < d_0) { /* cow is mobilizing */

      BWC = (2 * DPP * mob / pow(d_0, 2)) - (2 * mob / d_0);

    } else if (DPP > d_0) { /* cow is gaining weight */

      /* total growth in between two calvings */
      G = W(age - DPP + CI, age_c1, W_b, W_c1, W_m) - W(age - DPP, age_c1, W_b, W_c1, W_m);

      /* growth weight gain at day age */
      dG = 2 * G / pow(CI - d_0, 2) * (DPP - d_0);

      /* weight gain reconstitution at day age */
      dW_mob = 2 * mob / pow(CI - d_0, 2) * (DPP - d_0);

      BWC = dG + dW_mob;

    }
  }

  return BWC;

};

/*
  Friggens et. al. (2004)

  Body weight change of young stock and cows (dry or lactating).

  BW      [kg]      body weight at day age
  DPP     [day]     days post partum
  d_mx    [day]     day milk peaks
  age     [day]     cow's age in days
  CI      [m]       calving interval in month
  W_m     [kg]      mature body weight
  age_c1  [month]   age first calving
  W_b     [kg]      weight of calf at birth
  W_c1    [kg kg-1] fraction (recommended) of mature body weight at first calving
  type    [enum]    cow type (milk or dual)
*/

var BW = function (DPP, d_mx, age, CI, W_m, age_c1, W_b, W_c1, type) {

  var BW = 0;

  /* month to days */
  CI = CI * DAYS_IN_MONTH;

  /* day of zero mobilization */
  var d_0 = d_mx + DAYS_ZERO_MOBILIZATION_AFTER_MILK_PEAK;

  if (age < age_c1 * DAYS_IN_MONTH) { /* young stock */

    BW = W(age, age_c1, W_b, W_c1, W_m);

  } else { /* cows */

    /* body weight mobilized [kg] */
    var mob = W_mob(W(age - DPP, age_c1, W_b, W_c1, W_m), type);

    /* body weight at begin of lactation */
    BW = W(age - DPP, age_c1, W_b, W_c1, W_m);

    /* integral from 0 to DPP */
    if (DPP < d_0) /* cow is mobilizing */
      BW -= 2 * mob * (d_0 * DPP - pow(DPP, 2) / 2) / pow(d_0, 2);
    else
      BW -= mob;

    if (DPP > d_0) { /* cow is beyond d_0 */

      /* total growth in between two calvings */
      G = W(age - DPP + CI, age_c1, W_b, W_c1, W_m) - W(age - DPP, age_c1, W_b, W_c1, W_m);

      /* integral growth weight gain */
      BW += G * pow(d_0 - DPP, 2) / pow(d_0 - CI, 2);
      // BW += (2 * G * (pow(DPP, 2) / 2 - d_0 * DPP) / pow(CI - d_0, 2));

      /* integral weight gain reconstitution at day age */
      BW += mob * pow(d_0 - DPP, 2) / pow(d_0 - CI, 2);
      // BW += (2 * mob * (pow(DPP, 2) / 2 - d_0 * DPP) / pow(CI - d_0, 2));

    }
  }

  return BW;

};

/*
  Body weight at calving

  BW_c    [kg]      body weight at calving
  DPP     [day]     days post partum
  age     [day]     cow's age in days
  W_m     [kg]      mature body weight
  age_c1  [month]   age first calving
  W_b     [kg]      weight of calf at birth
  W_c1    [kg kg-1] fraction (recommended) of mature body weight at first calving
*/

var BW_c = function (DPP, age, W_m, age_c1, W_b, W_c1) {

  return W(age - DPP, age_c1, W_b, W_c1, W_m);

};

return {

    BWC: BWC
  , weightChange: BWC
  , BW: BW
  , weight: BW
  , BW_c: BW_c
  , weightAtCalving: BW_c
  , BCS: BCS
  , conditionScore: BCS
  , W: W
  , weightPotential: W
  , WB: W_b
  , weightAtBirth: W_b

};

}());
<commit_msg>Update references<commit_after>/*
  Body condition score, mobilization and body weight.

  REFERENCES

  Friggens, N.C., Ingvartsen, K.L. and Emmans, G.C. 2004. Prediction of body lipid change in pregnancy and lactation.
  Journal of Dairy Science 87(4):988–1000.

  Johnson, I.R. 2008. Biophysical pasture model documentation: model documentation for DairyMod, EcoMod and the SGS
  Pasture Model. IMJ Consultants, Armidale, NSW, Australia. p. 144. Available at:
  http://imj.com.au/wp-content/uploads/2014/08/GrazeMod.pdf

  Johnson, I.R. 2013. DairyMod and the SGS Pasture Model: a mathematical description of the biophysical model structure.
  IMJ Consultants, Darrigo, NSW, Australia. p. 120. Available at:
  http://imj.com.au/wp-content/uploads/2014/08/DM_SGS_documentation.pdf

  Metzner, M., Heuwieser, W. und Klee, W. 1993. Die Beurteilung der Körperkondition (body condition scoring) im
  Herdenmanagement. Der praktische Tierarzt 74(11):991–998.

  Wright, I.A. and Russel, A.J.F. 1984a. Partition of fat, body composition and body condition score in mature cows.
  Animal Science 38(1):23-32.

  Wright, I.A. and Russel, A.J.F. 1984b. Estimation in vivo of the chemical composition of the bodies of mature cows.
  Animal Science 38(1):33-44.

  LICENSE

  Copyright 2014 Jan Vaillant   <jan.vaillant@zalf.de>
  Copyright 2014 Lisa Baldinger <lisa.baldinger@boku.ac.at>

  Distributed under the MIT License. See accompanying file LICENSE or copy at http://opensource.org/licenses/MIT

  Any publication for which this file or a derived work is used must include an a reference to at least one source:

  Vaillant, J. and Baldinger, L. 2014.
  dairy.js - an open-source JavaScript library for simulation of dairy cow herds and rapid model prototyping.
  Poster presentation at the International Livestock Modelling and Research Colloquium, 14-16 October, Bilbao, Spain.

  Baldinger, L., Vaillant, J., Zollitsch, W. and Rinne, M. 2014.
  Making a decision support system for dairy farmers usable throughout Europe - the challenge of feed evaluation.
  Oral presentation at the International Livestock Modelling and Research Colloquium, 14-16 October, Bilbao, Spain.

  TODO:
  - reference for "DAYS_ZERO_MOBILIZATION_AFTER_MILK_PEAK"
  - improve BCS function
  - implement either "full" Friggens approach or investigate how to "reasonably" relate mobilization, day max milk, day
    min milk solids, day of conception ...
*/

var dairy = dairy || {};

dairy.body = (function () {

var pow = Math.pow
  , log = Math.log
  , exp = Math.exp
  , DAYS_IN_MONTH = 30.5
  , DAYS_ZERO_MOBILIZATION_AFTER_MILK_PEAK = 55
  ;

/*
  Metzner et. al. (1993)

  We assume BCS of BCS_max during dry period and a minimum BCS at day d_mx + 55.
  BCS is everywhere expressed on a six point scale.

  BCS     [-]     body condition score
  DIM     [day]   days in milk
  CI      [month] calving interval in month
  DP      [day]   dry period in days
  d_mx    [day]   day milk peaks
*/

var BCS = function (DIM, CI, DP, d_mx) {

      /* BCS maximum */
  var BCS_max = 3.5
      /* BCS minimum */
    , BCS_min = 3.0
      /* calving interval in days */
    , CI_d = CI * DAYS_IN_MONTH
    , BCS = BCS_max
    , BWC_0 = DAYS_ZERO_MOBILIZATION_AFTER_MILK_PEAK + d_mx
    ;

  if (DIM <= BWC_0)
    BCS = BCS_max - ((BCS_max - BCS_min) / BWC_0) * DIM;
  else if (DIM <= CI_d - DP)
    BCS = BCS_min +  ((BCS_max - BCS_min) / (CI_d - DP - BWC_0)) * (DIM - BWC_0);

  return BCS;

};

/*
  Johnson (2008) eq. 7.8a

  W       [kg]      weight of cow or young stock at day age
  age     [day]     age in days
  age_c1  [month]   age first calving
  W_b     [kg]      weight of calf at birth
  W_c1    [kg kg-1] fraction (recommended) of mature body weight at first calving
  W_m     [kg]      weight of mature cow
*/

var W = function (age, age_c1, W_b, W_c1, W_m) {

  var W = 0;

  /* make sure W_c1 < 1 */
  W_c1 = (W_c1 >= 1) ? 0.99 : W_c1;

  /* growth parameter (solve W_m * W_c1 = W_m - (W_m - W_b) * exp(-k * age) for k) */
  var k = log((W_b - W_m) / (W_m * (W_c1 - 1))) / (age_c1 * DAYS_IN_MONTH);

  W = W_m - (W_m - W_b) * exp(-k * age);

  /* make sure mature body weight is reached at some point (W_m is an asymptote) */
  // W = (W >= W_m - 1) ? W_m : W; // TODO: round ?

  return W;

};

/*
  Johnson IR (2005 & 2008), eq. 7.6

  Calf birth weight.

  W_b [kg]  weight of calf at birth
  W_m [kg]  weight of mature cow
*/

var W_b = function (W_m) {

  var W_b = 0
      /* parameters for cattle, table 7.3 */
    , c_b = -2
    , m_b = 0.066
    ;

  W_b = c_b + m_b * W_m;

  return W_b;

};

/*
  Wright, Russel (1984b) table 2, Wright, Russel (1984a) table 1

  Mobilization of body fat in early lactation.

  TODO:
    - body lipid change to body weight change conversion?

  W_mob [kg]    mobilized body fat
  W_m   [kg]    mature body weight
  type  [enum]  cow type (milk or dual)
*/

var W_mob = function (W_m, type) {

  var W_mob = 0
    , b_1 = (type === 'dual' ? 52.3 : 84.2)
    , BCS_mx = 3.5
    , BCS_mn = 3.0
    , W_ref = (type === 'dual' ? 542 : 560)
    ;

  W_mob = b_1 * (BCS_mx - BCS_mn) * W_m / W_ref;

  return W_mob;

};

/*
  Friggens et. al. (2004)

  Body weight change of young stock and cows (dry or lactating). Simplified version of Friggens' approach.

  We assume that..

  * the day of zero mobilization is 55 days after milk peaks (d_0).
  * either the cow mobilizes or gains weight, there is no longer period w/o weight change.
  * a mature cow gains after d_0 the same amout of body weight she lost till day d_0.
  * a growing cow will additionally gain the total body weight she should gain according to growth (W) function within
    the total lactaion after d_0 (i.e. she will not grow during mobilization but compensate those "losses", "non-gains").

  TODO:
  - fat vs body weight (tissue). fat === body weight ?

  BWC     [kg d-1]  body weight change
  DPP     [day]     days post partum
  d_mx    [day]     day milk peaks
  age     [day]     cow's age in days
  CI      [m]       calving interval in month
  W_m     [kg]      mature body weight
  age_c1  [month]   age first calving
  W_b     [kg]      weight of calf at birth
  W_c1    [kg kg-1] fraction (recommended) of mature body weight at first calving
  type    [enum]    cow type (milk or dual)
*/

var BWC = function (DPP, d_mx, age, CI, W_m, age_c1, W_b, W_c1, type) {

  var BWC = 0;

  /* month to days */
  CI = CI * DAYS_IN_MONTH;

  /* day of zero mobilization */
  var d_0 = d_mx + DAYS_ZERO_MOBILIZATION_AFTER_MILK_PEAK;

  if (age < age_c1 * DAYS_IN_MONTH) { /* young stock */

    BWC = W(age, age_c1, W_b, W_c1, W_m) - W(age - 1, age_c1, W_b, W_c1, W_m);

  } else { /* cows */

    /* body weight mobilized [kg] */
    var mob = W_mob(W(age - DPP, age_c1, W_b, W_c1, W_m), type);

    if (DPP < d_0) { /* cow is mobilizing */

      BWC = (2 * DPP * mob / pow(d_0, 2)) - (2 * mob / d_0);

    } else if (DPP > d_0) { /* cow is gaining weight */

      /* total growth in between two calvings */
      G = W(age - DPP + CI, age_c1, W_b, W_c1, W_m) - W(age - DPP, age_c1, W_b, W_c1, W_m);

      /* growth weight gain at day age */
      dG = 2 * G / pow(CI - d_0, 2) * (DPP - d_0);

      /* weight gain reconstitution at day age */
      dW_mob = 2 * mob / pow(CI - d_0, 2) * (DPP - d_0);

      BWC = dG + dW_mob;

    }
  }

  return BWC;

};

/*
  Friggens et. al. (2004)

  Body weight change of young stock and cows (dry or lactating).

  BW      [kg]      body weight at day age
  DPP     [day]     days post partum
  d_mx    [day]     day milk peaks
  age     [day]     cow's age in days
  CI      [m]       calving interval in month
  W_m     [kg]      mature body weight
  age_c1  [month]   age first calving
  W_b     [kg]      weight of calf at birth
  W_c1    [kg kg-1] fraction (recommended) of mature body weight at first calving
  type    [enum]    cow type (milk or dual)
*/

var BW = function (DPP, d_mx, age, CI, W_m, age_c1, W_b, W_c1, type) {

  var BW = 0;

  /* month to days */
  CI = CI * DAYS_IN_MONTH;

  /* day of zero mobilization */
  var d_0 = d_mx + DAYS_ZERO_MOBILIZATION_AFTER_MILK_PEAK;

  if (age < age_c1 * DAYS_IN_MONTH) { /* young stock */

    BW = W(age, age_c1, W_b, W_c1, W_m);

  } else { /* cows */

    /* body weight mobilized [kg] */
    var mob = W_mob(W(age - DPP, age_c1, W_b, W_c1, W_m), type);

    /* body weight at begin of lactation */
    BW = W(age - DPP, age_c1, W_b, W_c1, W_m);

    /* integral from 0 to DPP */
    if (DPP < d_0) /* cow is mobilizing */
      BW -= 2 * mob * (d_0 * DPP - pow(DPP, 2) / 2) / pow(d_0, 2);
    else
      BW -= mob;

    if (DPP > d_0) { /* cow is beyond d_0 */

      /* total growth in between two calvings */
      G = W(age - DPP + CI, age_c1, W_b, W_c1, W_m) - W(age - DPP, age_c1, W_b, W_c1, W_m);

      /* integral growth weight gain */
      BW += G * pow(d_0 - DPP, 2) / pow(d_0 - CI, 2);
      // BW += (2 * G * (pow(DPP, 2) / 2 - d_0 * DPP) / pow(CI - d_0, 2));

      /* integral weight gain reconstitution at day age */
      BW += mob * pow(d_0 - DPP, 2) / pow(d_0 - CI, 2);
      // BW += (2 * mob * (pow(DPP, 2) / 2 - d_0 * DPP) / pow(CI - d_0, 2));

    }
  }

  return BW;

};

/*
  Body weight at calving

  BW_c    [kg]      body weight at calving
  DPP     [day]     days post partum
  age     [day]     cow's age in days
  W_m     [kg]      mature body weight
  age_c1  [month]   age first calving
  W_b     [kg]      weight of calf at birth
  W_c1    [kg kg-1] fraction (recommended) of mature body weight at first calving
*/

var BW_c = function (DPP, age, W_m, age_c1, W_b, W_c1) {

  return W(age - DPP, age_c1, W_b, W_c1, W_m);

};

return {

    BWC: BWC
  , weightChange: BWC
  , BW: BW
  , weight: BW
  , BW_c: BW_c
  , weightAtCalving: BW_c
  , BCS: BCS
  , conditionScore: BCS
  , W: W
  , weightPotential: W
  , WB: W_b
  , weightAtBirth: W_b

};

}());
<|endoftext|>