<commit_before>export const initialState = {
  ui: {
    sidemenuVisibility: 'expanded'
  },
  patients: {
    activePatient: {},
    searchResults: [
      {
        id: 1,
        mrn: 2345237,
        dob: '1964-02-12T00:00Z',
        name: 'Raphael Trueman',
        address: `95 Wallum Court
      TYALGUM NSW 2484`,
        phone: '(02) 9372 4355',
        email: 'raphael.trueman@rnsh.pilot.com',
        gender: 'M',
        tumorType: 'Prostate'
      },
      {
        id: 2,
        mrn: 2349675,
        dob: '1964-02-12T00:00Z',
        name: 'Jon Ingram',
        address: `89 Larissa Court
      COWANGIE VIC 3506`,
        phone: '(02) 9372 6785',
        email: 'jon.ingram@rnsh.pilot.com',
        gender: 'M',
        tumorType: 'Prostate'
      },
      {
        id: 3,
        mrn: 9876345,
        dob: '1964-02-12T00:00Z',
        name: 'Anabelle Elliott',
        address: `35 Patton Street
      KOOYONG VIC 3144`,
        phone: '(02) 9372 2342',
        email: 'anabelle.elliott@rnsh.pilot.com',
        gender: 'F',
        tumorType: 'CNS'
      },
      {
        id: 4,
        mrn: 3456234,
        dob: '1964-02-12T00:00Z',
        name: 'Gary Earl',
        address: `15 Mendooran Road
      CUMBOOGLE NSW 2830`,
        phone: '(02) 9372 4567',
        email: 'gary.earl@rnsh.pilot.com',
        gender: 'M',
        tumorType: 'CNS'
      },
      {
        id: 5,
        mrn: 1276543,
        dob: '1964-02-12T00:00Z',
        name: 'Madonna Dawson',
        address: `83 Inglewood Court
      PASTORIA VIC 3444`,
        phone: '(02) 9372 6234',
        email: 'madonna.dawson@rnsh.pilot.com',
        gender: 'F',
        tumorType: 'CNS'
      },
      {
        id: 6,
        mrn: 3456734,
        dob: '1964-02-12T00:00Z',
        name: 'Felix Sudworth',
        address: `10 Carolina Park Road
      PATONGA NSW 2256`,
        phone: '(02) 9372 5555',
        email: 'felix.sudworth@rnsh.pilot.com',
        gender: 'M',
        tumorType: 'CNS'
      },
      {
        id: 7,
        mrn: 3334526,
        dob: '1964-02-12T00:00Z',
        name: 'Bill Snoogie',
        address: `45 Farrar Parade
      JURIEN BAY WA 6516`,
        phone: '(02) 9372 3335',
        email: 'bill.snoogie@rnsh.pilot.com',
        gender: 'M',
        tumorType: 'Prostate'
      },
      {
        id: 8,
        mrn: 3452777,
        dob: '1964-02-12T00:00Z',
        name: 'Lenora Christians',
        address: `61 Eungella Road
      HOME HILL QLD 4806`,
        phone: '(02) 9372 9000',
        email: 'lenora.christians@rnsh.pilot.com',
        gender: 'F',
        tumorType: 'CNS'
      },
      {
        id: 9,
        mrn: 3334521,
        dob: '1964-02-12T00:00Z',
        name: 'Karlene Cotterill',
        address: `51 Savages Road
      PARKINSON QLD 4115`,
        phone: '(02) 9372 0078',
        email: 'karlene.cotterill@rnsh.pilot.com',
        gender: 'F',
        tumorType: 'CNS'
      },
      {
        id: 10,
        mrn: 9878776,
        dob: '1964-02-12T00:00Z',
        name: 'Kelcey Walker',
        address: `85 Zipfs Road
      FLINDERS VIEW QLD 4305`,
        phone: '(02) 9372 6745',
        email: 'kelcey.walker@rnsh.pilot.com',
        gender: 'F',
        tumorType: 'CNS'
      }
    ]
  },
  graphs: [
    {
      'name': 'psa-testosterone',
      'type': 'dual-plot',
      'left': {
        'name': 'psa',
        'displayName': 'PSA',
        'type': 'line',
        'yAxisLabel': 'ng / mL',
        'data': [
          { 'date': '29-Nov-06', 'data': 2.37 },
          { 'date': '09-Nov-10', 'data': 4.42 },
          { 'date': '21-Jan-11', 'data': 5.18 },
          { 'date': '21-Feb-12', 'data': 11 },
          { 'date': '01-Jul-12', 'data': 1.6 },
          { 'date': '09-Sep-13', 'data': 0.1 },
          { 'date': '23-Feb-15', 'data': 0.1 }
        ]
      },
      'right': {
        'name': 'testosterone',
        'displayName': 'Testosterone',
        'type': 'line',
        'yAxisLabel': 'nmol / L',
        'data': [
          { 'date': '29-Nov-06', 'data': 6.4 },
          { 'date': '09-Nov-10', 'data': 3.0 },
          { 'date': '21-Jan-11', 'data': 1.2 },
          { 'date': '21-Feb-12', 'data': 2.4 },
          { 'date': '01-Jul-12', 'data': 4.8 },
          { 'date': '09-Sep-13', 'data': 5.5 },
          { 'date': '23-Feb-15', 'data': 6.3 }
        ]
      }
    },
    {
      'name': 'androgen',
      'displayName': 'ADT',
      'type': 'timeline',
      'data': [
        { 'start': '24-Jul-12', 'end': '24-Jan-13' }
      ]
    },
    {
      'name': 'radiotherapy',
      'displayName': 'Radiotherapy',
      'type': 'timeline',
      'data': [
        { 'start': '04-Sep-12', 'end': '23-Nov-12' }
      ]
    },
    {
      'name': 'surgery',
      'displayName': 'Surgery',
      'type': 'point',
      'data': [
        { 'date': '14-May-12', 'hoverTitle': 'Prostatectomy' }
      ]
    }
  ]
};
<commit_msg>added surgical to the patient data set<commit_after>export const initialState = {
  ui: {
    sidemenuVisibility: 'collapsed'
  },
  patients: {
    activePatient: {},
    searchResults: [
      {
        id: 1,
        mrn: 2345237,
        dob: '1964-02-12T00:00Z',
        name: 'Raphael Trueman',
        address: `95 Wallum Court
      TYALGUM NSW 2484`,
        phone: '(02) 9372 4355',
        email: 'raphael.trueman@rnsh.pilot.com',
        gender: 'M',
        tumorType: 'Prostate',
        surgical: 'Y'
      },
      {
        id: 2,
        mrn: 2349675,
        dob: '1964-02-12T00:00Z',
        name: 'Jon Ingram',
        address: `89 Larissa Court
      COWANGIE VIC 3506`,
        phone: '(02) 9372 6785',
        email: 'jon.ingram@rnsh.pilot.com',
        gender: 'M',
        tumorType: 'Prostate',
        surgical: 'N'
      },
      {
        id: 3,
        mrn: 9876345,
        dob: '1964-02-12T00:00Z',
        name: 'Anabelle Elliott',
        address: `35 Patton Street
      KOOYONG VIC 3144`,
        phone: '(02) 9372 2342',
        email: 'anabelle.elliott@rnsh.pilot.com',
        gender: 'F',
        tumorType: 'CNS',
        surgical: 'Y'
      },
      {
        id: 4,
        mrn: 3456234,
        dob: '1964-02-12T00:00Z',
        name: 'Gary Earl',
        address: `15 Mendooran Road
      CUMBOOGLE NSW 2830`,
        phone: '(02) 9372 4567',
        email: 'gary.earl@rnsh.pilot.com',
        gender: 'M',
        tumorType: 'CNS',
        surgical: 'Y'
      },
      {
        id: 5,
        mrn: 1276543,
        dob: '1964-02-12T00:00Z',
        name: 'Madonna Dawson',
        address: `83 Inglewood Court
      PASTORIA VIC 3444`,
        phone: '(02) 9372 6234',
        email: 'madonna.dawson@rnsh.pilot.com',
        gender: 'F',
        tumorType: 'CNS',
        surgical: 'N'
      },
      {
        id: 6,
        mrn: 3456734,
        dob: '1964-02-12T00:00Z',
        name: 'Felix Sudworth',
        address: `10 Carolina Park Road
      PATONGA NSW 2256`,
        phone: '(02) 9372 5555',
        email: 'felix.sudworth@rnsh.pilot.com',
        gender: 'M',
        tumorType: 'CNS',
        surgical: 'Y'
      },
      {
        id: 7,
        mrn: 3334526,
        dob: '1964-02-12T00:00Z',
        name: 'Bill Snoogie',
        address: `45 Farrar Parade
      JURIEN BAY WA 6516`,
        phone: '(02) 9372 3335',
        email: 'bill.snoogie@rnsh.pilot.com',
        gender: 'M',
        tumorType: 'Prostate',
        surgical: 'N'
      },
      {
        id: 8,
        mrn: 3452777,
        dob: '1964-02-12T00:00Z',
        name: 'Lenora Christians',
        address: `61 Eungella Road
      HOME HILL QLD 4806`,
        phone: '(02) 9372 9000',
        email: 'lenora.christians@rnsh.pilot.com',
        gender: 'F',
        tumorType: 'CNS',
        surgical: 'Y'
      },
      {
        id: 9,
        mrn: 3334521,
        dob: '1964-02-12T00:00Z',
        name: 'Karlene Cotterill',
        address: `51 Savages Road
      PARKINSON QLD 4115`,
        phone: '(02) 9372 0078',
        email: 'karlene.cotterill@rnsh.pilot.com',
        gender: 'F',
        tumorType: 'CNS',
        surgical: 'Y'
      },
      {
        id: 10,
        mrn: 9878776,
        dob: '1964-02-12T00:00Z',
        name: 'Kelcey Walker',
        address: `85 Zipfs Road
      FLINDERS VIEW QLD 4305`,
        phone: '(02) 9372 6745',
        email: 'kelcey.walker@rnsh.pilot.com',
        gender: 'F',
        tumorType: 'CNS',
        surgical: 'Y'
      }
    ]
  },
  graphs: [
    {
      'name': 'psa-testosterone',
      'type': 'dual-plot',
      'left': {
        'name': 'psa',
        'displayName': 'PSA',
        'type': 'line',
        'yAxisLabel': 'ng / mL',
        'data': [
          { 'date': '29-Nov-06', 'data': 2.37 },
          { 'date': '09-Nov-10', 'data': 4.42 },
          { 'date': '21-Jan-11', 'data': 5.18 },
          { 'date': '21-Feb-12', 'data': 11 },
          { 'date': '01-Jul-12', 'data': 1.6 },
          { 'date': '09-Sep-13', 'data': 0.1 },
          { 'date': '23-Feb-15', 'data': 0.1 }
        ]
      },
      'right': {
        'name': 'testosterone',
        'displayName': 'Testosterone',
        'type': 'line',
        'yAxisLabel': 'nmol / L',
        'data': [
          { 'date': '29-Nov-06', 'data': 6.4 },
          { 'date': '09-Nov-10', 'data': 3.0 },
          { 'date': '21-Jan-11', 'data': 1.2 },
          { 'date': '21-Feb-12', 'data': 2.4 },
          { 'date': '01-Jul-12', 'data': 4.8 },
          { 'date': '09-Sep-13', 'data': 5.5 },
          { 'date': '23-Feb-15', 'data': 6.3 }
        ]
      }
    },
    {
      'name': 'androgen',
      'displayName': 'ADT',
      'type': 'timeline',
      'data': [
        { 'start': '24-Jul-12', 'end': '24-Jan-13' }
      ]
    },
    {
      'name': 'radiotherapy',
      'displayName': 'Radiotherapy',
      'type': 'timeline',
      'data': [
        { 'start': '04-Sep-12', 'end': '23-Nov-12' }
      ]
    },
    {
      'name': 'surgery',
      'displayName': 'Surgery',
      'type': 'point',
      'data': [
        { 'date': '14-May-12', 'hoverTitle': 'Prostatectomy' }
      ]
    }
  ]
};
<|endoftext|>


