<commit_before>import Company from '../Company/company'

/**
 * Class representing an Asset Manager
 * @memberof module:parties
 * @extends module:parties.Company
 */
class AssetManager extends Company {
  /**
   * Construct a new Asset Manager instance
   * @param {object} params - Asset Manager creation options
   * @param {number} params.assetManagerId - Asset Manager ID of the Asset Manager
   * @param {string} params.partyId - Party ID of the Asset Manager
   * @param {string} params.partyStatus=Active - Status of the Asset Manager (e.g. 'Active')
   * @param {string} params.baseCurrency - Base Currency of the Asset Manager (e.g. SGD, USD)
   * @param {string} params.description - Description of the Asset Manager
   * @param {string} [params.licenseNumber] - Company license number (if applicable)
   * @param {string} [params.licenseType] - Company license type
   * @param {string} [params.assetsUnderManagement] - Value of assets under management
   * @param {string} [params.registrationNumber] - Business registration number (if applicable)
   * @param {string} [params.yearOfIncorporation] - Year of incorporation
   * @param {string} [params.contactNumber] - Contact number
   * @param {object} params.addresses - Object of Addresses associated with this Asset Manager
   * @param {object} params.emails - Object of Emails associated with this Asset Manager
   * @param {object} params.references - Object of References associated with this Asset Manager
   * @param {object} params.comments - Object of Comments associated with the Asset Manager
   * @param {object} params.links - Object of Links associated with the Asset Manager
   * @param {string} params.legalName- Legal name of the Asset Manager associated with this party
   * @param {string} params.displayName - Display name of the Asset Manager associated with this party
   * @param {string} params.url - Url of this Party
   * @param {string} params.createdBy - ID of the user that created the Asset Manager
   * @param {string} params.updatedBy - ID of the user that updated the Asset Manager
   * @param {date} params.createdTime - Time that the Asset Manager was created
   * @param {date} params.updatedTime - Time that the Asset Manager was updated
   * @param {number} params.version - Version number of the Asset Manager
   */
  constructor({
    assetManagerId,
    partyId,
    partyStatus='Active',
    baseCurrency,
    description='',
    licenseNumber,
    licenseType,
    assetsUnderManagement,
    registrationNumber,
    yearOfIncoporation,
    contactNumber,
    addresses={},
    emails={},
    references={},
    comments={},
    links={},
    legalName,
    displayName,
    url,
    createdBy,
    updatedBy,
    createdTime,
    updatedTime,
    version
  }) {
    super({
      assetManagerId,
      partyId,
      partyStatus,
      baseCurrency,
      description,
      yearOfIncoporation,
      contactNumber,
      addresses,
      emails,
      references,
      comments,
      links,
      legalName,
      displayName,
      url,
      createdBy,
      updatedBy,
      createdTime,
      updatedTime,
      version
    })
    this.licenseNumber = licenseNumber
    this.licenseType = licenseType
    this.assetsUnderManagement = assetsUnderManagement
    this.registrationNumber = registrationNumber
  }
}

export default AssetManager
<commit_msg>More ‘incoporation’ fixes.<commit_after>import Company from '../Company/company'

/**
 * Class representing an Asset Manager
 * @memberof module:parties
 * @extends module:parties.Company
 */
class AssetManager extends Company {
  /**
   * Construct a new Asset Manager instance
   * @param {object} params - Asset Manager creation options
   * @param {number} params.assetManagerId - Asset Manager ID of the Asset Manager
   * @param {string} params.partyId - Party ID of the Asset Manager
   * @param {string} params.partyStatus=Active - Status of the Asset Manager (e.g. 'Active')
   * @param {string} params.baseCurrency - Base Currency of the Asset Manager (e.g. SGD, USD)
   * @param {string} params.description - Description of the Asset Manager
   * @param {string} [params.licenseNumber] - Company license number (if applicable)
   * @param {string} [params.licenseType] - Company license type
   * @param {string} [params.assetsUnderManagement] - Value of assets under management
   * @param {string} [params.registrationNumber] - Business registration number (if applicable)
   * @param {string} [params.yearOfIncorporation] - Year of incorporation
   * @param {string} [params.contactNumber] - Contact number
   * @param {object} params.addresses - Object of Addresses associated with this Asset Manager
   * @param {object} params.emails - Object of Emails associated with this Asset Manager
   * @param {object} params.references - Object of References associated with this Asset Manager
   * @param {object} params.comments - Object of Comments associated with the Asset Manager
   * @param {object} params.links - Object of Links associated with the Asset Manager
   * @param {string} params.legalName- Legal name of the Asset Manager associated with this party
   * @param {string} params.displayName - Display name of the Asset Manager associated with this party
   * @param {string} params.url - Url of this Party
   * @param {string} params.createdBy - ID of the user that created the Asset Manager
   * @param {string} params.updatedBy - ID of the user that updated the Asset Manager
   * @param {date} params.createdTime - Time that the Asset Manager was created
   * @param {date} params.updatedTime - Time that the Asset Manager was updated
   * @param {number} params.version - Version number of the Asset Manager
   */
  constructor({
    assetManagerId,
    partyId,
    partyStatus='Active',
    baseCurrency,
    description='',
    licenseNumber,
    licenseType,
    assetsUnderManagement,
    registrationNumber,
    yearOfIncorporation,
    contactNumber,
    addresses={},
    emails={},
    references={},
    comments={},
    links={},
    legalName,
    displayName,
    url,
    createdBy,
    updatedBy,
    createdTime,
    updatedTime,
    version
  }) {
    super({
      assetManagerId,
      partyId,
      partyStatus,
      baseCurrency,
      description,
      yearOfIncorporation,
      contactNumber,
      addresses,
      emails,
      references,
      comments,
      links,
      legalName,
      displayName,
      url,
      createdBy,
      updatedBy,
      createdTime,
      updatedTime,
      version
    })
    this.licenseNumber = licenseNumber
    this.licenseType = licenseType
    this.assetsUnderManagement = assetsUnderManagement
    this.registrationNumber = registrationNumber
  }
}

export default AssetManager
<|endoftext|>


<commit_before>/**
 * jQuery if-else plugin
 *
 * Creates if(), else() and fi() methods that can be used in
 * a chain of methods on jQuery objects
 *
 * @author Vegard Løkken <vegard@headspin.no>
 * @copyright 2013
 * @version 0.2
 * @licence MIT
 */
;(function( $ ) {

    /* Undef object that all chained jQuery methods work on
     * if they should not be executed */
    var $undef = $();

    /* The original object is stored here so we can restore
     * it later */
    var orig;

    /* We store the condition given in the if() method */
    var condition;

    $.fn["if"] = function(options) {
        orig = this;
        condition = !!options;

        if (!condition) {
            return $undef;
        } else {
            return this;
        }
    };

    $.fn["else"] = function( options) {
        if (orig === undefined)
            throw "else() can't be used before if()";

        return this === $undef ? orig : $undef;
    };

    $.fn["fi"] = function(options) {
        if (orig === undefined)
            throw "fi() can't be used before if()";

        return orig;
    };

})(jQuery);
<commit_msg>Remove unused variables. Fix nesting bug.<commit_after>/**
 * jQuery if-else plugin
 *
 * Creates if(), else() and fi() methods that can be used in
 * a chain of methods on jQuery objects
 *
 * @author Vegard Løkken <vegard@headspin.no>
 * @copyright 2013
 * @version 0.3
 * @licence MIT
 */
;(function( $ ) {

    /* Undef object that all chained jQuery methods work on
     * if they should not be executed */
    var $undef = $();

    /* The original object is stored here so we can restore
     * it later */
    var orig;

    $.fn["if"] = function(condition) {
        if (this === $undef) {
            return $();
        } else {
            orig = this;
            return !!condition ? this : $undef;
        }
    };

    $.fn["else"] = function() {
        if (orig === undefined)
            throw "else() can't be used before if()";

        return this === $undef ? orig : $undef;
    };

    $.fn["fi"] = function() {
        if (orig === undefined)
            throw "fi() can't be used before if()";

        return orig;
    };

})(jQuery);
<|endoftext|>


<commit_before>'use strict';

var acadYearStartDates = {
  '16/17' : new Date('August 1, 2016'),
  '15/16' : new Date('August 3, 2015'),
  '14/15' : new Date('August 4, 2014')
};

var oneWeekTime = 1000 * 60 * 60 * 24 * 7;

module.exports = {

  currentAcadYear: function (date) {
    var years = Object.keys(acadYearStartDates);
    years.sort().reverse();

    for (var i = 0; i < years.length; i++) {
      var year = years[i];
      if (date >= acadYearStartDates[year]) {
        return {year: year, startDate: acadYearStartDates[year]};
      }
    }
  },

  currentAcadSem: function (acadWeekNumber) {
    if (acadWeekNumber <= 23) {
      return 'Semester 1';
    } else if (acadWeekNumber <= 40 || acadWeekNumber === 53) {
      return 'Semester 2';
    } else if (acadWeekNumber <= 46) {
      return 'Special Term I';
    } else {
      // acadWeekNumber <= 52
      return 'Special Term II';
    }
  },

  /**
   * Compute the current academic week and return in json format
   * @param  {Date} date
   * @return {json} {
                      'year': "15/16",
                      'sem': 'Semester 1'|'Semester 2'|'Special Sem 1'|'Special Sem 2',
                      'type': 'Instructional'|'Reading'|'Examination'|'Recess'|'Vacation'|'Orientation',
                      'num': <weekNum>
                    }
   */
  currentAcadWeek: function (date) {
    var currentAcad = this.currentAcadYear(date);
    var acadYear = currentAcad.year;
    var acadYearStartDate = currentAcad.startDate;

    var acadWeekNumber = Math.ceil((date.getTime() - acadYearStartDate.getTime() + 1) / oneWeekTime);
    var semester = this.currentAcadSem(acadWeekNumber);

    var weekType;
    var weekNumber = 0;

    switch (semester) {
      case 'Semester 2':
        acadWeekNumber -= 22;
      case 'Semester 1':
        if (acadWeekNumber === 1) {
          weekType = 'Orientation';
          break;
        }
        if (acadWeekNumber > 18) {
          weekType = 'Vacation';
          weekNumber = acadWeekNumber - 18;
          if (weekNumber > 5) {
            weekNumber = 0;
          }
          break;
        }
        acadWeekNumber -= 1;
        var week = this.acadWeekOfNormalSem(acadWeekNumber);
        weekType = week.weekType;
        weekNumber = week.weekNumber;
        break;
      case 'Special Term I':
        acadWeekNumber -= 6;
      case 'Special Term II':
        acadWeekNumber -= 40;
        weekType = 'Instructional';
        weekNumber = acadWeekNumber;
        break;
    }

    return {
      year: acadYear,
      sem: semester,
      type: weekType,
      num: weekNumber
    };
  },

  acadWeekOfNormalSem: function (acadWeekNumber) {
    switch (acadWeekNumber) {
      case 7:
        return {weekType: 'Recess', weekNumber: 0};
      case 15:
        return {weekType: 'Reading', weekNumber : 0};
      case 16:
      case 17:
        return {weekType: 'Examination', weekNumber: acadWeekNumber - 15};
      default:
        var weekNumber = acadWeekNumber;
        if (weekNumber >= 8) { // For weeks after recess week
          weekNumber--;
        }
        return {weekType: 'Instructional', weekNumber: weekNumber};
    }
  }
};
<commit_msg>Refactor academicCalendar.js, added more comments<commit_after>'use strict';

