<commit_before>/*
  node-http-proxy.js: http proxy for node.js

  Copyright (c) 2010 Charlie Robbins, Mikeal Rogers, & Marak Squires

  Permission is hereby granted, free of charge, to any person obtaining
  a copy of this software and associated documentation files (the
  "Software"), to deal in the Software without restriction, including
  without limitation the rights to use, copy, modify, merge, publish,
  distribute, sublicense, and/or sell copies of the Software, and to
  permit persons to whom the Software is furnished to do so, subject to
  the following conditions:

  The above copyright notice and this permission notice shall be
  included in all copies or substantial portions of the Software.

  THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND,
  EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF
  MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND
  NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE
  LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION
  OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION
  WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.

*/

var sys = require('sys'),
    http = require('http'),
    events = require('events'),
    pool = require('pool'),
    min = 0,
    max = 100;

// Setup the PoolManager
var manager = pool.createPoolManager();
manager.setMinClients(min);
manager.setMaxClients(max);

exports.createServer = function () {
  var args, callback, port, host;
  args = Array.prototype.slice.call(arguments);
  callback = typeof args[args.length - 1] === 'function' && args.pop();
  if (args[0]) port = args[0];
  if (args[1]) host = args[1];

  var server = http.createServer(function (req, res){
    var proxy = new HttpProxy(req, res);

    proxy.emitter.on('proxy', function (err, body) {
      server.emit('proxy', err, body);
    });

    // If we were passed a callback to process the request
    // or response in some way, then call it.
    if(callback) {
      callback(req, res, proxy);
    }
    else {
      proxy.proxyRequest(port, server);
    }
  });

  // WebSocket support
  server.on('update', function() {
  });

  return server;
};

exports.setMin = function (value) {
  min = value;
  manager.setMinClients(min);
};

exports.setMax = function (value) {
  max = value;
  manager.setMaxClients(max);
};

var HttpProxy = function (req, res, /* optional */ head) {
  this.emitter = new(events.EventEmitter);
  this.events = {};
  this.req = req;
  // If this request is upgrade request
  // No response will be passed
  if (!req.headers.upgrade) {
    this.res = res;
    this.watch(req);
  } else {
    // Second argument will be socket
    this.sock = res;
    this.head = head;
    this.watch(res);
  }
};

HttpProxy.prototype = {
  toArray: function (obj){
    var len = obj.length,
        arr = new Array(len);
    for (var i = 0; i < len; ++i) {
        arr[i] = obj[i];
    }
    return arr;
  },

  watch: function (req) {
    this.events = [];
    var self = this;

    this.onData = function () {
      self.events.push(['data'].concat(self.toArray(arguments)));
    };
    this.onEnd = function () {
      self.events.push(['end'].concat(self.toArray(arguments)));
    };

    req.addListener('data', this.onData);
    req.addListener('end', this.onEnd);
  },

  unwatch: function (req) {
    req.removeListener('data', this.onData);
    req.removeListener('end', this.onEnd);

    // Rebroadcast any events that have been buffered
    for (var i = 0, len = this.events.length; i < len; ++i) {
      req.emit.apply(req, this.events[i]);
    }
  },

  proxyRequest: function (port, server) {
    // Remark: nodeProxy.body exists solely for testability
    var self = this, req = this.req, res = this.res;
    self.body = '';

    // Open new HTTP request to internal resource with will act as a reverse proxy pass
    var p = manager.getPool(port, server);

    p.on('error', function (err) {
      // Remark: We should probably do something here
      // but this is a hot-fix because I don't think 'pool'
      // should be emitting this event.
    });

    p.request(req.method, req.url, req.headers, function (reverse_proxy) {
      // Create an error handler so we can use it temporarily
      var error = function (err) {
        res.writeHead(200, {'Content-Type': 'text/plain'});

        if(req.method !== 'HEAD') {
          res.write('An error has occurred: ' + sys.puts(JSON.stringify(err)));
        }

        res.end();
      };

      // Add a listener for the connection timeout event
      reverse_proxy.addListener('error', error);

      // Add a listener for the reverse_proxy response event
      reverse_proxy.addListener('response', function (response) {
        if (response.headers.connection) {
          if (req.headers.connection) response.headers.connection = req.headers.connection;
          else response.headers.connection = 'close';
        }

        // Set the response headers of the client response
        res.writeHead(response.statusCode, response.headers);

        // Status code = 304
        // No 'data' event and no 'end'
        if (response.statusCode === 304) {
          res.end();
          return;
        }

        // Add event handler for the proxied response in chunks
        response.addListener('data', function (chunk) {
          if(req.method !== 'HEAD') {
            res.write(chunk, 'binary');
            self.body += chunk;
          }
        });

        // Add event listener for end of proxied response
        response.addListener('end', function () {
          // Remark: Emit the end event for testability
          self.emitter.emit('proxy', null, self.body);
          res.end();
        });
      });

      // Chunk the client request body as chunks from the proxied request come in
      req.addListener('data', function (chunk) {
        reverse_proxy.write(chunk, 'binary');
      })

      // At the end of the client request, we are going to stop the proxied request
      req.addListener('end', function () {
        reverse_proxy.end();
        reverse_proxy.removeListener('error', error);
      });

      self.unwatch(req);
    });
  },

  /**
  * WebSocket Tunnel realization
  * Copyright (c) 2010 Fedor Indutny : http://github.com/donnerjack13589
  */
  proxyWebSocketRequest: function (port, server, host /* optional */) {
    var self = this, update = self.update, req = self.req, socket = self.sock,
        head = self.head, headers = new _headers(req.headers), CRLF = '\r\n',
        listeners = {};

    // Will generate clone of headers
    // To not change original
    function _headers(headers) {
      var h = {};
      for (var i in headers) {
        h[i] = headers[i];
      }
      return h;
    }

    // WebSocket requests has
    // method = GET
    if (req.method !== 'GET' || headers.upgrade.toLowerCase() !== 'websocket') {
      // This request is not WebSocket request
      return;
    }

    // Turn of all bufferings
    // For server set KeepAlive
    // For client set encoding
    function _socket(socket, server) {
      socket.setTimeout(0);
      socket.setNoDelay(true);
      if (server) {
        socket.setKeepAlive(true, 0);
      } else {
        socket.setEncoding('utf8');
      }
    }

    // Client socket
    _socket(socket);

    // If host is undefined
    // Get it from headers
    if (!host) {
      host = headers.Host;
    }
    // Remote host address
    var remote_host = server + (port - 80 === 0 ? '' : ':' + port);

    // Change headers
    headers.Host = remote_host;
    headers.Origin = 'http://' + remote_host;

    // Open request
    var p = manager.getPool(port, server);

    p.getClient(function(client) {
      // Based on 'pool/main.js'
      var request = client.request('GET', req.url, headers);

      var errorListener = function (error) {
        p.emit('error', error);
        request.emit('error', error);
        socket.end();
      }

      // Not disconnect on update
      client.on('upgrade', function(request, remote_socket, head) {
        // Prepare socket
        _socket(remote_socket, true);

        // Emit event
        onUpgrade(remote_socket);
      });

      client.on('error', errorListener);
      request.on('response', function (response) {
        response.on('end', function () {
          client.removeListener('error', errorListener);
          client.busy = false;
          p.onFree(client);
        })
      })
      client.busy = true;

      var t;
      request.socket.on('data', t = function(data) {
        // Handshaking

        // Ok, kind of harmfull part of code
        // Socket.IO is sending hash at the end of handshake
        // If protocol = 76
        // But we need to replace 'host' and 'origin' in response
        // So we split data to printable data and to non-printable
        // (Non-printable will come after double-CRLF)
        var sdata = data.toString();

        // Get Printable
        sdata = sdata
                  .substr(0, sdata.search(CRLF + CRLF));

        // Get Non-Printable
        data = data.slice(Buffer.byteLength(sdata), data.length);

        // Replace host and origin
        sdata = sdata
                  .replace(remote_host, host)
                  .replace(remote_host, host);

        // Write printable
        socket.write(sdata);

        // Write non-printable
        socket.write(data);

        // Remove data listener
        request.socket.removeListener('data', t);
      });

      // Write upgrade-head
      request.write(head);
      self.unwatch(socket);
    });

    // Request

    function onUpgrade(reverse_proxy) {
      // We're now connected to the server
      // So lets change server socket

      reverse_proxy.on('data', listeners._r_data = function(data) {
        // Pass data to client
        if (socket.writable) {
          socket.write(data);
        }
      });

      socket.on('data', listeners._data = function(data){
        // Pass data from client to server
        // Socket thougth that it isn't writable
        reverse_proxy.write(data);
      });

      // Detach event listeners from reverse_proxy
      function detach() {
        reverse_proxy.removeListener('close', listeners._r_close);
        reverse_proxy.removeListener('data', listeners._r_data);
        socket.removeListener('data', listeners._data);
        socket.removeListener('close', listeners._close);
      }

      // Hook disconnections
      reverse_proxy.on('close', listeners._r_close = function() {
        socket.end();
        detach();
      });

      socket.on('close', listeners._close = function() {
        reverse_proxy.end();
        detach();
      });

    };

  }
};

