<commit_before>(function() {
  shl.db = {};

  //function to create table based on an object
  shl.db.createTable = function (table) {
    //bootstrap database
    var db = Ti.Database.open('Outreach');
    var qstring = 'CREATE TABLE IF NOT EXISTS ' + table.name + ' (';
    var firstField = true;
    for (var field in table.fields) {
      if (table.fields.hasOwnProperty(field)) {
        if (!firstField) {
          qstring += ', ';
        }
        qstring += (field + ' ' + table.fields[field]);
        firstField = false;
      }
    }
    qstring += ')'
    db.execute('DROP TABLE IF EXISTS ' + table.name); //TODO Remove Before Flight
    db.execute(qstring);
    db.close();
    return table;
  }

  //create the prospects table; save field defs for later
  shl.db.prospects = shl.db.createTable({
    name : 'prospects',
    fields : {
      id : 'INTEGER PRIMARY KEY',
      last : 'TEXT',
      firstMale : 'TEXT',
      firstFemale : 'TEXT',
      street : 'TEXT',
      city : 'TEXT',
      state : 'TEXT',
      zip : 'TEXT',
      country : 'TEXT',
      phoneHome : 'TEXT',
      phoneMoble : 'TEXT',
      email : 'TEXT',
      firstContactDate : 'INTEGER',
      firstContactPoint : 'TEXT',
      previouslySaved : 'INTEGER',
      previouslyBaptized : 'INTEGER',
      sundaySchool : 'INTEGER',
      status : 'TEXT',
      nextStep : 'TEXT',
      lastContact : 'INTEGER',
      created : 'INTEGER',
      modified : 'INTEGER',
      uuid : 'TEXT'
    }
  });

  //base class
  shl.db.Model = function() {
    Ti.API.info('just made an object of type Model');
    Ti.API.info(JSON.stringify(this));
  }

  shl.db.Model.prototype.save = function() {
    Ti.API.info('just called save method for Model');
    Ti.API.info(JSON.stringify(this));
  }

  shl.db.Model.prototype.find = function(params) {
    if (!params){
      return false;
    }
    if (typeof(params) === "number"){

    }

  }

  shl.Prospect = function() {
    shl.db.Model.call(this);
    Ti.API.info('just made an object of type Prospect');
    Ti.API.info(JSON.stringify(this));
  }

  shl.Prospect.prototype = new shl.db.Model();
  shl.Prospect.prototype.constructor = shl.Prospect;

  //we can define static defaults here - these will get saved to the database if no other is specified
  shl.db.Model.prototype.previouslySaved = 0;
  shl.db.Model.prototype.previouslyBaptized = 0;
  shl.db.Model.prototype.sundaySchool = 0;
  shl.db.Model.prototype.status = 'Active Prospect';
  shl.db.Model.prototype.nextStep = 'Salvation';

  //adds a new prospect to the database
  //_item : an object with ALL the attributes listed, else it will break
  shl.db.insertProspect = function(_item) {
    var db = Ti.Database.open('Outreach');
    var currentTimeStamp = Math.round(new Date().getTime()/1000.0);
    db.execute('INSERT INTO prospects(last,firstMale, firstFemale, street, city, state, zip, country, phoneHome, '+
    'phoneMoble, email, firstContactDate, firstContactPoint, previouslySaved, previouslyBaptized, sundaySchool, status, nextStep, lastContact, created, modified, uuid) '+
    'VALUES(?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?)',
    ('last' in _item) ? _item.last : "",
    ('firstMale' in _item) ? _item.firstMale : "",
    ('firstFemale' in _item) ? _item.firstFemale : "",
    ('street' in _item) ? _item.street : "",
    ('city' in _item) ? _item.city : "",
    ('state' in _item) ? _item.state : "",
    ('zip' in _item) ? _item.zip : "",
    ('country' in _item) ? _item.country : "",
    ('phoneHome' in _item) ? _item.phoneHome : "",
    ('phoneMoble' in _item) ? _item.phoneMoble : "",
    ('email' in _item) ? _item.email : "",
    ('firstContactDate' in _item) ? _item.firstContactDate : currentTimeStamp,
    ('firstContactPoint' in _item) ? _item.firstContactPoint : "",
    ('previouslySaved' in _item) ? _item.previouslySaved : 0,
    ('previouslyBaptized' in _item) ? _item.previouslyBaptized : 0,
    ('sundaySchool' in _item) ? _item.sundaySchool : 0,
    ('status' in _item) ? _item.status : "Active Prospect",
    ('nextStep' in _item) ? _item.nextStep : "Salvation",
    ('lastContact' in _item) ? _item.lastContact : currentTimeStamp,
    ('created' in _item) ? _item.created : currentTimeStamp,
    ('modified' in _item) ? _item.modified : currentTimeStamp,
    ('uuid' in _item) ? _item.uuid : Ti.Platform.createUUID()
    );
    //TODO check to see if uuid, timestamp are empty
    var lastId = db.lastInsertRowId;
    db.close();
    return lastId;
  }

  //low level update function
  //TODO we need a higher level function that updates status flags and the like
  //will crash if there is not a valid id
  //all other properties must be valid columbs of the prospects table
  //_item an object that contains only data to be updated and an id
  shl.db.updateProspect = function(_item) {

    var first = true;
    var subList = [];
    var set = '';
    var rows = 0;

    for (var property in _item) {
      //TODO check against a list of valid properties
      if (_item[property] != undefined && property != 'id') {
        set += (first == false ? ', ' : '') + property + ' = ?';
        subList.push(_item[property]);
        first = false;
      }
    }
    subList.push(_item.id);
    if (set != '') {
      var db = Ti.Database.open('Outreach');
      db.execute('UPDATE prospects SET ' + set + ' WHERE id = ?', subList);
      rows = db.rowsAffected;
      db.close();
    }
    return rows;
  }

  //dumps all the items in the prospect table into an array of objects for testing
  //TODO pass this funciton a WHERE statement
  shl.db.listAllProspects = function() {
    var prospectList = [];
    var db = Ti.Database.open('Outreach');
    var result = db.execute('SELECT * FROM prospects ORDER BY last ASC');
    while(result.isValidRow()) {
      prospectList.push({
        id: result.fieldByName('id'),
        last: result.fieldByName('last'),
        firstMale: result.fieldByName('firstMale'),
        firstFemale: result.fieldByName('firstFemale'),
        street: result.fieldByName('street'),
        city: result.fieldByName('city'),
        state: result.fieldByName('state'),
        zip: result.fieldByName('zip'),
        country: result.fieldByName('country'),
        phoneHome: result.fieldByName('phoneHome'),
        phoneMoble: result.fieldByName('phoneMoble'),
        email: result.fieldByName('email'),
        firstContactDate: result.fieldByName('firstContactDate'),
        firstContactPoint: result.fieldByName('firstContactPoint'),
        previouslySaved: result.fieldByName('previouslySaved'),
        previouslyBaptized: result.fieldByName('previouslyBaptized'),
        sundaySchool: result.fieldByName('sundaySchool'),
        status: result.fieldByName('status'),
        nextStep: result.fieldByName('nextStep'),
        lastContact: result.fieldByName('lastContact'),
        created: result.fieldByName('created'),
        modified: result.fieldByName('modified'),
        uuid: result.fieldByName('uuid')
      });
      result.next();
    }
    result.close();
    db.close();
    return prospectList;
  }

  shl.db.deleteProspect = function(_id) {
    var db = Ti.Database.open('Outreach');
    db.execute("DELETE FROM prospects WHERE id = ?", _id);
    db.close();
  }

  shl.db.getProspect = function(prospectId) {
    var db = Ti.Database.open('Outreach');
    var result = db.execute('SELECT * FROM prospects WHERE id = ?', prospectId);
    var prospect = {
      id: result.fieldByName('id'),
      last: result.fieldByName('last'),
      firstMale: result.fieldByName('firstMale'),
      firstFemale: result.fieldByName('firstFemale'),
      street: result.fieldByName('street'),
      city: result.fieldByName('city'),
      state: result.fieldByName('state'),
      zip: result.fieldByName('zip'),
      country: result.fieldByName('country'),
      phoneHome: result.fieldByName('phoneHome'),
      phoneMoble: result.fieldByName('phoneMoble'),
      email: result.fieldByName('email'),
      firstContactDate: result.fieldByName('firstContactDate'),
      firstContactPoint: result.fieldByName('firstContactPoint'),
      previouslySaved: result.fieldByName('previouslySaved'),
      previouslyBaptized: result.fieldByName('previouslyBaptized'),
      sundaySchool: result.fieldByName('sundaySchool'),
      status: result.fieldByName('status'),
      nextStep: result.fieldByName('nextStep'),
      lastContact: result.fieldByName('lastContact'),
      created: result.fieldByName('created'),
      modified: result.fieldByName('modified'),
      uuid: result.fieldByName('uuid')
    };
    result.close();
    db.close();
    return prospect;
  }

  //testing stuff
  //TODO remove all this testing code and its evil global vars

  var testProspect = new shl.Prospect();
  testProspect.save();
  testProspect.find();
  Ti.API.info(testProspect.nextStep);

  var lastId = shl.db.insertProspect({
    last: "Smith",
    firstMale: "John",
    firstFemale: "Jill",
    street: "1234 Asdf St.",
    city: "Lancaster",
    state: "CA",
    zip: "93535",
    country: "United States",
    phoneHome: "(360)456-6436",
    phoneMoble: "661.158.4882",
    email: "test@example.com",
    firstContactDate: 1305998777,
    firstContactPoint: "Door knocking",
    previouslySaved: 0,
    previouslyBaptized: 0,
    sundaySchool: 0,
    status: "Active Prospect",
    nextStep: "Salvation",
    lastContact: "1306171747",
    created: "1306171747",
    modified: "1306171747",
    uuid: "a145d9a5-dbef-4e09-b112-1b8209c57aba"
  });

  shl.db.updateProspect({
    id: lastId,
    street: "new street",
    last: "Bass"
  });

  var lastprospect = shl.db.getProspect(lastId);
  Ti.API.info(JSON.stringify(lastprospect));

  shl.db.insertProspect({
    last: "Jones",
    firstMale: "John",
    firstFemale: "Jill",
    street: "1234 Asdf St."
  });

  shl.db.insertProspect({
    firstMale: "John",
    firstFemale: "Jill",
    street: "1234 Asdf St.",
    nextStep: "Salvation"
  });

  var testResult = shl.db.listAllProspects();
  for(i=0; i<testResult.length; i++) {
    Ti.API.info(JSON.stringify(testResult[i]));
  }
})();<commit_msg>inheritance structure and find function taking shape<commit_after>(function() {
  shl.db = {};

  //function to create table based on an object
  shl.db.createTable = function (table) {
    //bootstrap database
    var db = Ti.Database.open('Outreach');
    var qstring = 'CREATE TABLE IF NOT EXISTS ' + table.name + ' (';
    var firstField = true;
    for (var field in table.fields) {
      if (table.fields.hasOwnProperty(field)) {
        if (!firstField) {
          qstring += ', ';
        }
        qstring += (field + ' ' + table.fields[field]);
        firstField = false;
      }
    }
    qstring += ')'
    db.execute('DROP TABLE IF EXISTS ' + table.name); //TODO Remove Before Flight
    db.execute(qstring);
    db.close();
    return table;
  }

  //create the prospects table; save field defs for later
  shl.db.prospects = shl.db.createTable({
    name : 'prospects',
    fields : {
      id : 'INTEGER PRIMARY KEY',
      last : 'TEXT',
      firstMale : 'TEXT',
      firstFemale : 'TEXT',
      street : 'TEXT',
      city : 'TEXT',
      state : 'TEXT',
      zip : 'TEXT',
      country : 'TEXT',
      phoneHome : 'TEXT',
      phoneMoble : 'TEXT',
      email : 'TEXT',
      firstContactDate : 'INTEGER',
      firstContactPoint : 'TEXT',
      previouslySaved : 'INTEGER',
      previouslyBaptized : 'INTEGER',
      sundaySchool : 'INTEGER',
      status : 'TEXT',
      nextStep : 'TEXT',
      lastContact : 'INTEGER',
      created : 'INTEGER',
      modified : 'INTEGER',
      uuid : 'TEXT'
    }
  });

  //base class
  shl.db.Model = function() {
    Ti.API.info('just made an object of type Model');
    Ti.API.info(JSON.stringify(this));

  }

  shl.db.Model.prototype.save = function() {
    Ti.API.info('just called save method for Model');
    Ti.API.info(JSON.stringify(this));
    //if it already exists, update
    if (this.id && typeof this.id === 'number' && this.id > 0) {

    }
    //if it does not exist, insert
    else {

    }
  }

  shl.db.Model.find = function(params) {
    if (!params) {
      return false;
    }
    if (typeof(params) === "number") {
      var db = Ti.Database.open('Outreach');
      var result = db.execute('SELECT * FROM ' + this.structure.name + ' WHERE id = ?', params);
      if (!result.rowCount === 0) {
        return false;
      }
      var foundObj = new this(); //hope this works
      for (field in this.structure.fields) {
        if (typeof field !== 'function') {
          foundObj[field] = result.fieldByName(field);
        }
      }
      result.close();
      db.close();
      return foundObj;
    }

  }

  //Propspect inherits from Model
  shl.Prospect = function() {
    shl.db.Model.call(this);

    Ti.API.info('just made an object of type Prospect');
    Ti.API.info(JSON.stringify(this));
  }

  shl.Prospect.prototype = new shl.db.Model();
  shl.Prospect.prototype.constructor = shl.Prospect;
  shl.Prospect.structure = shl.db.prospects;//define table name, fields, etc.
  shl.Prospect.find = shl.db.Model.find;

  //we can define static defaults here - these will get saved to the database if no other is specified
  shl.Prospect.prototype.previouslySaved = 0;
  shl.Prospect.prototype.previouslyBaptized = 0;
  shl.Prospect.prototype.sundaySchool = 0;
  shl.Prospect.prototype.status = 'Active Prospect';
  shl.Prospect.prototype.nextStep = 'Salvation';

  //adds a new prospect to the database
  //_item : an object with ALL the attributes listed, else it will break
  shl.db.insertProspect = function(_item) {
    var db = Ti.Database.open('Outreach');
    var currentTimeStamp = Math.round(new Date().getTime()/1000.0);
    db.execute('INSERT INTO prospects(last,firstMale, firstFemale, street, city, state, zip, country, phoneHome, '+
    'phoneMoble, email, firstContactDate, firstContactPoint, previouslySaved, previouslyBaptized, sundaySchool, status, nextStep, lastContact, created, modified, uuid) '+
    'VALUES(?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?)',
    ('last' in _item) ? _item.last : "",
    ('firstMale' in _item) ? _item.firstMale : "",
    ('firstFemale' in _item) ? _item.firstFemale : "",
    ('street' in _item) ? _item.street : "",
    ('city' in _item) ? _item.city : "",
    ('state' in _item) ? _item.state : "",
    ('zip' in _item) ? _item.zip : "",
    ('country' in _item) ? _item.country : "",
    ('phoneHome' in _item) ? _item.phoneHome : "",
    ('phoneMoble' in _item) ? _item.phoneMoble : "",
    ('email' in _item) ? _item.email : "",
    ('firstContactDate' in _item) ? _item.firstContactDate : currentTimeStamp,
    ('firstContactPoint' in _item) ? _item.firstContactPoint : "",
    ('previouslySaved' in _item) ? _item.previouslySaved : 0,
    ('previouslyBaptized' in _item) ? _item.previouslyBaptized : 0,
    ('sundaySchool' in _item) ? _item.sundaySchool : 0,
    ('status' in _item) ? _item.status : "Active Prospect",
    ('nextStep' in _item) ? _item.nextStep : "Salvation",
    ('lastContact' in _item) ? _item.lastContact : currentTimeStamp,
    ('created' in _item) ? _item.created : currentTimeStamp,
    ('modified' in _item) ? _item.modified : currentTimeStamp,
    ('uuid' in _item) ? _item.uuid : Ti.Platform.createUUID()
    );
    //TODO check to see if uuid, timestamp are empty
    var lastId = db.lastInsertRowId;
    db.close();
    return lastId;
  }

  //low level update function
  //TODO we need a higher level function that updates status flags and the like
  //will crash if there is not a valid id
  //all other properties must be valid columbs of the prospects table
  //_item an object that contains only data to be updated and an id
  shl.db.updateProspect = function(_item) {

    var first = true;
    var subList = [];
    var set = '';
    var rows = 0;

    for (var property in _item) {
      //TODO check against a list of valid properties
      if (_item[property] != undefined && property != 'id') {
        set += (first == false ? ', ' : '') + property + ' = ?';
        subList.push(_item[property]);
        first = false;
      }
    }
    subList.push(_item.id);
    if (set != '') {
      var db = Ti.Database.open('Outreach');
      db.execute('UPDATE prospects SET ' + set + ' WHERE id = ?', subList);
      rows = db.rowsAffected;
      db.close();
    }
    return rows;
  }

  //dumps all the items in the prospect table into an array of objects for testing
  //TODO pass this funciton a WHERE statement
  shl.db.listAllProspects = function() {
    var prospectList = [];
    var db = Ti.Database.open('Outreach');
    var result = db.execute('SELECT * FROM prospects ORDER BY last ASC');
    while(result.isValidRow()) {
      prospectList.push({
        id: result.fieldByName('id'),
        last: result.fieldByName('last'),
        firstMale: result.fieldByName('firstMale'),
        firstFemale: result.fieldByName('firstFemale'),
        street: result.fieldByName('street'),
        city: result.fieldByName('city'),
        state: result.fieldByName('state'),
        zip: result.fieldByName('zip'),
        country: result.fieldByName('country'),
        phoneHome: result.fieldByName('phoneHome'),
        phoneMoble: result.fieldByName('phoneMoble'),
        email: result.fieldByName('email'),
        firstContactDate: result.fieldByName('firstContactDate'),
        firstContactPoint: result.fieldByName('firstContactPoint'),
        previouslySaved: result.fieldByName('previouslySaved'),
        previouslyBaptized: result.fieldByName('previouslyBaptized'),
        sundaySchool: result.fieldByName('sundaySchool'),
        status: result.fieldByName('status'),
        nextStep: result.fieldByName('nextStep'),
        lastContact: result.fieldByName('lastContact'),
        created: result.fieldByName('created'),
        modified: result.fieldByName('modified'),
        uuid: result.fieldByName('uuid')
      });
      result.next();
    }
    result.close();
    db.close();
    return prospectList;
  }

  shl.db.deleteProspect = function(_id) {
    var db = Ti.Database.open('Outreach');
    db.execute("DELETE FROM prospects WHERE id = ?", _id);
    db.close();
  }

  shl.db.getProspect = function(prospectId) {
    var db = Ti.Database.open('Outreach');
    var result = db.execute('SELECT * FROM prospects WHERE id = ?', prospectId);
    var prospect = {
      id: result.fieldByName('id'),
      last: result.fieldByName('last'),
      firstMale: result.fieldByName('firstMale'),
      firstFemale: result.fieldByName('firstFemale'),
      street: result.fieldByName('street'),
      city: result.fieldByName('city'),
      state: result.fieldByName('state'),
      zip: result.fieldByName('zip'),
      country: result.fieldByName('country'),
      phoneHome: result.fieldByName('phoneHome'),
      phoneMoble: result.fieldByName('phoneMoble'),
      email: result.fieldByName('email'),
      firstContactDate: result.fieldByName('firstContactDate'),
      firstContactPoint: result.fieldByName('firstContactPoint'),
      previouslySaved: result.fieldByName('previouslySaved'),
      previouslyBaptized: result.fieldByName('previouslyBaptized'),
      sundaySchool: result.fieldByName('sundaySchool'),
      status: result.fieldByName('status'),
      nextStep: result.fieldByName('nextStep'),
      lastContact: result.fieldByName('lastContact'),
      created: result.fieldByName('created'),
      modified: result.fieldByName('modified'),
      uuid: result.fieldByName('uuid')
    };
    result.close();
    db.close();
    return prospect;
  }

  //testing stuff
  //TODO remove all this testing code and its evil global vars

  var testProspect = new shl.Prospect();
  testProspect.save();
  Ti.API.info(testProspect.nextStep);

  var lastId = shl.db.insertProspect({
    last: "Smith",
    firstMale: "John",
    firstFemale: "Jill",
    street: "1234 Asdf St.",
    city: "Lancaster",
    state: "CA",
    zip: "93535",
    country: "United States",
    phoneHome: "(360)456-6436",
    phoneMoble: "661.158.4882",
    email: "test@example.com",
    firstContactDate: 1305998777,
    firstContactPoint: "Door knocking",
    previouslySaved: 0,
    previouslyBaptized: 0,
    sundaySchool: 0,
    status: "Active Prospect",
    nextStep: "Salvation",
    lastContact: "1306171747",
    created: "1306171747",
    modified: "1306171747",
    uuid: "a145d9a5-dbef-4e09-b112-1b8209c57aba"
  });

  shl.db.updateProspect({
    id: lastId,
    street: "new street",
    last: "Bass"
  });

  var lastprospect = shl.db.getProspect(lastId);
  Ti.API.info(JSON.stringify(lastprospect));

  shl.db.insertProspect({
    last: "Jones",
    firstMale: "John",
    firstFemale: "Jill",
    street: "1234 Asdf St."
  });

  shl.db.insertProspect({
    firstMale: "John",
    firstFemale: "Jill",
    street: "1234 Asdf St.",
    nextStep: "Salvation"
  });

  var testResult = shl.db.listAllProspects();
  for(i=0; i<testResult.length; i++) {
    Ti.API.info(JSON.stringify(testResult[i]));
  }

  var foundProspect = shl.Prospect.find(1);
  Ti.API.info(JSON.stringify(foundProspect));
})();<|endoftext|>