var acadYearStartDates = {
  '16/17' : new Date('August 1, 2016'),
  '15/16' : new Date('August 3, 2015'),
  '14/15' : new Date('August 4, 2014')
};

// Constant variables
var oneWeekTime = 1000 * 60 * 60 * 24 * 7;
var sem1 = 'Semester 1';
var sem2 = 'Semester 2';
var special1 = 'Special Term I';
var special2 = 'Special Term II';

module.exports = {

  currentAcadYear: function (date) {
    var years = Object.keys(acadYearStartDates);
    years.sort().reverse();

    for (var i = 0; i < years.length; i++) {
      var year = years[i];
      if (date >= acadYearStartDates[year]) {
        return {year: year, startDate: acadYearStartDates[year]};
      }
    }
  },

  currentAcadSem: function (acadWeekNumber) {
    if (acadWeekNumber <= 23) {
      return sem1;
    } else if (acadWeekNumber <= 40 || acadWeekNumber === 53) {
      return sem2;
    } else if (acadWeekNumber <= 46) {
      return special1;
    } else {
      // acadWeekNumber <= 52
      return special2;
    }
  },

  /**
   * Compute the current academic week and return in json format
   * @param  {Date} date
   * @return {json} {
                      year: "15/16",
                      sem: 'Semester 1'|'Semester 2'|'Special Sem 1'|'Special Sem 2',
                      type: 'Instructional'|'Reading'|'Examination'|'Recess'|'Vacation'|'Orientation',
                      num: <weekNum>
                    }
   */
  currentAcadWeek: function (date) {
    var currentAcad = this.currentAcadYear(date);
    var acadYear = currentAcad.year;
    var acadYearStartDate = currentAcad.startDate;

    var acadWeekNumber = Math.ceil((date.getTime() - acadYearStartDate.getTime() + 1) / oneWeekTime);
    var semester = this.currentAcadSem(acadWeekNumber);

    var weekType;
    var weekNumber = 0;

    switch (semester) {
      case sem2: // Semester 2 starts 22 weeks after Week 1 of semester 1
        acadWeekNumber -= 22;
      case sem1:
        if (acadWeekNumber === 1) {
          weekType = 'Orientation';
          break;
        }
        if (acadWeekNumber > 18) {
          weekType = 'Vacation';
          weekNumber = acadWeekNumber - 18;
          if (weekNumber > 5) {
            // This means it is the 53th week of the AY, and this week is Vacation.
            // This happens 5 times every 28 years.
            weekNumber = 0;
          }
          break;
        }
        acadWeekNumber -= 1;
        var week = this.acadWeekOfNormalSem(acadWeekNumber);
        weekType = week.weekType;
        weekNumber = week.weekNumber;
        break;
      case special2: // Special Term II starts 6 weeks after Special Term I
        acadWeekNumber -= 6;
      case special1: // Special Term I starts on week 41 of the AY
        acadWeekNumber -= 40;
        weekType = 'Instructional';
        weekNumber = acadWeekNumber;
        break;
    }

    return {
      year: acadYear,
      sem: semester,
      type: weekType,
      num: weekNumber
    };
  },

  acadWeekOfNormalSem: function (acadWeekNumber) {
    switch (acadWeekNumber) {
      case 7:
        return {weekType: 'Recess', weekNumber: 0};
      case 15:
        return {weekType: 'Reading', weekNumber : 0};
      case 16:
      case 17:
        return {weekType: 'Examination', weekNumber: acadWeekNumber - 15};
      default:
        var weekNumber = acadWeekNumber;
        if (weekNumber >= 8) { // For weeks after recess week
          weekNumber--;
        }
        return {weekType: 'Instructional', weekNumber: weekNumber};
    }
  }
};
<|endoftext|>


<commit_before>output = { db: mongojs(input.connectionString) }
<commit_msg>beautify<commit_after>output = {
  db: mongojs(input.connectionString)
}
<|endoftext|>


<commit_before>var global = require('../../global');

module.exports = function(unitReceiptNote) {

    var items = [].concat.apply([], unitReceiptNote.items);

    var iso = "FM-PB-00-06-010";
    var number = unitReceiptNote.no;

    var locale = global.config.locale;

    var moment = require('moment');
    moment.locale(locale.name);

    var header = [{
        alignment: "center",
        text: 'BON PENERIMAAN BARANG',
        style: ['size10', 'bold']
    }, {
        columns: [
            {
                columns: [{
                    width: '*',
                    stack: [{
                        text: 'PT DAN LIRIS',
                        style: ['size15', 'bold']
                    }, {
                        text: 'BANARAN, GROGOL, SUKOHARJO',
                        style: ['size09']
                    }]
                }]

            },
            {
                columns: [{
                    width: '*',
                    stack: [{
                        alignment: "right",
                        text: ' ',
                        style: ['size15', 'bold']
                    }, {
                        alignment: "right",
                        text: iso,
                        style: ['size08', 'bold']
                    }]
                }]

            }]
    }];

    var subHeader = [{
        columns: [
            {
                width: '60%',
                columns: [{
                    width: '30%',
                    stack: ['Tanggal', 'Diterima dari']
                }, {
                    width: '5%',
                    stack: [':', ':']
                }, {
                    width: '*',
                    stack: [`${moment(unitReceiptNote.date).format(locale.date.format)}`, unitReceiptNote.supplier.name]
                }],
                style: ['size08']

            },
            {
                width: '10%',
                text: ''
            },
            {
                width: '30%',
                columns: [{
                    width: '25%',
                    stack: ['Bagian', 'No.']
                }, {
                    width: '5%',
                    stack: [':', ':']
                }, {
                    width: '*',
                    stack: [unitReceiptNote.unit.name, unitReceiptNote.no]
                }],
                style: ['size08']
            }
        ]
    }, '\n'];

    var line = [{
        canvas: [{
            type: 'line',
            x1: 0,
            y1: 5,
            x2: 378,
            y2: 5,
            lineWidth: 0.5
        }
        ]
    }, '\n'];

    var thead = [{
        text: 'No.',
        style: 'tableHeader'
    }, {
        text: 'Nama barang',
        style: 'tableHeader'
    }, {
        text: 'Jumlah',
        style: 'tableHeader'
    }, {
        text: 'Satuan',
        style: 'tableHeader'
    }, {
        text: 'Keterangan',
        style: 'tableHeader'
    }];

    var tbody = items.map(function(item, index) {
        return [{
            text: (index + 1).toString() || '',
            style: ['size08', 'center']
        }, {
            text: item.product.code + " - " + item.product.name,
            style: ['size08', 'left']
        }, {
            text: parseFloat(item.deliveredQuantity).toLocaleString(locale, locale.decimal),
            style: ['size08', 'center']
        }, {
            text: item.deliveredUom.unit,
            style: ['size08', 'center']
        }, {
            text: item.remark || '',
            style: ['size08', 'left']
        }];
    });

    tbody = tbody.length > 0 ? tbody : [
        [{
            text: "tidak ada barang",
            style: ['size08', 'center'],
            colSpan: 5
        }, "", "", "", ""]
    ];

    var table = [{
        table: {
            widths: ['5%', '40%', '20%', '10%', '25%'],
            headerRows: 1,
            body: [].concat([thead], tbody)
        }
    }];

    var footer = [
        '\n', {
            stack: [{
                text: `Sukoharjo, ${moment(unitReceiptNote.date).format(locale.date.format)}`,
                alignment: "right"
            }, {
                columns: [{
                    width: '35%',
                    stack: ['Mengetahui\n\n\n\n\n', '(_______________________)'],
                    style: 'center'
                }, {
                    width: '30%',
                    text: ''
                }, {
                    width: '35%',
                    stack: ['Yang Menerima\n\n\n\n\n', '(_______________________)'],
                    style: 'center'
                }]
            }
            ],
            style: ['size08']
        }
    ];

    var dd = {
        pageSize: 'A6',
        pageOrientation: 'landscape',
        pageMargins: 20,
        content: [].concat(header, line, subHeader, table, footer),
        styles: {
            size06: {
                fontSize: 6
            },
            size07: {
                fontSize: 7
            },
            size08: {
                fontSize: 8
            },
            size09: {
                fontSize: 9
            },
            size10: {
                fontSize: 10
            },
            size15: {
                fontSize: 15
            },
            bold: {
                bold: true
            },
            center: {
                alignment: 'center'
            },
            left: {
                alignment: 'left'
            },
            right: {
                alignment: 'right'
            },
            justify: {
                alignment: 'justify'
            },
            tableHeader: {
                bold: true,
                fontSize: 8,
                color: 'black',
                alignment: 'center'
            }
        }
    };

    return dd;
}<commit_msg>fix file definition<commit_after>var global = require('../../global');