exports.HttpProxy = HttpProxy;<commit_msg>'end' event becomes 'close', added more try-catch handling<commit_after>/*
  node-http-proxy.js: http proxy for node.js

  Copyright (c) 2010 Charlie Robbins, Mikeal Rogers, & Marak Squires

  Permission is hereby granted, free of charge, to any person obtaining
  a copy of this software and associated documentation files (the
  "Software"), to deal in the Software without restriction, including
  without limitation the rights to use, copy, modify, merge, publish,
  distribute, sublicense, and/or sell copies of the Software, and to
  permit persons to whom the Software is furnished to do so, subject to
  the following conditions:

  The above copyright notice and this permission notice shall be
  included in all copies or substantial portions of the Software.

  THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND,
  EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF
  MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND
  NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE
  LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION
  OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION
  WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.

*/

var sys = require('sys'),
    http = require('http'),
    events = require('events'),
    pool = require('pool'),
    min = 0,
    max = 100;

// Setup the PoolManager
var manager = pool.createPoolManager();
manager.setMinClients(min);
manager.setMaxClients(max);

exports.createServer = function () {
  var args, callback, port, host;
  args = Array.prototype.slice.call(arguments);
  callback = typeof args[args.length - 1] === 'function' && args.pop();
  if (args[0]) port = args[0];
  if (args[1]) host = args[1];

  var server = http.createServer(function (req, res){
    var proxy = new HttpProxy(req, res);

    proxy.emitter.on('proxy', function (err, body) {
      server.emit('proxy', err, body);
    });

    // If we were passed a callback to process the request
    // or response in some way, then call it.
    if(callback) {
      callback(req, res, proxy);
    }
    else {
      proxy.proxyRequest(port, server);
    }
  });

  // WebSocket support
  server.on('update', function() {
  });

  return server;
};

exports.setMin = function (value) {
  min = value;
  manager.setMinClients(min);
};

exports.setMax = function (value) {
  max = value;
  manager.setMaxClients(max);
};

var HttpProxy = function (req, res, /* optional */ head) {
  this.emitter = new(events.EventEmitter);
  this.events = {};
  this.req = req;
  // If this request is upgrade request
  // No response will be passed
  if (!req.headers.upgrade) {
    this.res = res;
    this.watch(req);
  } else {
    // Second argument will be socket
    this.sock = res;
    this.head = head;
    this.watch(res);
  }
};

HttpProxy.prototype = {
  toArray: function (obj){
    var len = obj.length,
        arr = new Array(len);
    for (var i = 0; i < len; ++i) {
        arr[i] = obj[i];
    }
    return arr;
  },

  watch: function (req) {
    this.events = [];
    var self = this;

    this.onData = function () {
      self.events.push(['data'].concat(self.toArray(arguments)));
    };
    this.onEnd = function () {
      self.events.push(['end'].concat(self.toArray(arguments)));
    };

    req.addListener('data', this.onData);
    req.addListener('end', this.onEnd);
  },

  unwatch: function (req) {
    req.removeListener('data', this.onData);
    req.removeListener('end', this.onEnd);

    // Rebroadcast any events that have been buffered
    for (var i = 0, len = this.events.length; i < len; ++i) {
      req.emit.apply(req, this.events[i]);
    }
  },

  proxyRequest: function (port, server) {
    // Remark: nodeProxy.body exists solely for testability
    var self = this, req = this.req, res = this.res;
    self.body = '';

    // Open new HTTP request to internal resource with will act as a reverse proxy pass
    var p = manager.getPool(port, server);

    p.on('error', function (err) {
      // Remark: We should probably do something here
      // but this is a hot-fix because I don't think 'pool'
      // should be emitting this event.
    });

    p.request(req.method, req.url, req.headers, function (reverse_proxy) {
      // Create an error handler so we can use it temporarily
      var error = function (err) {
        res.writeHead(200, {'Content-Type': 'text/plain'});

        if(req.method !== 'HEAD') {
          res.write('An error has occurred: ' + sys.puts(JSON.stringify(err)));
        }

        res.end();
      };

      // Add a listener for the connection timeout event
      reverse_proxy.addListener('error', error);

      // Add a listener for the reverse_proxy response event
      reverse_proxy.addListener('response', function (response) {
        if (response.headers.connection) {
          if (req.headers.connection) response.headers.connection = req.headers.connection;
          else response.headers.connection = 'close';
        }

        // Set the response headers of the client response
        res.writeHead(response.statusCode, response.headers);

        // Status code = 304
        // No 'data' event and no 'end'
        if (response.statusCode === 304) {
          res.end();
          return;
        }

        // Add event handler for the proxied response in chunks
        response.addListener('data', function (chunk) {
          if(req.method !== 'HEAD') {
            res.write(chunk, 'binary');
            self.body += chunk;
          }
        });

        // Add event listener for end of proxied response
        response.addListener('end', function () {
          // Remark: Emit the end event for testability
          self.emitter.emit('proxy', null, self.body);
          res.end();
        });
      });

      // Chunk the client request body as chunks from the proxied request come in
      req.addListener('data', function (chunk) {
        reverse_proxy.write(chunk, 'binary');
      })

      // At the end of the client request, we are going to stop the proxied request
      req.addListener('end', function () {
        reverse_proxy.end();
        reverse_proxy.removeListener('error', error);
      });

      self.unwatch(req);
    });
  },

  /**
  * WebSocket Tunnel realization
  * Copyright (c) 2010 Fedor Indutny : http://github.com/donnerjack13589
  */
  proxyWebSocketRequest: function (port, server, host /* optional */) {
    var self = this, update = self.update, req = self.req, socket = self.sock,
        head = self.head, headers = new _headers(req.headers), CRLF = '\r\n',
        listeners = {};

    // Will generate clone of headers
    // To not change original
    function _headers(headers) {
      var h = {};
      for (var i in headers) {
        h[i] = headers[i];
      }
      return h;
    }

    // WebSocket requests has
    // method = GET
    if (req.method !== 'GET' || headers.upgrade.toLowerCase() !== 'websocket') {
      // This request is not WebSocket request
      return;
    }

    // Turn of all bufferings
    // For server set KeepAlive
    // For client set encoding
    function _socket(socket, server) {
      socket.setTimeout(0);
      socket.setNoDelay(true);
      if (server) {
        socket.setKeepAlive(true, 0);
      } else {
        socket.setEncoding('utf8');
      }
    }

    // Client socket
    _socket(socket);

    // If host is undefined
    // Get it from headers
    if (!host) {
      host = headers.Host;
    }
    // Remote host address
    var remote_host = server + (port - 80 === 0 ? '' : ':' + port);

    // Change headers
    headers.Host = remote_host;
    headers.Origin = 'http://' + remote_host;

    // Open request
    var p = manager.getPool(port, server);

    p.getClient(function(client) {
      // Based on 'pool/main.js'
      var request = client.request('GET', req.url, headers);

      var errorListener = function (error) {
        p.emit('error', error);
        request.emit('error', error);
        socket.end();
      }

      // Not disconnect on update
      client.on('upgrade', function(request, remote_socket, head) {
        // Prepare socket
        _socket(remote_socket, true);

        // Emit event
        onUpgrade(remote_socket);
      });

      client.on('error', errorListener);
      request.on('response', function (response) {
        response.on('end', function () {
          client.removeListener('error', errorListener);
          client.busy = false;
          p.onFree(client);
        })
      })
      client.busy = true;

      var t;
      request.socket.on('data', t = function(data) {
        // Handshaking

        // Ok, kind of harmfull part of code
        // Socket.IO is sending hash at the end of handshake
        // If protocol = 76
        // But we need to replace 'host' and 'origin' in response
        // So we split data to printable data and to non-printable
        // (Non-printable will come after double-CRLF)
        var sdata = data.toString();

        // Get Printable
        sdata = sdata
                  .substr(0, sdata.search(CRLF + CRLF));

        // Get Non-Printable
        data = data.slice(Buffer.byteLength(sdata), data.length);

        // Replace host and origin
        sdata = sdata
                  .replace(remote_host, host)
                  .replace(remote_host, host);
        try {
          // Write printable
          socket.write(sdata);

          // Write non-printable
          socket.write(data);
        } catch (e) {
          request.end();
          socket.end();
        }

        // Catch socket errors
        socket.on('error', function() {
          request.end();
        });

        // Remove data listener
        request.socket.removeListener('data', t);
      });

      // Write upgrade-head
      try {
        request.write(head);
      } catch(e) {
        request.end();
        socket.end();
      }
      self.unwatch(socket);
    });

    // Request

    function onUpgrade(reverse_proxy) {
      // We're now connected to the server
      // So lets change server socket

      reverse_proxy.on('data', listeners._r_data = function(data) {
        // Pass data to client
        if (socket.writable) {
          try {
            socket.write(data);
          } catch (e) {
            socket.end();
            reverse_proxy.end();
          }
        }
      });

      socket.on('data', listeners._data = function(data){
        // Pass data from client to server
        try {
          reverse_proxy.write(data);
        } catch (e) {
          reverse_proxy.end();
          socket.end();
        }
      });

      // Detach event listeners from reverse_proxy
      function detach() {
        reverse_proxy.removeListener('close', listeners._r_close);
        reverse_proxy.removeListener('data', listeners._r_data);
        socket.removeListener('data', listeners._data);
        socket.removeListener('close', listeners._close);
      }

      // Hook disconnections
      reverse_proxy.on('end', listeners._r_close = function() {
        socket.end();
        detach();
      });

      socket.on('end', listeners._close = function() {
        reverse_proxy.end();
        detach();
      });

    };

  }
};