<commit_before>/**
 * write a function `max` that takes two `Numbers` as arguments
 * and returns the largest of them. HINT: Use `if-else`...!
 */
console.assert(max(1,3) === 3);
console.assert(max(0,3) === 3);
console.assert(max(10,3) === 10);
console.assert(max(-1,-3) === -1);

// Why would you do this?
console.assert(max("aaa",0) === 0);

// Okay, that's just silly...
console.assert(isNaN(max("aaa","bbb")));

/**
 * @param {Number} A to compare to B
 * @param {Number} B to compare to A
 * @return {Number} the greater of A or B
 */
function max(A, B) {
  if (A > B) {
    return A;
  } else {
    return B;
  };
}

/**
 * Write a function `maxOfThree` that takes _three_
 * `Numbers` as arguments and returns the largest of them.
 */
console.assert(maxOfThree(1,3,2) === 3);
console.assert(maxOfThree(0,3,-1) === 3);
console.assert(maxOfThree(10,3,50) === 50);
console.assert(maxOfThree(-1,-3,-10) === -1);

// Look, that's just mean...
console.assert(maxOfThree("aaa",0,1) === 1);

// Who's running this picture, anyway?
console.assert(isNaN(maxOfThree("aaa","bbb","ccc")));

/**
 * @param {Number} A
 * @param {Number} B
 * @param {Number} C
 * @return {Number} greatest of A, B, and C
 */
function maxOfThree(A, B, C) {
  if ((A > B) && (A > C)) {
    return A;
  } else if (B > C) {
    return B;
  } else {
    return C;
  };
} //end of maxOfThree

/**
 * Write a function `isVowel` that takes a character
 * (i.e. a `String` of length 1) and returns a `Boolean`
 * indicating whether the input is a vowel or not.

* First we must determine if we are working with a string.
    -Use typeof
*Next we must determine if string is 1 character long.
    -Use .length
 */

// What a cruel, cruel master you are...
console.assert(isVowel(0) === false);
console.assert(isVowel("B") === false);
console.assert(isVowel("b") === false);
console.assert(isVowel("a") === true);
console.assert(isVowel("E") === true);

// What should _this_ do?
console.assert(isVowel("AEIOU") === false);

/**
 * @param {String} char of length 1
 * @return {Boolean} whether `char` is an English vowel
 */
function isVowel(char) {
  if (typeof char == "string") {
    if (char.length == 1) {
      char = char.toUpperCase();
      switch (char) {
        case "A":
        case "E":
        case "I":
        case "O":
        case "U":
          return true;
          break;
        default:
          return false;
      }//END switch
    } else {
      return false;
    };//END length if
  } else {
    return false;
  };//END typeof if
};//END isVowel