module.exports = function (unitReceiptNote) {

    var items = [].concat.apply([], unitReceiptNote.items);

    var iso = "FM-PB-00-06-010";
    var number = unitReceiptNote.no;

    var locale = global.config.locale;

    var moment = require('moment');
    moment.locale(locale.name);

    var header = [{
        alignment: "center",
        text: 'BON PENERIMAAN BARANG',
        style: ['size10', 'bold']
    }, {
            columns: [
                {
                    columns: [{
                        width: '*',
                        stack: [{
                            text: 'PT DAN LIRIS',
                            style: ['size15', 'bold']
                        }, {
                                text: 'BANARAN, GROGOL, SUKOHARJO',
                                style: ['size09']
                            }]
                    }]

                },
                {
                    columns: [{
                        width: '*',
                        stack: [{
                            alignment: "right",
                            text: ' ',
                            style: ['size15', 'bold']
                        }, {
                                alignment: "right",
                                text: iso,
                                style: ['size08', 'bold']
                            }]
                    }]

                }]
        }];

    var subHeader = [{
        columns: [
            {
                width: '60%',
                stack: [{
                    columns: [{
                        width: '30%',
                        text: 'Tanggal'
                    }, {
                            width: '5%',
                            text: ':'
                        }, {
                            width: '*',
                            text: `${moment(unitReceiptNote.date).format(locale.date.format)}`
                        }]
                }, {
                        columns: [{
                            width: '30%',
                            text: 'Diterima dari'
                        }, {
                                width: '5%',
                                text: ':'
                            }, {
                                width: '*',
                                text: unitReceiptNote.supplier.name
                            }]
                    }
                ],
                style: ['size08']
            },
            {
                width: '10%',
                text: ''
            },
            {
                width: '30%',
                stack: [{
                    columns: [{
                        width: '25%',
                        text: 'Bagian'
                    }, {
                            width: '5%',
                            text: ':'
                        }, {
                            width: '*',
                            text: unitReceiptNote.unit.name
                        }]
                }, {
                        columns: [{
                            width: '25%',
                            text: 'No.'
                        }, {
                                width: '5%',
                                text: ':'
                            }, {
                                width: '*',
                                text: unitReceiptNote.no
                            }]
                    }],
                style: ['size08']
            }
        ]
    }, '\n'];

    var line = [{
        canvas: [{
            type: 'line',
            x1: 0,
            y1: 5,
            x2: 378,
            y2: 5,
            lineWidth: 0.5
        }
        ]
    }, '\n'];

    var thead = [{
        text: 'No.',
        style: 'tableHeader'
    }, {
            text: 'Nama barang',
            style: 'tableHeader'
        }, {
            text: 'Jumlah',
            style: 'tableHeader'
        }, {
            text: 'Satuan',
            style: 'tableHeader'
        }, {
            text: 'Keterangan',
            style: 'tableHeader'
        }];

    var tbody = items.map(function (item, index) {
        return [{
            text: (index + 1).toString() || '',
            style: ['size08', 'center']
        }, {
                text: item.product.code + " - " + item.product.name,
                style: ['size08', 'left']
            }, {
                text: parseFloat(item.deliveredQuantity).toLocaleString(locale, locale.decimal),
                style: ['size08', 'center']
            }, {
                text: item.deliveredUom.unit,
                style: ['size08', 'center']
            }, {
                text: item.remark || '',
                style: ['size08', 'left']
            }];
    });

    tbody = tbody.length > 0 ? tbody : [
        [{
            text: "tidak ada barang",
            style: ['size08', 'center'],
            colSpan: 5
        }, "", "", "", ""]
    ];

    var table = [{
        table: {
            widths: ['5%', '40%', '20%', '10%', '25%'],
            headerRows: 1,
            body: [].concat([thead], tbody)
        }
    }];

    var footer = [
        '\n', {
            stack: [{
                text: `Sukoharjo, ${moment(unitReceiptNote.date).format(locale.date.format)}`,
                alignment: "right"
            }, {
                    columns: [{
                        width: '35%',
                        stack: ['Mengetahui\n\n\n\n\n', '(_______________________)'],
                        style: 'center'
                    }, {
                            width: '30%',
                            text: ''
                        }, {
                            width: '35%',
                            stack: ['Yang Menerima\n\n\n\n\n', '(_______________________)'],
                            style: 'center'
                        }]
                }
            ],
            style: ['size08']
        }
    ];

    var dd = {
        pageSize: 'A6',
        pageOrientation: 'landscape',
        pageMargins: 20,
        content: [].concat(header, line, subHeader, table, footer),
        styles: {
            size06: {
                fontSize: 6
            },
            size07: {
                fontSize: 7
            },
            size08: {
                fontSize: 8
            },
            size09: {
                fontSize: 9
            },
            size10: {
                fontSize: 10
            },
            size15: {
                fontSize: 15
            },
            bold: {
                bold: true
            },
            center: {
                alignment: 'center'
            },
            left: {
                alignment: 'left'
            },
            right: {
                alignment: 'right'
            },
            justify: {
                alignment: 'justify'
            },
            tableHeader: {
                bold: true,
                fontSize: 8,
                color: 'black',
                alignment: 'center'
            }
        }
    };

    return dd;
}<|endoftext|>


<commit_before>BasicGame.Game = function(game) {
	// When a State is added to Phaser it automatically has the following
	// properties set on it, even if they already exist:
	this.game; // a reference to the currently running game
	this.add; // used to add sprites, text, groups, etc
	this.camera; // a reference to the game camera
	this.cache; // the game cache
	this.input; // the global input manager (you can access this.input.keyboard,
	// this.input.mouse, as well from it)
	this.load; // for preloading assets
	this.math; // lots of useful common math operations
	this.sound; // the sound manager - add a sound, play one, set-up markers,
	// etc
	this.stage; // the game stage
	this.time; // the clock
	this.tweens; // the tween manager
	this.world; // the game world
	this.particles; // the particle manager
	this.physics; // the physics manager
	this.rnd; // the repeatable random number generator
	// You can use any of these from any function within this State.
	// But do consider them as being 'reserved words', i.e. don't create a
	// property for your own game called "world" or you'll over-write the world
	// reference.
};
BasicGame.Game.prototype = {
	dropRate:0.2,
	catchAssist:false,
	claw : null,
	claw_length : 720,
	claw_state : 0,
	claw_speed : 5,
	claw_rope:null,
    claw_pip:null,
    claw_box:null,
	zero_point : [100,100],
	gifts : null,
	layer : null,
	sfx_win : null,
	sfx_lose : null,
	bgm : null,
	sfx_claw : [],
    giftCollisionGroup:null,
    clawCollisionGroup:null,
    tilesCollisionGroup:null,
	score_text:null,
	max_doll:5,
	score:0,
    timer:null,
    checkGifts: function(){
        if (this.gifts.children.length < this.max_doll) {
            this.spawnDoll();
        }
    },
	claw_sfx : function(index) {
		for ( var i in this.sfx_claw) {
			var sfx = this.sfx_claw[i];
			if (i == index) {
				sfx.loopFull();
			} else {
				sfx.stop();
			}
		}
	},
	click : function() {
		if (this.claw_state === 0) {
			this.claw_state = 1;
			this.claw_sfx(0);
		}
	},
	release : function() {
		if (this.claw_state === 1) {
			this.claw_state = 2;
			this.claw_sfx(1);
		}
	},
	spawnDoll: function(){
		var index = Math.round(Math.random()*9+3);
        var gift = this.gifts.create(this.game.world.centerX + Math.random() * 100 * 1.5, 0, 'sprites',index + ".png");
        gift.body.debug = false;
        gift.body.clearShapes();
        gift.body.loadPolygon('spritePhysics', index);
        gift.body.setCollisionGroup(this.giftCollisionGroup);
        gift.body.collides([ this.giftCollisionGroup, this.clawCollisionGroup,
            this.tilesCollisionGroup ]);
        //gift.body.velocity.x = this.claw_speed * 20;
    },
	closeClaw : function(isClose) {
		this.claw.body.clearShapes();
		if (isClose) {
			this.claw.loadTexture('claw_closed');
			this.claw.body.loadPolygon('physicsData', "claw_closed");
		} else {
			this.claw.loadTexture('claw');
			this.claw.body.loadPolygon('physicsData', "claw_open");
		}
        this.claw.body.setCollisionGroup(this.clawCollisionGroup);
        this.claw.body.collides([ this.tilesCollisionGroup, this.giftCollisionGroup ],
            this.clawHitHandler, this);
	},
	clawHitHandler : function(body1, body2,hit) {
        var dx = Math.abs(body1.x - body2.x);
        var dy = Math.abs(body1.y - body2.y);
        if(hit.boundingRadius >= 1.8){
            console.log(hit.boundingRadius);
            this.claw_state = 3;
            this.closeClaw(true);
        }
		if (this.claw_state == 2 && this.catchAssist) {
			//console.log(JSON.stringify([ dx, dy ]));
			// var constraint =
			// this.game.physics.p2.createDistanceConstraint(body1, body2, 50);
			if (dx <= 15 && dy < 50) {
				this.closeClaw(true);
				this.claw_sfx(2);
				this.hitGift = body2;
				body2.static = true;
				body2.immovable = true;
				body2.setZeroVelocity();
				this.claw_state = 3;
			}
		}
	},
	create : function() {
		this.game.stage.backgroundColor = '#82abba';
		this.game.physics.startSystem(Phaser.Physics.P2JS);
		this.game.physics.p2.gravity.y = 500;
		this.game.physics.p2.setImpactEvents(true);
		this.score_text = this.game.add.text(this.game.world.centerX, this.game.world.centerY, " 分数 : " + this.score, {
            font: "65px Arial",
            fill: "#ff0044",
            align: "center"
        });
        this.score_text.anchor.setTo(0.5, 0.5);

		this.giftCollisionGroup = this.game.physics.p2.createCollisionGroup();
        this.clawCollisionGroup = this.game.physics.p2.createCollisionGroup();
        this.tilesCollisionGroup = this.game.physics.p2.createCollisionGroup();
		var map = this.game.add.tilemap('level1');
		var x = 350;
		var y = 350;

		this.bgm = this.game.add.audio('bgm');
		this.bgm.loopFull();
		this.sfx_claw[0] = this.game.add.audio('sfx_claw_0');
		this.sfx_claw[1] = this.game.add.audio('sfx_claw_1');
		this.sfx_claw[2] = this.game.add.audio('sfx_claw_2');
		map.addTilesetImage('world');
		this.sfx_lose = this.game.add.audio('lose');
		this.sfx_win = this.game.add.audio('win');
		this.layer = map.createLayer('Tile Layer 1');
		this.layer.resizeWorld();
		map.setCollisionBetween(1, 99);

		var tileObjects = this.game.physics.p2.convertTilemap(map, this.layer);
		for ( var i in tileObjects) {
			tileObjects[i].setCollisionGroup(this.tilesCollisionGroup);
			tileObjects[i].collides([ this.giftCollisionGroup, this.clawCollisionGroup ]);
		}
		this.claw_length = this.layer.layer.heightInPixels - 140 - 35;
		console.log(this.claw_length);
		this.layer.debug = false;
		this.claw = this.game.add.sprite(this.zero_point[0], this.zero_point[1],
				'claw');
		this.game.physics.p2.enable(this.claw, false);
		this.claw.body.static = true;
		this.claw.body.immovable = true;
		this.closeClaw(false);
        this.claw_rope = this.game.add.sprite(this.zero_point[0] - 4,this.zero_point[1] - this.claw.height / 2 -
3,'claw_rope');
		this.claw.body.collideWorldBounds = true;
		this.claw_pip = this.game.add.sprite(0,this.claw_rope.y-3,'claw_pip');
        this.claw_pip.width = this.game.width;
		this.claw_box = this.game.add.sprite(this.claw.body.x,this.claw_pip.y,'claw_box');
		this.gifts = this.game.add.group();
		this.gifts.enableBody = true;
		this.gifts.physicsBodyType = Phaser.Physics.P2JS;
		// attach pointer events
		this.game.input.onDown.add(this.click, this);
		this.game.input.onUp.add(this.release, this);
		this.game.physics.p2.updateBoundsCollisionGroup();

        this.timer = this.game.time.create(false);
        this.timer.loop(1000, this.checkGifts, this);
        this.timer.start();
        //var button = this.game.add.button(this.game.world.centerX, this.game.world.height - 90, 'btn_play_up', this.actionOnClick, this, 2, 1, 0);
		//button.onInputDown.add(this.click,this);
        //button.onInputUp.add(this.release, this);
		console.log("starting play state");
	},
    actionOnClick:function(){

	},
	update : function() {
		this.claw.body.setZeroVelocity();
		for ( var i in this.gifts.children) {
			var gift = this.gifts.children[i];
			if (gift.body.y >= this.game.world.height - 70) {
				this.sfx_win.play();
				gift.destroy();
				this.score++;
				this.score_text.setText(" 分数 : " + this.score);
			}
		}
		if (this.claw_state == 1) {
			if(this.claw.body.x + this.claw.width / 2 >= this.game.world.width){
                this.claw_state = 4;
			}else{
                this.claw.body.x += this.claw_speed;
                this.claw_rope.x += this.claw_speed;
			}
		} else if (this.claw_state == 2) {
			this.claw.body.y += this.claw_speed;
            this.claw_rope.height += this.claw_speed;
			if (this.claw.body.y >= this.claw_length) {
				this.closeClaw(true);
				this.claw_state = 3;
				this.claw_sfx(2);
			}
		} else if (this.claw_state == 3) {
			this.claw.body.y -= this.claw_speed;
            this.claw_rope.height -= this.claw_speed;
			if (this.hitGift) {
				this.hitGift.y -= this.claw_speed;
			}
			if (this.claw.body.y <= this.zero_point[1]) {
				this.claw.body.y = this.zero_point[1];
				this.claw_state = 4;
			}
		} else if (this.claw_state == 4 || this.claw_state == 5) {
			this.claw.body.x -= this.claw_speed;
            this.claw_rope.x -= this.claw_speed;
			if (this.hitGift) {
				this.hitGift.x -= this.claw_speed;
			}
			if (this.claw.body.x <= this.zero_point[0]) {
				if(this.claw_state == 5){
					this.claw_state = 1;
				}else{
                    this.claw.body.x = this.zero_point[0];
                    this.claw_state = 0;
                    this.claw_sfx(-1);
                    this.closeClaw(false);
                    if (this.hitGift) {
                        this.hitGift.static = false;
                        this.hitGift = null;
                    }
				}
			}
		}
		if (this.hitGift && this.game.time.now % 30 == 0) {
			var seed = Math.random();
			// console.log("SEED:" + seed);
			if (seed <= this.dropRate && seed > 0) {
				this.hitGift.static = false;
				this.hitGift.immovable = false;
                this.claw.body.clearShapes();
				if(this.claw_state == 4){
					this.hitGift.velocity.x = -this.claw_speed * 20;
				}
				this.hitGift = null;
				this.sfx_lose.play();
			}
		}else if((this.claw_state == 3 || this.claw_state == 4) && this.game.time.now % 30 == 0){
            var seed = Math.random();
            if (seed <= this.dropRate && seed > 0) {
                this.claw.body.clearShapes();
                console.log("Drop It!");
            }
		}
        this.claw_box.x = this.claw.body.x - this.claw_box.width / 2;
        this.claw_box.y = this.claw_pip.y - this.claw_pip.height / 2;
	},
	quitGame : function(pointer) {
		// Here you should destroy anything you no longer need.
		// Stop music, delete sprites, purge caches, free resources, all that
		// good stuff.
		// Then let's go back to the main menu.
		this.state.start('MainMenu');
	}
};