<commit_before>;(function(window, document, undefined){

  'use strict';

  var DEFAULTS = {},
      arrowKeys = [37, 38, 39, 40];

  function _extend( a, b ) {
    for ( var prop in b ) {
      if( b.hasOwnProperty(prop) ){
        a[ prop ] = b[ prop ];
      }
    }
    return a;
  }

  function _attachEvts( elem ){
    elem.addEventListener('keyup', _addDots, false);
    elem.addEventListener('paste', _addDots, false);
  }

  function _addDots(e) {
    // Don't execute anything if the user is just moving the cursor around and
    // not really enetring anything new.
    if(arrowKeys.indexOf(e.keyCode) !== -1){ return; }

    // keep track of the cursor position
    var cursorPos = this.selectionStart,
    // remove the dots (and any non-integer character),
    // split the string and reverse it
        a = this.value.replace(/\D/g,'').split('').reverse();

    // start from 3 and as long as there's a number
    // add a dot every three digits.
    var pos = 3;
    while(a[pos] !== undefined){
      a.splice(pos,0,'.');
      pos = pos + 4;
    }
    // reverse, join and reassign the value
    this.value = a.reverse().join('');
  }

  var Dotdot = function( node, opts ){

    if(!node){
      throw new Error('Dotdot needs an input element to be passed as a parameter');
    }

    if(opts){
      DEFAULTS = _extend(DEFAULTS, opts);
    }

    if(node.length !== undefined){
      Array.prototype.forEach.call(node, _attachEvts);
    } else {
      _attachEvts(node);
    }
  };

  window.Dotdot = Dotdot;

})(window, document);<commit_msg>add cursor tracking<commit_after>;(function(window, document, undefined){

  'use strict';

  var DEFAULTS = {},
      arrowKeys = [37, 38, 39, 40];

  function _extend( a, b ) {
    for ( var prop in b ) {
      if( b.hasOwnProperty(prop) ){
        a[ prop ] = b[ prop ];
      }
    }
    return a;
  }

  function _attachEvts( elem ){
    elem.addEventListener('keyup', _addDots, false);
    elem.addEventListener('paste', _addDots, false);
  }

  function _addDots(e) {
    // Don't execute anything if the user is just moving the cursor around and
    // not really enetring anything new.
    if(arrowKeys.indexOf(e.keyCode) !== -1){ return; }
    // keep track of the cursor position for later
    var cursorPos = this.selectionEnd,
        len = this.value.length,
        newLen,
        // remove the dots (and any non-integer character),
        // split the string and reverse it
        a = this.value.replace(/\D/g,'').split('').reverse();

    // start from 3 and as long as there's a number
    // add a dot every three digits.
    var pos = 3;
    while(a[pos] !== undefined){
      a.splice(pos,0,'.');
      pos = pos + 4;
    }
    newLen = a.length;
    // reverse, join and reassign the value
    this.value = a.reverse().join('');
    // Compare the original string with the generated one.
    // If the 2 strings length are identical (hence no new dot was added)
    // place the cursor at the same position it was placed in the beginning.
    // If the strings length is different a new dot was added and we need to
    // shift the cursor one step forward.
    this.selectionEnd = len === newLen ? cursorPos : cursorPos + 1;
    console.log(cursorPos%4)
    this.focus();
  }

  var Dotdot = function( node, opts ){

    if(!node){
      throw new Error('Dotdot needs an input element to be passed as a parameter');
    }

    if(opts){
      DEFAULTS = _extend(DEFAULTS, opts);
    }

    if(node.length !== undefined){
      Array.prototype.forEach.call(node, _attachEvts);
    } else {
      _attachEvts(node);
    }
  };

  window.Dotdot = Dotdot;

})(window, document);<|endoftext|>


<commit_before>/*******************************************************************************
 * Code contributed to the webinos project
 *
 * 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.
 *
 * Copyright 2012 Felix-Johannes Jendrusch, Fraunhofer FOKUS
 ******************************************************************************/

// Mid-term issues:
// [WP-?] Support write/truncate abortion.
// [WP-?] Add extension to mime type mapping.

if (typeof webinos === "undefined") webinos = {};
if (typeof webinos.file === "undefined") webinos.file = {};

(function (exports) {
  exports.Service = Service;

  webinos.util.inherits(Service, WebinosService);
  function Service(object, rpc) {
    Service.parent.call(this, object);

    this.rpc = rpc;
  }

  Service.prototype.requestFileSystem = function (type, size, successCallback,
      errorCallback) {
    var self = this;
    var request = self.rpc.createRPC(self, "requestFileSystem",
        { type : type, size : size });
    self.rpc.executeRPC(request, function (filesystem) {
      successCallback(new FileSystem(self, filesystem.name));
    }, errorCallback);
  };

  Service.prototype.resolveLocalFileSystemURL = function (url, successCallback,
      errorCallback) {
    var self = this;
    var request = self.rpc.createRPC(self, "resolveLocalFileSystemURL",
        { url : url });
    self.rpc.executeRPC(request, function (entry) {
      var filesystem = new FileSystem(self, entry.filesystem.name);
      if (entry.isDirectory) {
        successCallback(new DirectoryEntry(filesystem, entry.fullPath));
      } else {
        successCallback(new FileEntry(filesystem, entry.fullPath));
      }
    }, errorCallback);
  };

  function FileSystem(service, name) {
    this.service = service;

    this.name = name;
    this.root = new DirectoryEntry(this, "/");
  }

  FileSystem.prototype.toJSON = function () {
    var json = { name : this.name };
    return json;
  };

  function Entry(filesystem, fullPath) {
    this.name = webinos.path.basename(fullPath);
    this.fullPath = fullPath;
    this.filesystem = filesystem;

    this.service = filesystem.service;
    this.rpc = filesystem.service.rpc;
  }

  Entry.prototype.isFile = false;
  Entry.prototype.isDirectory = false;

  Entry.prototype.getMetadata = function (successCallback, errorCallback) {
    var request = this.rpc.createRPC(this.service, "getMetadata",
        { entry : this });
    this.rpc.executeRPC(request, function (metadata) {
      successCallback(new Metadata(metadata));
    }, errorCallback);
  };

  Entry.prototype.moveTo = function (parent, newName, successCallback,
      errorCallback) {
    var self = this;
    var request = self.rpc.createRPC(self.service, "moveTo",
        { source : self, parent : parent, newName : newName });
    self.rpc.executeRPC(request, function (entry) {
      if (self.isDirectory) {
        successCallback(new DirectoryEntry(self.filesystem, entry.fullPath));
      } else {
        successCallback(new FileEntry(self.filesystem, entry.fullPath));
      }
    }, errorCallback);
  };

  Entry.prototype.copyTo = function (parent, newName, successCallback,
      errorCallback) {
    var self = this;
    var request = self.rpc.createRPC(self.service, "copyTo",
        { source : self, parent : parent, newName : newName });
    self.rpc.executeRPC(request, function (entry) {
      if (self.isDirectory) {
        successCallback(new DirectoryEntry(self.filesystem, entry.fullPath));
      } else {
        successCallback(new FileEntry(self.filesystem, entry.fullPath));
      }
    }, errorCallback);
  };

  Entry.prototype.toURL = function () {
    return "webinos:" + this.filesystem.name + this.fullPath;
  };

  Entry.prototype.remove = function (successCallback, errorCallback) {
    var request = this.rpc.createRPC(this.service, "remove", { entry : this });
    this.rpc.executeRPC(request, successCallback, errorCallback);
  };

  Entry.prototype.getParent = function (successCallback, errorCallback) {
    var self = this;
    var request = self.rpc.createRPC(self.service, "getParent",
        { entry : self });
    self.rpc.executeRPC(request, function (entry) {
      successCallback(new DirectoryEntry(self.filesystem, entry.fullPath));
    }, errorCallback);
  };

  Entry.prototype.toJSON = function () {
    var json = { name        : this.name
               , fullPath    : this.fullPath
               , filesystem  : this.filesystem
               , isFile      : this.isFile
               , isDirectory : this.isDirectory
               };
    return json;
  };

  function Metadata(metadata) {
    this.modificationTime = new Date(metadata.modificationTime);
    this.size = metadata.size;
  }

  webinos.util.inherits(DirectoryEntry, Entry);
  function DirectoryEntry(filesystem, fullPath) {
    DirectoryEntry.parent.call(this, filesystem, fullPath);
  }

  DirectoryEntry.prototype.isDirectory = true;

  DirectoryEntry.prototype.createReader = function () {
    return new DirectoryReader(this);
  };

  DirectoryEntry.prototype.getFile = function (path, options, successCallback,
      errorCallback) {
    var self = this;
    var request = self.rpc.createRPC(self.service, "getFile",
        { entry : self, path : path, options : options });
    self.rpc.executeRPC(request, function (entry) {
      successCallback(new FileEntry(self.filesystem, entry.fullPath));
    }, errorCallback);
  };

  DirectoryEntry.prototype.getDirectory = function (path, options,
      successCallback, errorCallback) {
    var self = this;
    var request = self.rpc.createRPC(self.service, "getDirectory",
        { entry : self, path : path, options : options });
    self.rpc.executeRPC(request, function (entry) {
      successCallback(new DirectoryEntry(self.filesystem, entry.fullPath));
    }, errorCallback);
  };

  DirectoryEntry.prototype.removeRecursively = function (successCallback,
      errorCallback) {
    var request = this.rpc.createRPC(this.service, "removeRecursively",
        { entry : this });
    this.rpc.executeRPC(request, successCallback, errorCallback);
  };

  function DirectoryReader(entry) {
    this.entry = entry;

    this.service = entry.filesystem.service;
    this.rpc = entry.filesystem.service.rpc;
  }

  DirectoryReader.prototype.readEntries = function (successCallback,
      errorCallback) {
    var self = this;

    function next() {
      if (!self.entries.length) return [];

      var chunk = self.entries.slice(0, 10);
      self.entries.splice(0, 10);
      return chunk;
    }

    if (typeof self.entries === "undefined") {
      var request = self.rpc.createRPC(self.service, "readEntries",
          { entry : self.entry });
      self.rpc.executeRPC(request, function (entries) {
        self.entries = entries.map(function (entry) {
          if (entry.isDirectory) {
            return new DirectoryEntry(self.entry.filesystem, entry.fullPath);
          } else {
            return new FileEntry(self.entry.filesystem, entry.fullPath);
          }
        });

        successCallback(next());
      }, errorCallback);
    } else webinos.util.async(successCallback)(next());
  };

  webinos.util.inherits(FileEntry, Entry);
  function FileEntry(filesystem, fullPath) {
    FileEntry.parent.call(this, filesystem, fullPath);
  }

  FileEntry.prototype.isFile = true;

  FileEntry.prototype.createWriter = function (successCallback, errorCallback) {
    var self = this;
    var request = self.rpc.createRPC(self.service, "getMetadata",
        { entry : self });
    self.rpc.executeRPC(request, function (metadata) {
      var writer = new FileWriter(self);
      writer.length = metadata.size;

      successCallback(writer);
    }, errorCallback);
  };

  FileEntry.prototype.file = function (successCallback, errorCallback) {
    var self = this;
    var request = self.rpc.createRPC(self.service, "getMetadata",
        { entry : self });
    self.rpc.executeRPC(request, function (metadata) {
      var blobParts = [];

      var remote;
      var port = self.rpc.createRPC(self.service, "read",
         { entry : self
         , options : { bufferSize : 16 * 1024, autopause : true }
         });
      port.ref = function (params, successCallback, errorCallback, ref) {
        remote = ref;
      };
      port.open = function () {};
      port.data = function (params) {
        blobParts.push(webinos.util.hex2ab(params.data));

        var message = self.rpc.createRPC(remote, "resume", null);
        self.rpc.executeRPC(message);
      };
      port.end = function () {};
      port.close = function () {
        try {
          var blob = new Blob(blobParts);
          blob.name = self.name;
          blob.lastModifiedDate = new Date(metadata.modificationTime);

          successCallback(blob);
        } finally {
          self.rpc.unregisterCallbackObject(port);
        }
      };
      port.error = function (params) {
        try {
          errorCallback(params.error);
        } finally {
          self.rpc.unregisterCallbackObject(port);
        }
      };

      self.rpc.registerCallbackObject(port);
      self.rpc.executeRPC(port);
    }, errorCallback);
  };

  webinos.util.inherits(FileWriter, webinos.util.EventTarget);
  function FileWriter(entry) {
    FileWriter.parent.call(this);

    this.entry = entry;

    this.readyState = FileWriter.INIT;
    this.length = 0;
    this.position = 0;

    this.service = entry.filesystem.service;
    this.rpc = entry.filesystem.service.rpc;

    this.addEventListener("writestart", function (event) {
      webinos.util.callback(this.onwritestart)(event);
    });
    this.addEventListener("progress", function (event) {
      webinos.util.callback(this.onprogress)(event);
    });
    this.addEventListener("abort", function (event) {
      webinos.util.callback(this.onabort)(event);
    });
    this.addEventListener("write", function (event) {
      webinos.util.callback(this.onwrite)(event);
    });
    this.addEventListener("writeend", function (event) {
      webinos.util.callback(this.onwriteend)(event);
    });
    this.addEventListener("error", function (event) {
      webinos.util.callback(this.onerror)(event);
    });
  }

  FileWriter.INIT = 0;
  FileWriter.WRITING = 1;
  FileWriter.DONE = 2;

  function BlobIterator(blob) {
    this.blob = blob;
    this.position = 0;
  }

  BlobIterator.prototype.hasNext = function () {
    return this.position < this.blob.size;
  };

  BlobIterator.prototype.next = function () {
    if (!this.hasNext()) {
      throw new webinos.util.CustomError("InvalidStateError");
    }

    var end = Math.min(this.position + 16 * 1024, this.blob.size);
    var chunk;
    if (this.blob.slice) {
      chunk = this.blob.slice(this.position, end);
    } else if (this.blob.webkitSlice) {
      chunk = this.blob.webkitSlice(this.position, end);
    } else if (this.blob.mozSlice) {
      chunk = this.blob.mozSlice(this.position, end);
    }
    this.position = end;
    return chunk;
  };

  FileWriter.prototype.write = function (data) {
    var self = this;

    if (self.readyState === FileWriter.WRITING) {
      throw new webinos.util.CustomError("InvalidStateError");
    }

    self.readyState = FileWriter.WRITING;
    self.dispatchEvent(new webinos.util.ProgressEvent("writestart"));

    var reader = new FileReader();
    // reader.onloadstart = function (event) {};
    // reader.onprogress = function (event) {};
    // reader.onabort = function (event) {};
    reader.onload = function () {
      var message = self.rpc.createRPC(remote, "write",
          { data : webinos.util.ab2hex(reader.result) });
      self.rpc.executeRPC(message, function (bytesWritten) {
        self.position += bytesWritten;
        self.length = Math.max(self.position, self.length);

        self.dispatchEvent(new webinos.util.ProgressEvent("progress"));
      });
    };
    // reader.onloadend = function (event) {};
    reader.onerror = function () {
      var message = self.rpc.createRPC(remote, "destroy");
      self.rpc.executeRPC(message, function () {
        try {
          self.error = reader.error;
          self.readyState = FileWriter.DONE;
          self.dispatchEvent(new webinos.util.ProgressEvent("error"));
          self.dispatchEvent(new webinos.util.ProgressEvent("writeend"));
        } finally {
          self.rpc.unregisterCallbackObject(port);
        }
      });
    };

    var iterator = new BlobIterator(data);
    function iterate() {
      if (iterator.hasNext()) {
        reader.readAsArrayBuffer(iterator.next());
      } else {
        var message = self.rpc.createRPC(remote, "end");
        self.rpc.executeRPC(message, function () {
          try {
            self.readyState = FileWriter.DONE;
            self.dispatchEvent(new webinos.util.ProgressEvent("write"));
            self.dispatchEvent(new webinos.util.ProgressEvent("writeend"));
          } finally {
            self.rpc.unregisterCallbackObject(port);
          }
        });
      }
    }

    var remote;
    var port = self.rpc.createRPC(self.service, "write",
       { entry : self.entry, options : { start : self.position } });
    port.ref = function (params, successCallback, errorCallback, ref) {
      remote = ref;
    };
    port.open = function () {
      iterate();
    };
    port.drain = function () {
      iterate();
    };
    port.close = function () {};
    port.error = function (params) {
      try {
        self.error = params.error;
        self.readyState = FileWriter.DONE;
        self.dispatchEvent(new webinos.util.ProgressEvent("error"));
        self.dispatchEvent(new webinos.util.ProgressEvent("writeend"));
      } finally {
        reader.abort();

        self.rpc.unregisterCallbackObject(port);
      }
    };

    self.rpc.registerCallbackObject(port);
    self.rpc.executeRPC(port);
  };

  FileWriter.prototype.seek = function (offset) {
    if (this.readyState === FileWriter.WRITING) {
      throw new webinos.util.CustomError("InvalidStateError");
    }

    this.position = offset;

    if (this.position > this.length) {
      this.position = this.length;
    }

    if (this.position < 0) {
      this.position = this.position + this.length;
    }

    if (this.position < 0) {
      this.position = 0;
    }
  };

  FileWriter.prototype.truncate = function (size) {
    var self = this;

    if (self.readyState === FileWriter.WRITING) {
      throw new webinos.util.CustomError("InvalidStateError");
    }

    self.readyState = FileWriter.WRITING;
    self.dispatchEvent(new webinos.util.ProgressEvent("writestart"));

    var request = self.rpc.createRPC(self.service, "truncate",
        { entry : self.entry, size : size });
    self.rpc.executeRPC(request, function () {
      self.length = size;
      self.position = Math.min(self.position, size);

      self.readyState = FileWriter.DONE;
      self.dispatchEvent(new webinos.util.ProgressEvent("write"));
      self.dispatchEvent(new webinos.util.ProgressEvent("writeend"));
    }, function (error) {
      self.error = error;
      self.readyState = FileWriter.DONE;
      s
      self.dispatchEvent(new webinos.util.ProgressEvent("error"));
      self.dispatchEvent(new webinos.util.ProgressEvent("writeend"));
    });
  };

  // FileWriter.prototype.abort = function () {
  //   if (this.readyState === FileWriter.DONE ||
  //       this.readyState === FileWriter.INIT) return;

  //   this.readyState = FileWriter.DONE;

  //   // If there are any tasks from the object's FileSaver task source in one of
  //   // the task queues, then remove those tasks.
  //   // Terminate the write algorithm being processed.

  //   this.error = new webinos.util.CustomError("AbortError");
  //   this.dispatchEvent(new webinos.util.ProgressEvent("abort"));
  //   this.dispatchEvent(new webinos.util.ProgressEvent("writeend"));
  // };
})(webinos.file);
<commit_msg>Remove "s"<commit_after>/*******************************************************************************
 * Code contributed to the webinos project
 *
 * 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.
 *
 * Copyright 2012 Felix-Johannes Jendrusch, Fraunhofer FOKUS
 ******************************************************************************/