exports.HttpProxy = HttpProxy;<|endoftext|>


<commit_before>'use strict';

angular.module('angular-jsvat-input', [])

    .directive('jsvat', function (JsVatFactory) {
      return {
        restrict: 'A',
        scope: {
          jsvatResult: '=?'
        },
        require: 'ngModel',
        link: function (scope, element) {
          function makeObj(name) {
            if (!angular.isObject(scope[name])) {
              var value = scope[name];
              scope[name] = {
                value: value
              }
            }
          }

          makeObj('jsvat');

          var invalid = '-jsvat-invalid';
          var valid = '-jsvat-valid';

          function setValidity(isValid) {
            if (isValid) {
              element.addClass(valid);
              element.removeClass(invalid);
            } else {
              element.addClass(invalid);
              element.removeClass(valid);
            }

            modelController.$setValidity('vat', isValid);
          }

          var modelController = element.controller('ngModel');

          scope.checkVAT = function (vat) {
            scope.jsvat = JsVatFactory.checkVAT(vat);
            var isEmpty = scope.jsvat.value === '' || (!scope.jsvat.value && scope.jsvat.value !== '0');
            setValidity(scope.jsvat.isValid || isEmpty);
            //setValidity(scope.jsvat.isValid);
          };

          scope.$watch(function () {
            return modelController.$modelValue;
          }, function (val) {
            scope.checkVAT(val);
          });

        }
      }
    })
;<commit_msg>fixes<commit_after>'use strict';

angular.module('angular-jsvat-input', [])

    .directive('jsvat', function (JsVatFactory) {
      return {
        restrict: 'A',
        scope: {
          jsvat: '=?'
        },
        require: 'ngModel',
        link: function (scope, element) {
          function makeObj(name) {
            if (!angular.isObject(scope[name])) {
              var value = scope[name];
              scope[name] = {
                value: value
              }
            }
          }

          makeObj('jsvat');

          var invalid = '-jsvat-invalid';
          var valid = '-jsvat-valid';

          function setValidity(isValid) {
            if (isValid) {
              element.addClass(valid);
              element.removeClass(invalid);
            } else {
              element.addClass(invalid);
              element.removeClass(valid);
            }

            modelController.$setValidity('vat', isValid);
          }

          var modelController = element.controller('ngModel');

          scope.checkVAT = function (vat) {
            scope.jsvat = JsVatFactory.checkVAT(vat);
            var isEmpty = scope.jsvat.value === '' || (!scope.jsvat.value && scope.jsvat.value !== '0');
            setValidity(scope.jsvat.isValid || isEmpty);
            //setValidity(scope.jsvat.isValid);
          };

          scope.$watch(function () {
            return modelController.$modelValue;
          }, function (val) {
            scope.checkVAT(val);
          });

        }
      }
    })
;<|endoftext|>


<commit_before>// plone integration for textext.
//
// Author: Nathan Van Gheem
// Contact: nathan@vangheem.us
// Version: 1.0
// Depends:
//    ++resource++plone.app.jquery.js
//    ++resource++plone.app.widgets/textext.js
//
// Description:
//
// License:
//
// Copyright (C) 2010 Plone Foundation
//
// This program is free software; you can redistribute it and/or modify it
// under the terms of the GNU General Public License as published by the Free
// Software Foundation; either version 2 of the License.
//
// This program is distributed in the hope that it will be useful, but WITHOUT
// ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or
// FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License for
// more details.
//
// You should have received a copy of the GNU General Public License along with
// this program; if not, write to the Free Software Foundation, Inc., 51
// Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA.
//

/*jshint bitwise:true, curly:true, eqeqeq:true, immed:true, latedef:true,
  newcap:true, noarg:true, noempty:true, nonew:true, plusplus:true,
  undef:true, strict:true, trailing:true, browser:true, evil:true */
/*global define:false */

define([
  'jquery',
  'js/patterns/base',
  'jam/plone-select2/select2',
  'jam/jquery.event.drag/jquery.event.drag',
  'jam/jquery.event.drop/jquery.event.drop'
], function($, Base) {
  "use strict";

  var Select2 = Base.extend({
    name: "select2",
    defaults: {
      separator: ","
    },
    initializeValueMap: function(){
      var self = this;
      // Init Selection ---------------------------------------------
      if (self.options.initvaluemap) {
        self.options.initSelection = function ($el, callback) {
          var data = [], value = $el.val(), seldefaults;

          // Create the initSelection value that contains the default selection,
          // but in a javascript object
          if (typeof(self.options.initvaluemap) === 'string' && self.options.initvaluemap !== '') {
            // if default selection value starts with a '{', then treat the value as
            // a JSON object that needs to be parsed
            if(self.options.initvaluemap[0] === '{') {
              seldefaults = JSON.parse(self.options.initvaluemap);
            }
            // otherwise, treat the value as a list, separated by the defaults.separator value of
            // strings in the format "id:text", and convert it to an object
            else {
              seldefaults = {};
              $(self.options.initvaluemap.split(self.options.separator)).each(function() {
                var selection = this.split(':');
                var id = selection[0];
                var text = selection[1];
                seldefaults[id] = text;
              });
            }
          }

          $(value.split(self.options.separator)).each(function() {
            var text = this;
            if (seldefaults[this]) {
              text = seldefaults[this];
            }
            data.push({id: this, text: text});
          });
          callback(data);
        };
      }
    },
    initializeTags: function(){
      var self = this;
      if (self.options.tags && typeof(self.options.tags) === 'string') {
        if (self.options.tags.substr(0, 1) === '[') {
          self.options.tags = JSON.parse(self.options.tags);
        } else {
          self.options.tags = self.options.tags.split(self.options.separator);
        }
      }
    },
    initializeOrdering: function(){
      var self = this;
      if (self.options.orderable) {
        var formatSelection = function(data, $container){
          return data ? data.text : undefined;
        };
        if(self.options.formatSelection){
          formatSelection = self.options.formatSelection;
        }
        self.options.formatSelection = function(data, $container) {
          $container.parents('li')
            .css({'cursor': 'move'})
            .drag("start", function(e, dd) {
              $(this).addClass('select2-choice-dragging');
              self.$el.select2("onSortStart");
              $.drop({
                tolerance: function(event, proxy, target) {
                  var test = event.pageY > (target.top + target.height / 2);
                  $.data(target.elem, "drop+reorder",
                         test ? "insertAfter" : "insertBefore" );
                  return this.contains(target, [event.pageX, event.pageY]);
                }
              });
            })
            .drag(function(e, dd) {
              var drop = dd.drop[0],
              method = $.data(drop || {}, "drop+reorder");
              if (drop && (drop !== dd.current || method !== dd.method)){
                $(this)[method](drop);
                dd.current = drop;
                dd.method = method;
                dd.update();
              }
            })
            .drag("end", function(e, dd) {
              $(this).removeClass('select2-choice-dragging');
              self.$el.select2("onSortEnd");
            })
            .drop("init", function(e, dd ) {
              return !(this !== dd.drag);
            });
          return formatSelection(data, $container);
        };
      }
    },
    init: function() {
      var self = this;

      self.initializeValueMap();
      self.initializeTags();

      if (self.options.ajax || self.options.ajaxvocabulary) {
        if(self.options.ajaxvocabulary) {
          self.options.multiple = true;
          self.options.ajax = self.options.ajax || {};
          self.options.ajax.url = self.options.ajaxvocabulary;
          self.options.initSelection = function ($el, callback) {
            var data = [], value = $el.val();
            $(value.split(self.options.separator)).each(function () {
              data.push({id: this, text: this});
            });
            callback(data);
          };
        }

        var query_term = '';
        self.options.ajax = $.extend({
          quietMillis: 300,
          data: function (term, page) {
            query_term = term;
            return {
              query: term,
              page_limit: 10,
              page: page
            };
          },
          results: function (data, page) {
            var results = data.results;
            if (self.options.ajaxvocabulary) {
              var data_ids = [];
              $.each(data.results, function(i, item) {
                data_ids.push(item.id);
              });
              results = [];
              if (query_term !== ''  && $.inArray(query_term, data_ids) === -1) {
                results.push({id:query_term, text:query_term});
              }
              $.each(data.results, function(i, item) {
                if (self.options.ajaxvocabulary) {
                  results.push({ id: item.text, text: item.text });
                } else {
                  results.push(item);
                }
              });
            }
            return { results: results };
          }
        }, self.options.ajax);
      }

      self.initializeOrdering();
      self.$el.select2(self.options);
      self.$el.parent().off('close.modal.patterns');
    }
  });

  return Select2;

});
<commit_msg>fix ordering<commit_after>// plone integration for textext.
//
// Author: Nathan Van Gheem
// Contact: nathan@vangheem.us
// Version: 1.0
// Depends:
//    ++resource++plone.app.jquery.js
//    ++resource++plone.app.widgets/textext.js
//
// Description:
//
// License:
//
// Copyright (C) 2010 Plone Foundation
//
// This program is free software; you can redistribute it and/or modify it
// under the terms of the GNU General Public License as published by the Free
// Software Foundation; either version 2 of the License.
//
// This program is distributed in the hope that it will be useful, but WITHOUT
// ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or
// FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License for
// more details.
//
// You should have received a copy of the GNU General Public License along with
// this program; if not, write to the Free Software Foundation, Inc., 51
// Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA.
//