<commit_msg>增加硬币概念，每2分获得一个硬币。增加防陷入地面检测。关闭随机掉落。<commit_after>BasicGame.Game = function(game) {
	// When a State is added to Phaser it automatically has the following
	// properties set on it, even if they already exist:
	this.game; // a reference to the currently running game
	this.add; // used to add sprites, text, groups, etc
	this.camera; // a reference to the game camera
	this.cache; // the game cache
	this.input; // the global input manager (you can access this.input.keyboard,
	// this.input.mouse, as well from it)
	this.load; // for preloading assets
	this.math; // lots of useful common math operations
	this.sound; // the sound manager - add a sound, play one, set-up markers,
	// etc
	this.stage; // the game stage
	this.time; // the clock
	this.tweens; // the tween manager
	this.world; // the game world
	this.particles; // the particle manager
	this.physics; // the physics manager
	this.rnd; // the repeatable random number generator
	// You can use any of these from any function within this State.
	// But do consider them as being 'reserved words', i.e. don't create a
	// property for your own game called "world" or you'll over-write the world
	// reference.
};
BasicGame.Game.prototype = {
	dropRate:0.2,
	catchAssist:false,
	claw : null,
	claw_length : 720,
	claw_state : 0,
	claw_speed : 5,
	claw_rope:null,
    claw_pip:null,
    claw_box:null,
	zero_point : [100,100],
	gifts : null,
	layer : null,
	sfx_win : null,
	sfx_lose : null,
	bgm : null,
	sfx_claw : [],
    giftCollisionGroup:null,
    clawCollisionGroup:null,
    tilesCollisionGroup:null,
	score_text:null,
	max_doll:5,
	score:0,
    coin:0,
    timer:null,
    tileObjects:null,
    checkGifts: function(){
        if (this.gifts.children.length < this.max_doll) {
            this.spawnDoll();
        }
    },
	claw_sfx : function(index) {
		for ( var i in this.sfx_claw) {
			var sfx = this.sfx_claw[i];
			if (i == index) {
				sfx.loopFull();
			} else {
				sfx.stop();
			}
		}
	},
	click : function() {
		if (this.claw_state === 0 && this.gifts.children.length == this.max_doll) {
			if(this.coin > 0){
				this.coin--;
                this.claw_state = 1;
                this.claw_sfx(0);
			}
		}
	},
	release : function() {
		if (this.claw_state === 1) {
			this.claw_state = 2;
			this.claw_sfx(1);
		}
	},
	spawnDoll: function(){
		var index = Math.round(Math.random()*9+3);
        var gift = this.gifts.create(this.game.world.centerX + Math.random() * 100 * 1.5, 0, 'sprites',index + ".png");
        gift.body.debug = false;
        gift.body.clearShapes();
        gift.body.loadPolygon('spritePhysics', index);
        gift.body.setCollisionGroup(this.giftCollisionGroup);
        gift.body.collides([ this.giftCollisionGroup, this.clawCollisionGroup,
            this.tilesCollisionGroup ]);
        //gift.body.velocity.x = this.claw_speed * 20;
    },
	closeClaw : function(isClose) {
		this.claw.body.clearShapes();
		if (isClose) {
			this.claw.loadTexture('claw_closed');
			this.claw.body.loadPolygon('physicsData', "claw_closed");
		} else {
			this.claw.loadTexture('claw');
			this.claw.body.loadPolygon('physicsData', "claw_open");
		}
        this.claw.body.setCollisionGroup(this.clawCollisionGroup);
        this.claw.body.collides([ this.tilesCollisionGroup, this.giftCollisionGroup ],
            this.clawHitHandler, this);
	},
	clawHitHandler : function(body1, body2,hit) {
        var dx = Math.abs(body1.x - body2.x);
        var dy = Math.abs(body1.y - body2.y);
        if(hit.boundingRadius >= 1.8){
            console.log(hit.boundingRadius);
            this.claw_state = 3;
            this.closeClaw(true);
        }
		if (this.claw_state == 2 && this.catchAssist) {
			//console.log(JSON.stringify([ dx, dy ]));
			// var constraint =
			// this.game.physics.p2.createDistanceConstraint(body1, body2, 50);
			if (dx <= 15 && dy < 50) {
				this.closeClaw(true);
				this.claw_sfx(2);
				this.hitGift = body2;
				body2.static = true;
				body2.immovable = true;
				body2.setZeroVelocity();
				this.claw_state = 3;
			}
		}
	},
	checkOverlap:function(){
		var tiles = this.layer.getTiles(0,0,this.game.world.width,this.game.world.height);
        for(var i in tiles){
        	if(tiles[i].index > -1){
                for(var j in this.gifts.children) {
                    var sprite = this.gifts.children[j];
                    var boundsA = new Phaser.Rectangle(sprite.centerX,sprite.centerY,sprite.width,sprite.height);
                    var tile = tiles[i];
                    var boundsB = new Phaser.Rectangle(tile.worldX,tile.worldY,tile.width,tile.height);

                    var overlap = Phaser.Rectangle.intersects(boundsA, boundsB);
                    if(overlap){
                    	var t1 = (boundsA.y - boundsB.y) + sprite.height / 2;
                    	if(t1 >= sprite.height / 2){
                            console.log(t1);
                            sprite.body.y -= sprite.height / 2;
                            //sprite.body.velocity.y = -1000;
						}
                    }
                }
			}
        }
		return false;
	},
	create : function() {
		this.game.stage.backgroundColor = '#82abba';
		this.game.physics.startSystem(Phaser.Physics.P2JS);
		this.game.physics.p2.gravity.y = 500;
		this.game.physics.p2.setImpactEvents(true);
		this.score_text = this.game.add.text(this.game.world.centerX, this.game.world.centerY, " 分数 : " + this.score, {
            font: "65px Arial",
            fill: "#ff0044",
            align: "center"
        });
        this.score_text.anchor.setTo(0.5, 0.5);

		this.giftCollisionGroup = this.game.physics.p2.createCollisionGroup();
        this.clawCollisionGroup = this.game.physics.p2.createCollisionGroup();
        this.tilesCollisionGroup = this.game.physics.p2.createCollisionGroup();
		var map = this.game.add.tilemap('level1');
		var x = 350;
		var y = 350;

		this.bgm = this.game.add.audio('bgm');
		this.bgm.loopFull();
		this.sfx_claw[0] = this.game.add.audio('sfx_claw_0');
		this.sfx_claw[1] = this.game.add.audio('sfx_claw_1');
		this.sfx_claw[2] = this.game.add.audio('sfx_claw_2');
		map.addTilesetImage('world');
		this.sfx_lose = this.game.add.audio('lose');
		this.sfx_win = this.game.add.audio('win');
		this.layer = map.createLayer('Tile Layer 1');
		this.layer.resizeWorld();
		map.setCollisionBetween(1, 99);

		this.tileObjects = this.game.physics.p2.convertTilemap(map, this.layer);
		for ( var i in this.tileObjects) {
            this.tileObjects[i].setCollisionGroup(this.tilesCollisionGroup);
            this.tileObjects[i].collides([ this.giftCollisionGroup, this.clawCollisionGroup ]);
		}
		this.claw_length = this.layer.layer.heightInPixels - 140 - 35;
		console.log(this.claw_length);
		this.layer.debug = false;
		this.claw = this.game.add.sprite(this.zero_point[0], this.zero_point[1],
				'claw');
		this.game.physics.p2.enable(this.claw, false);
		this.claw.body.static = true;
		this.claw.body.immovable = true;
		this.closeClaw(false);
        this.claw_rope = this.game.add.sprite(this.zero_point[0] - 4,this.zero_point[1] - this.claw.height / 2 -
3,'claw_rope');
		this.claw.body.collideWorldBounds = true;
		this.claw_pip = this.game.add.sprite(0,this.claw_rope.y-3,'claw_pip');
        this.claw_pip.width = this.game.width;
		this.claw_box = this.game.add.sprite(this.claw.body.x,this.claw_pip.y,'claw_box');
		this.gifts = this.game.add.group();
		this.gifts.enableBody = true;
		this.gifts.physicsBodyType = Phaser.Physics.P2JS;
		// attach pointer events
		this.game.input.onDown.add(this.click, this);
		this.game.input.onUp.add(this.release, this);
		this.game.physics.p2.updateBoundsCollisionGroup();

        this.timer = this.game.time.create(false);
        this.timer.loop(1000, this.checkGifts, this);
        this.timer.start();

        var overlapTimer = this.game.time.create(false);
        overlapTimer.loop(1000,this.checkOverlap,this);
        overlapTimer.start();
		this.coin = 50;
		console.log("starting play state");
	},
    updateUI:function(){
        this.score_text.setText("硬币:" + this.coin + "\n分数:" + this.score);
	},
    actionOnClick:function(){

	},
	update : function() {
		this.claw.body.setZeroVelocity();
		for ( var i in this.gifts.children) {
			var gift = this.gifts.children[i];
			if (gift.body.y >= this.game.world.height - 70) {
				this.sfx_win.play();
				gift.destroy();
				this.score++;
				if(this.score % 2 == 0){
					this.coin++;
				}
			}
		}
		if (this.claw_state == 1) {
			if(this.claw.body.x + this.claw.width / 2 >= this.game.world.width){
                this.claw_state = 4;
                this.coin++;
			}else{
                this.claw.body.x += this.claw_speed;
                this.claw_rope.x += this.claw_speed;
			}
		} else if (this.claw_state == 2) {
			this.claw.body.y += this.claw_speed;
            this.claw_rope.height += this.claw_speed;
			if (this.claw.body.y >= this.claw_length) {
				this.closeClaw(true);
				this.claw_state = 3;
				this.claw_sfx(2);
			}
		} else if (this.claw_state == 3) {
			this.claw.body.y -= this.claw_speed;
            this.claw_rope.height -= this.claw_speed;
			if (this.hitGift) {
				this.hitGift.y -= this.claw_speed;
			}
			if (this.claw.body.y <= this.zero_point[1]) {
				this.claw.body.y = this.zero_point[1];
				this.claw_state = 4;
			}
		} else if (this.claw_state == 4 || this.claw_state == 5) {
			this.claw.body.x -= this.claw_speed;
            this.claw_rope.x -= this.claw_speed;
			if (this.hitGift) {
				this.hitGift.x -= this.claw_speed;
			}
			if (this.claw.body.x <= this.zero_point[0]) {
				if(this.claw_state == 5){
					this.claw_state = 1;
				}else{
                    this.claw.body.x = this.zero_point[0];
                    this.claw_state = 0;
                    this.claw_sfx(-1);
                    this.closeClaw(false);
                    if (this.hitGift) {
                        this.hitGift.static = false;
                        this.hitGift = null;
                    }
				}
			}
		}
		if (this.hitGift && this.game.time.now % 30 == 0) {
			var seed = Math.random();
			// console.log("SEED:" + seed);
			if (seed <= this.dropRate && seed > 0) {
				this.hitGift.static = false;
				this.hitGift.immovable = false;
                this.claw.body.clearShapes();
				if(this.claw_state == 4){
					this.hitGift.velocity.x = -this.claw_speed * 20;
				}
				this.hitGift = null;
				this.sfx_lose.play();
			}
		}else if((this.claw_state == 3 || this.claw_state == 4) && this.game.time.now % 30 == 0){
            var seed = Math.random();
            if (seed <= this.dropRate && seed > 0) {
                //this.claw.body.clearShapes();
            }
		}
        this.claw_box.x = this.claw.body.x - this.claw_box.width / 2;
        this.claw_box.y = this.claw_pip.y - this.claw_pip.height / 2;

        this.updateUI();
	},
	quitGame : function(pointer) {
		// Here you should destroy anything you no longer need.
		// Stop music, delete sprites, purge caches, free resources, all that
		// good stuff.
		// Then let's go back to the main menu.
		this.state.start('MainMenu');
	}
};