// Mid-term issues:
// [WP-?] Support write/truncate abortion.
// [WP-?] Add extension to mime type mapping.

if (typeof webinos === "undefined") webinos = {};
if (typeof webinos.file === "undefined") webinos.file = {};

(function (exports) {
  exports.Service = Service;

  webinos.util.inherits(Service, WebinosService);
  function Service(object, rpc) {
    Service.parent.call(this, object);

    this.rpc = rpc;
  }

  Service.prototype.requestFileSystem = function (type, size, successCallback,
      errorCallback) {
    var self = this;
    var request = self.rpc.createRPC(self, "requestFileSystem",
        { type : type, size : size });
    self.rpc.executeRPC(request, function (filesystem) {
      successCallback(new FileSystem(self, filesystem.name));
    }, errorCallback);
  };

  Service.prototype.resolveLocalFileSystemURL = function (url, successCallback,
      errorCallback) {
    var self = this;
    var request = self.rpc.createRPC(self, "resolveLocalFileSystemURL",
        { url : url });
    self.rpc.executeRPC(request, function (entry) {
      var filesystem = new FileSystem(self, entry.filesystem.name);
      if (entry.isDirectory) {
        successCallback(new DirectoryEntry(filesystem, entry.fullPath));
      } else {
        successCallback(new FileEntry(filesystem, entry.fullPath));
      }
    }, errorCallback);
  };

  function FileSystem(service, name) {
    this.service = service;

    this.name = name;
    this.root = new DirectoryEntry(this, "/");
  }

  FileSystem.prototype.toJSON = function () {
    var json = { name : this.name };
    return json;
  };

  function Entry(filesystem, fullPath) {
    this.name = webinos.path.basename(fullPath);
    this.fullPath = fullPath;
    this.filesystem = filesystem;

    this.service = filesystem.service;
    this.rpc = filesystem.service.rpc;
  }

  Entry.prototype.isFile = false;
  Entry.prototype.isDirectory = false;

  Entry.prototype.getMetadata = function (successCallback, errorCallback) {
    var request = this.rpc.createRPC(this.service, "getMetadata",
        { entry : this });
    this.rpc.executeRPC(request, function (metadata) {
      successCallback(new Metadata(metadata));
    }, errorCallback);
  };

  Entry.prototype.moveTo = function (parent, newName, successCallback,
      errorCallback) {
    var self = this;
    var request = self.rpc.createRPC(self.service, "moveTo",
        { source : self, parent : parent, newName : newName });
    self.rpc.executeRPC(request, function (entry) {
      if (self.isDirectory) {
        successCallback(new DirectoryEntry(self.filesystem, entry.fullPath));
      } else {
        successCallback(new FileEntry(self.filesystem, entry.fullPath));
      }
    }, errorCallback);
  };

  Entry.prototype.copyTo = function (parent, newName, successCallback,
      errorCallback) {
    var self = this;
    var request = self.rpc.createRPC(self.service, "copyTo",
        { source : self, parent : parent, newName : newName });
    self.rpc.executeRPC(request, function (entry) {
      if (self.isDirectory) {
        successCallback(new DirectoryEntry(self.filesystem, entry.fullPath));
      } else {
        successCallback(new FileEntry(self.filesystem, entry.fullPath));
      }
    }, errorCallback);
  };

  Entry.prototype.toURL = function () {
    return "webinos:" + this.filesystem.name + this.fullPath;
  };

  Entry.prototype.remove = function (successCallback, errorCallback) {
    var request = this.rpc.createRPC(this.service, "remove", { entry : this });
    this.rpc.executeRPC(request, successCallback, errorCallback);
  };

  Entry.prototype.getParent = function (successCallback, errorCallback) {
    var self = this;
    var request = self.rpc.createRPC(self.service, "getParent",
        { entry : self });
    self.rpc.executeRPC(request, function (entry) {
      successCallback(new DirectoryEntry(self.filesystem, entry.fullPath));
    }, errorCallback);
  };

  Entry.prototype.toJSON = function () {
    var json = { name        : this.name
               , fullPath    : this.fullPath
               , filesystem  : this.filesystem
               , isFile      : this.isFile
               , isDirectory : this.isDirectory
               };
    return json;
  };

  function Metadata(metadata) {
    this.modificationTime = new Date(metadata.modificationTime);
    this.size = metadata.size;
  }

  webinos.util.inherits(DirectoryEntry, Entry);
  function DirectoryEntry(filesystem, fullPath) {
    DirectoryEntry.parent.call(this, filesystem, fullPath);
  }

  DirectoryEntry.prototype.isDirectory = true;

  DirectoryEntry.prototype.createReader = function () {
    return new DirectoryReader(this);
  };

  DirectoryEntry.prototype.getFile = function (path, options, successCallback,
      errorCallback) {
    var self = this;
    var request = self.rpc.createRPC(self.service, "getFile",
        { entry : self, path : path, options : options });
    self.rpc.executeRPC(request, function (entry) {
      successCallback(new FileEntry(self.filesystem, entry.fullPath));
    }, errorCallback);
  };

  DirectoryEntry.prototype.getDirectory = function (path, options,
      successCallback, errorCallback) {
    var self = this;
    var request = self.rpc.createRPC(self.service, "getDirectory",
        { entry : self, path : path, options : options });
    self.rpc.executeRPC(request, function (entry) {
      successCallback(new DirectoryEntry(self.filesystem, entry.fullPath));
    }, errorCallback);
  };

  DirectoryEntry.prototype.removeRecursively = function (successCallback,
      errorCallback) {
    var request = this.rpc.createRPC(this.service, "removeRecursively",
        { entry : this });
    this.rpc.executeRPC(request, successCallback, errorCallback);
  };

  function DirectoryReader(entry) {
    this.entry = entry;

    this.service = entry.filesystem.service;
    this.rpc = entry.filesystem.service.rpc;
  }

  DirectoryReader.prototype.readEntries = function (successCallback,
      errorCallback) {
    var self = this;

    function next() {
      if (!self.entries.length) return [];

      var chunk = self.entries.slice(0, 10);
      self.entries.splice(0, 10);
      return chunk;
    }

    if (typeof self.entries === "undefined") {
      var request = self.rpc.createRPC(self.service, "readEntries",
          { entry : self.entry });
      self.rpc.executeRPC(request, function (entries) {
        self.entries = entries.map(function (entry) {
          if (entry.isDirectory) {
            return new DirectoryEntry(self.entry.filesystem, entry.fullPath);
          } else {
            return new FileEntry(self.entry.filesystem, entry.fullPath);
          }
        });

        successCallback(next());
      }, errorCallback);
    } else webinos.util.async(successCallback)(next());
  };

  webinos.util.inherits(FileEntry, Entry);
  function FileEntry(filesystem, fullPath) {
    FileEntry.parent.call(this, filesystem, fullPath);
  }

  FileEntry.prototype.isFile = true;

  FileEntry.prototype.createWriter = function (successCallback, errorCallback) {
    var self = this;
    var request = self.rpc.createRPC(self.service, "getMetadata",
        { entry : self });
    self.rpc.executeRPC(request, function (metadata) {
      var writer = new FileWriter(self);
      writer.length = metadata.size;

      successCallback(writer);
    }, errorCallback);
  };

  FileEntry.prototype.file = function (successCallback, errorCallback) {
    var self = this;
    var request = self.rpc.createRPC(self.service, "getMetadata",
        { entry : self });
    self.rpc.executeRPC(request, function (metadata) {
      var blobParts = [];

      var remote;
      var port = self.rpc.createRPC(self.service, "read",
         { entry : self
         , options : { bufferSize : 16 * 1024, autopause : true }
         });
      port.ref = function (params, successCallback, errorCallback, ref) {
        remote = ref;
      };
      port.open = function () {};
      port.data = function (params) {
        blobParts.push(webinos.util.hex2ab(params.data));

        var message = self.rpc.createRPC(remote, "resume", null);
        self.rpc.executeRPC(message);
      };
      port.end = function () {};
      port.close = function () {
        try {
          var blob = new Blob(blobParts);
          blob.name = self.name;
          blob.lastModifiedDate = new Date(metadata.modificationTime);

          successCallback(blob);
        } finally {
          self.rpc.unregisterCallbackObject(port);
        }
      };
      port.error = function (params) {
        try {
          errorCallback(params.error);
        } finally {
          self.rpc.unregisterCallbackObject(port);
        }
      };

      self.rpc.registerCallbackObject(port);
      self.rpc.executeRPC(port);
    }, errorCallback);
  };

  webinos.util.inherits(FileWriter, webinos.util.EventTarget);
  function FileWriter(entry) {
    FileWriter.parent.call(this);

    this.entry = entry;

    this.readyState = FileWriter.INIT;
    this.length = 0;
    this.position = 0;

    this.service = entry.filesystem.service;
    this.rpc = entry.filesystem.service.rpc;

    this.addEventListener("writestart", function (event) {
      webinos.util.callback(this.onwritestart)(event);
    });
    this.addEventListener("progress", function (event) {
      webinos.util.callback(this.onprogress)(event);
    });
    this.addEventListener("abort", function (event) {
      webinos.util.callback(this.onabort)(event);
    });
    this.addEventListener("write", function (event) {
      webinos.util.callback(this.onwrite)(event);
    });
    this.addEventListener("writeend", function (event) {
      webinos.util.callback(this.onwriteend)(event);
    });
    this.addEventListener("error", function (event) {
      webinos.util.callback(this.onerror)(event);
    });
  }

  FileWriter.INIT = 0;
  FileWriter.WRITING = 1;
  FileWriter.DONE = 2;

  function BlobIterator(blob) {
    this.blob = blob;
    this.position = 0;
  }

  BlobIterator.prototype.hasNext = function () {
    return this.position < this.blob.size;
  };

  BlobIterator.prototype.next = function () {
    if (!this.hasNext()) {
      throw new webinos.util.CustomError("InvalidStateError");
    }

    var end = Math.min(this.position + 16 * 1024, this.blob.size);
    var chunk;
    if (this.blob.slice) {
      chunk = this.blob.slice(this.position, end);
    } else if (this.blob.webkitSlice) {
      chunk = this.blob.webkitSlice(this.position, end);
    } else if (this.blob.mozSlice) {
      chunk = this.blob.mozSlice(this.position, end);
    }
    this.position = end;
    return chunk;
  };

  FileWriter.prototype.write = function (data) {
    var self = this;

    if (self.readyState === FileWriter.WRITING) {
      throw new webinos.util.CustomError("InvalidStateError");
    }

    self.readyState = FileWriter.WRITING;
    self.dispatchEvent(new webinos.util.ProgressEvent("writestart"));

    var reader = new FileReader();
    // reader.onloadstart = function (event) {};
    // reader.onprogress = function (event) {};
    // reader.onabort = function (event) {};
    reader.onload = function () {
      var message = self.rpc.createRPC(remote, "write",
          { data : webinos.util.ab2hex(reader.result) });
      self.rpc.executeRPC(message, function (bytesWritten) {
        self.position += bytesWritten;
        self.length = Math.max(self.position, self.length);

        self.dispatchEvent(new webinos.util.ProgressEvent("progress"));
      });
    };
    // reader.onloadend = function (event) {};
    reader.onerror = function () {
      var message = self.rpc.createRPC(remote, "destroy");
      self.rpc.executeRPC(message, function () {
        try {
          self.error = reader.error;
          self.readyState = FileWriter.DONE;
          self.dispatchEvent(new webinos.util.ProgressEvent("error"));
          self.dispatchEvent(new webinos.util.ProgressEvent("writeend"));
        } finally {
          self.rpc.unregisterCallbackObject(port);
        }
      });
    };

    var iterator = new BlobIterator(data);
    function iterate() {
      if (iterator.hasNext()) {
        reader.readAsArrayBuffer(iterator.next());
      } else {
        var message = self.rpc.createRPC(remote, "end");
        self.rpc.executeRPC(message, function () {
          try {
            self.readyState = FileWriter.DONE;
            self.dispatchEvent(new webinos.util.ProgressEvent("write"));
            self.dispatchEvent(new webinos.util.ProgressEvent("writeend"));
          } finally {
            self.rpc.unregisterCallbackObject(port);
          }
        });
      }
    }

    var remote;
    var port = self.rpc.createRPC(self.service, "write",
       { entry : self.entry, options : { start : self.position } });
    port.ref = function (params, successCallback, errorCallback, ref) {
      remote = ref;
    };
    port.open = function () {
      iterate();
    };
    port.drain = function () {
      iterate();
    };
    port.close = function () {};
    port.error = function (params) {
      try {
        self.error = params.error;
        self.readyState = FileWriter.DONE;
        self.dispatchEvent(new webinos.util.ProgressEvent("error"));
        self.dispatchEvent(new webinos.util.ProgressEvent("writeend"));
      } finally {
        reader.abort();

        self.rpc.unregisterCallbackObject(port);
      }
    };

    self.rpc.registerCallbackObject(port);
    self.rpc.executeRPC(port);
  };

  FileWriter.prototype.seek = function (offset) {
    if (this.readyState === FileWriter.WRITING) {
      throw new webinos.util.CustomError("InvalidStateError");
    }

    this.position = offset;

    if (this.position > this.length) {
      this.position = this.length;
    }

    if (this.position < 0) {
      this.position = this.position + this.length;
    }

    if (this.position < 0) {
      this.position = 0;
    }
  };

  FileWriter.prototype.truncate = function (size) {
    var self = this;

    if (self.readyState === FileWriter.WRITING) {
      throw new webinos.util.CustomError("InvalidStateError");
    }

    self.readyState = FileWriter.WRITING;
    self.dispatchEvent(new webinos.util.ProgressEvent("writestart"));

    var request = self.rpc.createRPC(self.service, "truncate",
        { entry : self.entry, size : size });
    self.rpc.executeRPC(request, function () {
      self.length = size;
      self.position = Math.min(self.position, size);

      self.readyState = FileWriter.DONE;
      self.dispatchEvent(new webinos.util.ProgressEvent("write"));
      self.dispatchEvent(new webinos.util.ProgressEvent("writeend"));
    }, function (error) {
      self.error = error;
      self.readyState = FileWriter.DONE;
      self.dispatchEvent(new webinos.util.ProgressEvent("error"));
      self.dispatchEvent(new webinos.util.ProgressEvent("writeend"));
    });
  };

  // FileWriter.prototype.abort = function () {
  //   if (this.readyState === FileWriter.DONE ||
  //       this.readyState === FileWriter.INIT) return;

  //   this.readyState = FileWriter.DONE;

  //   // If there are any tasks from the object's FileSaver task source in one of
  //   // the task queues, then remove those tasks.
  //   // Terminate the write algorithm being processed.

  //   this.error = new webinos.util.CustomError("AbortError");
  //   this.dispatchEvent(new webinos.util.ProgressEvent("abort"));
  //   this.dispatchEvent(new webinos.util.ProgressEvent("writeend"));
  // };
})(webinos.file);
<|endoftext|>