/**
 * The `disemvowel` function combats the Internet
 * Trolls by handily removing all of the vowels from
 * their angry, hurtful comments. Its Super-Effective!
 *
 * @param {String} comment to disemvowel
 * @return {String} cmmnt dsmvwld
 */

function disemvowel(comment){
  // YOUR CODE HERE
}

// Shorter test cases might be appreciated...
console.assert(
  disemvowel("This website is for losers LOL!") === "Ths wbst s fr lsrs LL!"
);

/**
 * The function `rovarspraket` will translate text into
 * a "rövarspråket", i.e. double every consonant and
 * place an occurrence of "o" in between them.
 *
 * For example, `rovarspraket("this is fun")` should
 * return `"tothohisos isos fofunon"`
 *
 * @see https://en.wikipedia.org/wiki/R%C3%B6varspr%C3%A5ket
 *
 * @param {String} text to translate into "rövarspråket"
 * @return {String} translation
 */
function rovarspraket(input){
    // YOUR CODE HERE
}

// Feel free to provide additional examples...
console.assert(rovarspraket("a") === "a")
console.assert(rovarspraket("b") === "bob")
console.assert(rovarspraket("cat") === "cocatot")
console.assert(rovarspraket("javascript") === "jojavovasoscocroripoptot")
console.assert(rovarspraket(0) === "0")
<commit_msg>made sure disemvowel only passed strings.<commit_after>/**
 * write a function `max` that takes two `Numbers` as arguments
 * and returns the largest of them. HINT: Use `if-else`...!
 */
console.assert(max(1,3) === 3);
console.assert(max(0,3) === 3);
console.assert(max(10,3) === 10);
console.assert(max(-1,-3) === -1);
console.assert(max("aaa",0) === 0);
console.assert(isNaN(max("aaa","bbb")));

/**
 * @param {Number} A to compare to B
 * @param {Number} B to compare to A
 * @return {Number} the greater of A or B
 */
function max(A, B) {
  if (A > B) {
    return A;
  } else {
    return B;
  };
}//END max

/**
 * Write a function `maxOfThree` that takes _three_
 * `Numbers` as arguments and returns the largest of them.
 */
console.assert(maxOfThree(1,3,2) === 3);
console.assert(maxOfThree(0,3,-1) === 3);
console.assert(maxOfThree(10,3,50) === 50);
console.assert(maxOfThree(-1,-3,-10) === -1);
console.assert(maxOfThree("aaa",0,1) === 1);
console.assert(isNaN(maxOfThree("aaa","bbb","ccc")));

/**
 * @param {Number} A
 * @param {Number} B
 * @param {Number} C
 * @return {Number} greatest of A, B, and C
 */
function maxOfThree(A, B, C) {
  if ((A > B) && (A > C)) {
    return A;
  } else if (B > C) {
    return B;
  } else {
    return C;
  };
} //END maxOfThree

/**
 * Write a function `isVowel` that takes a character
 * (i.e. a `String` of length 1) and returns a `Boolean`
 * indicating whether the input is a vowel or not.

* First we must determine if we are working with a string.
    -Use typeof
*Next we must determine if string is 1 character long.
    -Use .length
 */

console.assert(isVowel(0) === false);
console.assert(isVowel("B") === false);
console.assert(isVowel("b") === false);
console.assert(isVowel("a") === true);
console.assert(isVowel("E") === true);
console.assert(isVowel("AEIOU") === false);

/**
 * @param {String} char of length 1
 * @return {Boolean} whether `char` is an English vowel
 */
function isVowel(char) {
  if (typeof char == "string") {
    if (char.length == 1) {
      char = char.toUpperCase();
      switch (char) {
        case "A":
        case "E":
        case "I":
        case "O":
        case "U":
          return true;
          break;
        default:
          return false;
      }//END switch
    } else {
      return false;
    };//END length if
  } else {
    return false;
  };//END typeof if
};//END isVowel

/**
 * The `disemvowel` function combats the Internet
 * Trolls by handily removing all of the vowels from
 * their angry, hurtful comments. Its Super-Effective!
 *
 * @param {String} comment to disemvowel
 * @return {String} cmmnt dsmvwld
 */

function disemvowel(comment){
  if (typeof comment == "string") {
    /*if (comment.length == 1) {
      comment = comment.toLowerCase();
      switch (char) {
        case "A":
        case "E":
        case "I":
        case "O":
        case "U":
          return true;
          break;
        default:
          return false;
      }//END switch
    } else {
      return false;
    };//END length if*/
    return true;
  } else {
    return false;
  };//END typeof if
}  //END DISEMVOWEL

// Shorter test cases might be appreciated...
console.assert(disemvowel(0) === false);
console.assert(disemvowel("string") === true);
console.assert(disemvowel("This website is for losers LOL!") === "Ths wbst s fr lsrs LL!"
);

/**
 * The function `rovarspraket` will translate text into
 * a "rövarspråket", i.e. double every consonant and
 * place an occurrence of "o" in between them.
 *
 * For example, `rovarspraket("this is fun")` should
 * return `"tothohisos isos fofunon"`
 *
 * @see https://en.wikipedia.org/wiki/R%C3%B6varspr%C3%A5ket

 * @param {String} text to translate into "rövarspråket"
 * @return {String} translation
 */
function rovarspraket(input){
    // YOUR CODE HERE
}

// Feel free to provide additional examples...
console.assert(rovarspraket("a") === "a")
console.assert(rovarspraket("b") === "bob")
console.assert(rovarspraket("cat") === "cocatot")
console.assert(rovarspraket("javascript") === "jojavovasoscocroripoptot")
console.assert(rovarspraket(0) === "0")
<|endoftext|>