<|endoftext|>


<commit_before>/**
 * This overrides existing contact code, and builds proper contacts
 * @constructor
 */

var Contact = function() {
  this.givenNames = [];
  this.familyName = "";
  this.phones = [];
  this.category = "";
  this.companyName = "";
  this.isCompany = false;
  this.email = [];
  this.addresses = [];
  this.uri = [];
  this.prefix = "";
  this.jobTitle = "";
  this.birthday = "";
  this.phoneticName = "";
}

var Address = function() {
  this.street = "";
  this.postalCode = "";
  this.city = "";
  this.region = "";
  this.countryCode = "";
  this.country = "";
  this.building = "";
  this.floor = "";
  this.accessCode = "";
}

var PhoneNumber = function() {
  this.number = "";
  this.type = "";
}

var Email = function() {
  this.address = "";
  this.type = "";
}

var ImHandle = function()
{
  this.address = "";
  this.type = "";
  this.network = "";
}

var Uri = function() {
  this.addr = "";
  this.rel = "";
}

var AddressBook = function() {
  this.name = "";
  this.resultSet = [];
}

AddressBook.prototype.addContact = function(newContact, win, fail)
{

}

AddressBook.prototype.removeContact = function(target, win, fail)
{

}

AddressBook.prototype.findContacts = function(filter,win, fail)
{
}

PhoneGap.addConstructor(function() {
  if (typeof navigator.AddressBook == "undefined")
    navigator.AddressBook = new AddressBook(); });
AddressBook.prototype.addContact = function(newContact, win, fail)
{

}

AddressBook.prototype.removeContact = function(target, win, fail)
{

}

AddressBook.prototype.findContacts = function(filter,win, fail)
{
  this.win = win;
  this.fail = fail;
  // Zero out the result set for the query
  this.resultSet = [];
  var name = "";
  var phone = "";
  var email = "";

  if (filter.givenName)
    name = filter.givenName;
  if (filter.familyName)
    name += filter.familyName;
  if (filter.phone)
    var phone = filter.phone;
  if (filter.email)
    var email = filter.email;
  ContactHook.search(name, phone, email);
}

AddressBook.prototype.droidFoundContact = function(name, npa, email)
{
  names = name.split(' ');
  personContact = new Contact();
  personContact.givenNames.push(names[0]);
  // This is technically wrong, but we can't distinguish right now
  if(names.length > 1)
  {
    personContact.familyName = name[name.length -1];
  }

  telNumber = new PhoneNumber();
  telNumber.number = npa;
  personContact.phones.push(telNumber);

  email_addr = new Email();
  email_addr.address = email;

  personContact.email.push(email_addr);

  this.resultSet.push(personContact);

}

AddressBook.prototype.droidDoneContacts = function()
{
  if(resultSet.length > 0)
    this.win(resultSet);
  else
    this.fail();
}
<commit_msg>Removing AddressBook<commit_after><|endoftext|>


<commit_before>// Ionic Starter App

// angular.module is a global place for creating, registering and retrieving Angular modules
// 'starter' is the name of this angular module example (also set in a <body> attribute in index.html)
// the 2nd parameter is an array of 'requires'
// 'starter.services' is found in services.js
// 'starter.controllers' is found in controllers.js
angular.module('wuw', ['ionic', 'wuw.controllers', 'wuw.services', 'angular.filter'])

.run(function($ionicPlatform, Settings) {
  $ionicPlatform.ready(function() {
    // predifined settings
    if (typeof Settings.getSetting('apiUrl') === 'undefined') {
        Settings.setSetting('apiUrl', 'http://localhost:8088/api/v0')
    }

    // Hide the accessory bar by default (remove this to show the accessory bar above the keyboard
    // for form inputs)
    if (window.cordova && window.cordova.plugins.Keyboard) {
      cordova.plugins.Keyboard.hideKeyboardAccessoryBar(true);
    }
    if (window.StatusBar) {
      // org.apache.cordova.statusbar required
      StatusBar.styleDefault();
    }
  });
})

.filter('rawHtml', ['$sce', function($sce){
  return function(val) {
    return $sce.trustAsHtml(val);
  };
}])

.config(function($stateProvider, $urlRouterProvider) {

    // Ionic uses AngularUI Router which uses the concept of states
    // Learn more here: https://github.com/angular-ui/ui-router
    // Set up the various states which the app can be in.
    // Each state's controller can be found in controllers.js

    $stateProvider
    // setup an abstract state for the tabs directive
    .state('tab', {
        url: "/tab",
        abstract: true,
        templateUrl: "templates/tabs.html"
    })

    // Each tab has its own nav history stack:

    .state('tab.home', {
        url: '/home',
        views: {
            'tab-home': {
            templateUrl: 'templates/tab-home.html',
            controller: 'HomeCtrl'
        }
      }
    })

    .state('tab.deadlines', {
        url: '/deadlines',
        views: {
            'tab-deadlines': {
            templateUrl: 'templates/tab-deadlines.html',
            controller: 'DeadlinesCtrl'
        }
      }
    })
    .state('tab.deadline-detail', {
        url: '/deadlines/:deadlineId',
        views: {
            'tab-deadlines': {
            templateUrl: 'templates/tab-deadline-detail.html',
            controller: 'DeadlinesDetailCtrl'
        }
      }
    })
    .state('tab.deadline-create', {
        url: '/createDeadline',
        views: {
            'tab-deadlines': {
            templateUrl: 'templates/tab-create-deadline.html',
            controller: 'DeadlinesCreateCtrl'
        }
      }
    })

    .state('tab.lectures', {
        url: '/lectures',
        views: {
            'tab-lectures': {
            templateUrl: 'templates/tab-lectures.html',
            controller: 'LecturesCtrl'
        }
      }
    })
    .state('tab.lectures-detail', {
        url: '/lectures/:lectureId',
        views: {
            'tab-lectures': {
            templateUrl: 'templates/tab-lectures-detail.html',
            controller: 'LecturesDetailCtrl'
        }
      }
    })

    .state('tab.settings', {
        url: '/settings',
        views: {
            'tab-settings': {
            templateUrl: 'templates/tab-settings.html',
            controller: 'SettingsCtrl'
        }
      }
    })
    // if none of the above states are matched, use this as the fallback
    $urlRouterProvider.otherwise('/tab/home');
});
<commit_msg>change default sever url<commit_after>// Ionic Starter App

// angular.module is a global place for creating, registering and retrieving Angular modules
// 'starter' is the name of this angular module example (also set in a <body> attribute in index.html)
// the 2nd parameter is an array of 'requires'
// 'starter.services' is found in services.js
// 'starter.controllers' is found in controllers.js
angular.module('wuw', ['ionic', 'wuw.controllers', 'wuw.services', 'angular.filter'])

.run(function($ionicPlatform, Settings) {
  $ionicPlatform.ready(function() {
    // predifined settings
    if (typeof Settings.getSetting('apiUrl') === 'undefined') {
        Settings.setSetting('apiUrl', 'http://wuw.benleb.de:8088/api/v0')
    }

    // Hide the accessory bar by default (remove this to show the accessory bar above the keyboard
    // for form inputs)
    if (window.cordova && window.cordova.plugins.Keyboard) {
      cordova.plugins.Keyboard.hideKeyboardAccessoryBar(true);
    }
    if (window.StatusBar) {
      // org.apache.cordova.statusbar required
      StatusBar.styleDefault();
    }
  });
})

.filter('rawHtml', ['$sce', function($sce){
  return function(val) {
    return $sce.trustAsHtml(val);
  };
}])