<commit_before>var spiralLooperSketch = function( sl ) {

  var radius, theta0, theta1, x, y;

  sl.setup = function() {
    sl.createCanvas(500, 500);
    sl.frameRate(10);
    sl.background(0);
    sl.noFill();
    sl.stroke(255);
    sl.smooth();
    sl.noLoop();
  };

  sl.draw = function() {
    //draws a 90deg arc around the initial mouse location
    sl.arc(x, y, radius, radius, theta0, theta1);

    //increments the radius and turns the angle by 90deg
    radius += 10;
    theta0 = theta1;
    theta1 += sl.HALF_PI;
  };

  sl.mousePressed = function() {
    //captures mouse location to start loop
    x = sl.mouseX;
    y = sl.mouseY;

    //resets radius and thetas to starting values
    radius = 10;
    theta0 = 0;
    theta1 = sl.HALF_PI;
    sl.loop();
  };

  sl.mouseReleased = function() {
    sl.noLoop();
  };

};

var spiralLooper = new p5(spiralLooperSketch, 'spiral-looper');
<commit_msg>Corrected active mouse issue in spiral-looper<commit_after>var spiralLooperSketch = function( sl ) {

  var canvas, radius, theta0, theta1, x, y;

  sl.setup = function() {
    canvas = sl.createCanvas(500, 500);
    canvas.id("spiral-looper");
    canvas.mousePressed(sl.newSpiral);

    sl.frameRate(10);
    sl.background(0);
    sl.noFill();
    sl.stroke(255);
    sl.smooth();
    sl.noLoop();
  };

  sl.draw = function() {
    //draws a 90deg arc around the initial mouse location
    sl.arc(x, y, radius, radius, theta0, theta1);

    //increments the radius and turns the angle by 90deg
    radius += 10;
    theta0 = theta1;
    theta1 += sl.HALF_PI;
  };

  sl.newSpiral = function() {
    //captures mouse location to start loop
    x = sl.mouseX;
    y = sl.mouseY;

    //resets radius and thetas to starting values
    radius = 10;
    theta0 = 0;
    theta1 = sl.HALF_PI;
    sl.loop();
  };

  sl.mouseReleased = function() {
    sl.noLoop();
  };

};