<commit_before>
<commit_msg>Update baidu.js<commit_after>//百度2015
var baidu = {
    init : function(){
        this.countdown();
        this.yore();
    },
    //星空
    universe : function(opt){
        var _this = this;
        this.settings = {
            canvas : [],
            clientWidth : document.documentElement.clientWidth,
            clientHeight : document.documentElement.clientHeight,
            starNum: 200,
            starColor: '#FBFFAF',
            starDepth: 500
        };
        huofengshui.extend(this.settings,opt);
        this.universe_cobj = [];
        for(var i=0;i<this.settings.canvas.length;i++){
            this.universe_cobj[i] = this.settings.canvas[i].getContext('2d');
            this.settings.canvas[i].width = _this.settings.clientWidth;
            this.settings.canvas[i].height = _this.settings.clientHeight;
        }
        this.universe_setup();
    },
    universe_draw : function(point3d){
        var scale = this.settings.starDepth/(this.settings.starDepth+point3d[2]);
        var x = ( point3d[0] * scale) + this.settings.clientWidth/2;
        var y = (point3d[1] * scale)  + this.settings.clientHeight/2;
        var r = Math.abs(scale)*6;
        if(r > 10){
            r = 15;
        }
        for(var i=0;i<this.settings.canvas.length;i++) {
            this.universe_cobj[i].drawImage( this.universe_yImg , x , y , r , r );
        }
    },
    universe_render : function(){
        for(var i=0;i<this.settings.canvas.length;i++) {
            this.universe_cobj[i].clearRect(0,0,this.settings.clientWidth,this.settings.clientHeight);
        }
        for (i=0; i< this.settings.starNum; i++){
            var point3d = this.points[i];
            var z = point3d[2];
            z -= 1;
            if( z < -this.settings.starDepth ){
                z += 400;
            };
            point3d[2] = z;
            this.universe_draw(point3d);
        }
    },
    universe_setup : function(){
        var _this = this;
        this.points = [];
        for (i=0; i<_this.settings.starNum; i++){
            var point = [(Math.random()*900)-500, (Math.random()*1040)-600 , (Math.random()*900)-500 ];
            this.points.push(point);
        }
        this.universe_yImg = new Image();
        this.universe_yImg.src = 'http://baiduworld.baidu.com/2015/images2015/star.png';
        this.universe_yImg.onload = function(){
            var loop = setInterval(function(){
                _this.universe_render();
            },60);
        };

    },
    //视频播放控制
    video_play : function(){
        var oTab = $(".f-lc-video-tab li");
        var oCon = $(".f-lc-video-con li");
        oTab.each(function(index,elem){
            elem.index = index;
            $(elem).on("click",function(){
                oCon.hide();
                oTab.removeClass("active");
                $(this).addClass("active");
                oCon.eq(this.index).show().find(".f-lc-video-box").show();
                $(".f-lc-iframe").removeAttr("src");
            })
        });
        $(".f-lc-video-play").each(function(index,elem){
            $(this).on("click",function(){
                $(this).parent().hide().next().attr("src",$(this).parent().next().attr("_src"));
                //$(this).parent().hide();
            })
        });
    },
    //倒计时
    countdown : function(){
        var _this = this;
        this.countdownLi = document.getElementById("countdown").getElementsByTagName("li");
        var EndTime = new Date('2015/12/08 09:00:00'); //截止时间
        var NowTime = new Date();
        var t = EndTime.getTime() - NowTime.getTime();
        var d = Math.floor(t/1000/60/60/24);
        var h = Math.floor(t/1000/60/60%24);
        var m = Math.floor(t/1000/60%60);
        var s = Math.floor(t/1000%60);
        d < 10 ? d = "0" + d : d = "" + d;
        h < 10 ? h = "0" + h : h = "" + h;
        m < 10 ? m = "0" + m : m = "" + m;
        s < 10 ? s = "0" + s : s = "" + s;
        parseInt(d) <= 0 ? d = "0" + 0 : d = "" + d;
        parseInt(h) <= 0 ? h = "0" + 0 : h = "" + h;
        parseInt(m) <= 0 ? m = "0" + 0 : m = "" + m;
        parseInt(s) <= 0 ? s = "0" + 0 : s = "" + s;
        this.countdownLi[0].innerHTML = '';
        this.countdownLi[1].innerHTML = '';
        this.countdownLi[3].innerHTML = '';
        this.countdownLi[4].innerHTML = '';
        this.countdownLi[6].innerHTML = '';
        this.countdownLi[7].innerHTML = '';
        this.countdownLi[9].innerHTML = '';
        this.countdownLi[10].innerHTML = '';
        setTimeout(function(){
            _this.countdown();
        },1000);
    },
    yore : function(){
        var _this = this;
        this.yore_box = document.getElementById("m-lc-yore");
        this.yore_tit = huofengshui.getByClass(this.yore_box,"m-lc-yore-tit","div")[0];
        this.yore_ul = this.yore_box.getElementsByTagName("ul")[0];
        this.yore_line = huofengshui.getByClass(this.yore_box,"u-lc-yore-line","div")[0];
        this.yore_ul.obj = {
            "h" : _this.yore_ul.offsetHeight
        };
        this.yore_line.obj = {
            "h" : _this.yore_line.offsetHeight
        };
        huofengshui.css(_this.yore_ul,{"height":0,"opacity":100});
        huofengshui.css(_this.yore_line,{"height":0,"opacity":100});
        this.yore_box.btn = true;
        this.yore_box.onmouseenter = function(){
            if(this.btn){
                this.btn = false;
                huofengshui.movement(_this.yore_ul,{"height":_this.yore_ul.obj.h},300,"easeOut");
                huofengshui.movement(_this.yore_line,{"height":_this.yore_line.obj.h},300,"easeOut",function(){
                    _this.yore_box.btn = true;
                });
            }
        }
        this.yore_box.onmouseleave = function(){
            if(this.btn){
                this.btn = false;
                huofengshui.movement(_this.yore_ul,{"height":0},300,"easeOut");
                huofengshui.movement(_this.yore_line,{"height":0},300,"easeOut",function(){
                    _this.yore_box.btn = true;
                });
            }
        }
    },
    show_tan : function(){
        var _this = this;
        //大会简介
        $("#dhjj").on("click",function(){
            $("#dhjj_alert").show();
        });
        $("#dhjj_text").on("click",function(){
            $("#dhjj_alert").show();
        });

        //会议日程
        $("#hyrc").on("click",function(){
            $("#hyrc_alert").show();
            _this.scroll($("#hyrc_alert"));
        });
        $("#shangwu").on("click",function(){
            $("#hyrc_alert").show();
            _this.scroll($("#hyrc_alert"));
        });
        $("#xiawu").on("click",function(){
            $("#hyrc_alert").show();
            _this.scroll($("#hyrc_alert"));
        });
        //嘉宾介绍
        $("#jbjs").on("click",function(){
            $("#jbjs_alert").show();
            _this.scroll($("#jbjs_alert"));
        });

        $("#jbjs_ul").on("click",function(){
            $("#jbjs_alert").show();
            _this.scroll($("#jbjs_alert"));
        });
        //会务联系
        $("#hwlx").on("click",function(){
            $("#hwlx_alert").show();
        });
        //展区介绍
        $("#zqjs").on("click",function(){
            $("#zqjs_alert").show();
            _this.scroll($("#zqjs_alert"));
        });
        //精彩视频
        $("#jcsp").on("click",function(){
            $("#jcsp_alert").show();
            _this.scroll($("#jcsp_alert"));
        });

        //新闻动态
        $("#xwdt").on("click",function(){
            $("#xwdt_alert").show();
            _this.scroll($("#xwdt_alert"));
        });

        //more操作
        $("#jcsp_more").on("click",function(){
            $("#jcsp_alert").show();
            _this.scroll($("#jcsp_alert"));
        });
        $("#jb_more").on("click",function(){
            $("#jbjs_alert").show();
            _this.scroll($("#jbjs_alert"));
        });
        $("#zq_more").on("click",function(){
            $("#zqjs_alert").show();
            _this.scroll($("#zqjs_alert"));
        });
        $("#hwlx_more").on("click",function(){
            $("#hwlx_alert").show();
        });

        $(".f-jqqd").on("click",function(){
            $("#jqqd_alert").show();
        });
    },
    hide_tan : function(){
        $(".f-lc-close").on("click",function(){
            $(this).parent().parent().hide();
        });
        $(".f-lc-back").on("click",function(){
            $(this).parent().parent().hide();
        })
    },
    hwlx : function(){
        var _this = this;
        $("#hwlc_tab > li").on("click",function(){
            $(this).addClass("active").siblings().removeClass("active");
            var name = $(this).attr("data-name");
            $("#hwlx_con").html(_this.html_a(hwlx[name]));
            _this.scroll($("#hwlx_alert"));
        });
        var names = $("#hwlc_tab > li").eq(0).attr("data-name");
        $("#hwlx_con").html(_this.html_a(hwlx[names]));
        this.scroll($("#hwlx_alert"));
    },
    html_a : function(obj){
        var str = "";
        for(var i=0;i< obj.length;i++){
            str += '
 \

'+ obj[i].name +'
 \

'+ obj[i].tel +'
 \

'+ obj[i].email +'
 \

';
        };
        return str;
    },
    news : function(){
        var str = "";
        for(var i=0;i<news.length;i++){
            str += '
 \
                        '+ (i+1) + '、' + news[i].title +' \

'
        }
        $("#xwdt_con").html(str);
    },
    hyrc : function(){
        var _this = this;
        $("#hyrc_tab > li").on("click",function(){
            $(this).addClass("active").siblings().removeClass("active");
            var name = $(this).attr("data-name");
            $("#hyrc_con").html(_this.html_b(hyrc[name],name));
            _this.scroll($("#hyrc_alert"));
        });
        var names = $("#hyrc_tab > li").eq(0).attr("data-name");
        $("#hyrc_con").html(_this.html_b(hyrc[names],names));
        this.scroll($("#hyrc_alert"));
    },
    html_b : function(obj,name){
        var str = "";
        for(var i=0;i< obj.length;i++){
            var className = obj[i].className+" "+name;
            //var className = name;
            str += '
 \

'+ obj[i].time +'
 \

'+ obj[i].yicheng +'
 \

'+ obj[i].guests +'
 \

';
        }
        return str;
    },
    jcsp : function(){
        var _this = this;
        $("#jcsp_tab > li").on("click",function(){
            $(this).addClass("active").siblings().removeClass("active");
            var name = $(this).attr("data-name");
            $("#jcsp_con").html(_this.html_s(video[name],name));
            _this.scroll($("#jcsp_alert"));
        });
        var names = $("#jcsp_tab > li").eq(0).attr("data-name");
        $("#jcsp_con").html(_this.html_s(video[names],names));
        _this.scroll($("#jcsp_alert"));
    },
    html_s : function(obj,name){
        var str = "";
        for(var i=0;i<obj.length;i++){
            str += '
\

\

\
                                \

\

\

\

'+ obj[i].title +'
\

';
        };
        return str;
    },
    jcsp_info : function(){
        var _this = this;
        $("#jcsp_con").delegate(".u-lc-shipin-play,.g-lc-shipin-right","click",function(){
            $("#jcsp_alert").hide();
            $("#jcsp_info_alert").show();
            $("#video_play").show();
            var name = $(this).attr("data-name");
            var i = parseInt($(this).attr("data-index"));
            $("#video_info").html(video[name][i].embed);
            $("#video_tit").html(video[name][i].title)
        });
        $(".f-lc-shipin-info-back").on("click",function() {
            $("#jcsp_alert").show();
            $("#jcsp_info_alert").hide();
            _this.scroll($("#jcsp_alert"));
        });
        $("#video_info_play").on("click",function(){
            $("#video_play").hide();
        });
    },
    exhibition : function(){
        var _this = this;
        $("#zqjs_tab > li").on("click",function(){
            $(this).addClass("active").siblings().removeClass("active");
            var name = $(this).attr("data-name");
            $("#zqjs_con").html(_this.html_c(exhibition[name]));
            _this.scroll($("#zqjs_alert"));
        });
        var names = $("#zqjs_tab > li").eq(0).attr("data-name");
        $("#zqjs_con").html(_this.html_c(exhibition[names]));
        this.scroll($("#zqjs_alert"));
    },
    html_c : function(obj){
        var str = "";
        for(var i=0;i< obj.length;i++){
            str += '
 \

 \
                             \

 \

 \

' + obj[i].title + '
 \

' + obj[i].content + '
 \

 \

';
        }
        return str;
    },
    guests : function(){
        var _this = this;
        $("#jbjs_tab > li").on("click",function(){
            $(this).addClass("active").siblings().removeClass("active");
            var name = $(this).attr("data-name");
            $("#jbjs_con").html(_this.html_d(guests[name],name));
            _this.scroll($("#jbjs_alert"));
        });
        var names = $("#jbjs_tab > li").eq(0).attr("data-name");
        $("#jbjs_con").html(_this.html_d(guests[names],names));
        this.scroll($("#jbjs_alert"));
    },
    html_d : function(obj,name){
        var str = "";
        for(var i=0;i< obj.length;i++){
            str += '
 \

 \

 \

 \

 \

' +
                                '
 ' +
                                    ''+ obj[i].name +'' + obj[i].job +
                                '
'+
                                '
'+
                                    obj[i].info+
                                '
 \

 \
                            查看更多 \

 \

';
        }
        return str;
    },
    guests_info : function(){
        var _this = this;
        $("#jbjs_con").delegate("a","click",function(){
            $("#jbjs_alert").hide();
            $("#jbjs_info_alert").show();
            var name = $(this).attr("data-name");
            var i = parseInt($(this).attr("data-index"));
            console.log(name);
            $("#jbjs_info_img").html('');
            $("#jbjs_info_name").html(guests[name][i].name);
            $("#jbjs_info_job").html(guests[name][i].job);
            $("#jbjs_info_info").html(guests[name][i].info);
            _this.scroll($("#jbjs_info_alert"));
        });
        $(".f-lc-guests-info-back").on("click",function() {
            $("#jbjs_alert").show();
            $("#jbjs_info_alert").hide();
            _this.scroll($("#jbjs_alert"));
        })
    },
    scroll : function(obj){
        var oWarpBox = obj.find(".f-lc-scroll-box").get(0);
        var oWarpBar = obj.find(".f-lc-scroll-bar").get(0);
        var oScrollBox = obj.find(".f-lc-bar-box").get(0);
        var oScrollBar = obj.find(".f-lc-bar-bar").get(0);
        var clientH = oWarpBox.clientHeight;
        var scrollH = oWarpBar.scrollHeight;
        var maxH = $(oScrollBox).outerHeight();
        var t = 0;
        var h = 30;
        h = Math.floor(clientH/scrollH * maxH);
        oWarpBar.style.top = "0px";
        oScrollBar.style.top = "0px";
        if(scrollH <= clientH){
            oScrollBox.style.display = "none";
            oWarpBox.onmousewheel = null;
            return false;
        }else{
            oScrollBox.style.display = "block";
        }
        if(h < 30){
            h = 30;
        }
        oScrollBar.style.height = h + "px";

        oScrollBar.onmousedown = function(e){
            var ev = window.event || e;
            var disY = ev.clientY - this.offsetTop;
            document.onmousemove = function(e){
                var ev = window.event || e;
                t = ev.clientY - disY;
                scrollT();
                return false;
            }
            document.onmouseup = function(){
                document.onmousemove = null;
                document.onmouseup = null;
            }
            return false;
        }

        oScrollBox.onmousedown = function(e){
            var ev = window.event || e;
            var disY = ev.clientY - this.offsetTop;
            var dt = null;
            dt = setInterval(function(){
                if(disY > h){
                    if(t<disY){
                        t += 5;
                        if(t >= disY - h){
                            clearInterval(dt);
                        }
                    }else{
                        t -= 5;
                        if(t <= disY){
                            clearInterval(dt);
                        }
                    }

                }else{
                    if( t > 0 ){
                        t -= 5;
                        if(t <= 0){
                            clearInterval(dt);
                        }
                    }
                }
                scrollT();
            },100);
            oScrollBox.onmouseup = oScrollBox.onmouseout = function(){
                clearInterval(dt);
            }
        }

        oWarpBox.onmousewheel = mouseScroll;
        if(oWarpBox.addEventListener){
            oWarpBox.addEventListener('DOMMouseScroll',mouseScroll,false);
        }

        function mouseScroll(e){
            var ev = e || window.event;
            var fx = ev.wheelDelta || ev.detail;
            var bDown = true;
            if( ev.detail ){
                bDown = fx > 0 ? true : false;
            }else{
                bDown = fx > 0 ? false : true;
            }
            if( bDown ){
                t += 10;
            }else{
                t -= 10;
            }
            scrollT();
            if( ev.preventDefault ){
                ev.preventDefault();
            }
            return false;
        }

        function scrollT(){
            if(t < 0){
                t = 0;
            }
            if(t > (maxH - h)){
                t = maxH - h;
            }
            oScrollBar.style.top = t + "px";
            oWarpBar.style.top = (clientH - scrollH)*(t/(maxH-h)) + "px";
        }
    }
}

function baiduMap(){
    var json = markerArr[0];
    var iconImg = createIcon(json.icon);
    var i=0;
    // 百度地图API功能
    var map = new BMap.Map("allmap");
    var point = new BMap.Point();
    var targetPoint = new BMap.Point(116.465799, 39.915672);//中国大饭店
    map.centerAndZoom(targetPoint, 17);
    map.addControl(new BMap.NavigationControl());  //添加默认缩放平移控件
    map.addControl(new BMap.NavigationControl({anchor: BMAP_ANCHOR_TOP_RIGHT, type: BMAP_NAVIGATION_CONTROL_SMALL}));  //右上角，仅包含平移和缩放按钮
    var marker1 = new BMap.Marker(new BMap.Point(116.465822, 39.915625),{icon:iconImg});  // 创建标注
    var iw = createInfoWindow(0);
    var label = new BMap.Label(json.title,{"offset":new BMap.Size(json.icon.lb-json.icon.x+10,-20)});
    marker1.setLabel(label);
    map.addOverlay(marker1);
    label.setStyle({
        borderColor:"#808080",
        color:"#333",
        cursor:"pointer"
    });
    (function(){
        var index = i;
        var _iw = createInfoWindow(i);
        var _marker = marker1;
        _marker.addEventListener("click",function(){
            this.openInfoWindow(_iw);
        });
        _iw.addEventListener("open",function(){
            _marker.getLabel().hide();
        })
        _iw.addEventListener("close",function(){
            _marker.getLabel().show();
        })
        label.addEventListener("click",function(){
            _marker.openInfoWindow(_iw);
        })
        if(!!json.isOpen){
            label.hide();
            _marker.openInfoWindow(_iw);
        }
    })()

}