/*jshint bitwise:true, curly:true, eqeqeq:true, immed:true, latedef:true,
  newcap:true, noarg:true, noempty:true, nonew:true, plusplus:true,
  undef:true, strict:true, trailing:true, browser:true, evil:true */
/*global define:false */

define([
  'jquery',
  'js/patterns/base',
  'jam/plone-select2/select2',
  'jam/jquery.event.drag/jquery.event.drag',
  'jam/jquery.event.drop/jquery.event.drop'
], function($, Base) {
  "use strict";

  var Select2 = Base.extend({
    name: "select2",
    defaults: {
      separator: ","
    },
    initializeValueMap: function(){
      var self = this;
      // Init Selection ---------------------------------------------
      if (self.options.initvaluemap) {
        self.options.initSelection = function ($el, callback) {
          var data = [], value = $el.val(), seldefaults;

          // Create the initSelection value that contains the default selection,
          // but in a javascript object
          if (typeof(self.options.initvaluemap) === 'string' && self.options.initvaluemap !== '') {
            // if default selection value starts with a '{', then treat the value as
            // a JSON object that needs to be parsed
            if(self.options.initvaluemap[0] === '{') {
              seldefaults = JSON.parse(self.options.initvaluemap);
            }
            // otherwise, treat the value as a list, separated by the defaults.separator value of
            // strings in the format "id:text", and convert it to an object
            else {
              seldefaults = {};
              $(self.options.initvaluemap.split(self.options.separator)).each(function() {
                var selection = this.split(':');
                var id = selection[0];
                var text = selection[1];
                seldefaults[id] = text;
              });
            }
          }

          $(value.split(self.options.separator)).each(function() {
            var text = this;
            if (seldefaults[this]) {
              text = seldefaults[this];
            }
            data.push({id: this, text: text});
          });
          callback(data);
        };
      }
    },
    initializeTags: function(){
      var self = this;
      if (self.options.tags && typeof(self.options.tags) === 'string') {
        if (self.options.tags.substr(0, 1) === '[') {
          self.options.tags = JSON.parse(self.options.tags);
        } else {
          self.options.tags = self.options.tags.split(self.options.separator);
        }
      }
    },
    initializeOrdering: function(){
      var self = this;
      if (self.options.orderable) {
        var formatSelection = function(data, $container){
          return data ? data.text : undefined;
        };
        if(self.options.formatSelection){
          formatSelection = self.options.formatSelection;
        }

        self.options.formatSelection = function(data, $container) {
          $container.parents('li')
            .css({'cursor': 'move'})
            .drag("start", function(e, dd) {
              $(this).addClass('select2-choice-dragging');
              self.$el.select2("onSortStart");
              $.drop({
                tolerance: function(event, proxy, target) {
                  var test = event.pageY > (target.top + target.height / 2);
                  $.data(target.elem, "drop+reorder",
                         test ? "insertAfter" : "insertBefore" );
                  return this.contains(target, [event.pageX, event.pageY]);
                }
              });
            })
            .drag(function(e, dd) {
              var drop = dd.drop[0],
              method = $.data(drop || {}, "drop+reorder");
              /* XXX Cannot use triple equals here */
              if (drop && (drop != dd.current || method != dd.method)){
                $(this)[method](drop);
                dd.current = drop;
                dd.method = method;
                dd.update();
              }
            })
            .drag("end", function(e, dd) {
              $(this).removeClass('select2-choice-dragging');
              self.$el.select2("onSortEnd");
            })
            .drop("init", function(e, dd ) {
              return !(this == dd.drag);
            });
          return formatSelection(data, $container);
        };
      }
    },
    init: function() {
      var self = this;

      self.initializeValueMap();
      self.initializeTags();

      if (self.options.ajax || self.options.ajaxvocabulary) {
        if(self.options.ajaxvocabulary) {
          self.options.multiple = true;
          self.options.ajax = self.options.ajax || {};
          self.options.ajax.url = self.options.ajaxvocabulary;
          self.options.initSelection = function ($el, callback) {
            var data = [], value = $el.val();
            $(value.split(self.options.separator)).each(function () {
              data.push({id: this, text: this});
            });
            callback(data);
          };
        }

        var query_term = '';
        self.options.ajax = $.extend({
          quietMillis: 300,
          data: function (term, page) {
            query_term = term;
            return {
              query: term,
              page_limit: 10,
              page: page
            };
          },
          results: function (data, page) {
            var results = data.results;
            if (self.options.ajaxvocabulary) {
              var data_ids = [];
              $.each(data.results, function(i, item) {
                data_ids.push(item.id);
              });
              results = [];
              if (query_term !== ''  && $.inArray(query_term, data_ids) === -1) {
                results.push({id:query_term, text:query_term});
              }
              $.each(data.results, function(i, item) {
                if (self.options.ajaxvocabulary) {
                  results.push({ id: item.text, text: item.text });
                } else {
                  results.push(item);
                }
              });
            }
            return { results: results };
          }
        }, self.options.ajax);
      }

      self.initializeOrdering();
      self.$el.select2(self.options);
      self.$el.parent().off('close.modal.patterns');
    }
  });

  return Select2;

});
<|endoftext|>


<commit_before>'use strict';
var Class           = require('appolo').Class,
    path            = require('path'),
    gaze            = require('gaze');

module.exports = Class.define({

    $config: {
        id: 'watcher',
        singleton: false,
        inject: ['env']
    },

    constructor: function(root, options, callback) {
        this._FSwatcher = null;
        this._timer = null;
        this._changes = [];
        this.callback = callback;
        this.path = root;

        // any file in project
        this._options = path.resolve(this.path) + '/**/*';

        if(options instanceof Array) {
            this._setOptions(options);
        }
    },

    start: function() {
        if(!this._FSwatcher) {
            this._FSwatcher = gaze(this._options, this._onGazeWatcherStart.bind(this));
        }
    },

    stop: function() {
        if(this._FSwatcher) {
            this._FSwatcher.close();
            this._FSwatcher = null;
        }
    },

    _onGazeWatcherStart: function() {
        this._FSwatcher.on('all', this._onWatcherEvent.bind(this));
    },

    _onWatcherEvent: function(event, file) {

        if(!this._timer) {
            this._changes.push({ event: event, path: file });
            this._timer = setTimeout(this._fireChangeEvent.bind(this, event, file), this.env.watcherTurtle);
        } else {
            clearTimeout(this._timer);
            this._timer = null;
            this._onWatcherEvent(event, file);
        }

    },

    _setOptions: function(options) {
        this._options = [];
        for(var i = 0, len = options.length; i < len; i ++) {
            this._options.push(path.resolve(this.path) + '/' + options[i]);
        }
    },

    _fireChangeEvent: function(event, file) {
        this._timer = null;
        this.callback && this.callback(this._changes);
        this._changes = [];
    }
});<commit_msg>commit<commit_after>'use strict';
var Class           = require('appolo').Class,
    path            = require('path'),
    gaze            = require('gaze');

module.exports = Class.define({

    $config: {
        id: 'watcher',
        singleton: false,
        inject: ['env']
    },

    constructor: function(root, options, callback) {
        this._FSwatcher = null;
        this._timer = null;
        this._changes = [];
        this.callback = callback;
        this.path = root;

        // any file in project
        this._options = path.resolve(this.path) + '/**/*';

        if(options instanceof Array) {
            this._setOptions(options);
        }
    },

    start: function() {
        if(!this._FSwatcher) {
            this._FSwatcher = gaze(this._options, this._onGazeWatcherStart.bind(this));
        }
    },

    stop: function() {
        if(this._FSwatcher) {
            this._FSwatcher.close();
            this._FSwatcher = null;
        }
    },

    _onGazeWatcherStart: function() {
        this._FSwatcher.on('all', this._onWatcherEvent.bind(this));
    },

    _onWatcherEvent: function(event, file) {

        if(!this._timer) {
            this._changes.push({ event: event, path: file });
            this._timer = setTimeout(this._fireChangeEvent.bind(this, event, file), this.env.watcherTurtle);
        } else {
            clearTimeout(this._timer);
            this._timer = null;
            this._onWatcherEvent(event, file);
        }

    },

    _setOptions: function(options) {
        this._options = [];
        for(var i = 0, len = options.length; i < len; i ++) {
            this._options.push(path.resolve(this.path, options[i]));
        }
    },

    _fireChangeEvent: function(event, file) {
        this._timer = null;
        this.callback && this.callback(this._changes);
        this._changes = [];
    }
});<|endoftext|>


<commit_before>/*
 * == BSD2 LICENSE ==
 * Copyright (c) 2014, Tidepool Project
 *
 * This program is free software; you can redistribute it and/or modify it under
 * the terms of the associated License, which is identical to the BSD 2-Clause
 * License as published by the Open Source Initiative at opensource.org.
 *
 * This program is distributed in the hope that it will be useful, but WITHOUT
 * ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS
 * FOR A PARTICULAR PURPOSE. See the License for more details.
 *
 * You should have received a copy of the License along with this program; if
 * not, you can obtain one from Tidepool Project at tidepool.org.
 * == BSD2 LICENSE ==
 */

var d3 = require('../../lib/').d3;
var _ = require('../../lib/')._;