var spiralLooper = new p5(spiralLooperSketch, 'spiral-looper');
<|endoftext|>


<commit_before>(function () {

  /**
    Display a list of cloaked items

    @class CloakedCollectionView
    @extends Ember.CollectionView
    @namespace Ember
  **/
  Ember.CloakedCollectionView = Ember.CollectionView.extend({
    topVisible: null,
    bottomVisible: null,
    offsetFixedTopElement: null,
    offsetFixedBottomElement: null,
    loadingHTML: "Loading...",

    init: function() {
      console.log("init")
      window.cloakedView = this;
      var cloakView = this.get('cloakView'),
          idProperty = this.get('idProperty'),
          uncloakDefault = !!this.get('uncloakDefault');

      // Set the slack ratio differently to allow for more or less slack in preloading
      var slackRatio = parseFloat(this.get('slackRatio'));
      if (!slackRatio) { this.set('slackRatio', 1.0); }

      this.set('itemViewClass', Ember.CloakedView.extend({
        classNames: [cloakView + '-cloak'],
        cloaks: cloakView,
        preservesContext: this.get('preservesContext') === "true",
        cloaksController: this.get('itemController'),
        defaultHeight: this.get('defaultHeight'),

        init: function() {
          this._super();

          if (idProperty) {
            this.set('elementId', cloakView + '-cloak-' + this.get('content.' + idProperty));
          }
          if (uncloakDefault) {
            this.uncloak();
          } else {
            this.cloak();
          }
        }
      }));

      this._super();
      Ember.run.next(this, 'scrolled');
    },

    /**
      If the topmost visible view changed, we will notify the controller if it has an appropriate hook.

      @method _topVisibleChanged
      @observes topVisible
    **/
    _topVisibleChanged: Ember.observer('topVisible', function() {
      console.log("_topVisibleChanged")
      var controller = this.get('controller');
      if (controller.topVisibleChanged) { controller.topVisibleChanged(this.get('topVisible')); }
    }),

    /**
      If the bottommost visible view changed, we will notify the controller if it has an appropriate hook.

      @method _bottomVisible
      @observes bottomVisible
    **/
    _bottomVisible: Ember.observer('bottomVisible', function() {
      console.log("_bottomVisible")
      var controller = this.get('controller');
      if (controller.bottomVisibleChanged) { controller.bottomVisibleChanged(this.get('bottomVisible')); }
    }),

    /**
      Binary search for finding the topmost view on screen.

      @method findTopView
      @param {Array} childViews the childViews to search through
      @param {Number} windowTop The top of the viewport to search against
      @param {Number} min The minimum index to search through of the child views
      @param {Number} max The max index to search through of the child views
      @returns {Number} the index into childViews of the topmost view
    **/
    findTopView: function(childViews, viewportTop, min, max) {
      console.log("findTopView")
      if (max < min) { return min; }

      var wrapperTop = this.get('wrapperTop')>>0;

      while(max>min){
        var mid = Math.floor((min + max) / 2),
            // in case of not full-window scrolling
            $view = childViews[mid].$(),
            viewBottom = $view.position().top + wrapperTop + $view.height();

        if (viewBottom > viewportTop) {
          max = mid-1;
        } else {
          min = mid+1;
        }
      }

      return min;
    },

    /**
      Determine what views are onscreen and cloak/uncloak them as necessary.

      @method scrolled
    **/
    scrolled: function() {
      console.log("scrolled")
      if (!this.get('scrollingEnabled')) { return; }

      var childViews = this.get('childViews');
      if ((!childViews) || (childViews.length === 0)) { return; }

      var self = this,
          toUncloak = [],
          onscreen = [],
          onscreenCloaks = [],
          // calculating viewport edges
          $w = Ember.$(window),
          windowHeight = this.get('wrapperHeight') || ( window.innerHeight ? window.innerHeight : $w.height() ),
          windowTop = this.get('wrapperTop') || $w.scrollTop(),
          slack = Math.round(windowHeight * this.get('slackRatio')),
          viewportTop = windowTop - slack,
          windowBottom = windowTop + windowHeight,
          viewportBottom = windowBottom + slack,
          topView = this.findTopView(childViews, viewportTop, 0, childViews.length-1),
          bodyHeight = this.get('wrapperHeight') ? this.$().height() : Ember.$('body').height(),
          bottomView = topView,
          offsetFixedTopElement = this.get('offsetFixedTopElement'),
          offsetFixedBottomElement = this.get('offsetFixedBottomElement');

      if (windowBottom > bodyHeight) { windowBottom = bodyHeight; }
      if (viewportBottom > bodyHeight) { viewportBottom = bodyHeight; }

      if (offsetFixedTopElement) {
        windowTop += (offsetFixedTopElement.outerHeight(true) || 0);
      }

      if (offsetFixedBottomElement) {
        windowBottom -= (offsetFixedBottomElement.outerHeight(true) || 0);
      }

      // Find the bottom view and what's onscreen
      while (bottomView < childViews.length) {
        var view = childViews[bottomView],
          $view = view.$(),
          // in case of not full-window scrolling
          scrollOffset = this.get('wrapperTop') || 0,
          viewTop = $view.offset().top + scrollOffset,
          viewBottom = viewTop + $view.height();

        if (viewTop > viewportBottom) { break; }
        toUncloak.push(view);

        if (viewBottom > windowTop && viewTop <= windowBottom) {
          onscreen.push(view.get('content'));
          onscreenCloaks.push(view);
        }

        bottomView++;
      }
      if (bottomView >= childViews.length) { bottomView = childViews.length - 1; }

      // If our controller has a `sawObjects` method, pass the on screen objects to it.
      var controller = this.get('controller');
      if (onscreen.length) {
        this.setProperties({topVisible: onscreen[0], bottomVisible: onscreen[onscreen.length-1]});
        if (controller && controller.sawObjects) {
          Em.run.schedule('afterRender', function() {
            controller.sawObjects(onscreen);
          });
        }
      } else {
        this.setProperties({topVisible: null, bottomVisible: null});
      }

      var toCloak = childViews.slice(0, topView).concat(childViews.slice(bottomView+1));

      this._uncloak = toUncloak;
      if(this._nextUncloak){
        Em.run.cancel(this._nextUncloak);
        this._nextUncloak = null;
      }

      Em.run.schedule('afterRender', this, function() {
        onscreenCloaks.forEach(function (v) {
          if(v && v.uncloak) {
            v.uncloak();
          }
        });
        toCloak.forEach(function (v) { v.cloak(); });
        if (self._nextUncloak) { Em.run.cancel(self._nextUncloak); }
        self._nextUncloak = Em.run.later(self, self.uncloakQueue,50);
      });

      for (var j=bottomView; j<childViews.length; j++) {
        var checkView = childViews[j];
        if (!checkView.get("childViews.length")) {
          if (!checkView.get('loading') && this.get('loadingHTML')) {
            checkView.$().html(this.get('loadingHTML'));
          }
          return;
        }
      }

    },

    uncloakQueue: function(){
      console.log("uncloakQueue")
      var maxPerRun = 3, delay = 50, processed = 0, self = this;

      if(this._uncloak){
        while(processed < maxPerRun && this._uncloak.length>0){
          var view = this._uncloak.shift();
          if(view && view.uncloak && !view.get("childViews.length")){
            Em.run.schedule('afterRender', view, view.uncloak);
            processed++;
          }
        }
        if(this._uncloak.length === 0){
          this._uncloak = null;
        } else {
          Em.run.schedule('afterRender', self, function(){
            console.log("uncloakQueue-afterRender")
            if(self._nextUncloak){
              Em.run.cancel(self._nextUncloak);
            }
            self._nextUncloak = Em.run.next(self, function(){
              if(self._nextUncloak){
                Em.run.cancel(self._nextUncloak);
              }
              self._nextUncloak = Em.run.later(self,self.uncloakQueue,delay);
            });
          });
        }
      }
    },

    scrollTriggered: function() {
      console.log("scrollTriggered")
      Em.run.scheduleOnce('afterRender', this, 'scrolled');
    },

    _startEvents: Ember.on('didInsertElement', function() {
      console.log("_startEvents")

      if (this.get('offsetFixed')) {
        Em.warn("Cloaked-collection's `offsetFixed` is deprecated. Use `offsetFixedTop` instead.");
      }

      var self = this,
          offsetFixedTop = this.get('offsetFixedTop') || this.get('offsetFixed'),
          offsetFixedBottom = this.get('offsetFixedBottom'),
          onScrollMethod = function() {
            Ember.run.debounce(self, 'scrollTriggered', 10);
          };

      if (offsetFixedTop) {
        this.set('offsetFixedTopElement', Ember.$(offsetFixedTop));
      }

      if (offsetFixedBottom) {
        this.set('offsetFixedBottomElement', Ember.$(offsetFixedBottom));
      }

      Ember.$(document).bind('touchmove', onScrollMethod);
      Ember.$(window).bind('scroll', onScrollMethod);
      this.addObserver('wrapperTop', self, onScrollMethod);
      this.addObserver('wrapperHeight', self, onScrollMethod);
      this.addObserver('content.@each', self, onScrollMethod);
      this.scrollTriggered();

      this.set('scrollingEnabled', true);
    }),

    cleanUp: function() {
      console.log("cleanUp")
      Ember.$(document).unbind('touchmove.ember-cloak');
      Ember.$(window).unbind('scroll.ember-cloak');
      this.set('scrollingEnabled', false);
    },

    _endEvents: Ember.on('willDestroyElement', function() {
      this.cleanUp();
    })
  });

  /**
    A cloaked view is one that removes its content when scrolled off the screen

    @class CloakedView
    @extends Ember.View
    @namespace Ember
  **/
  Ember.CloakedView = Ember.ContainerView.extend({
    attributeBindings: ['style'],

    /**
      Triggers the set up for rendering a view that is cloaked.

      @method uncloak
    */
    uncloak: function() {
      console.log("uncloak")
      var state = this._state || this.state;
      if (state !== 'inDOM' && state !== 'preRender') { return; }

      if (!this.get("childViews.length")) {
        var model = this.get('content'),
            controller = null,
            container = this.get('container');

        // Wire up the itemController if necessary
        var controllerName = this.get('cloaksController');
        if (controllerName) {
          var controllerFullName = 'controller:' + controllerName,
              factory = container.lookupFactory(controllerFullName),
              parentController = this.get('controller');

          // let ember generate controller if needed
          if (factory === undefined) {
            factory = Ember.generateControllerFactory(container, controllerName, model);

            // inform developer about typo
            Ember.Logger.warn('ember-cloaking: can\'t lookup controller by name "' + controllerFullName + '".');
            Ember.Logger.warn('ember-cloaking: using ' + factory.toString() + '.');
          }

          controller = factory.create({
            model: model,
            parentController: parentController,
            target: parentController
          });
        }

        var createArgs = {},
            target = controller || model;

        if (this.get('preservesContext')) {
          createArgs.content = target;
        } else {
          createArgs.context = target;
        }
        if (controller) { createArgs.controller = controller; }
        this.setProperties({
          style: null,
          loading: false
        });

        console.log("childViewS: " + this.get("childViews.length"));
        this.pushObject(this.createChildView(this.get('cloaks'), createArgs))
        this.rerender();
      }
    },

    /**
      Removes the view from the DOM and tears down all observers.

      @method cloak
    */
    cloak: function() {
      console.log("cloak")
      var self = this;

      if (this.get("childViews.length") && (this._state || this.state) === 'inDOM') {
        var style = 'height: ' + this.$().height() + 'px;';
        this.set('style', style);
        this.$().prop('style', style);

        // We need to remove the container after the height of the element has taken
        // effect.
        Ember.run.schedule('afterRender', function() {
          self.get("childViews").forEach(function(view) {
            self.removeObject(view);
            view.remove();
          });
          console.log("cloak-afterRender")
        });
      }
    },

    _setHeights: Ember.on('didInsertElement', function(){
      console.log("_setHeights")
      if (!this.get("childViews.length")) {
        // setting default height
        // but do not touch if height already defined
        if(!this.$().height()){
          var defaultHeight = 100;
          if(this.get('defaultHeight')) {
            defaultHeight = this.get('defaultHeight');
          }

          this.$().css('height', defaultHeight);
        }
      }
    })
  });

  Ember.Handlebars.registerHelper('cloaked-collection', function(options) {
    var hash = options.hash,
        types = options.hashTypes;

    for (var prop in hash) {
      if (types[prop] === 'ID') {
        hash[prop + 'Binding'] = hash[prop];
        delete hash[prop];
      }
    }
    return Ember.Handlebars.helpers.view.call(this, Ember.CloakedCollectionView, options);
  });

})();
<commit_msg>Removing console loggin<commit_after>(function () {

  /**
    Display a list of cloaked items

    @class CloakedCollectionView
    @extends Ember.CollectionView
    @namespace Ember
  **/
  Ember.CloakedCollectionView = Ember.CollectionView.extend({
    topVisible: null,
    bottomVisible: null,
    offsetFixedTopElement: null,
    offsetFixedBottomElement: null,
    loadingHTML: "Loading...",

    init: function() {
      var cloakView = this.get('cloakView'),
          idProperty = this.get('idProperty'),
          uncloakDefault = !!this.get('uncloakDefault');

      // Set the slack ratio differently to allow for more or less slack in preloading
      var slackRatio = parseFloat(this.get('slackRatio'));
      if (!slackRatio) { this.set('slackRatio', 1.0); }

      this.set('itemViewClass', Ember.CloakedView.extend({
        classNames: [cloakView + '-cloak'],
        cloaks: cloakView,
        preservesContext: this.get('preservesContext') === "true",
        cloaksController: this.get('itemController'),
        defaultHeight: this.get('defaultHeight'),

        init: function() {
          this._super();

          if (idProperty) {
            this.set('elementId', cloakView + '-cloak-' + this.get('content.' + idProperty));
          }
          if (uncloakDefault) {
            this.uncloak();
          } else {
            this.cloak();
          }
        }
      }));

      this._super();
      Ember.run.next(this, 'scrolled');
    },

    /**
      If the topmost visible view changed, we will notify the controller if it has an appropriate hook.

      @method _topVisibleChanged
      @observes topVisible
    **/
    _topVisibleChanged: Ember.observer('topVisible', function() {
      var controller = this.get('controller');
      if (controller.topVisibleChanged) { controller.topVisibleChanged(this.get('topVisible')); }
    }),

    /**
      If the bottommost visible view changed, we will notify the controller if it has an appropriate hook.

      @method _bottomVisible
      @observes bottomVisible
    **/
    _bottomVisible: Ember.observer('bottomVisible', function() {
      var controller = this.get('controller');
      if (controller.bottomVisibleChanged) { controller.bottomVisibleChanged(this.get('bottomVisible')); }
    }),

    /**
      Binary search for finding the topmost view on screen.

      @method findTopView
      @param {Array} childViews the childViews to search through
      @param {Number} windowTop The top of the viewport to search against
      @param {Number} min The minimum index to search through of the child views
      @param {Number} max The max index to search through of the child views
      @returns {Number} the index into childViews of the topmost view
    **/
    findTopView: function(childViews, viewportTop, min, max) {
      if (max < min) { return min; }

      var wrapperTop = this.get('wrapperTop')>>0;

      while(max>min){
        var mid = Math.floor((min + max) / 2),
            // in case of not full-window scrolling
            $view = childViews[mid].$(),
            viewBottom = $view.position().top + wrapperTop + $view.height();

        if (viewBottom > viewportTop) {
          max = mid-1;
        } else {
          min = mid+1;
        }
      }

      return min;
    },

    /**
      Determine what views are onscreen and cloak/uncloak them as necessary.

      @method scrolled
    **/
    scrolled: function() {
      if (!this.get('scrollingEnabled')) { return; }

      var childViews = this.get('childViews');
      if ((!childViews) || (childViews.length === 0)) { return; }

      var self = this,
          toUncloak = [],
          onscreen = [],
          onscreenCloaks = [],
          // calculating viewport edges
          $w = Ember.$(window),
          windowHeight = this.get('wrapperHeight') || ( window.innerHeight ? window.innerHeight : $w.height() ),
          windowTop = this.get('wrapperTop') || $w.scrollTop(),
          slack = Math.round(windowHeight * this.get('slackRatio')),
          viewportTop = windowTop - slack,
          windowBottom = windowTop + windowHeight,
          viewportBottom = windowBottom + slack,
          topView = this.findTopView(childViews, viewportTop, 0, childViews.length-1),
          bodyHeight = this.get('wrapperHeight') ? this.$().height() : Ember.$('body').height(),
          bottomView = topView,
          offsetFixedTopElement = this.get('offsetFixedTopElement'),
          offsetFixedBottomElement = this.get('offsetFixedBottomElement');

      if (windowBottom > bodyHeight) { windowBottom = bodyHeight; }
      if (viewportBottom > bodyHeight) { viewportBottom = bodyHeight; }

      if (offsetFixedTopElement) {
        windowTop += (offsetFixedTopElement.outerHeight(true) || 0);
      }

      if (offsetFixedBottomElement) {
        windowBottom -= (offsetFixedBottomElement.outerHeight(true) || 0);
      }

      // Find the bottom view and what's onscreen
      while (bottomView < childViews.length) {
        var view = childViews[bottomView],
          $view = view.$(),
          // in case of not full-window scrolling
          scrollOffset = this.get('wrapperTop') || 0,
          viewTop = $view.offset().top + scrollOffset,
          viewBottom = viewTop + $view.height();

        if (viewTop > viewportBottom) { break; }
        toUncloak.push(view);

        if (viewBottom > windowTop && viewTop <= windowBottom) {
          onscreen.push(view.get('content'));
          onscreenCloaks.push(view);
        }

        bottomView++;
      }
      if (bottomView >= childViews.length) { bottomView = childViews.length - 1; }

      // If our controller has a `sawObjects` method, pass the on screen objects to it.
      var controller = this.get('controller');
      if (onscreen.length) {
        this.setProperties({topVisible: onscreen[0], bottomVisible: onscreen[onscreen.length-1]});
        if (controller && controller.sawObjects) {
          Em.run.schedule('afterRender', function() {
            controller.sawObjects(onscreen);
          });
        }
      } else {
        this.setProperties({topVisible: null, bottomVisible: null});
      }

      var toCloak = childViews.slice(0, topView).concat(childViews.slice(bottomView+1));

      this._uncloak = toUncloak;
      if(this._nextUncloak){
        Em.run.cancel(this._nextUncloak);
        this._nextUncloak = null;
      }

      Em.run.schedule('afterRender', this, function() {
        onscreenCloaks.forEach(function (v) {
          if(v && v.uncloak) {
            v.uncloak();
          }
        });
        toCloak.forEach(function (v) { v.cloak(); });
        if (self._nextUncloak) { Em.run.cancel(self._nextUncloak); }
        self._nextUncloak = Em.run.later(self, self.uncloakQueue,50);
      });

      for (var j=bottomView; j<childViews.length; j++) {
        var checkView = childViews[j];
        if (!checkView.get("childViews.length")) {
          if (!checkView.get('loading') && this.get('loadingHTML')) {
            checkView.$().html(this.get('loadingHTML'));
          }
          return;
        }
      }

    },

    uncloakQueue: function(){
      var maxPerRun = 3, delay = 50, processed = 0, self = this;

      if(this._uncloak){
        while(processed < maxPerRun && this._uncloak.length>0){
          var view = this._uncloak.shift();
          if(view && view.uncloak && !view.get("childViews.length")){
            Em.run.schedule('afterRender', view, view.uncloak);
            processed++;
          }
        }
        if(this._uncloak.length === 0){
          this._uncloak = null;
        } else {
          Em.run.schedule('afterRender', self, function(){
            if(self._nextUncloak){
              Em.run.cancel(self._nextUncloak);
            }
            self._nextUncloak = Em.run.next(self, function(){
              if(self._nextUncloak){
                Em.run.cancel(self._nextUncloak);
              }
              self._nextUncloak = Em.run.later(self,self.uncloakQueue,delay);
            });
          });
        }
      }
    },

    scrollTriggered: function() {
      Em.run.scheduleOnce('afterRender', this, 'scrolled');
    },

    _startEvents: Ember.on('didInsertElement', function() {

      if (this.get('offsetFixed')) {
        Em.warn("Cloaked-collection's `offsetFixed` is deprecated. Use `offsetFixedTop` instead.");
      }

      var self = this,
          offsetFixedTop = this.get('offsetFixedTop') || this.get('offsetFixed'),
          offsetFixedBottom = this.get('offsetFixedBottom'),
          onScrollMethod = function() {
            Ember.run.debounce(self, 'scrollTriggered', 10);
          };

      if (offsetFixedTop) {
        this.set('offsetFixedTopElement', Ember.$(offsetFixedTop));
      }

      if (offsetFixedBottom) {
        this.set('offsetFixedBottomElement', Ember.$(offsetFixedBottom));
      }

      Ember.$(document).bind('touchmove', onScrollMethod);
      Ember.$(window).bind('scroll', onScrollMethod);
      this.addObserver('wrapperTop', self, onScrollMethod);
      this.addObserver('wrapperHeight', self, onScrollMethod);
      this.addObserver('content.@each', self, onScrollMethod);
      this.scrollTriggered();

      this.set('scrollingEnabled', true);
    }),

    cleanUp: function() {
      Ember.$(document).unbind('touchmove.ember-cloak');
      Ember.$(window).unbind('scroll.ember-cloak');
      this.set('scrollingEnabled', false);
    },

    _endEvents: Ember.on('willDestroyElement', function() {
      this.cleanUp();
    })
  });

  /**
    A cloaked view is one that removes its content when scrolled off the screen

    @class CloakedView
    @extends Ember.View
    @namespace Ember
  **/
  Ember.CloakedView = Ember.ContainerView.extend({
    attributeBindings: ['style'],

    /**
      Triggers the set up for rendering a view that is cloaked.

      @method uncloak
    */
    uncloak: function() {
      var state = this._state || this.state;
      if (state !== 'inDOM' && state !== 'preRender') { return; }

      if (!this.get("childViews.length")) {
        var model = this.get('content'),
            controller = null,
            container = this.get('container');

        // Wire up the itemController if necessary
        var controllerName = this.get('cloaksController');
        if (controllerName) {
          var controllerFullName = 'controller:' + controllerName,
              factory = container.lookupFactory(controllerFullName),
              parentController = this.get('controller');

          // let ember generate controller if needed
          if (factory === undefined) {
            factory = Ember.generateControllerFactory(container, controllerName, model);

            // inform developer about typo
            Ember.Logger.warn('ember-cloaking: can\'t lookup controller by name "' + controllerFullName + '".');
            Ember.Logger.warn('ember-cloaking: using ' + factory.toString() + '.');
          }

          controller = factory.create({
            model: model,
            parentController: parentController,
            target: parentController
          });
        }

        var createArgs = {},
            target = controller || model;

        if (this.get('preservesContext')) {
          createArgs.content = target;
        } else {
          createArgs.context = target;
        }
        if (controller) { createArgs.controller = controller; }
        this.setProperties({
          style: null,
          loading: false
        });

        this.pushObject(this.createChildView(this.get('cloaks'), createArgs))
        this.rerender();
      }
    },

    /**
      Removes the view from the DOM and tears down all observers.

      @method cloak
    */
    cloak: function() {
      var self = this;

      if (this.get("childViews.length") && (this._state || this.state) === 'inDOM') {
        var style = 'height: ' + this.$().height() + 'px;';
        this.set('style', style);
        this.$().prop('style', style);

        // We need to remove the container after the height of the element has taken
        // effect.
        Ember.run.schedule('afterRender', function() {
          self.get("childViews").forEach(function(view) {
            self.removeObject(view);
            view.remove();
          });
        });
      }
    },

    _setHeights: Ember.on('didInsertElement', function(){
      if (!this.get("childViews.length")) {
        // setting default height
        // but do not touch if height already defined
        if(!this.$().height()){
          var defaultHeight = 100;
          if(this.get('defaultHeight')) {
            defaultHeight = this.get('defaultHeight');
          }

          this.$().css('height', defaultHeight);
        }
      }
    })
  });

  Ember.Handlebars.registerHelper('cloaked-collection', function(options) {
    var hash = options.hash,
        types = options.hashTypes;

    for (var prop in hash) {
      if (types[prop] === 'ID') {
        hash[prop + 'Binding'] = hash[prop];
        delete hash[prop];
      }
    }
    return Ember.Handlebars.helpers.view.call(this, Ember.CloakedCollectionView, options);
  });

})();
<|endoftext|>