//标注点数组
var markerArr = [{title:"中国大饭店",content:"我的备注",point:"116.465799|39.915672",isOpen:0,icon:{w:21,h:21,l:0,t:0,x:6,lb:5}}];
//创建InfoWindow
function createInfoWindow(i){
    var json = markerArr[i];
    var opts = {enableMessage:false};
    var iw = new BMap.InfoWindow("" + json.title + "
"+json.content+"
",opts);
    return iw;
}
//创建一个Icon
function createIcon(json){
    var icon = new BMap.Icon("http://app.baidu.com/map/images/us_mk_icon.png",
        new BMap.Size(json.w,json.h),
        {imageOffset: new BMap.Size(-json.l,-json.t),infoWindowOffset:new BMap.Size(json.lb+5,1),offset:new BMap.Size(json.x,json.h)}
    )
    return icon;
}
<|endoftext|>


<commit_before>var isNetscape = navigator.appName=="Netscape";
var isIE = navigator.appName=="Microsoft Internet Explorer";

function getMouseButton(event) {
  // 1 is the left, 2 the middle, 3 the right button
  var button;
  if (window.event) {
      button=window.event.button;
  } else  {
      button= event.button +1;
  }
  return button;
}

var windows= new Object();;

function displayPropertyNames(obj) {
  var names="";
  for (var name in obj) {
   try {
     names += name +" - " + obj[name] + "][";
   }
   catch (ex) {
     names += name +" - " + "unreadable" + "][";
   }
  }
  alert(names);
}
function getConnexeWindows(w) {
  var cw;

   try {
     cw=getChildFrames(w.top);

     if ((w.top.opener)&& (w.top.opener != w.top) ) cw=cw+getConnexeWindows(w.top.opener);

   }
   catch (ex) {
   }
  return cw;
}
function getChildFrames(w) {

  var fnames='';
  var fname='';

  try {
      fname=w.frames;
  }
  catch (ex) {
    return fnames;
  }
  for (var i=0;i<w.frames.length;i++) {
    try {
      fname=w.frames[i].name;
    }
    catch (ex) {
      fname='';
    }
    if (fname && (fname != '')) windows[fname]=w.frames[i];
    fnames = fnames + ' ' +i + fname;

    fnames = fnames+getChildFrames(w.frames[i]);

  }

  return fnames;
}

function windowExist(Name, NoOpen) {

  getChildFrames(window);

  if (windows[Name]  ) {

    if ( windows[Name]=='none') return false;

    if (windows[Name].closed) return false;

    try {
      var w=windows[Name].document;
    }
    catch (ex) {
      windows[Name]='none';
      return false;
    }
    return  windows[Name];
  }

  getConnexeWindows(window);
  if (windows[Name]) return  windows[Name];

  // ---------------------
  // Try open
  if (NoOpen == '') {
    var dy=self.screen.availHeight;
    var dx=self.screen.availWidth;
    var w=window.open('',Name,'top='+dy+',left='+dx+'menubar=no,resizable=no,scrollbars=no,width=1,height=1');
    if (w.opener && (w.opener.location.href == self.location.href) && (w.location.href=='about:blank')) {
      w.close();
      windows[Name]='none';
      return false;
    }
    windows[Name]=w;
    getConnexeWindows(w);
  }
  return w;
}
var warnmsg='';
function displayWarningMsg(logmsg) {
  warnmsg=logmsg;
  setTimeout('alert(warnmsg)',1000);
}
function displayLogMsg(logmsg) {

  if (logmsg.length == 0) return;

  var log=false;
  if (top.foot) {
    log=top.foot.document.getElementById('slog');
  } else {
    // redirect to foot function
      if (window.name != "foot") {
	var wfoot = windowExist('foot');
	if (wfoot)  wfoot.displayLogMsg(logmsg);
      }
    return;
  }

  if (log) {
    var classn = 'CORETblCell';
    var k=0;

    if ((log.options) && (log.options.length > 0)) {
      if (log.options[log.options.length-1].className == "CORETblCell")
	classn='CORETblCellAltern';
      k=log.options.length;
    }
    for (var i=0;i<logmsg.length;i++) {
      log.options[k]=new Option(logmsg[i],'',false,false);
      log.options[k].className=classn;
      k=log.options.length;
    }
    log.selectedIndex=log.options.length-1;

    logi=top.foot.document.getElementById('ilog');
    if ((! log.options) || (log.options.length == 0)) logi.style.display='none';
    else logi.style.display='inline';
  }

}

// Utility function to add an event listener
function addEvent(o,e,f){
	if (o.addEventListener){ o.addEventListener(e,f,true); return true; }
	else if (o.attachEvent){ return o.attachEvent("on"+e,f); }
	else { return false; }
}
// Utility function to add an event listener
function delEvent(o,e,f){
	if (o.removeEventListener){ o.removeEventListener(e,f,true); return true; }
	else if (o.detachEvent){ return o.detachEvent("on"+e,f); }
	else { return false; }
}
function correctPNG() {// correctly handle PNG transparency in Win IE 5.5 or higher.
   for(var i=0; i<document.images.length; i++)
      {
	correctOnePNG(document.images[i]);
      }
}
function correctOnePNG(img) {// correctly handle PNG transparency in Win IE 5.5 or higher.
  var imgName = img.src.toUpperCase();
  if (imgName.substring(imgName.length-3, imgName.length) == "PNG")
	     {
	        img.style.filter="progid:DXImageTransform.Microsoft.AlphaImageLoader(src='" +img.src+"',sizingMethod='scale') ";
		 img.style.width = img.width;
		 img.style.height = img.height;
		 img.src='Images/1x1.gif';
	     }

}

if (isIE) addEvent(window,"load",correctPNG);
<commit_msg>debug for IE<commit_after>var isNetscape = navigator.appName=="Netscape";
var isIE = navigator.appName=="Microsoft Internet Explorer";

function getMouseButton(event) {
  // 1 is the left, 2 the middle, 3 the right button
  var button;
  if (window.event) {
      button=window.event.button;
  } else  {
      button= event.button +1;
  }
  return button;
}

var windows= new Object();;

function displayPropertyNames(obj) {
  var names="";
  for (var name in obj) {
   try {
     names += name +" - " + obj[name] + "][";
   }
   catch (ex) {
     names += name +" - " + "unreadable" + "][";
   }
  }
  alert(names);
}
function getConnexeWindows(w) {
  var cw;

   try {
     cw=getChildFrames(w.top);

     if ((w.top.opener)&& (w.top.opener != w.top) ) cw=cw+getConnexeWindows(w.top.opener);

   }
   catch (ex) {
   }
  return cw;
}
function getChildFrames(w) {

  var fnames='';
  var fname='';

  try {
      fname=w.frames;
  }
  catch (ex) {
    return fnames;
  }
  for (var i=0;i<w.frames.length;i++) {
    try {
      fname=w.frames[i].name;
    }
    catch (ex) {
      fname='';
    }
    if (fname && (fname != '')) windows[fname]=w.frames[i];
    fnames = fnames + ' ' +i + fname;

    fnames = fnames+getChildFrames(w.frames[i]);

  }

  return fnames;
}

function windowExist(Name, NoOpen) {

  getChildFrames(window);

  if (windows[Name]  ) {

    if ( windows[Name]=='none') return false;

    if (windows[Name].closed) return false;

    try {
      var w=windows[Name].document;
    }
    catch (ex) {
      windows[Name]='none';
      return false;
    }
    return  windows[Name];
  }

  getConnexeWindows(window);
  if (windows[Name]) return  windows[Name];

  // ---------------------
  // Try open
  if (NoOpen == '') {
    var dy=self.screen.availHeight;
    var dx=self.screen.availWidth;
    var w=window.open('',Name,'top='+dy+',left='+dx+'menubar=no,resizable=no,scrollbars=no,width=1,height=1');
    if (w.opener && (w.opener.location.href == self.location.href) && (w.location.href=='about:blank')) {
      w.close();
      windows[Name]='none';
      return false;
    }
    windows[Name]=w;
    getConnexeWindows(w);
  }
  return w;
}
var warnmsg='';
function displayWarningMsg(logmsg) {
  warnmsg=logmsg;
  setTimeout('alert(warnmsg)',1000);
}
function displayLogMsg(logmsg) {

  if (logmsg.length == 0) return;

  var log=false;
  if (top.foot) {
    log=top.foot.document.getElementById('slog');
  } else {
    // redirect to foot function
      if (window.name != "foot") {
	var wfoot = windowExist('foot');
	if (wfoot)  wfoot.displayLogMsg(logmsg);
      }
    return;
  }

  if (log) {
    var classn = 'CORETblCell';
    var k=0;

    if ((log.options) && (log.options.length > 0)) {
      if (log.options[log.options.length-1].className == "CORETblCell")
	classn='CORETblCellAltern';
      k=log.options.length;
    }
    for (var i=0;i<logmsg.length;i++) {
      log.options[k]=new Option(logmsg[i],'',false,false);
      log.options[k].className=classn;
      k=log.options.length;
    }
    log.selectedIndex=log.options.length-1;

    logi=top.foot.document.getElementById('ilog');
    if ((! log.options) || (log.options.length == 0)) logi.style.display='none';
    else logi.style.display='inline';
  }

}

// Utility function to add an event listener
function addEvent(o,e,f){
	if (o.addEventListener){ o.addEventListener(e,f,true); return true; }
	else if (o.attachEvent){ return o.attachEvent("on"+e,f); }
	else { return false; }
}
// Utility function to add an event listener
function delEvent(o,e,f){
	if (o.removeEventListener){ o.removeEventListener(e,f,true); return true; }
	else if (o.detachEvent){ return o.detachEvent("on"+e,f); }
	else { return false; }
}
function correctPNG() {// correctly handle PNG transparency in Win IE 5.5 or higher.
   for(var i=0; i<document.images.length; i++)
      {
	correctOnePNG(document.images[i]);
      }
}
function correctOnePNG(img) {// correctly handle PNG transparency in Win IE 5.5 or higher.
  if (img.className == 'icon') return;
  var imgName = img.src.toUpperCase();
  if (imgName.substring(imgName.length-3, imgName.length) == "PNG")
	     {

	        img.style.filter="progid:DXImageTransform.Microsoft.AlphaImageLoader(src='" +img.src+"',sizingMethod='scale') ";
		 img.style.width = img.width;
		 img.style.height = img.height;
		 img.src='Images/1x1.gif';
	     }

}

if (isIE) addEvent(window,"load",correctPNG);
<|endoftext|>


<commit_before>/*!
	Defines functions designed to facilitate meta-programming.
*/

"use strict";

// Returns a value indicating whether the given value has been a value that is not null or undefined.
var isAssigned = function(value) {
	return typeof value !== "undefined" && value !== null;
};

// Returns the first passed value to be assigned a value other than null or undefined.
// If none of the values are assigned, then the last value is returned.
var getAssigned = function() {
	var value;
	var i, length;

	for (i = 0, length = arguments.length; i < length; i += 1) {
		value = arguments[i];

		if (isAssigned(value)) {
			return value;
		}
	}

	return value;
};

// Parses the given namespace string into an array.
var parseNamespace = function(namespaceString) {
	return namespaceString.split(".");
};

// Creates the given namespace structure and executes the constructor to generate the object
// only if it's not already defined.
var defineGlobalOnce = function(namespace, constructor) {
	var hierarchy = parseNamespace(namespace);
	var leafName = hierarchy.pop();
	var context = window;

	if (!leafName) {
		throw new Error("Invalid namespace or object name.");
	}

	hierarchy.forEach(function(nodeName) {
		var node = context[nodeName] || {};

		if (node !== window) {
			context[nodeName] = node;
		}

		context = node;
	});

	if (!isAssigned(context[leafName])) {
		context[leafName] = constructor();
	}

	return context[leafName];
};

var defineProperty = Object.defineProperty;

// Defines a constant value in the given object.
var defineConstant = function(object, key, value) {
	defineProperty(object, key, {
		value: value,
		writable: false
	});

	return value;
};

// Defines an accessor in the given object.
var defineAccessor = function(object, key, settings) {
	defineProperty(object, key, {
		get: settings.get,
		set: settings.set
	});
};

module.exports = {
	isAssigned:       isAssigned,
	getAssigned:      getAssigned,
	defineGlobalOnce: defineGlobalOnce,
	defineConstant:   defineConstant,
	defineAccessor:   defineAccessor
};
<commit_msg>Adding createContantGetter function.<commit_after>/*!
	Defines functions designed to facilitate meta-programming.
*/

"use strict";

// Returns a value indicating whether the given value has been a value that is not null or undefined.
var isAssigned = function(value) {
	return typeof value !== "undefined" && value !== null;
};

// Returns the first passed value to be assigned a value other than null or undefined.
// If none of the values are assigned, then the last value is returned.
var getAssigned = function() {
	var value;
	var i, length;

	for (i = 0, length = arguments.length; i < length; i += 1) {
		value = arguments[i];

		if (isAssigned(value)) {
			return value;
		}
	}

	return value;
};

// Parses the given namespace string into an array.
var parseNamespace = function(namespaceString) {
	return namespaceString.split(".");
};

// Creates the given namespace structure and executes the constructor to generate the object
// only if it's not already defined.
var defineGlobalOnce = function(namespace, constructor) {
	var hierarchy = parseNamespace(namespace);
	var leafName = hierarchy.pop();
	var context = window;

	if (!leafName) {
		throw new Error("Invalid namespace or object name.");
	}

	hierarchy.forEach(function(nodeName) {
		var node = context[nodeName] || {};

		if (node !== window) {
			context[nodeName] = node;
		}

		context = node;
	});

	if (!isAssigned(context[leafName])) {
		context[leafName] = constructor();
	}

	return context[leafName];
};

// Returns a function which returns the value passed.
var createConstantGetter = function(value) {
	return function() {
		return value;
	};
};

var defineProperty = Object.defineProperty;

// Defines a constant value in the given object.
var defineConstant = function(object, key, value) {
	defineProperty(object, key, {
		value: value,
		writable: false
	});

	return value;
};

// Defines an accessor in the given object.
var defineAccessor = function(object, key, settings) {
	defineProperty(object, key, {
		get: settings.get,
		set: settings.set
	});
};

module.exports = {
	isAssigned:           isAssigned,
	getAssigned:          getAssigned,
	defineGlobalOnce:     defineGlobalOnce,
	createConstantGetter: createConstantGetter,
	defineConstant:       defineConstant,
	defineAccessor:       defineAccessor
};
<|endoftext|>


<commit_before>/*
 * Copyright (c) 2016 Maxwell Dreytser
 *
 * 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.
 *
 */

// If you would like IE 8 support, include the polyfill here: https://developer.mozilla.org/en-US/docs/Web/API/EventTarget/addEventListener#Compatibility
/**
 * Adds a speech bubble above or below the specified element.
 * @param {HTMLElement} targetElement - Element that the
 * @param {string} content - What the bubble will contain (html is ok).
 * @param {string} [additionalCSSClasses] The CSS class to add to the element.
 * @param {HTMLElement} [appendToElement=body] The element to which the SpeechBubble will actually be appended to. By default this is the `body` element.
 * @returns {HTMLElement} The Speech Bubble element.
 */
window.SpeechBubble = function(targetElement, content, additionalCSSClasses, appendToElement){
	// http://stackoverflow.com/a/34014786/1610754 and http://stackoverflow.com/a/442474/1610754
	function getOffset(elm) {
		// Find the offset of elm from the body or html element
		var _x = 0;
		var _y = 0;
		while( elm && !isNaN( elm.offsetLeft ) && !isNaN( elm.offsetTop ) )
		{
			_x += elm.offsetLeft - elm.scrollLeft + elm.clientLeft;
			_y += elm.offsetTop - elm.scrollTop + elm.clientTop;
			elm = elm.offsetParent;
		}
		return { top: _y, left: _x };
	}

	var element;
	if (typeof jQuery !== "undefined" && targetElement instanceof jQuery) {
		element = targetElement[0];
	} else {
		element = targetElement;
	}
	var appendElm;
	if (typeof jQuery !== "undefined" && appendToElement instanceof jQuery) {
		appendElm = appendToElement[0];
	} else {
		appendElm = appendToElement;
	}

	var SpeechDiv = document.createElement('div');
	if (additionalCSSClasses) {
		SpeechDiv.className = 'speech-bubble-main speech-bubble-top ' + additionalCSSClasses;
	} else {
		SpeechDiv.className = 'speech-bubble-main speech-bubble-top';
	}
	SpeechDiv.innerHTML = content;
	var SpeechID;
	do {
		SpeechID='bubble-' + new Date().getTime();
	} while (document.getElementById(SpeechID));
	SpeechDiv.id = SpeechID;
	SpeechDiv.setAttribute("style", "");
	(appendElm || document.getElementsByTagName('body')[0]).appendChild(SpeechDiv);

	var SpeechStyle = document.createElement('style');
	document.getElementsByTagName('body')[0].appendChild(SpeechStyle);

	function DoAutoPosition() {
		var elmXY = getOffset(element);

		var speechX;
		var speechY;

		var elmWidth = (element.offsetWidth && element.offsetWidth > element.clientWidth) ? element.offsetWidth : element.clientWidth;
		var elmHeight = (element.offsetHeight && element.offsetHeight > element.clientHeight) ? element.offsetHeight : element.clientHeight;

		var targetPointerCoefficient = 0;
		if (SpeechDiv.clientWidth < element.clientWidth)
			speechX = elmXY.left + (element.clientWidth - SpeechDiv.clientWidth) / 2;
		else if (elmXY.left + SpeechDiv.clientWidth >= document.documentElement.clientWidth) {
			// If the size of the SpeechDiv is greater than the amount of space there is from
			// the beginning of the element to the edge of the page, the SpeechDiv must be moved closer to the left.
			speechX = document.documentElement.clientWidth - SpeechDiv.clientWidth;
			// If the SpeechDiv is larger that the viewport, let the SpeechBubble become taller.
			if (speechX < 0) {
				speechX = 0;
			}

			// Now, calculate how much the pointer should be moved to compensate for the new position of the SpeechDiv.
			targetPointerCoefficient = elmXY.left - speechX;
		} else
			speechX = elmXY.left;

		// Temporarily set the X coordinate of the SpeechDiv manually to correctly calculate the Y coordinate.
		SpeechDiv.style.left = speechX;

		if (elmXY.top + elmHeight + SpeechDiv.clientHeight + 23 > (window.innerHeight || document.documentElement.clientHeight || document.body.clientHeight)) {
			var appliedClasses = SpeechDiv.className.split(' ');
			for ( var i = 0; i < appliedClasses.length; i++ ) {
				if (appliedClasses[i] == 'speech-bubble-top') {
					appliedClasses[i] = 'speech-bubble-bottom';
				}
			}
			SpeechDiv.className = appliedClasses.join(' ');

			speechY = elmXY.top - SpeechDiv.clientHeight - 23;
		} else {
			var appliedClasses = SpeechDiv.className.split(' ');
			for ( var i = 0; i < appliedClasses.length; i++ ) {
				if (appliedClasses[i] == 'speech-bubble-bottom') {
					appliedClasses[i] = 'speech-bubble-top';
				}
			}
			SpeechDiv.className = appliedClasses.join(' ');

			speechY = elmXY.top + elmHeight + 2;
		}

		// Unset inline style.
		SpeechDiv.style.left = "";

		SpeechStyle.innerHTML =
				'#' + SpeechDiv.id + ' {' +
				'  left: ' + speechX + 'px;' +
				'  top: ' + speechY + 'px;' +
				'}' +
				'#' + SpeechDiv.id + ':before {';
		if (SpeechDiv.clientWidth < elmWidth)
			SpeechStyle.innerHTML += '  left: ' + (targetPointerCoefficient + (SpeechDiv.clientWidth - 20) / 2 - 7) + 'px';
		else
			SpeechStyle.innerHTML += '  left: ' + (targetPointerCoefficient + elmWidth / 2 - 27) + 'px;';
		SpeechStyle.innerHTML +=
				'}' +
				'#' + SpeechDiv.id + ':after {';
		if (SpeechDiv.clientWidth < elmWidth)
			SpeechStyle.innerHTML += '  left: ' + (targetPointerCoefficient + (SpeechDiv.clientWidth - 20) / 2) + 'px';
		else
			SpeechStyle.innerHTML += '  left: ' + (targetPointerCoefficient + elmWidth / 2 - 20) + 'px;';
		SpeechStyle.innerHTML += '}';
	}

	DoAutoPosition();

	window.addEventListener('resize', function(){
		DoAutoPosition();
	}, true);

	SpeechDiv.removeBubble = function() {
		SpeechStyle.parentNode.removeChild(SpeechStyle);
		SpeechDiv.parentNode.removeChild(SpeechDiv);

		for ( var i = 0; i < OpenSpeechBubbles.length; i++ ) {
			if (OpenSpeechBubbles[i] == SpeechDiv) {
				OpenSpeechBubbles.splice(i, 1);
			}
		}
	};

	OpenSpeechBubbles.push(SpeechDiv);

	return SpeechDiv;
};

window.OpenSpeechBubbles = [];
<commit_msg>Add project name next to copyright notice.<commit_after>/*
 * SpeechBubble.js
 *
 * Copyright (c) 2016 Maxwell Dreytser
 *
 * 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.
 *
 */

// If you would like IE 8 support, include the polyfill here: https://developer.mozilla.org/en-US/docs/Web/API/EventTarget/addEventListener#Compatibility
/**
 * Adds a speech bubble above or below the specified element.
 * @param {HTMLElement} targetElement - Element that the
 * @param {string} content - What the bubble will contain (html is ok).
 * @param {string} [additionalCSSClasses] The CSS class to add to the element.
 * @param {HTMLElement} [appendToElement=body] The element to which the SpeechBubble will actually be appended to. By default this is the `body` element.
 * @returns {HTMLElement} The Speech Bubble element.
 */
window.SpeechBubble = function(targetElement, content, additionalCSSClasses, appendToElement){
	// http://stackoverflow.com/a/34014786/1610754 and http://stackoverflow.com/a/442474/1610754
	function getOffset(elm) {
		// Find the offset of elm from the body or html element
		var _x = 0;
		var _y = 0;
		while( elm && !isNaN( elm.offsetLeft ) && !isNaN( elm.offsetTop ) )
		{
			_x += elm.offsetLeft - elm.scrollLeft + elm.clientLeft;
			_y += elm.offsetTop - elm.scrollTop + elm.clientTop;
			elm = elm.offsetParent;
		}
		return { top: _y, left: _x };
	}

	var element;
	if (typeof jQuery !== "undefined" && targetElement instanceof jQuery) {
		element = targetElement[0];
	} else {
		element = targetElement;
	}
	var appendElm;
	if (typeof jQuery !== "undefined" && appendToElement instanceof jQuery) {
		appendElm = appendToElement[0];
	} else {
		appendElm = appendToElement;
	}

	var SpeechDiv = document.createElement('div');
	if (additionalCSSClasses) {
		SpeechDiv.className = 'speech-bubble-main speech-bubble-top ' + additionalCSSClasses;
	} else {
		SpeechDiv.className = 'speech-bubble-main speech-bubble-top';
	}
	SpeechDiv.innerHTML = content;
	var SpeechID;
	do {
		SpeechID='bubble-' + new Date().getTime();
	} while (document.getElementById(SpeechID));
	SpeechDiv.id = SpeechID;
	SpeechDiv.setAttribute("style", "");
	(appendElm || document.getElementsByTagName('body')[0]).appendChild(SpeechDiv);

	var SpeechStyle = document.createElement('style');
	document.getElementsByTagName('body')[0].appendChild(SpeechStyle);

	function DoAutoPosition() {
		var elmXY = getOffset(element);

		var speechX;
		var speechY;

		var elmWidth = (element.offsetWidth && element.offsetWidth > element.clientWidth) ? element.offsetWidth : element.clientWidth;
		var elmHeight = (element.offsetHeight && element.offsetHeight > element.clientHeight) ? element.offsetHeight : element.clientHeight;

		var targetPointerCoefficient = 0;
		if (SpeechDiv.clientWidth < element.clientWidth)
			speechX = elmXY.left + (element.clientWidth - SpeechDiv.clientWidth) / 2;
		else if (elmXY.left + SpeechDiv.clientWidth >= document.documentElement.clientWidth) {
			// If the size of the SpeechDiv is greater than the amount of space there is from
			// the beginning of the element to the edge of the page, the SpeechDiv must be moved closer to the left.
			speechX = document.documentElement.clientWidth - SpeechDiv.clientWidth;
			// If the SpeechDiv is larger that the viewport, let the SpeechBubble become taller.
			if (speechX < 0) {
				speechX = 0;
			}

			// Now, calculate how much the pointer should be moved to compensate for the new position of the SpeechDiv.
			targetPointerCoefficient = elmXY.left - speechX;
		} else
			speechX = elmXY.left;

		// Temporarily set the X coordinate of the SpeechDiv manually to correctly calculate the Y coordinate.
		SpeechDiv.style.left = speechX;

		if (elmXY.top + elmHeight + SpeechDiv.clientHeight + 23 > (window.innerHeight || document.documentElement.clientHeight || document.body.clientHeight)) {
			var appliedClasses = SpeechDiv.className.split(' ');
			for ( var i = 0; i < appliedClasses.length; i++ ) {
				if (appliedClasses[i] == 'speech-bubble-top') {
					appliedClasses[i] = 'speech-bubble-bottom';
				}
			}
			SpeechDiv.className = appliedClasses.join(' ');

			speechY = elmXY.top - SpeechDiv.clientHeight - 23;
		} else {
			var appliedClasses = SpeechDiv.className.split(' ');
			for ( var i = 0; i < appliedClasses.length; i++ ) {
				if (appliedClasses[i] == 'speech-bubble-bottom') {
					appliedClasses[i] = 'speech-bubble-top';
				}
			}
			SpeechDiv.className = appliedClasses.join(' ');

			speechY = elmXY.top + elmHeight + 2;
		}

		// Unset inline style.
		SpeechDiv.style.left = "";

		SpeechStyle.innerHTML =
				'#' + SpeechDiv.id + ' {' +
				'  left: ' + speechX + 'px;' +
				'  top: ' + speechY + 'px;' +
				'}' +
				'#' + SpeechDiv.id + ':before {';
		if (SpeechDiv.clientWidth < elmWidth)
			SpeechStyle.innerHTML += '  left: ' + (targetPointerCoefficient + (SpeechDiv.clientWidth - 20) / 2 - 7) + 'px';
		else
			SpeechStyle.innerHTML += '  left: ' + (targetPointerCoefficient + elmWidth / 2 - 27) + 'px;';
		SpeechStyle.innerHTML +=
				'}' +
				'#' + SpeechDiv.id + ':after {';
		if (SpeechDiv.clientWidth < elmWidth)
			SpeechStyle.innerHTML += '  left: ' + (targetPointerCoefficient + (SpeechDiv.clientWidth - 20) / 2) + 'px';
		else
			SpeechStyle.innerHTML += '  left: ' + (targetPointerCoefficient + elmWidth / 2 - 20) + 'px;';
		SpeechStyle.innerHTML += '}';
	}

	DoAutoPosition();

	window.addEventListener('resize', function(){
		DoAutoPosition();
	}, true);

	SpeechDiv.removeBubble = function() {
		SpeechStyle.parentNode.removeChild(SpeechStyle);
		SpeechDiv.parentNode.removeChild(SpeechDiv);

		for ( var i = 0; i < OpenSpeechBubbles.length; i++ ) {
			if (OpenSpeechBubbles[i] == SpeechDiv) {
				OpenSpeechBubbles.splice(i, 1);
			}
		}
	};

	OpenSpeechBubbles.push(SpeechDiv);

	return SpeechDiv;
};

window.OpenSpeechBubbles = [];
<|endoftext|>


<commit_before><commit_msg>Adding initial code<commit_after>function fillString(string) {
  var numArray = processArray(string.split(',')),
    resultArray = [];

  numArray.forEach(function(ele, index, array) {
    if(Number.isNaN(ele)) {
      resultArray = resultArray.concat(findMissingNumbers(index, array));
    } else {
      resultArray.push(ele);
    }
  });

  return resultArray;
}

function processArray(array) {
  var temp = [];

  array.forEach(function(ele) {
    if(Number.isNaN(parseInt(ele)) {
      temp = temp.concat(processString(ele));
    } else {
      temp.push(parseInt(ele));
    }
  });

  return temp;
}

function processString(string) {
  var tempArray = [],
  strLength = string.length, i;

  for(i = 0, i < strLength; i += 3) {
    tempArray.push(parseInt(string[i]));

    if(tempArray[i+1] !== undefined)  {
      tempArray.push(',');
    }
  }

  return tempArray;
}

function findMissingNumbers(index, array) {
  var prev = array[index - 1] || 0,
    next = array[index + 1] || (prev + 1),
    missingNumbers = [], i;

  for(i = prev + 1; i < next; i++ ) {
    missingNumbers.push(i);
  }

  return missingNumbers;
}
<|endoftext|>


<commit_before>define(function (require) {

  var Backbone = require('backbone'),
    globals = require('globals'),
    VolumeState = require('./VolumeState');

  var extractAttachData = function (attrs) {
    if (attrs.attach_data && attrs.attach_data.instance_alias) {
      return {
        device: attrs.attach_data.device,
        instance_id: attrs.attach_data.instance_alias
      };
    }

    return {
      device: null,
      instance_id: null
    };
  };

  return Backbone.Model.extend({
    urlRoot: globals.API_V2_ROOT + "/volumes",

    parse: function (attributes) {
      if(attributes.start_date){
        attributes.start_date = new Date(attributes.start_date);
      }
      if(attributes.status){
        attributes.state = new VolumeState({status_raw: attributes.status});
      }
      else{
        attributes.status = "Unknown";
      }
      attributes.attach_data = extractAttachData(attributes);
      return attributes;
    },

    isAttached: function () {
      return this.get('status') == 'in-use' || this.get('status') == 'detaching';
    },

    fetchFromCloud: function (cb) {
      var volumeId = this.get('uuid'),
        providerId = this.get('provider').uuid,
        identityId = this.get('identity').uuid;

      var url = (
        globals.API_ROOT +
        "/provider/" + providerId +
        "/identity/" + identityId +
        "/volume/" + volumeId
      );

      Backbone.sync("read", this, {
        url: url
      }).done(function (attrs, status, response) {
        this.set('status', attrs.status || "Unknown");
        this.set('state', new VolumeState({status_raw: attrs.status}));
        this.set('attach_data', extractAttachData(attrs));
        cb(response);
      }.bind(this));
    },

    createOnV1Endpoint: function (options, cb) {
      if (!options.name) throw new Error("Missing name");
      if (!options.size) throw new Error("Missing size");

      var volumeId = this.get('uuid'),
        providerId = this.get('provider').uuid,
        identityId = this.get('identity').uuid,
        name = options.name,
        size = options.size;

      var url = (
        globals.API_ROOT +
        "/provider/" + providerId +
        "/identity/" + identityId +
        "/volume"
      );

      return Backbone.sync("create", this, {
        url: url,
        attrs: {
          name: name,
          size: size
        }
      });
      //.done(function(attrs, status, response){
      //  cb(null, attrs);
      //}.bind(this)).fail(function(response){
      //  cb(response);
      //});
    }

  });

});
<commit_msg>Provide an empty state if no status for Volume<commit_after>define(function (require) {

  var Backbone = require('backbone'),
    globals = require('globals'),
    VolumeState = require('./VolumeState');

  var extractAttachData = function (attrs) {
    if (attrs.attach_data && attrs.attach_data.instance_alias) {
      return {
        device: attrs.attach_data.device,
        instance_id: attrs.attach_data.instance_alias
      };
    }

    return {
      device: null,
      instance_id: null
    };
  };

  return Backbone.Model.extend({
    urlRoot: globals.API_V2_ROOT + "/volumes",

    parse: function (attributes) {
      if(attributes.start_date){
        attributes.start_date = new Date(attributes.start_date);
      }
      if(attributes.status){
        attributes.state = new VolumeState({status_raw: attributes.status});
      }
      else{
        attributes.status = "Unknown";
        attributes.state = new VolumeState({});
      }
      attributes.attach_data = extractAttachData(attributes);
      return attributes;
    },

    isAttached: function () {
      return this.get('status') == 'in-use' || this.get('status') == 'detaching';
    },

    fetchFromCloud: function (cb) {
      var volumeId = this.get('uuid'),
        providerId = this.get('provider').uuid,
        identityId = this.get('identity').uuid;

      var url = (
        globals.API_ROOT +
        "/provider/" + providerId +
        "/identity/" + identityId +
        "/volume/" + volumeId
      );

      Backbone.sync("read", this, {
        url: url
      }).done(function (attrs, status, response) {
        this.set('status', attrs.status || "Unknown");
        this.set('state', new VolumeState({status_raw: attrs.status}));
        this.set('attach_data', extractAttachData(attrs));
        cb(response);
      }.bind(this));
    },

    createOnV1Endpoint: function (options, cb) {
      if (!options.name) throw new Error("Missing name");
      if (!options.size) throw new Error("Missing size");

      var volumeId = this.get('uuid'),
        providerId = this.get('provider').uuid,
        identityId = this.get('identity').uuid,
        name = options.name,
        size = options.size;

      var url = (
        globals.API_ROOT +
        "/provider/" + providerId +
        "/identity/" + identityId +
        "/volume"
      );

      return Backbone.sync("create", this, {
        url: url,
        attrs: {
          name: name,
          size: size
        }
      });
      //.done(function(attrs, status, response){
      //  cb(null, attrs);
      //}.bind(this)).fail(function(response){
      //  cb(response);
      //});
    }

  });

});
<|endoftext|>


<commit_before>import { React, PropTypes, styled, observable, observer, action, modelize } from 'vendor';
import { createRef } from 'react';
import { map } from 'lodash';
import { Button, Popover, Overlay } from 'react-bootstrap';
import { Icon } from 'shared';
import { colors } from 'theme';

/** https://www.w3schools.com/howto/howto_css_custom_checkbox.asp  */
const StyledCheckbox = styled.label`
  display: block;
  position: relative;
  padding-left: 30px;
  margin-bottom: 10px;
  cursor: pointer;
  font-size: 14px;

  /* Hide default checkbox */
  input {
    position: absolute;
    cursor: pointer;
    visibility: hidden;
  }

.check {
  position: absolute;
  top: 2px;
  left: 0;
  height: 20px;
  width: 20px;
  background-color: ${colors.white};
  border: 2px solid ${colors.neutral.pale};
}

& input:checked ~ .check:after {
  display: block;
}

/* Style the check */
& .check:after {
  content: "";
  position: absolute;
  display: none;
  left: 5px;
  top: 2px;
  width: 6px;
  height: 10px;
  border: solid ${colors.neutral.dark};
  border-width: 0 3px 3px 0;
  transform: rotate(45deg);
}
`;

const Toggles = styled(Popover.Content)`
  padding: 1rem;
  label {
    display: block;
  }
  input {
    margin-right: 1rem;
  }
`;

const MoreInfo = styled.p`
  color: ${colors.neutral.thin};
  border-top: 1px solid ${colors.neutral.gray};
`;

const SettingsCheckbox = observer(({ ux, title, property }) => (

));
SettingsCheckbox.propTypes = {
    ux: PropTypes.object.isRequired,
    title: PropTypes.string.isRequired,
    property: PropTypes.string.isRequired,
};

@observer
export default class Settings extends React.Component {
    static propTypes = {
        ux: PropTypes.object.isRequired,
        label: PropTypes.string.isRequired,
        controls: PropTypes.object.isRequired,
        moreInfo: PropTypes.string,
    };

    target = createRef();
    @observable showPopoverInfo = false;
    @observable showPopoverSettings = false;

    constructor(props) {
        super(props);
        modelize(this);
    }

    @action.bound onBtnClick() {
        this.showPopoverInfo = false;
        this.showPopoverSettings = true;
    }

    @action.bound onMouseEnter() {
        this.showPopoverInfo = true;
    }

    @action.bound onMouseLeave() {
        this.showPopoverInfo = false;
    }

    render() {
        const { ux, label, controls, moreInfo } = this.props;
        return (
            <>
                <Button
                    ref={this.target}
                    data-test-id="settings-btn"
                    onClick={this.onBtnClick}
                    onMouseEnter={this.onMouseEnter}
                    onMouseLeave={this.onMouseLeave}
                    variant='plain'
                    className={`${this.showPopoverSettings ? 'gradebook-btn-selected' : ''}`}
                >
                    <Icon type="cog" />
                </Button>
                {/* Overlay for the settings controller */}
                <Overlay
                    rootClose
                    target={this.target.current}
                    placement="bottom"
                    show={this.showPopoverSettings}
                    onHide={() => this.showPopoverSettings = false}>
                    <Popover className="scores-popover" >
                        <Toggles>
                            {map(controls, (title, property) => <SettingsCheckbox key={property} ux={ux} property={property} title={title} />)}
                        </Toggles>
                        {moreInfo && <MoreInfo>{moreInfo}</MoreInfo>}
                    </Popover>
                </Overlay>
                {/* Overlay for the button information */}
                <Overlay
                    target={this.target.current}
                    placement="bottom"
                    show={this.showPopoverInfo && !this.showPopoverSettings}>
                    <Popover className="scores-popover" >

{label}

                    </Popover>
                </Overlay>
            </>
        );
    }
}
<commit_msg>fix mobx observed warning<commit_after>import { React, PropTypes, styled, observable, observer, action, modelize } from 'vendor';
import { createRef } from 'react';
import { map } from 'lodash';
import { Button, Popover, Overlay } from 'react-bootstrap';
import { Icon } from 'shared';
import { colors } from 'theme';

/** https://www.w3schools.com/howto/howto_css_custom_checkbox.asp  */
const StyledCheckbox = styled.label`
  display: block;
  position: relative;
  padding-left: 30px;
  margin-bottom: 10px;
  cursor: pointer;
  font-size: 14px;

  /* Hide default checkbox */
  input {
    position: absolute;
    cursor: pointer;
    visibility: hidden;
  }

.check {
  position: absolute;
  top: 2px;
  left: 0;
  height: 20px;
  width: 20px;
  background-color: ${colors.white};
  border: 2px solid ${colors.neutral.pale};
}

& input:checked ~ .check:after {
  display: block;
}

/* Style the check */
& .check:after {
  content: "";
  position: absolute;
  display: none;
  left: 5px;
  top: 2px;
  width: 6px;
  height: 10px;
  border: solid ${colors.neutral.dark};
  border-width: 0 3px 3px 0;
  transform: rotate(45deg);
}
`;

const Toggles = styled(Popover.Content)`
  padding: 1rem;
  label {
    display: block;
  }
  input {
    margin-right: 1rem;
  }
`;

const MoreInfo = styled.p`
  color: ${colors.neutral.thin};
  border-top: 1px solid ${colors.neutral.gray};
`;

const SettingsCheckbox = observer(({ ux, title, property }) => (

));
SettingsCheckbox.propTypes = {
    ux: PropTypes.object.isRequired,
    title: PropTypes.string.isRequired,
    property: PropTypes.string.isRequired,
};

@observer
export default class Settings extends React.Component {
    static propTypes = {
        ux: PropTypes.object.isRequired,
        label: PropTypes.string.isRequired,
        controls: PropTypes.object.isRequired,
        moreInfo: PropTypes.string,
    };

    target = createRef();
    @observable showPopoverInfo = false;
    @observable showPopoverSettings = false;

    constructor(props) {
        super(props);
        modelize(this);
    }

    @action.bound onBtnClick() {
        this.showPopoverInfo = false;
        this.showPopoverSettings = true;
    }

    @action.bound onMouseEnter() {
        this.showPopoverInfo = true;
    }

    @action.bound onMouseLeave() {
        this.showPopoverInfo = false;
    }

    render() {
        const { ux, label, controls, moreInfo } = this.props;
        return (
            <>
                <Button
                    ref={this.target}
                    data-test-id="settings-btn"
                    onClick={this.onBtnClick}
                    onMouseEnter={this.onMouseEnter}
                    onMouseLeave={this.onMouseLeave}
                    variant='plain'
                    className={`${this.showPopoverSettings ? 'gradebook-btn-selected' : ''}`}
                >
                    <Icon type="cog" />
                </Button>
                {/* Overlay for the settings controller */}
                <Overlay
                    rootClose
                    target={this.target.current}
                    placement="bottom"
                    show={this.showPopoverSettings}
                    onHide={action(() => this.showPopoverSettings = false)}>
                    <Popover className="scores-popover" >
                        <Toggles>
                            {map(controls, (title, property) => <SettingsCheckbox key={property} ux={ux} property={property} title={title} />)}
                        </Toggles>
                        {moreInfo && <MoreInfo>{moreInfo}</MoreInfo>}
                    </Popover>
                </Overlay>
                {/* Overlay for the button information */}
                <Overlay
                    target={this.target.current}
                    placement="bottom"
                    show={this.showPopoverInfo && !this.showPopoverSettings}>
                    <Popover className="scores-popover" >

{label}

                    </Popover>
                </Overlay>
            </>
        );
    }
}
<|endoftext|>


<commit_before>define( [
    'osg/Notify',
    'osg/Utils'
], function ( Notify, Utils ) {

    /**
     * Shader manage shader for vertex and fragment, you need both to create a glsl program.
     * @class Shader
     */
    var Shader = function ( type, text ) {

        var t = type;
        if ( typeof ( type ) === 'string' ) {
            t = Shader[ type ];
        }
        this.type = t;
        this.setText( text );
    };

    Shader.VERTEX_SHADER = 0x8B31;
    Shader.FRAGMENT_SHADER = 0x8B30;

    // Debug Pink shader for when shader fails
    Shader.VS_DBG = 'attribute vec3 Vertex;uniform mat4 ModelViewMatrix;uniform mat4 ProjectionMatrix;void main(void) {  gl_Position = ProjectionMatrix * ModelViewMatrix * vec4(Vertex, 1.0);}';
    Shader.FS_DBG = 'precision lowp float; void main(void) { gl_FragColor = vec4(1.0, 0.6, 0.6, 1.0);}';

    /** @lends Shader.prototype */
    Shader.prototype = {
        setText: function ( text ) {
            this.text = text;
        },
        getText: function () {
            return this.text;
        },
        // this is where it creates a fail safe shader that should work everywhere
        failSafe: function ( gl ) {
            this.shader = gl.createShader( this.type );
            gl.shaderSource( this.shader, this.type === Shader.VERTEX_SHADER ? Shader.VS_DBG : Shader.FS_DBG );
            gl.compileShader( this.shader );
        },
        // webgl shader compiler error to source contextualization
        // for better console log messages
        processErrors: function ( errors, source ) {
            // regex to extract error message and line from webgl compiler reporting
            var r = /ERROR: [\d]+:([\d]+): (.+)/gmi;
            // split sources in indexable per line array
            var lines = source.split( '\n' );
            var i, m;

            while ( ( m = r.exec( errors ) ) != null ) {
                if ( m.index === r.lastIndex ) {
                    r.lastIndex++; // moving between errors
                }
                // get error line
                var line = parseInt( m[ 1 ] );

                // webgl error report.
                Notify.error( 'ERROR ' + m[ 2 ] + ' in line ' + line, false, true );

                // for context
                // log surrounding line priori to error with bof check
                for ( i = 2; i < 7 && ( 0 < line - i ); i++ ) {
                    Notify.log( lines[ line - i ].replace( /^[ \t]+/g, '' ), false, true );
                }

                // Warn adds a lovely /!\ icon in front of the culprit line
                Notify.warn( lines[ line - 1 ].replace( /^[ \t]+/g, '' ), false, true );

                // for context
                // surrounding line posterior to error (with eof check)
                for ( i = 0; i < 5 && ( lines.length > line + i ); i++ ) {
                    Notify.log( lines[ line + i ].replace( /^[ \t]+/g, '' ), false, true );
                }
            }
        },
        compile: function ( gl ) {
            this.shader = gl.createShader( this.type );
            gl.shaderSource( this.shader, this.text );
            Utils.timeStamp( 'osgjs.metrics:compileShader' );
            gl.compileShader( this.shader );
            if ( !gl.getShaderParameter( this.shader, gl.COMPILE_STATUS ) && !gl.isContextLost() ) {

                var err = gl.getShaderInfoLog( this.shader );
                this.processErrors( err, this.text );

                var tmpText = '\n' + this.text;
                var splittedText = tmpText.split( '\n' );
                var newText = '\n';
                for ( var i = 0, l = splittedText.length; i < l; ++i ) {
                    newText += i + ' ' + splittedText[ i ] + '\n';
                }
                // still logging whole source but folded
                Notify.log( 'can\'t compile shader:\n' + newText, true );

                return false;
            }
            return true;
        }
    };

    Shader.create = function ( type, text ) {
        Notify.log( 'Shader.create is deprecated, use new Shader with the same arguments instead' );
        return new Shader( type, text );
    };

    return Shader;
} );<commit_msg>[#91596966] Adds IE specific regexp for shader error reporting in console<commit_after>define( [
    'osg/Notify',
    'osg/Utils'
], function ( Notify, Utils ) {

    /**
     * Shader manage shader for vertex and fragment, you need both to create a glsl program.
     * @class Shader
     */
    var Shader = function ( type, text ) {

        var t = type;
        if ( typeof ( type ) === 'string' ) {
            t = Shader[ type ];
        }
        this.type = t;
        this.setText( text );
    };

    Shader.VERTEX_SHADER = 0x8B31;
    Shader.FRAGMENT_SHADER = 0x8B30;

    // Debug Pink shader for when shader fails
    Shader.VS_DBG = 'attribute vec3 Vertex;uniform mat4 ModelViewMatrix;uniform mat4 ProjectionMatrix;void main(void) {  gl_Position = ProjectionMatrix * ModelViewMatrix * vec4(Vertex, 1.0);}';
    Shader.FS_DBG = 'precision lowp float; void main(void) { gl_FragColor = vec4(1.0, 0.6, 0.6, 1.0);}';

    /** @lends Shader.prototype */
    Shader.prototype = {
        setText: function ( text ) {
            this.text = text;
        },
        getText: function () {
            return this.text;
        },
        // this is where it creates a fail safe shader that should work everywhere
        failSafe: function ( gl ) {
            this.shader = gl.createShader( this.type );
            gl.shaderSource( this.shader, this.type === Shader.VERTEX_SHADER ? Shader.VS_DBG : Shader.FS_DBG );
            gl.compileShader( this.shader );
        },
        // webgl shader compiler error to source contextualization
        // for better console log messages
        processErrors: function ( errors, source ) {
            // regex to extract error message and line from webgl compiler reporting
            var r = /ERROR: [\d]+:([\d]+): (.+)/gmi;
            // split sources in indexable per line array
            var lines = source.split( '\n' );
            var i, m;

            // IE reporting is not the same
            if (r.exec(errors) === null){
             r = /Shader compilation errors\n\((\d+)\, \d+\): (.+)/gmi;
            }

            while ( ( m = r.exec( errors ) ) != null ) {
                if ( m.index === r.lastIndex ) {
                    r.lastIndex++; // moving between errors
                }
                // get error line
                var line = parseInt( m[ 1 ] );

                // webgl error report.
                Notify.error( 'ERROR ' + m[ 2 ] + ' in line ' + line, false, true );

                // for context
                // log surrounding line priori to error with bof check
                for ( i = 2; i < 7 && ( 0 < line - i ); i++ ) {
                    Notify.log( lines[ line - i ].replace( /^[ \t]+/g, '' ), false, true );
                }

                // Warn adds a lovely /!\ icon in front of the culprit line
                Notify.warn( lines[ line - 1 ].replace( /^[ \t]+/g, '' ), false, true );

                // for context
                // surrounding line posterior to error (with eof check)
                for ( i = 0; i < 5 && ( lines.length > line + i ); i++ ) {
                    Notify.log( lines[ line + i ].replace( /^[ \t]+/g, '' ), false, true );
                }
            }
        },
        compile: function ( gl ) {
            this.shader = gl.createShader( this.type );
            gl.shaderSource( this.shader, this.text );
            Utils.timeStamp( 'osgjs.metrics:compileShader' );
            gl.compileShader( this.shader );
            if ( !gl.getShaderParameter( this.shader, gl.COMPILE_STATUS ) && !gl.isContextLost() ) {

                var err = gl.getShaderInfoLog( this.shader );
                this.processErrors( err, this.text );

                var tmpText = '\n' + this.text;
                var splittedText = tmpText.split( '\n' );
                var newText = '\n';
                for ( var i = 0, l = splittedText.length; i < l; ++i ) {
                    newText += i + ' ' + splittedText[ i ] + '\n';
                }
                // still logging whole source but folded
                Notify.log( 'can\'t compile shader:\n' + newText, true );

                return false;
            }
            return true;
        }
    };

    Shader.create = function ( type, text ) {
        Notify.log( 'Shader.create is deprecated, use new Shader with the same arguments instead' );
        return new Shader( type, text );
    };

    return Shader;
} );<|endoftext|>