.config(function($stateProvider, $urlRouterProvider) {

    // Ionic uses AngularUI Router which uses the concept of states
    // Learn more here: https://github.com/angular-ui/ui-router
    // Set up the various states which the app can be in.
    // Each state's controller can be found in controllers.js

    $stateProvider
    // setup an abstract state for the tabs directive
    .state('tab', {
        url: "/tab",
        abstract: true,
        templateUrl: "templates/tabs.html"
    })

    // Each tab has its own nav history stack:

    .state('tab.home', {
        url: '/home',
        views: {
            'tab-home': {
            templateUrl: 'templates/tab-home.html',
            controller: 'HomeCtrl'
        }
      }
    })

    .state('tab.deadlines', {
        url: '/deadlines',
        views: {
            'tab-deadlines': {
            templateUrl: 'templates/tab-deadlines.html',
            controller: 'DeadlinesCtrl'
        }
      }
    })
    .state('tab.deadline-detail', {
        url: '/deadlines/:deadlineId',
        views: {
            'tab-deadlines': {
            templateUrl: 'templates/tab-deadline-detail.html',
            controller: 'DeadlinesDetailCtrl'
        }
      }
    })
    .state('tab.deadline-create', {
        url: '/createDeadline',
        views: {
            'tab-deadlines': {
            templateUrl: 'templates/tab-create-deadline.html',
            controller: 'DeadlinesCreateCtrl'
        }
      }
    })

    .state('tab.lectures', {
        url: '/lectures',
        views: {
            'tab-lectures': {
            templateUrl: 'templates/tab-lectures.html',
            controller: 'LecturesCtrl'
        }
      }
    })
    .state('tab.lectures-detail', {
        url: '/lectures/:lectureId',
        views: {
            'tab-lectures': {
            templateUrl: 'templates/tab-lectures-detail.html',
            controller: 'LecturesDetailCtrl'
        }
      }
    })

    .state('tab.settings', {
        url: '/settings',
        views: {
            'tab-settings': {
            templateUrl: 'templates/tab-settings.html',
            controller: 'SettingsCtrl'
        }
      }
    })
    // if none of the above states are matched, use this as the fallback
    $urlRouterProvider.otherwise('/tab/home');
});
<|endoftext|>


<commit_before>// Tempest jQuery Templating Plugin
// ================================
//
// Copyright (c) 2009 Nick Fitzgerald - http://fitzgeraldnick.com/
//
// Permission is hereby granted, free of charge, to any person obtaining a copy
// of this software and associated documentation files (the "Software"), to deal
// in the Software without restriction, including without limitation the rights
// to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
// copies of the Software, and to permit persons to whom the Software is
// furnished to do so, subject to the following conditions:
//
// The above copyright notice and this permission notice shall be included in
// all copies or substantial portions of the Software.
//
// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
// IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
// FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
// AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
// LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
// OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
// THE SOFTWARE.

"use strict";
(function ($) {
    // PRIVATE VARS AND FUNCTIONS
    var templateCache = {},

        // hack to get the HTML of a jquery object as a string
        jQueryToString = function (jq) {
            return $(document.createElement("div")).append(jq).html();
        },

        // return an array of all the stored templates and the key to
        // access each of them
        storedTemplates = function () {
            var cache = [];
            $.each(templateCache, function (key, val) {
                cache.push([ key, val ]);
            });
            return cache;
        },

        // determine if the string is a key to a stored template or a
        // one-time-use template
        chooseTemplate = function (str) {
            if (templateCache[str] !== undefined) {
                return templateCache[str];
            } else {
                return str;
            }
        },

        // return true if an object is an array
        isArray = function (objToTest) {
            return Object.prototype
                         .toString
                         .apply(objToTest) === "[object Array]";
        },

        // call a rendering function on arrays of objects or just single
        // object seemlessly
        renderEach = function (data, f) {
            if (isArray(data)) {
                return $.each(data, f);
            } else {
                return f(0, data);
            }
        },

        // Clean the passed value the best we can
        cleanVal = function (val) {
            if (val instanceof $) {
                return jQueryToString(val);
            } else if (!isArray(val) && typeof(val) === "[object Object]") {
                if (typeof(val.toHTML) === "function") {
                    return cleanVal(val.toHTML());
                } else {
                    return val.toString();
                }
            } else {
                return val;
            }
        },

        // traverse a path of an obj from a string representation,
        // ie "object.child.attr"
        getValFromObj = function (str, obj) {
            var path = str.split("."),
                val = obj[path[0]];
                i;
            for (i = 1; i < path.length; i++) {
                // filter for undefined values
                if (val !== undefined) {
                    val = val[path[i]];
                } else {
                    return "";
                }
            }

            // make sure the last peice did not end up undefined
            val = val || "";
            return cleanVal(val);
        },

        // return the template rendered with the given object(s) as jQuery
        renderToJQ = function (str, objects) {
            var template = chooseTemplate(str),
                lines = [];

            renderEach(objects, function (i, obj) {
                lines.push(template.replace(/\{\{[ ]?[\w\-\.]+?[ ]?\}\}/g,
                    function (match) {
                        var attr = match.replace(/\{\{[ ]?/, "")
                                        .replace(/[ ]?\}\}/, ""),
                            val = obj[attr] || "";
                        if (val === "" && attr.search(/\./) !== -1) {
                            return getValFromObj(attr, obj);
                        }
                        return cleanVal(val);
                    }
                ));
            });

            // return jQuery objects
            return $(lines.join(""));
        };

    // EXTEND JQUERY OBJECT
    $.extend({
        tempest: function () {
            var args = arguments;

            if (args.length === 0) {

                return storedTemplates();

            } else if (args.length === 2 &&
                       typeof(args[0]) === "string" &&
                       typeof(args[1]) === "object") {

                return renderToJQ(args[0], args[1]);

            } else if (args.length === 1 && typeof(args[0]) === "string") {

                // template getter
                return templateCache[args[0]];

            } else if (args.length === 2 &&
                       typeof(args[0]) === "string" &&
                       typeof(args[1]) === "string") {

                // template setter
                templateCache[args[0]] = args[1].replace(/^\s+/g, "")
                                                .replace(/\s+$/g, "")
                                                .replace(/[\n\r]+/g, "");
                return templateCache[args[0]];

            } else {

                // raise an exception becuase no use case matched the arguments
                throw ({
                    name: "Input Error",
                    message: "jQuery.tempest can't handle the given arguments."
                });

            }
        }
    });

    // GET ALL TEXTAREA TEMPLATES ON READY
    $(document).ready(function () {
        $("textarea.tempest-template").each(function (obj) {
            templateCache[$(this).attr('title')] = $(this).val()
                                                          .replace(/^\s+/g, "")
                                                          .replace(/\s+$/g, "")
                                                          .replace(/[\n\r]+/g, "");
            $(this).remove();
        });
    });
}(jQuery));
<commit_msg>Adding JSLint options to the top and fixing a tiny bug that JSLint caught.<commit_after>// Tempest jQuery Templating Plugin
// ================================
//
// Copyright (c) 2009 Nick Fitzgerald - http://fitzgeraldnick.com/
//
// Permission is hereby granted, free of charge, to any person obtaining a copy
// of this software and associated documentation files (the "Software"), to deal
// in the Software without restriction, including without limitation the rights
// to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
// copies of the Software, and to permit persons to whom the Software is
// furnished to do so, subject to the following conditions:
//
// The above copyright notice and this permission notice shall be included in
// all copies or substantial portions of the Software.
//
// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
// IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
// FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
// AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
// LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
// OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
// THE SOFTWARE.

// JSLint
/*jslint white: true, onevar: true, browser: true, undef: true, nomen: true, eqeqeq: true, bitwise: true, regexp: true, strict: true, newcap: true, immed: true */
"use strict";

(function ($) {
    // PRIVATE VARS AND FUNCTIONS
    var templateCache = {},

        // hack to get the HTML of a jquery object as a string
        jQueryToString = function (jq) {
            return $(document.createElement("div")).append(jq).html();
        },

        // return an array of all the stored templates and the key to
        // access each of them
        storedTemplates = function () {
            var cache = [];
            $.each(templateCache, function (key, val) {
                cache.push([ key, val ]);
            });
            return cache;
        },

        // determine if the string is a key to a stored template or a
        // one-time-use template
        chooseTemplate = function (str) {
            if (templateCache[str] !== undefined) {
                return templateCache[str];
            } else {
                return str;
            }
        },

        // return true if an object is an array
        isArray = function (objToTest) {
            return Object.prototype
                         .toString
                         .apply(objToTest) === "[object Array]";
        },

        // call a rendering function on arrays of objects or just single
        // object seemlessly
        renderEach = function (data, f) {
            if (isArray(data)) {
                return $.each(data, f);
            } else {
                return f(0, data);
            }
        },

        // Clean the passed value the best we can
        cleanVal = function (val) {
            if (val instanceof $) {
                return jQueryToString(val);
            } else if (!isArray(val) && typeof(val) === "[object Object]") {
                if (typeof(val.toHTML) === "function") {
                    return cleanVal(val.toHTML());
                } else {
                    return val.toString();
                }
            } else {
                return val;
            }
        },

        // traverse a path of an obj from a string representation,
        // ie "object.child.attr"
        getValFromObj = function (str, obj) {
            var path = str.split("."),
                val = obj[path[0]],
                i;
            for (i = 1; i < path.length; i++) {
                // filter for undefined values
                if (val !== undefined) {
                    val = val[path[i]];
                } else {
                    return "";
                }
            }

            // make sure the last peice did not end up undefined
            val = val || "";
            return cleanVal(val);
        },

        // return the template rendered with the given object(s) as jQuery
        renderToJQ = function (str, objects) {
            var template = chooseTemplate(str),
                lines = [];

            renderEach(objects, function (i, obj) {
                lines.push(template.replace(/\{\{[ ]?[\w\-\.]+?[ ]?\}\}/g,
                    function (match) {
                        var attr = match.replace(/\{\{[ ]?/, "")
                                        .replace(/[ ]?\}\}/, ""),
                            val = obj[attr] || "";
                        if (val === "" && attr.search(/\./) !== -1) {
                            return getValFromObj(attr, obj);
                        }
                        return cleanVal(val);
                    }
                ));
            });

            // return jQuery objects
            return $(lines.join(""));
        };

    // EXTEND JQUERY OBJECT
    $.extend({
        tempest: function () {
            var args = arguments;

            if (args.length === 0) {

                return storedTemplates();

            } else if (args.length === 2 &&
                       typeof(args[0]) === "string" &&
                       typeof(args[1]) === "object") {

                return renderToJQ(args[0], args[1]);

            } else if (args.length === 1 && typeof(args[0]) === "string") {

                // template getter
                return templateCache[args[0]];

            } else if (args.length === 2 &&
                       typeof(args[0]) === "string" &&
                       typeof(args[1]) === "string") {

                // template setter
                templateCache[args[0]] = args[1].replace(/^\s+/g, "")
                                                .replace(/\s+$/g, "")
                                                .replace(/[\n\r]+/g, "");
                return templateCache[args[0]];

            } else {

                // raise an exception becuase no use case matched the arguments
                throw ({
                    name: "Input Error",
                    message: "jQuery.tempest can't handle the given arguments."
                });

            }
        }
    });

    // GET ALL TEXTAREA TEMPLATES ON READY
    $(document).ready(function () {
        $("textarea.tempest-template").each(function (obj) {
            templateCache[$(this).attr('title')] = $(this).val()
                                                          .replace(/^\s+/g, "")
                                                          .replace(/\s+$/g, "")
                                                          .replace(/[\n\r]+/g, "");
            $(this).remove();
        });
    });
}(jQuery));
<|endoftext|>