<commit_before>/*
 * Copyright © 2013 VillageReach.  All Rights Reserved.  This Source Code Form is subject to the terms of the Mozilla Public License, v. 2.0.
 *
 * If a copy of the MPL was not distributed with this file, You can obtain one at http://mozilla.org/MPL/2.0/.
 */

function SupplylineController($scope,$location,$dialog,messageService,ReportPrograms, AllFacilites, SupervisoryNodes, Supplylines, Supplyline, SupplylineDelete) {

    //initialize
    $scope.supplylinesBackupMap = [];
    $scope.newSupplyline = {};
    $scope.supplylines = {};
    $scope.editSupplyline = {};
    $scope.creationError = '';

    if ($scope.$parent.newSupplylineMode || $scope.$parent.editSupplylineMode) {
        $scope.AddEditMode = true;
        $scope.title = ($scope.$parent.newSupplylineMode) ? $scope.title = 'Add Supply Line' : $scope.title = 'Edit Supply Line';

    } else {
        $scope.AddEditMode = false;
        $scope.title = 'Supply Lines';
    }

    // drop down lists
    ReportPrograms.get(function (data){
        $scope.programs = data.programs;
        //alert(JSON.stringify($scope.programs, null, 4));
    });

    AllFacilites.get(function(data){
        $scope.facilities = data.allFacilities;
    });

    //$scope.facilities  ={};

    SupervisoryNodes.get(function(data){
        $scope.supervisoryNodes = data.supervisoryNodes;
    });

    // all supply lines
    Supplylines.get({}, function (data) {
        $scope.initialSupplylines = angular.copy(data.supplylines, $scope.initialSupplylines);
        $scope.supplylines = data.supplylines;
        //alert(JSON.stringify($scope.supplylines, null, 4));
        for(var supplylineIndex in data.supplylines){
            var supplyline = data.supplylines[supplylineIndex];
            $scope.supplylinesBackupMap[supplyline.id] =  $scope.getBackupSupplyline(supplyline);
        }

    }, function (data) {
        $location.path($scope.$parent.sourceUrl);
    });

//  given supply line
    $scope.getBackupSupplyline = function (supplyline) {
        return {
            programid: supplyline.programid,
            supplyingfacilityid: supplyline.supplyingfacilityid,
            supervisorynodeid: supplyline.supervisorynodeid,
            description: supplyline.description
        };
    };

    $scope.processSave = function (supplyline,form)
    {
      if ($scope.$parent.newSupplylineMode)
      {
         $scope.createSupplyline();
      } else {
          $scope.updateSupplyline(supplyline, form);
      }
    }

    //  switch to new mode
    $scope.startAddNewSupplyline = function() {
        $scope.setFlags('add','start');
        $scope.$parent.formActive = "supplyline-form-active";
    };

    // create supply line
    $scope.createSupplyline = function () {
        $scope.error = "";

        if ($scope.supplylineForm.$invalid) {
            $scope.showError = true;
            return;
        }
        $scope.showError = false;
        Supplylines.save({}, $scope.supplyline, function (data) {

            //alert(JSON.stringify(data.supplyline, null, 4));
            $scope.supplylines.unshift(data.supplyline);
            $scope.completeAddNewSupplyline(data.supplyline);
            $scope.message = data.success;
            setTimeout(function() {
                $scope.$apply(function() {
                    $scope.supplylineslist = data.supplyLineList;
                    $scope.message = "";
                });
            }, 4000);
            $scope.newSupplyline = {};
        }, function (data) {
            $scope.message = "";
            $scope.creationError = data.data.error;
        });
    };

   //  backup record
    $scope.completeAddNewSupplyline = function(supplyline) {
        $scope.supplylinesBackupMap[supplyline.id] = $scope.getBackupSupplyline(supplyline);
        $scope.showError = false;
        $scope.setFlags('add','end');
    };

// cancel record
    $scope.cancelAddNewSupplyline = function(supplyline) {
        $scope.showError = false;
        $scope.setFlags('cancel','cancel');
      };

//    //  scope is undefined,
    $scope.supplylineLoaded = function () {
        //alert(JSON.stringify($scope.supplylines, null, 4));
        return !($scope.supplylines == undefined || $scope.supplylines == null);
    };

    //
    $scope.startSupplylineEdit = function (supplylineUnderEdit) {
        $scope.supplylinesBackupMap[supplylineUnderEdit.id].editFormActive = "supplyline-form-active";
        Supplyline.get({id: supplylineUnderEdit.id}, function (data) {
        $scope.supplyline = data.supplyline;
            //alert(JSON.stringify($scope.supplyline, null, 4));
        }, {});
        $scope.setFlags('edit','start');
    };
    // update
    $scope.updateSupplyline = function (supplyline, form) {

       function updateUiData(sourceSupplyline) {

            var supplylinesLength = $scope.supplylines.length;

            for (var i = 0; i < supplylinesLength; i++) {
                if ($scope.supplylines[i].id == sourceSupplyline.id) {
                    $scope.supplylines[i].program = sourceSupplyline.program;
                    $scope.supplylines[i].supervisoryNode = sourceSupplyline.supervisoryNode;
                    $scope.supplylines[i].supplyingFacility = sourceSupplyline.supplyingFacility;
                    $scope.supplylines[i].description = sourceSupplyline.description;
                    $scope.supplylines[i].modifiedBy = sourceSupplyline.modifiedBy;
                    $scope.supplylines[i].modifiedDate = sourceSupplyline.modifiedDate;
                }
            }

        }
          $scope.error = "";
        if (form.$invalid) {
            $scope.showErrorForEdit = true;
            return;
        }

        $scope.supplylinesBackupMap[supplyline.id].error = '';
        $scope.showErrorForEdit = true;

        Supplyline.update({id:supplyline.id}, supplyline, function (data) {
            var returnedSupplyline = data.supplyline;
            $scope.supplylinesBackupMap[returnedSupplyline.id] = $scope.getBackupSupplyline(returnedSupplyline);
            updateUiData(data.supplylines);
            $scope.completeEditSupplyline(returnedSupplyline);
            $scope.message = data.success;
            setTimeout(function() {
                $scope.$apply(function() {
                    // refresh list
                    $scope.message = "";
                });
            }, 4000);
            $scope.error = "";
            $scope.newSupplyline = {};
            $scope.editSupplyline = {};
            $scope.AddEditMode = false;

            $scope.supplylinesBackupMap[returnedSupplyline.id].editFormActive = 'updated-item';
            $scope.supplylinesBackupMap[returnedSupplyline.id].edit = false;
        }, function (data) {
            $scope.message = "";
            $scope.startSupplylineEdit(supplyline);
            $scope.supplylinesBackupMap[supplyline.id].error = data.data.error;
        });
    };

    //  backup record
    $scope.completeEditSupplyline = function(supplyline) {
        $scope.supplylinesBackupMap[supplyline.id] = $scope.getBackupSupplyline(supplyline);

        var supplylinesLength = $scope.supplylines.length;

        for (var i = 0; i < supplylinesLength; i++) {
            if ($scope.supplylines[i].id == supplyline.id) {
                $scope.supplylines[i].program = supplyline.program;
                $scope.supplylines[i].supervisoryNode = supplyline.supervisoryNode;
                $scope.supplylines[i].supplyingFacility = supplyline.supplyingFacility;
                $scope.supplylines[i].description = supplyline.description;
                $scope.supplylines[i].modifiedBy = supplyline.modifiedBy;
                $scope.supplylines[i].modifiedDate = supplyline.modifiedDate;
            }
        }
        $scope.showError = false;
        $scope.setFlags('edit','end');
    };

    $scope.cancelSupplylineEdit = function (supplylineUnderEdit) {
        var backupSupplylineRow = $scope.supplylinesBackupMap[supplylineUnderEdit.id];
        supplylineUnderEdit.programid = backupSupplylineRow.programid;
        supplylineUnderEdit.supervisorynodeid = backupSupplylineRow.supervisorynodeid;
        supplylineUnderEdit.supplyingfacilityid = backupSupplylineRow.supplyingfacilityid;
        supplylineUnderEdit.description = backupSupplylineRow.description;
        $scope.supplylinesBackupMap[supplylineUnderEdit.id].error = '';
        $scope.supplylinesBackupMap[supplylineUnderEdit.id].editFormActive = '';
        alert('cancel');
        $scope.setFlags('cancel','cancel');
    };

    $scope.showConfirmSupplylineDeleteWindow = function (supplylineUnderDelete) {
        var dialogOpts = {
            id: "deleteSupplylineDialog",
            header: messageService.get('Delete supplyline'),
            body: messageService.get('delete.facility.confirm', supplylineUnderDelete.description, supplylineUnderDelete.id)
        };
        $scope.supplylineUnderDelete = supplylineUnderDelete;
        OpenLmisDialog.newDialog(dialogOpts, $scope.deleteSupplylineCallBack, $dialog, messageService);
    };

    $scope.deleteSupplylineCallBack = function (result) {
        if (!result)
        {
            $scope.supplylinesBackupMap[$scope.supplylineUnderDelete.id].deleted = false;
            return;
        }

          SupplylineDelete.get({id : $scope.supplylineUnderDelete.id }, $scope.supplyline, function (data) {
          $scope.message = data.success;
          setTimeout(function() {
                $scope.$apply(function() {
                    $scope.supplylines = data.supplylines;
                    $scope.message = "";
                });
            }, 4000);
            $scope.error = "";
            $scope.newSupplyline = {};
            $scope.editSupplyline = {};
            $scope.setFlags('delete','delete');

         });

    };

 $scope.setFlags = function(mode, state)
 {

         $scope.$parent.editSupplylineMode = false;
         $scope.$parent.newSupplylineMode = false;
         $scope.AddEditMode = false;
         $scope.title = 'Supply Lines';

       if (mode == 'edit' && state == 'start') {
        $scope.$parent.editSupplylineMode = true;
        $scope.$parent.newSupplylineMode = false;
        $scope.AddEditMode = true;
        $scope.title = 'Edit Supply Line';
    }

     if (mode == 'edit' && state == 'end') {
         $scope.$parent.editSupplylineMode = false;
         $scope.$parent.newSupplylineMode = false;
         $scope.AddEditMode = false;
         $scope.title = 'Supply Lines';
     }

     if (mode == 'add' && state == 'start') {
         $scope.$parent.editSupplylineMode = false;
         $scope.$parent.newSupplylineMode = true;
         $scope.AddEditMode = true;
         $scope.title = 'Add Supply Line';
     }

     if (mode == 'add' && state == 'end') {
         $scope.$parent.editSupplylineMode = false;
         $scope.$parent.newSupplylineMode = false;
         $scope.AddEditMode = false;
         $scope.title = 'Supply Lines';
     }

 }

    //

};
<commit_msg>ELMIS-390 Changes for the save.  Fixed AngularJS errors<commit_after>/*
 * Copyright © 2013 VillageReach.  All Rights Reserved.  This Source Code Form is subject to the terms of the Mozilla Public License, v. 2.0.
 *
 * If a copy of the MPL was not distributed with this file, You can obtain one at http://mozilla.org/MPL/2.0/.
 */