var scales = {
  MAX_CBG: 401,

  bg: function(data, pool, pad) {
    var ext = d3.extent(data, function(d) { return d.value; });
    if (ext[1] > this.MAX_CBG) {
      return d3.scale.linear()
        .domain([0, this.MAX_CBG])
        .range([pool.height() - pad, pad])
        .clamp();
    }
    else {
      return d3.scale.linear()
        .domain([0, ext[1]])
        .range([pool.height() - pad, pad]);
    }
  },
  bgLog: function(data, pool, pad) {
    var ext = d3.extent(data, function(d) { return d.value; });
    if (ext[1] > this.MAX_CBG) {
      return d3.scale.log()
        .domain(ext[0], this.MAX_CBG)
        .range([pool.height() - pad, pad])
        .clamp();
    }
    else {
      return d3.scale.log()
        .domain(ext)
        .range([pool.height() - pad, pad]);
    }
  },
  bgTicks: function(data) {
    var defaultTicks = [40, 80, 120, 180, 300];
    // check for data that looks like mmol and generation of different defaultTicks should go here
    var ext = d3.extent(data, function(d) { return d.value; });
    // if the min of our data is greater than any of the defaultTicks, remove that tick
    defaultTicks.forEach(function(tick) {
      if (ext[0] > tick) {
        defaultTicks.shift();
      }
    });
    defaultTicks.reverse();
    defaultTicks.forEach(function(tick) {
      if (ext[1] < tick) {
        defaultTicks.shift();
      }
    });
    return defaultTicks.reverse();
  },
  carbs: function(data, pool) {
    var scale = d3.scale.linear()
      .domain([0, d3.max(data, function(d) { return d.value; })])
      .range([0, 0.475 * pool.height()]);
    return scale;
  },
  bolus: function(data, pool) {
    var scale = d3.scale.linear()
      .domain([0, d3.max(data, function(d) { return d.value; })])
      .range([pool.height(), 0.525 * pool.height()]);
    return scale;
  },
  basal: function(data, pool) {
    var scale = d3.scale.linear()
      .domain([0, d3.max(data, function(d) { return d.value; }) * 1.1])
      .rangeRound([pool.height(), 0]);
    return scale;
  }
};

module.exports = scales;
<commit_msg>additional fixes for BG scales, uncaught because of typo preventing 'if' clause from ever being satisfied<commit_after>/*
 * == BSD2 LICENSE ==
 * Copyright (c) 2014, Tidepool Project
 *
 * This program is free software; you can redistribute it and/or modify it under
 * the terms of the associated License, which is identical to the BSD 2-Clause
 * License as published by the Open Source Initiative at opensource.org.
 *
 * This program is distributed in the hope that it will be useful, but WITHOUT
 * ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS
 * FOR A PARTICULAR PURPOSE. See the License for more details.
 *
 * You should have received a copy of the License along with this program; if
 * not, you can obtain one from Tidepool Project at tidepool.org.
 * == BSD2 LICENSE ==
 */

var d3 = require('../../lib/').d3;
var _ = require('../../lib/')._;

var scales = {
  MAX_CBG: 401,

  bg: function(data, pool, pad) {
    var ext = d3.extent(data, function(d) { return d.value; });
    if (ext[1] > this.MAX_CBG) {
      return d3.scale.linear()
        .domain([0, this.MAX_CBG])
        .range([pool.height() - pad, pad])
        .clamp(true);
    }
    else {
      return d3.scale.linear()
        .domain([0, ext[1]])
        .range([pool.height() - pad, pad]);
    }
  },
  bgLog: function(data, pool, pad) {
    var ext = d3.extent(data, function(d) { return d.value; });
    if (ext[1] > this.MAX_CBG) {
      return d3.scale.log()
        .domain([ext[0], this.MAX_CBG])
        .range([pool.height() - pad, pad])
        .clamp(true);
    }
    else {
      return d3.scale.log()
        .domain(ext)
        .range([pool.height() - pad, pad]);
    }
  },
  bgTicks: function(data) {
    var defaultTicks = [40, 80, 120, 180, 300];
    var ext = d3.extent(data, function(d) { return d.value; });
    // if the min of our data is greater than any of the defaultTicks, remove that tick
    defaultTicks.forEach(function(tick) {
      if (ext[0] > tick) {
        defaultTicks.shift();
      }
    });
    defaultTicks.reverse();
    // same thing for max
    defaultTicks.forEach(function(tick) {
      if (ext[1] < tick) {
        defaultTicks.shift();
      }
    });
    return defaultTicks.reverse();
  },
  carbs: function(data, pool) {
    var scale = d3.scale.linear()
      .domain([0, d3.max(data, function(d) { return d.value; })])
      .range([0, 0.475 * pool.height()]);
    return scale;
  },
  bolus: function(data, pool) {
    var scale = d3.scale.linear()
      .domain([0, d3.max(data, function(d) { return d.value; })])
      .range([pool.height(), 0.525 * pool.height()]);
    return scale;
  },
  basal: function(data, pool) {
    var scale = d3.scale.linear()
      .domain([0, d3.max(data, function(d) { return d.value; }) * 1.1])
      .rangeRound([pool.height(), 0]);
    return scale;
  }
};

module.exports = scales;
<|endoftext|>


<commit_before>/**
 Copyright 2014 Gordon Williams (gw@pur3.co.uk)

 This Source Code is subject to the terms of the Mozilla Public
 License, v2.0. If a copy of the MPL was not distributed with this
 file, You can obtain one at http://mozilla.org/MPL/2.0/.

 ------------------------------------------------------------------
  An Example Plugin
 ------------------------------------------------------------------
**/
"use strict";
(function(){

  function init() {
    Espruino.Core.Config.add("FONT_SIZE", {
      section : "General",
      name : "Font Size",
      description : "The size of font used in the Terminal and Code Editor windows",
      type : {8:8,10:10,12:12,14:14,18:18,24:24,32:32},
      defaultValue : 12,
      onChange :setFontSize
    });

    setFontSize(Espruino.Config.FONT_SIZE);
  }

  function setFontSize(size) {
    $("#terminal,.CodeMirror").css("font-size", size+"px");
  }

  Espruino.Plugins.FontSize = {
    init : init,
  };
}());<commit_msg>fix: refresh CodeMirror on font size change<commit_after>/**
 Copyright 2014 Gordon Williams (gw@pur3.co.uk)

 This Source Code is subject to the terms of the Mozilla Public
 License, v2.0. If a copy of the MPL was not distributed with this
 file, You can obtain one at http://mozilla.org/MPL/2.0/.

 ------------------------------------------------------------------
  An Example Plugin
 ------------------------------------------------------------------
**/
"use strict";
(function(){

  function init() {
    Espruino.Core.Config.add("FONT_SIZE", {
      section : "General",
      name : "Font Size",
      description : "The size of font used in the Terminal and Code Editor windows",
      type : {8:8,10:10,12:12,14:14,18:18,24:24,32:32},
      defaultValue : 12,
      onChange :setFontSize
    });

    setFontSize(Espruino.Config.FONT_SIZE);
  }

  function setFontSize(size) {
    $("#terminal,.CodeMirror").css("font-size", size+"px");
    Espruino.Core.EditorJavaScript.getCodeMirror().refresh();
  }

  Espruino.Plugins.FontSize = {
    init : init,
  };
}());<|endoftext|>


<commit_before>/**
 * Competence class
 */
function Competence(viewmodel, id, code, name, weight, locked, subcompetences) {
    return {
        id: ko.observable(id),
        code: ko.observable(code),
        name: ko.observable(name),
        weight: ko.observable(weight),
        locked: false,
        subcompetences: ko.observableArray(subcompetences),

        addSubCompetence: function() {
            this.subcompetences.push(new SubCompetence(this));

            /*var total = 100;
            alert(total);
            console.log(this.subcompetences);
            for(var sub in this.subcompetences){
                alert(sub);
                sub.calculateWeight(100);
                total -= sub.weight;
                alert(total);
            }*/
        },

        removeThis: function() {
            viewmodel.removeCompetence(this);
        },

        toggleLock: function(data, event){
            if(this.locked == true)
            {
                $(event.target).addClass("icon-unlock").removeClass("icon-lock");
                this.locked = false;
            }
            else
            {
                $(event.target).addClass("icon-lock").removeClass("icon-unlock");
                this.locked = true;
            }
        },

        removeSubCompetence: function(subCompetence) {
            this.subcompetences.remove(subCompetence);
        }
    };

}

/**
 * SubCompetence class
 */
function SubCompetence(parent, id, code, name, weight, locked, indicators) {
    return {
        id: ko.observable(id),
        code: ko.observable(code),
        name: ko.observable(name),
        weight: ko.observable(weight),
        locked: ko.observable(locked),
        indicators: ko.observableArray(indicators),

        addIndicator: function() {
            this.indicators.push(new Indicator(this));
        },

        /*calculateWeight: function(total){
            this.weight = total;
        },*/

        removeThis: function() {
            parent.removeSubCompetence(this);
        },

        toggleLock: function(data, event){
            if(this.locked == true)
            {
                $(event.target).addClass("icon-unlock").removeClass("icon-lock");
                this.locked = false;
            }
            else
            {
                $(event.target).addClass("icon-lock").removeClass("icon-unlock");
                this.locked = true;
            }
        },

        removeIndicator: function(indicator) {
            this.indicators.remove(indicator);
        }

    };
}

/**
 * Indicator class
 */