<commit_before>(function() {

	var app = angular.module('app.projectDetailCtrl', []);

	app.controller('app.projectDetailCtrl', ['$scope', '$location', '$routeParams', 'app.appFactory', 'ndb_users.userFactory', 'app.projectFactory', function($scope, $location, $routeParams, appFactory, userFactory, projectFactory) {

		// Perform setup and reset $scope variables...
		$scope.init = function() {
			console.log('[app.projectDetailCtrl] $scope.init(): call');
			appFactory.config({
				'pageTitle': 'Project',
				'navActive': 'projects'
			});

			$scope.projectId = $routeParams.projectId;

			$scope.user = {};
			$scope.userLoaded = false;
			$scope.hasUser = false;

			$scope.project = {};
			$scope.projectLoaded = true;

			userFactory.user().then(function(response) {
				$scope.userFactory = true;
				if (response.hasOwnProperty('user')) {
					$scope.user = response.user;
					$scope.hasUser = true;

					projectFactory.project($scope.projectId).then(function(response) {
						$scope.projectLoaded = true;
						if (!response.error) {
							// Success
							$scope.project = response;
						} else {
							// Error
						}
					});
				} else {
					// Not logged in
					$location.path('/login');
				}
			});
		};

		$scope.login = function() {
			console.log('[app.projectDetailCtrl] $scope.login: called');
		};

		// Init
		$scope.init();
	}]);

})();<commit_msg>Displays Project name as page title<commit_after>(function() {

	var app = angular.module('app.projectDetailCtrl', []);

	app.controller('app.projectDetailCtrl', ['$scope', '$location', '$routeParams', 'app.appFactory', 'ndb_users.userFactory', 'app.projectFactory', function($scope, $location, $routeParams, appFactory, userFactory, projectFactory) {

		// Perform setup and reset $scope variables...
		$scope.init = function() {
			console.log('[app.projectDetailCtrl] $scope.init(): call');
			appFactory.config({
				'pageTitle': 'Project',
				'navActive': 'projects'
			});

			$scope.projectId = $routeParams.projectId;

			$scope.user = {};
			$scope.userLoaded = false;
			$scope.hasUser = false;

			$scope.project = {};
			$scope.projectLoaded = true;

			userFactory.user().then(function(response) {
				$scope.userFactory = true;
				if (response.hasOwnProperty('user')) {
					$scope.user = response.user;
					$scope.hasUser = true;

					projectFactory.project($scope.projectId).then(function(response) {
						$scope.projectLoaded = true;
						if (!response.error) {
							// Success
							$scope.project = response;

							appFactory.config({
								'pageTitle': response.name
							});
						} else {
							// Error
						}
					});
				} else {
					// Not logged in
					$location.path('/login');
				}
			});
		};

		// Init
		$scope.init();
	}]);

})();<|endoftext|>


<commit_before>// Copyright 2014 Globo.com Player authors. All rights reserved.
// Use of this source code is governed by a BSD-style
// license that can be found in the LICENSE file.

import Events from 'base/events'
import find from 'lodash.find'
import HTML5Video from 'playbacks/html5_video'

export default class HTML5Audio extends HTML5Video {
  get name() { return 'html5_audio' }
  get tagName() { return 'audio' }

  durationChange() {
    this.settings.left = ["playpause", "position", "duration"]
    this.settings.seekEnabled = this.isSeekEnabled()
    this.trigger(Events.PLAYBACK_SETTINGSUPDATE)
  }

  getPlaybackType() {
    return 'aod'
  }

  stalled() {
    if (this.el.readyState < this.el.HAVE_FUTURE_DATA) {
      this.trigger(Events.PLAYBACK_BUFFERING, this.name)
    }
  }

  timeUpdated() {
    this.trigger(Events.PLAYBACK_TIMEUPDATE, this.el.currentTime, this.el.duration, this.name)
  }
}

HTML5Audio.canPlay = function(resource, mimeType) {
  var mimetypes = {
    'wav': ['audio/wav'],
    'mp3': ['audio/mp3', 'audio/mpeg;codecs="mp3"'],
    'aac': ['audio/mp4;codecs="mp4a.40.5"'],
    'oga': ['audio/ogg']
  }
  var resourceParts = resource.split('?')[0].match(/.*\.(.*)$/) || []
  if ((resourceParts.length > 1) && (mimetypes[resourceParts[1]] !== undefined)) {
    var a = document.createElement('audio')
    return !!find(mimetypes[resourceParts[1]], (ext) => { return !!a.canPlayType(ext).replace(/no/, '') })
  } else if (mimeType && !/m3u8/.test(resourceParts[1])) {
    var a = document.createElement('audio')
    return !!a.canPlayType(mimeType).replace(/no/, '')
  }
  return false
}
<commit_msg>html5 audio: use playback type constant<commit_after>// Copyright 2014 Globo.com Player authors. All rights reserved.
// Use of this source code is governed by a BSD-style
// license that can be found in the LICENSE file.

import Events from 'base/events'
import Playback from 'base/playback'
import HTML5Video from 'playbacks/html5_video'
import find from 'lodash.find'

export default class HTML5Audio extends HTML5Video {
  get name() { return 'html5_audio' }
  get tagName() { return 'audio' }

  durationChange() {
    this.settings.left = ["playpause", "position", "duration"]
    this.settings.seekEnabled = this.isSeekEnabled()
    this.trigger(Events.PLAYBACK_SETTINGSUPDATE)
  }

  getPlaybackType() {
    return Playback.AOD
  }

  stalled() {
    if (this.el.readyState < this.el.HAVE_FUTURE_DATA) {
      this.trigger(Events.PLAYBACK_BUFFERING, this.name)
    }
  }

  timeUpdated() {
    this.trigger(Events.PLAYBACK_TIMEUPDATE, this.el.currentTime, this.el.duration, this.name)
  }
}

HTML5Audio.canPlay = function(resource, mimeType) {
  var mimetypes = {
    'wav': ['audio/wav'],
    'mp3': ['audio/mp3', 'audio/mpeg;codecs="mp3"'],
    'aac': ['audio/mp4;codecs="mp4a.40.5"'],
    'oga': ['audio/ogg']
  }
  var resourceParts = resource.split('?')[0].match(/.*\.(.*)$/) || []
  if ((resourceParts.length > 1) && (mimetypes[resourceParts[1]] !== undefined)) {
    var a = document.createElement('audio')
    return !!find(mimetypes[resourceParts[1]], (ext) => { return !!a.canPlayType(ext).replace(/no/, '') })
  } else if (mimeType && !/m3u8/.test(resourceParts[1])) {
    var a = document.createElement('audio')
    return !!a.canPlayType(mimeType).replace(/no/, '')
  }
  return false
}
<|endoftext|>


<commit_before>/*
 * timeago: a jQuery plugin, version: 0.8.1 (2010-01-04)
 * @requires jQuery v1.2.3 or later
 *
 * Timeago is a jQuery plugin that makes it easy to support automatically
 * updating fuzzy timestamps (e.g. "4 minutes ago" or "about 1 day ago").
 *
 * For usage and examples, visit:
 * http://timeago.yarp.com/
 *
 * Licensed under the MIT:
 * http://www.opensource.org/licenses/mit-license.php
 *
 * Copyright (c) 2008-2010, Ryan McGeary (ryanonjavascript -[at]- mcgeary [*dot*] org)
 */
(function($) {
  $.timeago = function(timestamp) {
    if (timestamp instanceof Date) return inWords(timestamp);
    else if (typeof timestamp == "string") return inWords($.timeago.parse(timestamp));
    else return inWords($.timeago.datetime(timestamp));
  };
  var $t = $.timeago;

  $.extend($.timeago, {
    settings: {
      refreshMillis: 60000,
      allowFuture: false,
      strings: {
        prefixAgo: null,
        prefixFromNow: null,
        suffixAgo: "ago",
        suffixFromNow: "from now",
        ago: null, // DEPRECATED, use suffixAgo
        fromNow: null, // DEPRECATED, use suffixFromNow
        seconds: "less than a minute",
        minute: "about a minute",
        minutes: "%d minutes",
        hour: "about an hour",
        hours: "about %d hours",
        day: "a day",
        days: "%d days",
        month: "about a month",
        months: "%d months",
        year: "about a year",
        years: "%d years"
      }
    },
    inWords: function(distanceMillis) {
      var $l = this.settings.strings;
      var prefix = $l.prefixAgo;
      var suffix = $l.suffixAgo || $l.ago;
      if (this.settings.allowFuture) {
        if (distanceMillis < 0) {
          prefix = $l.prefixFromNow;
          suffix = $l.suffixFromNow || $l.fromNow;
        }
        distanceMillis = Math.abs(distanceMillis);
      }

      var seconds = distanceMillis / 1000;
      var minutes = seconds / 60;
      var hours = minutes / 60;
      var days = hours / 24;
      var years = days / 365;

      var words = seconds < 45 && substitute($l.seconds, Math.round(seconds)) ||
        seconds < 90 && substitute($l.minute, 1) ||
        minutes < 45 && substitute($l.minutes, Math.round(minutes)) ||
        minutes < 90 && substitute($l.hour, 1) ||
        hours < 24 && substitute($l.hours, Math.round(hours)) ||
        hours < 48 && substitute($l.day, 1) ||
        days < 30 && substitute($l.days, Math.floor(days)) ||
        days < 60 && substitute($l.month, 1) ||
        days < 365 && substitute($l.months, Math.floor(days / 30)) ||
        years < 2 && substitute($l.year, 1) ||
        substitute($l.years, Math.floor(years));

      return $.trim([prefix, words, suffix].join(" "));
    },
    parse: function(iso8601) {
      var s = $.trim(iso8601);
      s = s.replace(/-/,"/").replace(/-/,"/");
      s = s.replace(/T/," ").replace(/Z/," UTC");
      s = s.replace(/([\+-]\d\d)\:?(\d\d)/," $1$2"); // -04:00 -> -0400
      return new Date(s);
    },
    datetime: function(elem) {
      // jQuery's `is()` doesn't play well with HTML5 in IE
      var isTime = $(elem).get(0).tagName.toLowerCase() == "time"; // $(elem).is("time");
      var iso8601 = isTime ? $(elem).attr("datetime") : $(elem).attr("title");
      return $t.parse(iso8601);
    }
  });

  $.fn.timeago = function() {
    var self = this;
    self.each(refresh);

    var $s = $t.settings;
    if ($s.refreshMillis > 0) {
      setInterval(function() { self.each(refresh); }, $s.refreshMillis);
    }
    return self;
  };

  function refresh() {
    var data = prepareData(this);
    if (!isNaN(data.datetime)) {
      $(this).text(inWords(data.datetime));
    }
    return this;
  }

  function prepareData(element) {
    element = $(element);
    if (element.data("timeago") === undefined) {
      element.data("timeago", { datetime: $t.datetime(element) });
      var text = $.trim(element.text());
      if (text.length > 0) element.attr("title", text);
    }
    return element.data("timeago");
  }

  function inWords(date) {
    return $t.inWords(distance(date));
  }

  function distance(date) {
    return (new Date().getTime() - date.getTime());
  }

  function substitute(stringOrFunction, value) {
    var string = $.isFunction(stringOrFunction) ? stringOrFunction(value) : stringOrFunction;
    return string.replace(/%d/i, value);
  }

  // fix for IE6 suckage
  document.createElement("abbr");
  document.createElement("time");
})(jQuery);
<commit_msg>Bug fix while checking for undefined attached data<commit_after>/*
 * timeago: a jQuery plugin, version: 0.8.1 (2010-01-04)
 * @requires jQuery v1.2.3 or later
 *
 * Timeago is a jQuery plugin that makes it easy to support automatically
 * updating fuzzy timestamps (e.g. "4 minutes ago" or "about 1 day ago").
 *
 * For usage and examples, visit:
 * http://timeago.yarp.com/
 *
 * Licensed under the MIT:
 * http://www.opensource.org/licenses/mit-license.php
 *
 * Copyright (c) 2008-2010, Ryan McGeary (ryanonjavascript -[at]- mcgeary [*dot*] org)
 */