function SupplylineController($scope,$location,$dialog,messageService,ReportPrograms, AllFacilites, SupervisoryNodes, Supplylines, Supplyline, SupplylineDelete) {

    //initialize
    $scope.supplylinesBackupMap = [];
    $scope.newSupplyline = {};
    $scope.supplylines = {};
    $scope.editSupplyline = {};
    $scope.creationError = '';

    if ($scope.$parent.newSupplylineMode || $scope.$parent.editSupplylineMode) {
        $scope.AddEditMode = true;
        $scope.title = ($scope.$parent.newSupplylineMode) ? $scope.title = 'Add Supply Line' : $scope.title = 'Edit Supply Line';

    } else {
        $scope.AddEditMode = false;
        $scope.title = 'Supply Lines';
    }

    // drop down lists
    ReportPrograms.get(function (data){
        $scope.programs = data.programs;
        //alert(JSON.stringify($scope.programs, null, 4));
    });

    AllFacilites.get(function(data){
        $scope.facilities = data.allFacilities;
    });

    //$scope.facilities  ={};

    SupervisoryNodes.get(function(data){
        $scope.supervisoryNodes = data.supervisoryNodes;
    });

    // all supply lines
    Supplylines.get({}, function (data) {
        $scope.initialSupplylines = angular.copy(data.supplylines, $scope.initialSupplylines);
        $scope.supplylines = data.supplylines;
        //alert(JSON.stringify($scope.supplylines, null, 4));
        for(var supplylineIndex in data.supplylines){
            var supplyline = data.supplylines[supplylineIndex];
            $scope.supplylinesBackupMap[supplyline.id] =  $scope.getBackupSupplyline(supplyline);
        }

    }, function (data) {
        $location.path($scope.$parent.sourceUrl);
    });

//  given supply line
    $scope.getBackupSupplyline = function (supplyline) {
        return {
            programid: supplyline.programid,
            supplyingfacilityid: supplyline.supplyingfacilityid,
            supervisorynodeid: supplyline.supervisorynodeid,
            description: supplyline.description
        };
    };

    $scope.processSave = function (supplyline,form)
    {
      if ($scope.$parent.newSupplylineMode)
      {
         $scope.createSupplyline();
      } else {
          $scope.updateSupplyline(supplyline, form);
      }
    }

    //  switch to new mode
    $scope.startAddNewSupplyline = function() {
        $scope.setFlags('add','start');
        $scope.$parent.formActive = "supplyline-form-active";
    };

    // create supply line
    $scope.createSupplyline = function () {
        $scope.error = "";

        var form = document.getElementById('createSupplylineForm');

        if (form.$invalid) {
            $scope.showError = true;
            return;
        }
        $scope.showError = false;
        Supplylines.save({}, $scope.supplyline, function (data) {

            //alert(JSON.stringify(data.supplyline, null, 4));
            $scope.supplylines.unshift(data.supplyline);
            $scope.completeAddNewSupplyline(data.supplyline);
            $scope.message = data.success;
            setTimeout(function() {
                $scope.$apply(function() {
                    $scope.supplylineslist = data.supplyLineList;
                    $scope.message = "";
                });
            }, 4000);
            $scope.newSupplyline = {};
        }, function (data) {
            $scope.message = "";
            $scope.creationError = data.data.error;
        });
    };

   //  backup record
    $scope.completeAddNewSupplyline = function(supplyline) {
        $scope.supplylinesBackupMap[supplyline.id] = $scope.getBackupSupplyline(supplyline);
        $scope.showError = false;
        $scope.setFlags('add','end');
    };

// cancel record
    $scope.cancelAddNewSupplyline = function(supplyline) {
        $scope.showError = false;
        $scope.setFlags('cancel','cancel');
      };

//    //  scope is undefined,
    $scope.supplylineLoaded = function () {
        //alert(JSON.stringify($scope.supplylines, null, 4));
        return !($scope.supplylines == undefined || $scope.supplylines == null);
    };

    //
    $scope.startSupplylineEdit = function (supplylineUnderEdit) {
        $scope.supplylinesBackupMap[supplylineUnderEdit.id].editFormActive = "supplyline-form-active";
        Supplyline.get({id: supplylineUnderEdit.id}, function (data) {
        $scope.supplyline = data.supplyline;
            //alert(JSON.stringify($scope.supplyline, null, 4));
        }, {});
        $scope.setFlags('edit','start');
    };
    // update
    $scope.updateSupplyline = function (supplyline, form) {

       function updateUiData(sourceSupplyline) {

            var supplylinesLength = $scope.supplylines.length;

            for (var i = 0; i < supplylinesLength; i++) {
                if ($scope.supplylines[i].id == sourceSupplyline.id) {
                    $scope.supplylines[i].program = sourceSupplyline.program;
                    $scope.supplylines[i].supervisoryNode = sourceSupplyline.supervisoryNode;
                    $scope.supplylines[i].supplyingFacility = sourceSupplyline.supplyingFacility;
                    $scope.supplylines[i].description = sourceSupplyline.description;
                    $scope.supplylines[i].modifiedBy = sourceSupplyline.modifiedBy;
                    $scope.supplylines[i].modifiedDate = sourceSupplyline.modifiedDate;
                }
            }

        }
          $scope.error = "";
        if (form.$invalid) {
            $scope.showErrorForEdit = true;
            return;
        }

        $scope.supplylinesBackupMap[supplyline.id].error = '';
        $scope.showErrorForEdit = true;

        Supplyline.update({id:supplyline.id}, supplyline, function (data) {
            var returnedSupplyline = data.supplyline;
            $scope.supplylinesBackupMap[returnedSupplyline.id] = $scope.getBackupSupplyline(returnedSupplyline);
            updateUiData(data.supplylines);
            $scope.completeEditSupplyline(returnedSupplyline);
            $scope.message = data.success;
            setTimeout(function() {
                $scope.$apply(function() {
                    // refresh list
                    $scope.message = "";
                });
            }, 4000);
            $scope.error = "";
            $scope.newSupplyline = {};
            $scope.editSupplyline = {};
            $scope.AddEditMode = false;

            $scope.supplylinesBackupMap[returnedSupplyline.id].editFormActive = 'updated-item';
            $scope.supplylinesBackupMap[returnedSupplyline.id].edit = false;
        }, function (data) {
            $scope.message = "";
            $scope.startSupplylineEdit(supplyline);
            $scope.supplylinesBackupMap[supplyline.id].error = data.data.error;
        });
    };

    //  backup record
    $scope.completeEditSupplyline = function(supplyline) {
        $scope.supplylinesBackupMap[supplyline.id] = $scope.getBackupSupplyline(supplyline);

        var supplylinesLength = $scope.supplylines.length;

        for (var i = 0; i < supplylinesLength; i++) {
            if ($scope.supplylines[i].id == supplyline.id) {
                $scope.supplylines[i].program = supplyline.program;
                $scope.supplylines[i].supervisoryNode = supplyline.supervisoryNode;
                $scope.supplylines[i].supplyingFacility = supplyline.supplyingFacility;
                $scope.supplylines[i].description = supplyline.description;
                $scope.supplylines[i].modifiedBy = supplyline.modifiedBy;
                $scope.supplylines[i].modifiedDate = supplyline.modifiedDate;
            }
        }
        $scope.showError = false;
        $scope.setFlags('edit','end');
    };

    $scope.cancelSupplylineEdit = function (supplylineUnderEdit) {
        var backupSupplylineRow = $scope.supplylinesBackupMap[supplylineUnderEdit.id];
        supplylineUnderEdit.programid = backupSupplylineRow.programid;
        supplylineUnderEdit.supervisorynodeid = backupSupplylineRow.supervisorynodeid;
        supplylineUnderEdit.supplyingfacilityid = backupSupplylineRow.supplyingfacilityid;
        supplylineUnderEdit.description = backupSupplylineRow.description;
        $scope.supplylinesBackupMap[supplylineUnderEdit.id].error = '';
        $scope.supplylinesBackupMap[supplylineUnderEdit.id].editFormActive = '';
        alert('cancel');
        $scope.setFlags('cancel','cancel');
    };

    $scope.showConfirmSupplylineDeleteWindow = function (supplylineUnderDelete) {
        var dialogOpts = {
            id: "deleteSupplylineDialog",
            header: messageService.get('Delete supplyline'),
            body: messageService.get('delete.facility.confirm', supplylineUnderDelete.description, supplylineUnderDelete.id)
        };
        $scope.supplylineUnderDelete = supplylineUnderDelete;
        OpenLmisDialog.newDialog(dialogOpts, $scope.deleteSupplylineCallBack, $dialog, messageService);
    };

    $scope.deleteSupplylineCallBack = function (result) {
        if (!result)
        {
            $scope.supplylinesBackupMap[$scope.supplylineUnderDelete.id].deleted = false;
            return;
        }

          SupplylineDelete.get({id : $scope.supplylineUnderDelete.id }, $scope.supplyline, function (data) {
          $scope.message = data.success;
          setTimeout(function() {
                $scope.$apply(function() {
                    $scope.supplylines = data.supplylines;
                    $scope.message = "";
                });
            }, 4000);
            $scope.error = "";
            $scope.newSupplyline = {};
            $scope.editSupplyline = {};
            $scope.setFlags('delete','delete');

         });

    };

 $scope.setFlags = function(mode, state)
 {

         $scope.$parent.editSupplylineMode = false;
         $scope.$parent.newSupplylineMode = false;
         $scope.AddEditMode = false;
         $scope.title = 'Supply Lines';

       if (mode == 'edit' && state == 'start') {
        $scope.$parent.editSupplylineMode = true;
        $scope.$parent.newSupplylineMode = false;
        $scope.AddEditMode = true;
        $scope.title = 'Edit Supply Line';
    }

     if (mode == 'edit' && state == 'end') {
         $scope.$parent.editSupplylineMode = false;
         $scope.$parent.newSupplylineMode = false;
         $scope.AddEditMode = false;
         $scope.title = 'Supply Lines';
     }

     if (mode == 'add' && state == 'start') {
         $scope.$parent.editSupplylineMode = false;
         $scope.$parent.newSupplylineMode = true;
         $scope.AddEditMode = true;
         $scope.title = 'Add Supply Line';
     }

     if (mode == 'add' && state == 'end') {
         $scope.$parent.editSupplylineMode = false;
         $scope.$parent.newSupplylineMode = false;
         $scope.AddEditMode = false;
         $scope.title = 'Supply Lines';
     }

 }

    //

};
<|endoftext|>


<commit_before>var h = require('html')

function Editor() {
  this.el = h('.editor', [
    h('.layers-panel'),
    h('.canvas'),
    h('.inspector-panel')
  ])
}

Editor.prototype.start = function() {
  document.body.appendChild(this.el)
  return this
}

exports = Editor
<commit_msg>Use panels in editor<commit_after>var h = require('html')
var Panel = require('panel')

function Editor() {
  this.layersPanel = new Panel(this, 215, h('.layers-panel'))
  this.inspectorPanel = new Panel(this, 215, h('.inspector-panel'))

  this.el = h('.editor', [
    this.layersPanel.el,
    h('.canvas'),
    this.inspectorPanel.el
  ])
}

Editor.prototype.start = function() {
  document.body.appendChild(this.el)
  return this
}

exports = Editor
<|endoftext|>