function Indicator(parent, id, name, weight, locked, description) {
    return {
        id: ko.observable(id),
        name: ko.observable(name),
        weight: ko.observable(weight),
        locked: ko.observable(locked),
        description : ko.observable(description),

        removeThis: function() {
            parent.removeIndicator(this);
        },

        toggleLock: function(data, event){
            if(this.locked == true)
            {
                $(event.target).addClass("icon-unlock").removeClass("icon-lock");
                this.locked = false;
            }
            else
            {
                $(event.target).addClass("icon-lock").removeClass("icon-unlock");
                this.locked = true;
            }
        }
    };
}

// View model for the courses page
function pageViewModel(gvm) {
    // projecttitle
    gvm.projecttitle = ko.observable("");
    //gvm.competences = 0;
    gvm.subcomp = 0;

    // Page specific i18n bindings
    gvm.title = ko.computed(function (){i18n.setLocale(gvm.lang()); return gvm.app() + ' - ' + i18n.__("ProjectTitle") + ": " + gvm.projecttitle();}, gvm);
    gvm.pageHeader = ko.observable("Project");
    gvm.projectname = ko.computed(function(){i18n.setLocale(gvm.lang()); return i18n.__("ProjectName");}, gvm);

    gvm.addCompetenceBtn = ko.computed(function(){i18n.setLocale(gvm.lang()); return i18n.__("AddCompetence");}, gvm);
    gvm.savePage = ko.computed(function(){i18n.setLocale(gvm.lang()); return i18n.__("SaveBtn");}, gvm);

    gvm.competences = ko.observableArray([]);

    gvm.addCompetence = function() {
        gvm.competences.push(new Competence(this));

        // Update automated weight calculation

        var lockedPercent = 0;
        var nrOfUnlocked = 0;

        console.log("Array lenght: " + gvm.competences().length);

        for(var index = 0; index < gvm.competences().length; index++)
        {
            if(gvm.competences()[index].locked == true)
            {
                lockedPercent += gvm.competences()[index].weight;
            }
            else
            {
                nrOfUnlocked++;
            }
        }
        console.log("Unlocked: " + nrOfUnlocked);
        console.log("Locked Percent: " + lockedPercent);

        var remainingPercent = 100 - lockedPercent;

        var percentPerCompetence = remainingPercent / nrOfUnlocked;

        console.log("Every unlocked should get: " + percentPerCompetence);
        console.log(gvm.competences()[0].locked);

        for(var index = 0; index < gvm.competences().length; index++)
        {
            if(gvm.competences()[index].locked == false)
            {
                gvm.competences()[index].weight(percentPerCompetence);
            }
        }

        ko.utils.arrayForEach(gvm.competences, function(competence){
            console.log(competence.weight);
            competence.weight(percent);
        });
    };

    gvm.removeCompetence = function(competence) {
        gvm.competences.remove(competence);
    }

    gvm.updateCompetence = function(id, code, description, max, weight) {
        var comp = new Competence(this, id, code, description, weight);
        gvm.competences.push(comp);
        return comp;
    }

    gvm.clearStructure = function() {
        gvm.competences.destroyAll();
    }
}

/**
 * Push the current project state to the database
 * @returns {undefined}
 */
function saveProjectStructure() {
    $.ajax({
       type: "POST",
       url: "/api/projectstructure/" + projectid,
       data: ko.toJSON(viewModel.competences),
       success: function(){
           // TODO make multilangual and with modals
           alert("Saved projectstructure to server");

           fetchProjectStructure();
       }
    });
}

function fetchProjectStructure() {
    viewModel.clearStructure();

    $.getJSON("/api/projectstructure/" + projectid, function(data){
        $.each(data, function(i, item){
            var competence = viewModel.updateCompetence(item.id, item.code, item.description, item.max, item.weight);

            $.each(item.subcompetences, function(i, subcomp){
               var subcompetence = new SubCompetence(competence, subcomp.id, subcomp.code, subcomp.description, subcomp.weight);
               competence.subcompetences.push(subcompetence);

               $.each(subcomp.indicators, function(i, indic){
                  subcompetence.indicators.push(new Indicator(subcompetence, indic.id, indic.name, indic.description));
               });
            });
        })
    });
}

function initPage() {
    fetchProjectStructure();

    $(".addCompetenceBtn").click(function() {
        viewModel.addCompetence();
    });

    $(".savePageBtn").click(function(){
        saveProjectStructure();
    });
}
<commit_msg>lock icons<commit_after>/**
 * Competence class
 */
function Competence(viewmodel, id, code, name, weight, locked, subcompetences) {
    return {
        id: ko.observable(id),
        code: ko.observable(code),
        name: ko.observable(name),
        weight: ko.observable(weight),
        locked: false,
        subcompetences: ko.observableArray(subcompetences),

        addSubCompetence: function() {
            this.subcompetences.push(new SubCompetence(this));

            /*var total = 100;
            alert(total);
            console.log(this.subcompetences);
            for(var sub in this.subcompetences){
                alert(sub);
                sub.calculateWeight(100);
                total -= sub.weight;
                alert(total);
            }*/
        },

        removeThis: function() {
            viewmodel.removeCompetence(this);
        },

        toggleLock: function(data, event){
            if(this.locked == true)
            {
                $(event.target).addClass("icon-unlock").removeClass("icon-lock");
                this.locked = false;
            }
            else
            {
                $(event.target).addClass("icon-lock").removeClass("icon-unlock");
                this.locked = true;
            }
        },

        removeSubCompetence: function(subCompetence) {
            this.subcompetences.remove(subCompetence);
        }
    };

}

/**
 * SubCompetence class
 */
function SubCompetence(parent, id, code, name, weight, locked, indicators) {
    return {
        id: ko.observable(id),
        code: ko.observable(code),
        name: ko.observable(name),
        weight: ko.observable(weight),
        locked: ko.observable(locked),
        indicators: ko.observableArray(indicators),

        addIndicator: function() {
            this.indicators.push(new Indicator(this));
        },

        /*calculateWeight: function(total){
            this.weight = total;
        },*/

        removeThis: function() {
            parent.removeSubCompetence(this);
        },

        toggleLock: function(data, event){
            if(this.locked == true)
            {
                $(event.target).addClass("icon-unlock").removeClass("icon-lock");
                this.locked = false;
            }
            else
            {
                $(event.target).addClass("icon-lock").removeClass("icon-unlock");
                this.locked = true;
            }
        },

        removeIndicator: function(indicator) {
            this.indicators.remove(indicator);
        }

    };
}

/**
 * Indicator class
 */
function Indicator(parent, id, name, weight, locked, description) {
    return {
        id: ko.observable(id),
        name: ko.observable(name),
        weight: ko.observable(weight),
        locked: ko.observable(locked),
        description : ko.observable(description),

        removeThis: function() {
            parent.removeIndicator(this);
        },

        toggleLock: function(data, event){
            if(this.locked == true)
            {
                $(event.target).addClass("icon-unlock").removeClass("icon-lock");
                this.locked = false;
            }
            else
            {
                $(event.target).addClass("icon-lock").removeClass("icon-unlock");
                this.locked = true;
            }
        }
    };
}

// View model for the courses page
function pageViewModel(gvm) {
    // projecttitle
    gvm.projecttitle = ko.observable("");
    //gvm.competences = 0;
    gvm.subcomp = 0;

    // Page specific i18n bindings
    gvm.title = ko.computed(function (){i18n.setLocale(gvm.lang()); return gvm.app() + ' - ' + i18n.__("ProjectTitle") + ": " + gvm.projecttitle();}, gvm);
    gvm.pageHeader = ko.observable("Project");
    gvm.projectname = ko.computed(function(){i18n.setLocale(gvm.lang()); return i18n.__("ProjectName");}, gvm);

    gvm.addCompetenceBtn = ko.computed(function(){i18n.setLocale(gvm.lang()); return i18n.__("AddCompetence");}, gvm);
    gvm.savePage = ko.computed(function(){i18n.setLocale(gvm.lang()); return i18n.__("SaveBtn");}, gvm);

    gvm.competences = ko.observableArray([]);

    gvm.addCompetence = function() {
        gvm.competences.push(new Competence(this));

        // Update automated weight calculation

        var lockedPercent = 0;
        var nrOfUnlocked = 0;

        console.log("Array lenght: " + gvm.competences().length);

        for(var index = 0; index < gvm.competences().length; index++)
        {
            if(gvm.competences()[index].locked == true)
            {
                lockedPercent = lockedPercent + gvm.competences()[index].weight;
            }
            else
            {
                nrOfUnlocked++;
            }
        }
        console.log("Unlocked: " + nrOfUnlocked);
        console.log("Locked Percent: " + lockedPercent);

        var remainingPercent = 100 - lockedPercent;

        var percentPerCompetence = remainingPercent / nrOfUnlocked;

        console.log("Every unlocked should get: " + percentPerCompetence);
        console.log(gvm.competences()[0].locked);

        for(var index = 0; index < gvm.competences().length; index++)
        {
            if(gvm.competences()[index].locked == false)
            {
                gvm.competences()[index].weight(percentPerCompetence);
            }
        }

        ko.utils.arrayForEach(gvm.competences, function(competence){
            console.log(competence.weight);
            competence.weight(percent);
        });
    };

    gvm.removeCompetence = function(competence) {
        gvm.competences.remove(competence);
    }

    gvm.updateCompetence = function(id, code, description, max, weight) {
        var comp = new Competence(this, id, code, description, weight);
        gvm.competences.push(comp);
        return comp;
    }

    gvm.clearStructure = function() {
        gvm.competences.destroyAll();
    }
}