(function($) {
  $.timeago = function(timestamp) {
    if (timestamp instanceof Date) return inWords(timestamp);
    else if (typeof timestamp == "string") return inWords($.timeago.parse(timestamp));
    else return inWords($.timeago.datetime(timestamp));
  };
  var $t = $.timeago;

  $.extend($.timeago, {
    settings: {
      refreshMillis: 60000,
      allowFuture: false,
      strings: {
        prefixAgo: null,
        prefixFromNow: null,
        suffixAgo: "ago",
        suffixFromNow: "from now",
        ago: null, // DEPRECATED, use suffixAgo
        fromNow: null, // DEPRECATED, use suffixFromNow
        seconds: "less than a minute",
        minute: "about a minute",
        minutes: "%d minutes",
        hour: "about an hour",
        hours: "about %d hours",
        day: "a day",
        days: "%d days",
        month: "about a month",
        months: "%d months",
        year: "about a year",
        years: "%d years"
      }
    },
    inWords: function(distanceMillis) {
      var $l = this.settings.strings;
      var prefix = $l.prefixAgo;
      var suffix = $l.suffixAgo || $l.ago;
      if (this.settings.allowFuture) {
        if (distanceMillis < 0) {
          prefix = $l.prefixFromNow;
          suffix = $l.suffixFromNow || $l.fromNow;
        }
        distanceMillis = Math.abs(distanceMillis);
      }

      var seconds = distanceMillis / 1000;
      var minutes = seconds / 60;
      var hours = minutes / 60;
      var days = hours / 24;
      var years = days / 365;

      var words = seconds < 45 && substitute($l.seconds, Math.round(seconds)) ||
        seconds < 90 && substitute($l.minute, 1) ||
        minutes < 45 && substitute($l.minutes, Math.round(minutes)) ||
        minutes < 90 && substitute($l.hour, 1) ||
        hours < 24 && substitute($l.hours, Math.round(hours)) ||
        hours < 48 && substitute($l.day, 1) ||
        days < 30 && substitute($l.days, Math.floor(days)) ||
        days < 60 && substitute($l.month, 1) ||
        days < 365 && substitute($l.months, Math.floor(days / 30)) ||
        years < 2 && substitute($l.year, 1) ||
        substitute($l.years, Math.floor(years));

      return $.trim([prefix, words, suffix].join(" "));
    },
    parse: function(iso8601) {
      var s = $.trim(iso8601);
      s = s.replace(/-/,"/").replace(/-/,"/");
      s = s.replace(/T/," ").replace(/Z/," UTC");
      s = s.replace(/([\+-]\d\d)\:?(\d\d)/," $1$2"); // -04:00 -> -0400
      return new Date(s);
    },
    datetime: function(elem) {
      // jQuery's `is()` doesn't play well with HTML5 in IE
      var isTime = $(elem).get(0).tagName.toLowerCase() == "time"; // $(elem).is("time");
      var iso8601 = isTime ? $(elem).attr("datetime") : $(elem).attr("title");
      return $t.parse(iso8601);
    }
  });

  $.fn.timeago = function() {
    var self = this;
    self.each(refresh);

    var $s = $t.settings;
    if ($s.refreshMillis > 0) {
      setInterval(function() { self.each(refresh); }, $s.refreshMillis);
    }
    return self;
  };

  function refresh() {
    var data = prepareData(this);
    if (!isNaN(data.datetime)) {
      $(this).text(inWords(data.datetime));
    }
    return this;
  }

  function prepareData(element) {
    element = $(element);
    if (!element.data("timeago")) {
      element.data("timeago", { datetime: $t.datetime(element) });
      var text = $.trim(element.text());
      if (text.length > 0) element.attr("title", text);
    }
    return element.data("timeago");
  }

  function inWords(date) {
    return $t.inWords(distance(date));
  }

  function distance(date) {
    return (new Date().getTime() - date.getTime());
  }

  function substitute(stringOrFunction, value) {
    var string = $.isFunction(stringOrFunction) ? stringOrFunction(value) : stringOrFunction;
    return string.replace(/%d/i, value);
  }

  // fix for IE6 suckage
  document.createElement("abbr");
  document.createElement("time");
})(jQuery);
<|endoftext|>


<commit_before>// Copyright 2014 Globo.com Player authors. All rights reserved.
// Use of this source code is governed by a BSD-style
// license that can be found in the LICENSE file.

var UIPlugin = require('../../base/ui_plugin');
var Styler = require('../../base/styler');

var HTML5Video = UIPlugin.extend({
  name: 'html5_video',
  type: 'playback',
  tagName: 'video',
  attributes: {
    'data-html5-video': ''
  },

  events: {
    'timeupdate': 'timeUpdated',
    'progress': 'progress',
    'ended': 'ended',
    'playing': 'playing',
    'stalled': 'buffering',
    'waiting': 'buffering',
    'canplaythrough': 'bufferFull',
    'loadedmetadata': 'loadedMetadata'
  },

  initialize: function(options) {
    this.options = options;
    this.src = options.src;
    this.el.src = options.src;
    this.el.loop = options.loop;
    this.settings = {
      left: ['playpause'],
      right: ['fullscreen', 'volume'],
      default: ['position', 'seekbar', 'duration']
    };
  },

  loadedMetadata: function(e) {
    this.trigger('playback:loadedmetadata', e.target.duration);
  },

  play: function() {
    this.el.play();
  },

  pause: function() {
    this.el.pause();
  },

  stop: function() {
    this.pause();
    if(this.el.readyState !== 0) {
      this.el.currentTime = 0;
    }
  },

  volume: function(value) {
    this.el.volume = value / 100;
  },

  mute: function() {
    this.el.volume = 0;
  },

  unmute: function() {
    this.el.volume = 1;
  },

  isMuted: function() {
    return !!this.el.volume;
  },

  isPlaying: function() {
    return !this.el.paused && !this.el.ended;
  },

  ended: function() {
    this.trigger('playback:ended', this.name);
    this.trigger('playback:timeupdate', 0, this.el.duration, this.name);
  },

  buffering: function() {
    this.trigger('playback:buffering', this.name);
  },

  bufferFull: function() {
    this.trigger('playback:bufferfull', this.name);
  },

  destroy: function() {
    this.stop();
    this.el.src = '';
    this.$el.remove();
  },

  seek: function(seekBarValue) {
    var time = this.el.duration * (seekBarValue / 100);
    this.el.currentTime = time;
  },

  getCurrentTime: function() {
    return this.el.currentTime;
  },

  getDuration: function() {
    return this.el.duration;
  },

  timeUpdated: function() {
    this.trigger('playback:timeupdate', this.el.currentTime, this.el.duration, this.name);
  },

  progress: function() {
    if (!this.el.buffered.length) return;
    var bufferedPos = 0;
    for (var i = 0;  i < this.el.buffered.length; i++) {
      if (this.el.currentTime >= this.el.buffered.start(i) && this.el.currentTime <= this.el.buffered.end(i)) {
        bufferedPos = i;
        break;
      }
    }
    this.trigger('playback:progress', this.el.buffered.start(bufferedPos), this.el.buffered.end(bufferedPos), this.el.duration, this.name);
  },

  playing: function() {
    this.trigger('playback:play', this.name);
  },

  render: function() {
    var style = Styler.getStyleFor(this.name);
    this.$el.append(style);
    this.trigger('playback:ready', this.name);
    this.options.autoPlay && this.play();
    return this;
  }
});

HTML5Video.canPlay = function(resource) {
    return !!resource.match(/(.*).mp4/);
}

module.exports = HTML5Video;
<commit_msg>html5 video: change to es6 syntax<commit_after>// Copyright 2014 Globo.com Player authors. All rights reserved.
// Use of this source code is governed by a BSD-style
// license that can be found in the LICENSE file.

var UIPlugin = require('../../base/ui_plugin')
var Styler = require('../../base/styler')

class HTML5Video extends UIPlugin {
  get name() { return 'html5_video' }
  get type() { return 'playback' }
  get tagName() { return 'video' }

  get attributes() {
    return {
      'data-html5-video': ''
    }
  }

  get events() {
    return {
      'timeupdate': 'timeUpdated',
      'progress': 'progress',
      'ended': 'ended',
      'playing': 'playing',
      'stalled': 'buffering',
      'waiting': 'buffering',
      'canplaythrough': 'bufferFull',
      'loadedmetadata': 'loadedMetadata'
    }
  }

  initialize(options) {
    this.options = options
    this.src = options.src
    this.el.src = options.src
    this.el.loop = options.loop
    this.settings = {
      left: ['playpause'],
      right: ['fullscreen', 'volume'],
      default: ['position', 'seekbar', 'duration']
    }
  }

  loadedMetadata(e) {
    this.trigger('playback:loadedmetadata', e.target.duration)
  }

  play() {
    this.el.play()
  }

  pause() {
    this.el.pause()
  }

  stop() {
    this.pause()
    if (this.el.readyState !== 0) {
      this.el.currentTime = 0
    }
  }

  volume(value) {
    this.el.volume = value / 100
  }

  mute() {
    this.el.volume = 0
  }

  unmute() {
    this.el.volume = 1
  }

  isMuted() {
    return !!this.el.volume
  }

  isPlaying() {
    return !this.el.paused && !this.el.ended
  }

  ended() {
    this.trigger('playback:ended', this.name)
    this.trigger('playback:timeupdate', 0, this.el.duration, this.name)
  }

  buffering() {
    this.trigger('playback:buffering', this.name)
  }

  bufferFull() {
    this.trigger('playback:bufferfull', this.name)
  }

  destroy() {
    this.stop()
    this.el.src = ''
    this.$el.remove()
  }

  seek(seekBarValue) {
    var time = this.el.duration * (seekBarValue / 100)
    this.el.currentTime = time
  }

  getCurrentTime() {
    return this.el.currentTime
  }

  getDuration() {
    return this.el.duration
  }

  timeUpdated() {
    this.trigger('playback:timeupdate', this.el.currentTime, this.el.duration, this.name)
  }

  progress() {
    if (!this.el.buffered.length) return
    var bufferedPos = 0
    for (var i = 0;  i < this.el.buffered.length; i++) {
      if (this.el.currentTime >= this.el.buffered.start(i) && this.el.currentTime <= this.el.buffered.end(i)) {
        bufferedPos = i
        break
      }
    }
    this.trigger('playback:progress', this.el.buffered.start(bufferedPos), this.el.buffered.end(bufferedPos), this.el.duration, this.name)
  }

  playing() {
    this.trigger('playback:play', this.name)
  }

  render() {
    var style = Styler.getStyleFor(this.name)
    this.$el.append(style)
    this.trigger('playback:ready', this.name)
    this.options.autoPlay && this.play()
    return this
  }
}

HTML5Video.canPlay = function(resource) {
    return !!resource.match(/(.*).mp4/)
}

module.exports = HTML5Video
<|endoftext|>