/**
 * Push the current project state to the database
 * @returns {undefined}
 */
function saveProjectStructure() {
    $.ajax({
       type: "POST",
       url: "/api/projectstructure/" + projectid,
       data: ko.toJSON(viewModel.competences),
       success: function(){
           // TODO make multilangual and with modals
           alert("Saved projectstructure to server");

           fetchProjectStructure();
       }
    });
}

function fetchProjectStructure() {
    viewModel.clearStructure();

    $.getJSON("/api/projectstructure/" + projectid, function(data){
        $.each(data, function(i, item){
            var competence = viewModel.updateCompetence(item.id, item.code, item.description, item.max, item.weight);

            $.each(item.subcompetences, function(i, subcomp){
               var subcompetence = new SubCompetence(competence, subcomp.id, subcomp.code, subcomp.description, subcomp.weight);
               competence.subcompetences.push(subcompetence);

               $.each(subcomp.indicators, function(i, indic){
                  subcompetence.indicators.push(new Indicator(subcompetence, indic.id, indic.name, indic.description));
               });
            });
        })
    });
}

function initPage() {
    fetchProjectStructure();

    $(".addCompetenceBtn").click(function() {
        viewModel.addCompetence();
    });

    $(".savePageBtn").click(function(){
        saveProjectStructure();
    });
}
<|endoftext|>


<commit_before>/**
 * Competence class
 */
function Competence(viewmodel, id, code, name, weight, subcompetences) {
    return {
        id: ko.observable(id),
        code: ko.observable(code),
        name: ko.observable(name),
        weight: ko.observable(weight),
        subcompetences: ko.observableArray(subcompetences),

        addSubCompetence: function() {
            this.subcompetences.push(new SubCompetence(this));
        },

        removeThis: function() {
            viewmodel.removeCompetence(this);
        },

        toggleLock: function(){
            alert(weight);
        },

        removeSubCompetence: function(subCompetence) {
            this.subcompetences.remove(subCompetence);
        }
    };

}

/**
 * SubCompetence class
 */
function SubCompetence(parent, id, code, name, weight, indicators) {
    return {
        id: ko.observable(id),
        code: ko.observable(code),
        name: ko.observable(name),
        weight: ko.observable(weight),
        indicators: ko.observableArray(indicators),

        addIndicator: function() {
            this.indicators.push(new Indicator(this));
        },

        removeThis: function() {
            parent.removeSubCompetence(this);
        },

        toggleLock: function(){
            alert((parseInt(parent.weight - this.weight)));
        },

        removeIndicator: function(indicator) {
            this.indicators.remove(indicator);
        }
    };
}

/**
 * Indicator class
 */
function Indicator(parent, id, name, description) {
    return {
        id: ko.observable(id),
        name: ko.observable(name),
        description : ko.observable(description),

        removeThis: function() {
            parent.removeIndicator(this);
        }
    };
}

// View model for the courses page
function pageViewModel(gvm) {
    // projecttitle
    gvm.projecttitle = ko.observable("");
    gvm.competences = 0;
    gvm.subcomp = 0;

    // Page specific i18n bindings
    gvm.title = ko.computed(function (){i18n.setLocale(gvm.lang()); return gvm.app() + ' - ' + i18n.__("ProjectTitle") + ": " + gvm.projecttitle();}, gvm);
    gvm.pageHeader = ko.observable("Project");
    gvm.projectname = ko.computed(function(){i18n.setLocale(gvm.lang()); return i18n.__("ProjectName");}, gvm);

    gvm.addCompetenceBtn = ko.computed(function(){i18n.setLocale(gvm.lang()); return i18n.__("AddCompetence");}, gvm);
    gvm.savePage = ko.computed(function(){i18n.setLocale(gvm.lang()); return i18n.__("SaveBtn");}, gvm);

    gvm.competences = ko.observableArray([]);

    gvm.addCompetence = function() {
        gvm.competences.push(new Competence(this));

        // Update automated weight calculation
        var size = gvm.competences.length;
        var percent = 100/size;
        gvm.competences[0] = 50;
        console.log(this.weight);

        ko.utils.arrayForEach(gvm.competences, function(competence){
            competence.weight(percent);
            alert(percent);
        });
    };

    gvm.removeCompetence = function(competence) {
        gvm.competences.remove(competence);
    }

    gvm.updateCompetence = function(id, code, description, max, weight) {
        var comp = new Competence(this, id, code, description, weight);
        gvm.competences.push(comp);
        return comp;
    }

    gvm.clearStructure = function() {
        gvm.competences.destroyAll();
    }
}

/**
 * Push the current project state to the database
 * @returns {undefined}
 */
function saveProjectStructure() {
    $.ajax({
       type: "POST",
       url: "/api/projectstructure/" + projectid,
       data: ko.toJSON(viewModel.competences),
       success: function(){
           // TODO make multilangual and with modals
           alert("Saved projectstructure to server");

           fetchProjectStructure();
       }
    });
}

function fetchProjectStructure() {
    viewModel.clearStructure();

    $.getJSON("/api/projectstructure/" + projectid, function(data){
        $.each(data, function(i, item){
            var competence = viewModel.updateCompetence(item.id, item.code, item.description, item.max, item.weight);

            $.each(item.subcompetences, function(i, subcomp){
               var subcompetence = new SubCompetence(competence, subcomp.id, subcomp.code, subcomp.description, subcomp.weight);
               competence.subcompetences.push(subcompetence);

               $.each(subcomp.indicators, function(i, indic){
                  subcompetence.indicators.push(new Indicator(subcompetence, indic.id, indic.name, indic.description));
               });
            });
        })
    });
}

function initPage() {
    fetchProjectStructure();

    $(".addCompetenceBtn").click(function() {
        viewModel.addCompetence();
    });

    $(".savePageBtn").click(function(){
        saveProjectStructure();
    });

    $(".locked").click(function() {
        setLocked();
    });
}
<commit_msg>lock weight<commit_after>/**
 * Competence class
 */
function Competence(viewmodel, id, code, name, weight, subcompetences) {
    return {
        id: ko.observable(id),
        code: ko.observable(code),
        name: ko.observable(name),
        weight: ko.observable(weight),
        subcompetences: ko.observableArray(subcompetences),

        addSubCompetence: function() {
            this.subcompetences.push(new SubCompetence(this));
        },

        removeThis: function() {
            viewmodel.removeCompetence(this);
        },

        toggleLock: function(){
            alert(weight);
        },

        removeSubCompetence: function(subCompetence) {
            this.subcompetences.remove(subCompetence);
        }
    };

}

/**
 * SubCompetence class
 */
function SubCompetence(parent, id, code, name, weight, indicators) {
    return {
        id: ko.observable(id),
        code: ko.observable(code),
        name: ko.observable(name),
        weight: ko.observable(weight),
        indicators: ko.observableArray(indicators),

        addIndicator: function() {
            this.indicators.push(new Indicator(this));
        },

        removeThis: function() {
            parent.removeSubCompetence(this);
        },

        toggleLock: function(){
            alert(parent.weight);
            alert(this.weight);
            alert((parseInt(parent.weight - this.weight)));
        },

        removeIndicator: function(indicator) {
            this.indicators.remove(indicator);
        }
    };
}

/**
 * Indicator class
 */
function Indicator(parent, id, name, description) {
    return {
        id: ko.observable(id),
        name: ko.observable(name),
        description : ko.observable(description),

        removeThis: function() {
            parent.removeIndicator(this);
        }
    };
}

// View model for the courses page
function pageViewModel(gvm) {
    // projecttitle
    gvm.projecttitle = ko.observable("");
    gvm.competences = 0;
    gvm.subcomp = 0;

    // Page specific i18n bindings
    gvm.title = ko.computed(function (){i18n.setLocale(gvm.lang()); return gvm.app() + ' - ' + i18n.__("ProjectTitle") + ": " + gvm.projecttitle();}, gvm);
    gvm.pageHeader = ko.observable("Project");
    gvm.projectname = ko.computed(function(){i18n.setLocale(gvm.lang()); return i18n.__("ProjectName");}, gvm);

    gvm.addCompetenceBtn = ko.computed(function(){i18n.setLocale(gvm.lang()); return i18n.__("AddCompetence");}, gvm);
    gvm.savePage = ko.computed(function(){i18n.setLocale(gvm.lang()); return i18n.__("SaveBtn");}, gvm);

    gvm.competences = ko.observableArray([]);

    gvm.addCompetence = function() {
        gvm.competences.push(new Competence(this));

        // Update automated weight calculation
        var size = gvm.competences.length;
        var percent = 100/size;
        gvm.competences[0] = 50;
        console.log(this.weight);

        ko.utils.arrayForEach(gvm.competences, function(competence){
            competence.weight(percent);
            alert(percent);
        });
    };

    gvm.removeCompetence = function(competence) {
        gvm.competences.remove(competence);
    }

    gvm.updateCompetence = function(id, code, description, max, weight) {
        var comp = new Competence(this, id, code, description, weight);
        gvm.competences.push(comp);
        return comp;
    }

    gvm.clearStructure = function() {
        gvm.competences.destroyAll();
    }
}

/**
 * Push the current project state to the database
 * @returns {undefined}
 */
function saveProjectStructure() {
    $.ajax({
       type: "POST",
       url: "/api/projectstructure/" + projectid,
       data: ko.toJSON(viewModel.competences),
       success: function(){
           // TODO make multilangual and with modals
           alert("Saved projectstructure to server");

           fetchProjectStructure();
       }
    });
}

function fetchProjectStructure() {
    viewModel.clearStructure();

    $.getJSON("/api/projectstructure/" + projectid, function(data){
        $.each(data, function(i, item){
            var competence = viewModel.updateCompetence(item.id, item.code, item.description, item.max, item.weight);

            $.each(item.subcompetences, function(i, subcomp){
               var subcompetence = new SubCompetence(competence, subcomp.id, subcomp.code, subcomp.description, subcomp.weight);
               competence.subcompetences.push(subcompetence);

               $.each(subcomp.indicators, function(i, indic){
                  subcompetence.indicators.push(new Indicator(subcompetence, indic.id, indic.name, indic.description));
               });
            });
        })
    });
}

function initPage() {
    fetchProjectStructure();

    $(".addCompetenceBtn").click(function() {
        viewModel.addCompetence();
    });

    $(".savePageBtn").click(function(){
        saveProjectStructure();
    });

    $(".locked").click(function() {
        setLocked();
    });
}
<|endoftext|>


<commit_before>// View model for the courses page
function pageViewModel(gvm) {
    // projecttitle
    gvm.projecttitle = ko.observable("");

    // Page specific i18n bindings
    gvm.title = ko.computed(function (){i18n.setLocale(gvm.lang()); return gvm.app() + ' - ' + i18n.__("ProjectTitle") + ": " + gvm.projecttitle();}, gvm);
    gvm.pageHeader = ko.observable("Project");
    gvm.projectname = ko.computed(function(){i18n.setLocale(gvm.lang()); return i18n.__("ProjectName");}, gvm);

    gvm.getProjectInfo = function() {
        console.log($("#projectHeader").data('value'));
        $.getJSON('/api/project/' + $("#projectHeader").data('value'), function(data) {
            gvm.pageHeader(data[0].code + ' - ' + data[0].name);
        });
    };
}

function addComptetence() {
    var competence = document.createElement("div");
    $(competence).addClass("col-md-9  competence");
    console.log(competence);
    $("#page-header").append(competence);
}

function addSubCompetence() {

}

function addIndicator() {

}

function initPage() {
    viewModel.getProjectInfo();
    $("#addCompetenceBtn").click(function() {
        console.log("clickec");
        addComptetence();
    })
}<commit_msg>project page<commit_after>// View model for the courses page
function pageViewModel(gvm) {
    // projecttitle
    gvm.projecttitle = ko.observable("");

    // Page specific i18n bindings
    gvm.title = ko.computed(function (){i18n.setLocale(gvm.lang()); return gvm.app() + ' - ' + i18n.__("ProjectTitle") + ": " + gvm.projecttitle();}, gvm);
    gvm.pageHeader = ko.observable("Project");
    gvm.projectname = ko.computed(function(){i18n.setLocale(gvm.lang()); return i18n.__("ProjectName");}, gvm);

    gvm.getProjectInfo = function() {
        console.log($("#projectHeader").data('value'));
        $.getJSON('/api/project/' + $("#projectHeader").data('value'), function(data) {
            gvm.pageHeader(data[0].code + ' - ' + data[0].name);
        });
    };
}

function addComptetence() {
    var competence = document.createElement("div");
    $(competence).addClass("col-md-9  competence");
    $(competence).text("Hallo competence");
    console.log(competence);
    $("#page-header").append(competence);
}

function addSubCompetence() {

}

function addIndicator() {

}

function initPage() {
    viewModel.getProjectInfo();
    $("#addCompetenceBtn").click(function() {
        console.log("clickec");
        addComptetence();
    })
}<|endoftext|>


<commit_before>game.SpendExp = me.ScreenObject.extend({
	/**
	 *  action to perform on state change
	 */
	onResetEvent: function() {
		me.game.world.addChild(new me.Sprite(0, 0, me.loader.getImage('title-screen')), -10); // TODO

		//this line of code will make the enter button be pressed and show up the game.
		me.game.world.addChild(new (me.Renderable.extend({
			init: function() {
				this._super(me.Renderable, 'init', [270, 240, 300, 50]);
				this.font = new me.Font("Arial", 46, "white");
				me.input.registerPointerEvent('pointerdown', this, this.newGame.bind(this), true)
			},
			//The code here will make an enter button show up and to make the game functional.
			draw: function(renderer) {
				this.font.draw(renderer.getContext(), "START NEW GAME", this.pos.x, this.pos.y);
			},

			update: function(dt){
				return true;
			},
			//the experince is used to upgrade to new levels and upgrade the character
			//the new game function contains some specific parts for
			//the experience
			newGame: function(){
				me.input.releasePointerEvent('pointerdown', this);
				me.save.remove('exp');
				me.save.remove('exp1');
				me.save.remove('exp2');
				me.save.remove('exp3');
				me.save.remove('exp4');
				me.state.change(me.state.PLAY);
			}
		})));

		//this line of code will make the enter button be pressed and show up the game
		//this code was copyed and some code was removed
		me.game.world.addChild(new (me.Renderable.extend({
			init: function() {
				this._super(me.Renderable, 'init', [380, 340, 250, 50]);
				this.font = new me.Font("Arial", 46, "white");
			},
			//The code here will make an enter button show up and to make the game functional.
			draw: function(renderer) {
				this.font.draw(renderer.getContext(), "PRESS F1-F4 TO BUY, F5 TO SKIP", this.pos.x, this.pos.y);
				this.fond.draw(renderer.detContext(), "CURRENT EXP: " + game.data.exp. toString(), this.pos.x + 100, this.pos.y + 50);
				this.fond.draw(renderer.detContext(), "CURRENT EXP: " + game.data.exp. toString(), this.pos.x + 200, this.pos.y + 100);
				this.fond.draw(renderer.detContext(), "CURRENT EXP: " + game.data.exp. toString(), this.pos.x + 200, this.pos.y + 150);
				this.fond.draw(renderer.detContext(), "CURRENT EXP: " + game.data.exp. toString(), this.pos.x + 200, this.pos.y + 200);
				this.fond.draw(renderer.detContext(), "CURRENT EXP: " + game.data.exp. toString(), this.pos.x + 200, this.pos.y + 250);
			},

		})));

	},
	//this will make the title show up, unfortunately it will not go into your game so you wont
	//be able to use the game till the title is functional

	/**
	 *  action to perform when leaving this screen (state change)
	 */
	onDestroyEvent: function() {

	}
});<commit_msg>Game Project Video 43 comments.<commit_after>game.SpendExp = me.ScreenObject.extend({
	/**
	 *  action to perform on state change
	 */
	onResetEvent: function() {
		me.game.world.addChild(new me.Sprite(0, 0, me.loader.getImage('title-screen')), -10); // TODO

		//this line of code will make the enter button be pressed and show up the game.
		me.game.world.addChild(new (me.Renderable.extend({
			init: function() {
				this._super(me.Renderable, 'init', [270, 240, 300, 50]);
				this.font = new me.Font("Arial", 46, "white");
				me.input.registerPointerEvent('pointerdown', this, this.newGame.bind(this), true)
			},
			//The code here will make an enter button show up and to make the game functional.
			draw: function(renderer) {
				this.font.draw(renderer.getContext(), "START NEW GAME", this.pos.x, this.pos.y);
			},

			update: function(dt){
				return true;
			},
			//the experince is used to upgrade to new levels and upgrade the character
			//the new game function contains some specific parts for
			//the experience
			newGame: function(){
				me.input.releasePointerEvent('pointerdown', this);
				me.save.remove('exp');
				me.save.remove('exp1');
				me.save.remove('exp2');
				me.save.remove('exp3');
				me.save.remove('exp4');
				me.state.change(me.state.PLAY);
			}
		})));

		//this line of code will make the enter button be pressed and show up the game
		//this code was copyed and some code was removed
		me.game.world.addChild(new (me.Renderable.extend({
			init: function() {
				this._super(me.Renderable, 'init', [380, 340, 250, 50]);
				this.font = new me.Font("Arial", 46, "white");
			},
			//The code here will make an enter button show up and to make the game functional.
			draw: function(renderer) {
				this.font.draw(renderer.getContext(), "PRESS F1-F4 TO BUY, F5 TO SKIP", this.pos.x, this.pos.y);
				this.fond.draw(renderer.detContext(), "CURRENT EXP: " + game.data.exp. toString(), this.pos.x + 100, this.pos.y + 50);
				this.fond.draw(renderer.detContext(), "CURRENT EXP: " + game.data.exp. toString(), this.pos.x + 200, this.pos.y + 100);
				this.fond.draw(renderer.detContext(), "CURRENT EXP: " + game.data.exp. toString(), this.pos.x + 200, this.pos.y + 150);
				this.fond.draw(renderer.detContext(), "CURRENT EXP: " + game.data.exp. toString(), this.pos.x + 200, this.pos.y + 200);
				this.fond.draw(renderer.detContext(), "CURRENT EXP: " + game.data.exp. toString(), this.pos.x + 200, this.pos.y + 250);
				//these will create more buttons in the game and I am going to fix it later, not going to do it now because it is not mandatory.
			},

		})));

	},
	//this will make the title show up, unfortunately it will not go into your game so you wont
	//be able to use the game till the title is functional

	/**
	 *  action to perform when leaving this screen (state change)
	 */
	onDestroyEvent: function() {

	}
});<|endoftext|>