<commit_before>const types = require("./types");

const CUBIC_METER_PER_DAY = "m3/d";
const THOUSAND_CUBIC_METERS_PER_DAY = "e3m3/d";
const CUBIC_FEET_PER_DAY = "cf/d";
const THOUSAND_CUBIC_FEET_PER_DAY = "Mcf/d";

module.exports = {
  convert({from = CUBIC_METER_PER_DAY, to = THOUSAND_CUBIC_METERS_PER_DAY, value = 0}) {

    if (from === to) return value;

    if (from === CUBIC_METER_PER_DAY) {
      if (to === THOUSAND_CUBIC_METERS_PER_DAY) return value / 1000;
      if (to === CUBIC_FEET_PER_DAY) return value * 35.314666213;
      if (to === THOUSAND_CUBIC_FEET_PER_DAY) return (value * 35.314666213) / 1000;
    }

    if (from === THOUSAND_CUBIC_METERS_PER_DAY) {
      if (to === CUBIC_METER_PER_DAY) return value * 1000;
      if (to === CUBIC_FEET_PER_DAY) return value * 35314.666213;
      if (to === THOUSAND_CUBIC_FEET_PER_DAY) return value * 35.314666213;
    }

    if (from === CUBIC_FEET_PER_DAY) {
      if (to === CUBIC_METER_PER_DAY) return value * 0.028316847;
      if (to === THOUSAND_CUBIC_METERS_PER_DAY) return (value * 0.028316847) / 1000;
      if (to === THOUSAND_CUBIC_FEET_PER_DAY) return value / 1000;
    }

    if (from === THOUSAND_CUBIC_FEET_PER_DAY) {
      if (to === CUBIC_METER_PER_DAY) return value * 28.316847;
      if (to === THOUSAND_CUBIC_METERS_PER_DAY) return (value * 28.316847) / 1000;
      if (to === CUBIC_FEET_PER_DAY) return value * 1000;
    }

    throw new Error(`Conversion from ${from} to ${to} unknown`);
  }
};
<commit_msg>lint<commit_after>const CUBIC_METER_PER_DAY = "m3/d";
const THOUSAND_CUBIC_METERS_PER_DAY = "e3m3/d";
const CUBIC_FEET_PER_DAY = "cf/d";
const THOUSAND_CUBIC_FEET_PER_DAY = "Mcf/d";

module.exports = {
  convert({from = CUBIC_METER_PER_DAY, to = THOUSAND_CUBIC_METERS_PER_DAY, value = 0}) {
    if (from === to) return value;

    if (from === CUBIC_METER_PER_DAY) {
      if (to === THOUSAND_CUBIC_METERS_PER_DAY) return value / 1000;
      if (to === CUBIC_FEET_PER_DAY) return value * 35.314666213;
      if (to === THOUSAND_CUBIC_FEET_PER_DAY) return (value * 35.314666213) / 1000;
    }

    if (from === THOUSAND_CUBIC_METERS_PER_DAY) {
      if (to === CUBIC_METER_PER_DAY) return value * 1000;
      if (to === CUBIC_FEET_PER_DAY) return value * 35314.666213;
      if (to === THOUSAND_CUBIC_FEET_PER_DAY) return value * 35.314666213;
    }

    if (from === CUBIC_FEET_PER_DAY) {
      if (to === CUBIC_METER_PER_DAY) return value * 0.028316847;
      if (to === THOUSAND_CUBIC_METERS_PER_DAY) return (value * 0.028316847) / 1000;
      if (to === THOUSAND_CUBIC_FEET_PER_DAY) return value / 1000;
    }

    if (from === THOUSAND_CUBIC_FEET_PER_DAY) {
      if (to === CUBIC_METER_PER_DAY) return value * 28.316847;
      if (to === THOUSAND_CUBIC_METERS_PER_DAY) return (value * 28.316847) / 1000;
      if (to === CUBIC_FEET_PER_DAY) return value * 1000;
    }

    throw new Error(`Conversion from ${from} to ${to} unknown`);
  }
};
<|endoftext|>


<commit_before>var nroonga = require('../wrapped-nroonga');
var ValidationError = require('../errors').ValidationError;
var FieldTypeValidationError = require('../errors').FieldTypeValidationError;

var MINIMUM_NAME_LENGTH =
      exports.MINIMUM_NAME_LENGTH =
      IndexField.MINIMUM_NAME_LENGTH = 3;
var MAXIMUM_NAME_LENGTH =
      exports.MAXIMUM_NAME_LENGTH =
      IndexField.MAXIMUM_NAME_LENGTH = 64;

var VALID_NAME_PATTERN =
      exports.VALID_NAME_PATTERN =
      IndexField.VALID_NAME_PATTERN = '[a-z][a-z0-9_]*';
var VALID_NAME_MATCHER =
      exports.VALID_NAME_MATCHER =
      IndexField.VALID_NAME_MATCHER = new RegExp('^' + VALID_NAME_PATTERN + '$');
var INVALID_COLUMN_NAME_CHARACTERS_MATCHER =
      exports.INVALID_COLUMN_NAME_CHARACTERS_MATCHER =
      IndexField.INVALID_COLUMN_NAME_CHARACTERS_MATCHER = /[^_a-z0-9]/g;

var VALID_FIELD_TYPES =
      IndexField.VALID_FIELD_TYPES =
      exports.VALID_FIELD_TYPES = [
        'text',
        'literal',
        'uint'
      ];

var RESERVED_NAMES =
      IndexField.RESERVED_NAMES =
      exports.RESERVED_NAMES = [
        'body',
        'docid',
        'text_relevance'
     ];
var RESERVED_COLUMN_NAMES =
      IndexField.RESERVED_COLUMN_NAMES =
      exports.RESERVED_COLUMN_NAMES = [
        '_key'
      ];

function assertValidFieldName(field) {
  if (typeof field != 'string') {
    var error = new Error('field name name must be a string');
    error.isValidationError = true;
    throw error;
  }

  var errors = [];
  var commonPrefix = 'Value \'' + field + '\' at \'%NAME_FIELD%\' failed ' +
                     'to satisfy constraint: ';

  if (!field.match(VALID_NAME_MATCHER)) {
    errors.push(commonPrefix + 'Member must satisfy regular ' +
                'expression pattern: ' + VALID_NAME_PATTERN);
  } else {
    var invalidCharacters = field.match(INVALID_COLUMN_NAME_CHARACTERS_MATCHER);
    if (invalidCharacters) {
      invalidCharacters = Array.prototype.slice.call(invalidCharacters, 0)
                            .map(function(aCharacter) {
                              return "'" + aCharacter + "'";
                            });
      errors.push(commonPrefix + 'Member cannot include these ' +
                  'characters: ' + invalidCharacters.join(', '));
    }
  }

  if (field.length < MINIMUM_NAME_LENGTH)
    errors.push(commonPrefix + 'Member must have length greater ' +
                'than or equal to ' + MINIMUM_NAME_LENGTH);

  if (field.length > MAXIMUM_NAME_LENGTH)
    errors.push(commonPrefix + 'Member must have length less ' +
                'than or equal to ' + MAXIMUM_NAME_LENGTH);

  var index = exports.RESERVED_NAMES.indexOf(field);
  if (index > -1) index = exports.RESERVED_COLUMN_NAMES.indexOf(field);
  if (index > -1)
    errors.push(field + ' is a reserved field name');

  if (errors.length) {
    var prefix = errors.length > 1 ?
                   errors.length + ' validation errors detected: ' :
                   '1 validation error detected: ';
    throw new ValidationError(prefix + errors.join('; '));
  }
}

function assertValidFieldType(type) {
  var errors = [];
  var commonPrefix = 'Value \'' + type + '\' at \'%TYPE_FIELD%\' failed ' +
                     'to satisfy constraint: ';

  if (!type) {
    errors.push('Value null at \'%TYPE_FIELD%\' failed to satisfy ' +
                  'constraint: Member must not be null');
  } else {
    if (VALID_FIELD_TYPES.indexOf(type) < 0)
      errors.push(commonPrefix + 'Member must satisfy enum value set: [' +
                    VALID_FIELD_TYPES.join(', ') + ']');
  }

  if (errors.length) {
    var prefix = errors.length > 1 ?
                   errors.length + ' validation errors detected: ' :
                   '1 validation error detected: ';
    throw new ValidationError(prefix + errors.join('; '));
  }
}

function IndexField(name, domain) {
  this.domain = domain;
  this.context = domain.context;
  this.name = name;
  this._type = null;
  this.initialize();
};
IndexField.prototype = {
  initialize: function() {
    // for validation
    this.columnName;
  },
  get columnName() {
    if (!this._columnName) {
      assertValidFieldName(this.name);
      this._columnName = IndexField.toColumnNamePart(this.name);
    }
    return this._columnName;
  },
  get indexColumnName() {
    return this.domain.indexTableBaseName + this.columnName;
  },
  get indexTableName() {
    return this.domain.indexTableBaseName + this.columnName;
  },
  get indexTableKeyType() {
    var type = this.type;
    switch (type) {
      case 'uint':
        return nroonga.UInt32;
      case 'literal':
        return nroonga.ShortText;
      default:
        throw new Error('Unsupported index field type ' + type +
                        ' for index table');
    }
  },
  fieldTypeToColumnType: function(fieldType) {
    switch (fieldType) {
      case 'text':
        return nroonga.ShortText;
      case 'uint':
        return nroonga.UInt32;
      case 'literal':
        return this.indexTableName;
      default:
        throw new Error('Unsupported index field type ' + fieldType);
    }
  },
  columnTypeToFieldType: function(columnType) {
    switch (columnType) {
      case nroonga.ShortText:
        return 'text';
      case nroonga.UInt32:
        return 'uint';
      case this.indexTableName:
        return 'literal';
      default:
        throw new Error('Unsupported column type ' + columnType);
    }
  },

  get column() {
    var columns = this.context.ordinalColumnsSync(this.domain.tableName);
    for (var i = 0, maxi = columns.length; i < maxi; i++) {
      if (columns[i].name == this.columnName)
        return columns[i];
    }
    return null;
  },

  get type() {
    if (this._type)
      return this._type;

    var column = this.column;
    if (!column)
      throw new Error('the index field ' + this.name + ' is not created yet');

    if (column.type == 'var') {
      if (column.range == nroonga.ShortText)
        return this._type = 'text';
      if (column.range == this.indexTableName)
        return this._type = 'literal';
    } else if (column.type == 'fix') {
      if (column.range == nroonga.UInt32)
        return this._type = 'uint';
      else if (column.range == this.indexTableName)
        return this._type = 'literal';
    }

    throw new Error('unknown unfixed column ' + this.columnName);
  },
  set type(type) {
    assertValidFieldType(type);
    if (this.exists()) {
      if  (type != this.type)
        this.changeTypeToSync(type);
    } else {
      this._type = type;
    }
    return type;
  },
  setType: function(type) {
    this.type = type;
    return this;
  },

  get defaultValue() {
    return null;
  },

  get facetEnabled() {
    // uint fields cannot be drilldowned by groonga...
    if (this.type == 'uint')
      return false;

    if (!this.exists() || this._facetEnabled !== undefined)
      return !!this._facetEnabled;

    var value = this.domain.getConfiguration(this.facetEnabledConfigurationKey);
    return !!(this._facetEnabled = value);
  },
  set facetEnabled(value) {
    var booleanValue = !!value;
    if (booleanValue != this.facetEnabled && this.type == 'uint')
      throw new Error('facet option cannot be configured for the type ' + this.type + '.');

    this._facetEnabled = booleanValue;
    this.validateOptions();
    return value;
  },
  setFacetEnabled: function(value) {
    this.facetEnabled = value;
    return this;
  },
  get facetEnabledConfigurationKey() {
    return 'column_' + this.name + '_option_facet_enabled';
  },

  get resultEnabled() {
    if (this.type == 'uint')
      return true;

    if (!this.exists() || this._resultEnabled !== undefined)
      return !!this._resultEnabled;

    var value = this.domain.getConfiguration(this.resultEnabledConfigurationKey);
    return !!(this._resultEnabled = value);
  },
  set resultEnabled(value) {
    var booleanValue = !!value;
    if (booleanValue != this.resultEnabled && this.type == 'uint')
      throw new Error('returnable option cannot be configured for the type ' + this.type + '.');

    this._resultEnabled = !!value;
    this.validateOptions();
    return value;
  },
  setResultEnabled: function(value) {
    this.resultEnabled = value;
    return this;
  },
  get resultEnabledConfigurationKey() {
    return 'column_' + this.name + '_option_result_enabled';
  },

  get searchEnabled() {
    if (this.type == 'text' || this.type == 'uint')
      return true;

    if (!this.exists() || this._searchEnabled !== undefined)
      return !!this._searchEnabled;

    var value = this.domain.getConfiguration(this.searchEnabledConfigurationKey);
    return !!(this._searchEnabled = value);
  },
  set searchEnabled(value) {
    var booleanValue = !!value;
    if (booleanValue != this.searchEnabled &&
        (this.type == 'text' || this.type == 'uint'))
      throw new Error('searchable option cannot be configured for the type ' + this.type + '.');

    this._searchEnabled = booleanValue;
    this.validateOptions();
    return value;
  },
  setSearchEnabled: function(value) {
    this.searchEnabled = value;
    return this;
  },
  get searchEnabledConfigurationKey() {
    return 'column_' + this.name + '_option_search_enabled';
  },

  get defaultSearchField() {
    if (!this.exists())
      return false;

    return this == this.domain.defaultSearchField;
  },
  set defaultSearchField(value) {
    this._defaultSearchField = !!value;
    return value;
  },
  setDefaultSearchField: function(value) {
    this.defaultSearchField = value;
    return value;
  },

  get options() {
    var options = [];
    if (this.searchEnabled) options.push('Search');
    if (this.facetEnabled) options.push('Facet');
    if (this.resultEnabled) options.push('Result');
    return options.join(' ');
  },

  get state() {
    return 'Active';
  },

  get summary() {
    return this.name + ' ' + this.state + ' ' +
             this.type + ' (' + this.options + ')';
  },

  get multipleValues() {
    return !!this.column &&
           this.column.flags.indexOf(nroonga.COLUMN_VECTOR) > -1;
  },

  createSync: function(multipleValues) {
    var indexTableName = this.domain.termsTableName;

    var type = this.type;
    var columnType = this.fieldTypeToColumnType(type);

    if (type == 'uint' || type == 'literal') {
      this.context.commandSync('table_create', {
        name: this.indexTableName,
        flags: nroonga.TABLE_PAT_KEY,
        key_type: this.indexTableKeyType
      });
      indexTableName = this.indexTableName;
    }

    var columnFlags = multipleValues ?
                        nroonga.COLUMN_VECTOR : nroonga.COLUMN_SCALAR;
    this.context.commandSync('column_create', {
      table: this.domain.tableName,
      name: this.columnName,
      flags: columnFlags,
      type: columnType
    });
    this.context.commandSync('column_create', {
      table: indexTableName,
      name: this.indexColumnName,
      flags: nroonga.INDEX_COLUMN_DEFAULT_FLAGS,
      type: this.domain.tableName,
      source: this.columnName
    });

    this.saveOptionsSync();

    return this;
  },
  saveOptionsSync: function() {
    if (!this.exists()) return this;

    this.facetEnabled;
    if (this._facetEnabled !== undefined)
      this.domain.setConfiguration(this.facetEnabledConfigurationKey,
                                   this._facetEnabled);

    this.resultEnabled;
    if (this._resultEnabled !== undefined)
      this.domain.setConfiguration(this.resultEnabledConfigurationKey,
                                   this._resultEnabled);

    this.searchEnabled;
    if (this._searchEnabled !== undefined)
      this.domain.setConfiguration(this.searchEnabledConfigurationKey,
                                   this._searchEnabled);

    if (this._defaultSearchField !== undefined) {
      this.domain.defaultSearchField = this._defaultSearchField ? this : null ;
      delete this._defaultSearchField;
    }

    return this;
  },
  deleteSync: function() {
    // backup information for re-creation
    this._type = this.type;
    this._facetEnabled = this.facetEnabled;
    this._resultEnabled = this.resultEnabled;
    this._searchEnabled = this.searchEnabled;
    this._defaultSearchField = this.defaultSearchField;

    if (this._type == 'uint' || this._type == 'literal') {
      this.context.commandSync('table_remove', {
        name: this.indexTableName
      });
    }
    this.context.commandSync('column_remove', {
      table: this.domain.tableName,
      name: this.columnName
    });

    this.domain.deleteConfiguration(this.facetEnabledConfigurationKey);
    this.domain.deleteConfiguration(this.resultEnabledConfigurationKey);
    this.domain.deleteConfiguration(this.searchEnabledConfigurationKey);
    if (this._defaultSearchField)
      this.domain.defaultSearchField = null;

    return this;
  },
  reindexSync: function() {
    var name = this.name;
    var type = this.type;
    if (type == 'uint' || type == 'literal') {
      this.context.commandSync('column_remove', {
        table: this.indexTableName,
        name: this.indexColumnName
      });
      this.context.commandSync('table_remove', {
        name: this.indexTableName
      });
      this.context.commandSync('table_create', {
        name: this.indexTableName,
        flags: nroonga.TABLE_PAT_KEY,
        key_type: this.indexTableKeyType
      });
      this.context.commandSync('column_create', {
        table: this.indexTableName,
        name: this.indexColumnName,
        flags: nroonga.INDEX_COLUMN_DEFAULT_FLAGS,
        type: this.domain.tableName,
        source: this.columnName
      });
    } else {
      this.context.commandSync('column_remove', {
        table: this.domain.termsTableName,
        name: this.indexColumnName
      });
      this.context.commandSync('column_create', {
        table: this.domain.termsTableName,
        name: this.indexColumnName,
        flags: nroonga.INDEX_COLUMN_DEFAULT_FLAGS,
        type: this.domain.tableName,
        source: this.columnName
      });
    }
    return this;
  },

  exists: function() {
    return !!this.column;
  },

  upgradeToMultipleValuesSync: function() {
    if (this.multipleValues) return this;
    var values = this.domain.dumpSync();
    this.deleteSync();
    this.createSync(true);
    this.domain.loadSync(values);
    return this;
  },

  changeTypeToSync: function(type) {
    var values = this.domain.dumpSync();
    this.deleteSync();
    this._type = type;
    this.createSync(true);
    var name = this.columnName;
    values.forEach(function(record) {
      var value = record[name];
      switch (type) {
        case 'text':
          record[name] = Array.isArray(value) ?
            value.map(this._toText, this) : this._toText(value);
          break;

        case 'literal':
          record[name] = Array.isArray(value) ?
            value.map(this._toLiteral, this) : this._toLiteral(value);
          break;

        case 'uint':
          record[name] = Array.isArray(value) ?
            value.map(this._toUInt, this) : this._toUInt(value);
          break;
      }
    });
    this.domain.loadSync(values);
    return this;
  },
  _toText: function(value) {
    return value.toString();
  },
  _toLiteral: function(value) {
    return value.toString();
  },
  _toUInt: function(value) {
     value = parseInt(value);
     if (isNaN(value))
       value = 0;
     return value;
  },

  validateOptions: function() {
    if (this.facetEnabled && this.resultEnabled)
      throw new FieldTypeValidationError(
              'Error defining field: ' + this.name + '. ' +
              'An IndexField may not be both FacetEnabled and ResultEnabled');
  }
};

exports.IndexField = IndexField;

IndexField.toColumnNamePart = function(fieldName) {
  return fieldName;
};
IndexField.toFieldName = function(columnNamePart) {
  return columnNamePart;
};
<commit_msg>Fix missing "this"<commit_after>var nroonga = require('../wrapped-nroonga');
var ValidationError = require('../errors').ValidationError;
var FieldTypeValidationError = require('../errors').FieldTypeValidationError;

var MINIMUM_NAME_LENGTH =
      exports.MINIMUM_NAME_LENGTH =
      IndexField.MINIMUM_NAME_LENGTH = 3;
var MAXIMUM_NAME_LENGTH =
      exports.MAXIMUM_NAME_LENGTH =
      IndexField.MAXIMUM_NAME_LENGTH = 64;

var VALID_NAME_PATTERN =
      exports.VALID_NAME_PATTERN =
      IndexField.VALID_NAME_PATTERN = '[a-z][a-z0-9_]*';
var VALID_NAME_MATCHER =
      exports.VALID_NAME_MATCHER =
      IndexField.VALID_NAME_MATCHER = new RegExp('^' + VALID_NAME_PATTERN + '$');
var INVALID_COLUMN_NAME_CHARACTERS_MATCHER =
      exports.INVALID_COLUMN_NAME_CHARACTERS_MATCHER =
      IndexField.INVALID_COLUMN_NAME_CHARACTERS_MATCHER = /[^_a-z0-9]/g;

var VALID_FIELD_TYPES =
      IndexField.VALID_FIELD_TYPES =
      exports.VALID_FIELD_TYPES = [
        'text',
        'literal',
        'uint'
      ];

var RESERVED_NAMES =
      IndexField.RESERVED_NAMES =
      exports.RESERVED_NAMES = [
        'body',
        'docid',
        'text_relevance'
     ];
var RESERVED_COLUMN_NAMES =
      IndexField.RESERVED_COLUMN_NAMES =
      exports.RESERVED_COLUMN_NAMES = [
        '_key'
      ];

function assertValidFieldName(field) {
  if (typeof field != 'string') {
    var error = new Error('field name name must be a string');
    error.isValidationError = true;
    throw error;
  }

  var errors = [];
  var commonPrefix = 'Value \'' + field + '\' at \'%NAME_FIELD%\' failed ' +
                     'to satisfy constraint: ';

  if (!field.match(VALID_NAME_MATCHER)) {
    errors.push(commonPrefix + 'Member must satisfy regular ' +
                'expression pattern: ' + VALID_NAME_PATTERN);
  } else {
    var invalidCharacters = field.match(INVALID_COLUMN_NAME_CHARACTERS_MATCHER);
    if (invalidCharacters) {
      invalidCharacters = Array.prototype.slice.call(invalidCharacters, 0)
                            .map(function(aCharacter) {
                              return "'" + aCharacter + "'";
                            });
      errors.push(commonPrefix + 'Member cannot include these ' +
                  'characters: ' + invalidCharacters.join(', '));
    }
  }

  if (field.length < MINIMUM_NAME_LENGTH)
    errors.push(commonPrefix + 'Member must have length greater ' +
                'than or equal to ' + MINIMUM_NAME_LENGTH);

  if (field.length > MAXIMUM_NAME_LENGTH)
    errors.push(commonPrefix + 'Member must have length less ' +
                'than or equal to ' + MAXIMUM_NAME_LENGTH);

  var index = exports.RESERVED_NAMES.indexOf(field);
  if (index > -1) index = exports.RESERVED_COLUMN_NAMES.indexOf(field);
  if (index > -1)
    errors.push(field + ' is a reserved field name');

  if (errors.length) {
    var prefix = errors.length > 1 ?
                   errors.length + ' validation errors detected: ' :
                   '1 validation error detected: ';
    throw new ValidationError(prefix + errors.join('; '));
  }
}

function assertValidFieldType(type) {
  var errors = [];
  var commonPrefix = 'Value \'' + type + '\' at \'%TYPE_FIELD%\' failed ' +
                     'to satisfy constraint: ';

  if (!type) {
    errors.push('Value null at \'%TYPE_FIELD%\' failed to satisfy ' +
                  'constraint: Member must not be null');
  } else {
    if (VALID_FIELD_TYPES.indexOf(type) < 0)
      errors.push(commonPrefix + 'Member must satisfy enum value set: [' +
                    VALID_FIELD_TYPES.join(', ') + ']');
  }

  if (errors.length) {
    var prefix = errors.length > 1 ?
                   errors.length + ' validation errors detected: ' :
                   '1 validation error detected: ';
    throw new ValidationError(prefix + errors.join('; '));
  }
}

function IndexField(name, domain) {
  this.domain = domain;
  this.context = domain.context;
  this.name = name;
  this._type = null;
  this.initialize();
};
IndexField.prototype = {
  initialize: function() {
    // for validation
    this.columnName;
  },
  get columnName() {
    if (!this._columnName) {
      assertValidFieldName(this.name);
      this._columnName = IndexField.toColumnNamePart(this.name);
    }
    return this._columnName;
  },
  get indexColumnName() {
    return this.domain.indexTableBaseName + this.columnName;
  },
  get indexTableName() {
    return this.domain.indexTableBaseName + this.columnName;
  },
  get indexTableKeyType() {
    var type = this.type;
    switch (type) {
      case 'uint':
        return nroonga.UInt32;
      case 'literal':
        return nroonga.ShortText;
      default:
        throw new Error('Unsupported index field type ' + type +
                        ' for index table');
    }
  },
  fieldTypeToColumnType: function(fieldType) {
    switch (fieldType) {
      case 'text':
        return nroonga.ShortText;
      case 'uint':
        return nroonga.UInt32;
      case 'literal':
        return this.indexTableName;
      default:
        throw new Error('Unsupported index field type ' + fieldType);
    }
  },
  columnTypeToFieldType: function(columnType) {
    switch (columnType) {
      case nroonga.ShortText:
        return 'text';
      case nroonga.UInt32:
        return 'uint';
      case this.indexTableName:
        return 'literal';
      default:
        throw new Error('Unsupported column type ' + columnType);
    }
  },

  get column() {
    var columns = this.context.ordinalColumnsSync(this.domain.tableName);
    for (var i = 0, maxi = columns.length; i < maxi; i++) {
      if (columns[i].name == this.columnName)
        return columns[i];
    }
    return null;
  },

  get type() {
    if (this._type)
      return this._type;

    var column = this.column;
    if (!column)
      throw new Error('the index field ' + this.name + ' is not created yet');

    if (column.type == 'var') {
      if (column.range == nroonga.ShortText)
        return this._type = 'text';
      if (column.range == this.indexTableName)
        return this._type = 'literal';
    } else if (column.type == 'fix') {
      if (column.range == nroonga.UInt32)
        return this._type = 'uint';
      else if (column.range == this.indexTableName)
        return this._type = 'literal';
    }

    throw new Error('unknown unfixed column ' + this.columnName);
  },
  set type(type) {
    assertValidFieldType(type);
    if (this.exists()) {
      if  (type != this.type)
        this.changeTypeToSync(type);
    } else {
      this._type = type;
    }
    return type;
  },
  setType: function(type) {
    this.type = type;
    return this;
  },

  get defaultValue() {
    return null;
  },

  get facetEnabled() {
    // uint fields cannot be drilldowned by groonga...
    if (this.type == 'uint')
      return false;

    if (!this.exists() || this._facetEnabled !== undefined)
      return !!this._facetEnabled;

    var value = this.domain.getConfiguration(this.facetEnabledConfigurationKey);
    return !!(this._facetEnabled = value);
  },
  set facetEnabled(value) {
    var booleanValue = !!value;
    if (booleanValue != this.facetEnabled && this.type == 'uint')
      throw new Error('facet option cannot be configured for the type ' + this.type + '.');

    this._facetEnabled = booleanValue;
    this.validateOptions();
    return value;
  },
  setFacetEnabled: function(value) {
    this.facetEnabled = value;
    return this;
  },
  get facetEnabledConfigurationKey() {
    return 'column_' + this.name + '_option_facet_enabled';
  },

  get resultEnabled() {
    if (this.type == 'uint')
      return true;

    if (!this.exists() || this._resultEnabled !== undefined)
      return !!this._resultEnabled;

    var value = this.domain.getConfiguration(this.resultEnabledConfigurationKey);
    return !!(this._resultEnabled = value);
  },
  set resultEnabled(value) {
    var booleanValue = !!value;
    if (booleanValue != this.resultEnabled && this.type == 'uint')
      throw new Error('returnable option cannot be configured for the type ' + this.type + '.');

    this._resultEnabled = !!value;
    this.validateOptions();
    return value;
  },
  setResultEnabled: function(value) {
    this.resultEnabled = value;
    return this;
  },
  get resultEnabledConfigurationKey() {
    return 'column_' + this.name + '_option_result_enabled';
  },

  get searchEnabled() {
    if (this.type == 'text' || this.type == 'uint')
      return true;

    if (!this.exists() || this._searchEnabled !== undefined)
      return !!this._searchEnabled;

    var value = this.domain.getConfiguration(this.searchEnabledConfigurationKey);
    return !!(this._searchEnabled = value);
  },
  set searchEnabled(value) {
    var booleanValue = !!value;
    if (booleanValue != this.searchEnabled &&
        (this.type == 'text' || this.type == 'uint'))
      throw new Error('searchable option cannot be configured for the type ' + this.type + '.');

    this._searchEnabled = booleanValue;
    this.validateOptions();
    return value;
  },
  setSearchEnabled: function(value) {
    this.searchEnabled = value;
    return this;
  },
  get searchEnabledConfigurationKey() {
    return 'column_' + this.name + '_option_search_enabled';
  },

  get defaultSearchField() {
    if (!this.exists())
      return false;

    return this == this.domain.defaultSearchField;
  },
  set defaultSearchField(value) {
    this._defaultSearchField = !!value;
    return value;
  },
  setDefaultSearchField: function(value) {
    this.defaultSearchField = value;
    return value;
  },

  get options() {
    var options = [];
    if (this.searchEnabled) options.push('Search');
    if (this.facetEnabled) options.push('Facet');
    if (this.resultEnabled) options.push('Result');
    return options.join(' ');
  },

  get state() {
    return 'Active';
  },

  get summary() {
    return this.name + ' ' + this.state + ' ' +
             this.type + ' (' + this.options + ')';
  },

  get multipleValues() {
    return !!this.column &&
           this.column.flags.indexOf(nroonga.COLUMN_VECTOR) > -1;
  },

  createSync: function(multipleValues) {
    var indexTableName = this.domain.termsTableName;

    var type = this.type;
    var columnType = this.fieldTypeToColumnType(type);

    if (type == 'uint' || type == 'literal') {
      this.context.commandSync('table_create', {
        name: this.indexTableName,
        flags: nroonga.TABLE_PAT_KEY,
        key_type: this.indexTableKeyType
      });
      indexTableName = this.indexTableName;
    }

    var columnFlags = multipleValues ?
                        nroonga.COLUMN_VECTOR : nroonga.COLUMN_SCALAR;
    this.context.commandSync('column_create', {
      table: this.domain.tableName,
      name: this.columnName,
      flags: columnFlags,
      type: columnType
    });
    this.context.commandSync('column_create', {
      table: indexTableName,
      name: this.indexColumnName,
      flags: nroonga.INDEX_COLUMN_DEFAULT_FLAGS,
      type: this.domain.tableName,
      source: this.columnName
    });

    this.saveOptionsSync();

    return this;
  },
  saveOptionsSync: function() {
    if (!this.exists()) return this;

    this.facetEnabled;
    if (this._facetEnabled !== undefined)
      this.domain.setConfiguration(this.facetEnabledConfigurationKey,
                                   this._facetEnabled);

    this.resultEnabled;
    if (this._resultEnabled !== undefined)
      this.domain.setConfiguration(this.resultEnabledConfigurationKey,
                                   this._resultEnabled);

    this.searchEnabled;
    if (this._searchEnabled !== undefined)
      this.domain.setConfiguration(this.searchEnabledConfigurationKey,
                                   this._searchEnabled);

    if (this._defaultSearchField !== undefined) {
      this.domain.defaultSearchField = this._defaultSearchField ? this : null ;
      delete this._defaultSearchField;
    }

    return this;
  },
  deleteSync: function() {
    // backup information for re-creation
    this._type = this.type;
    this._facetEnabled = this.facetEnabled;
    this._resultEnabled = this.resultEnabled;
    this._searchEnabled = this.searchEnabled;
    this._defaultSearchField = this.defaultSearchField;

    if (this._type == 'uint' || this._type == 'literal') {
      this.context.commandSync('table_remove', {
        name: this.indexTableName
      });
    }
    this.context.commandSync('column_remove', {
      table: this.domain.tableName,
      name: this.columnName
    });

    this.domain.deleteConfiguration(this.facetEnabledConfigurationKey);
    this.domain.deleteConfiguration(this.resultEnabledConfigurationKey);
    this.domain.deleteConfiguration(this.searchEnabledConfigurationKey);
    if (this._defaultSearchField)
      this.domain.defaultSearchField = null;

    return this;
  },
  reindexSync: function() {
    var name = this.name;
    var type = this.type;
    if (type == 'uint' || type == 'literal') {
      this.context.commandSync('column_remove', {
        table: this.indexTableName,
        name: this.indexColumnName
      });
      this.context.commandSync('table_remove', {
        name: this.indexTableName
      });
      this.context.commandSync('table_create', {
        name: this.indexTableName,
        flags: nroonga.TABLE_PAT_KEY,
        key_type: this.indexTableKeyType
      });
      this.context.commandSync('column_create', {
        table: this.indexTableName,
        name: this.indexColumnName,
        flags: nroonga.INDEX_COLUMN_DEFAULT_FLAGS,
        type: this.domain.tableName,
        source: this.columnName
      });
    } else {
      this.context.commandSync('column_remove', {
        table: this.domain.termsTableName,
        name: this.indexColumnName
      });
      this.context.commandSync('column_create', {
        table: this.domain.termsTableName,
        name: this.indexColumnName,
        flags: nroonga.INDEX_COLUMN_DEFAULT_FLAGS,
        type: this.domain.tableName,
        source: this.columnName
      });
    }
    return this;
  },

  exists: function() {
    return !!this.column;
  },

  upgradeToMultipleValuesSync: function() {
    if (this.multipleValues) return this;
    var values = this.domain.dumpSync();
    this.deleteSync();
    this.createSync(true);
    this.domain.loadSync(values);
    return this;
  },

  changeTypeToSync: function(type) {
    var values = this.domain.dumpSync();
    this.deleteSync();
    this._type = type;
    this.createSync(true);
    var name = this.columnName;
    values.forEach(function(record) {
      var value = record[name];
      switch (type) {
        case 'text':
          record[name] = Array.isArray(value) ?
            value.map(this._toText, this) : this._toText(value);
          break;

        case 'literal':
          record[name] = Array.isArray(value) ?
            value.map(this._toLiteral, this) : this._toLiteral(value);
          break;

        case 'uint':
          record[name] = Array.isArray(value) ?
            value.map(this._toUInt, this) : this._toUInt(value);
          break;
      }
    }, this);
    this.domain.loadSync(values);
    return this;
  },
  _toText: function(value) {
    return value.toString();
  },
  _toLiteral: function(value) {
    return value.toString();
  },
  _toUInt: function(value) {
     value = parseInt(value);
     if (isNaN(value))
       value = 0;
     return value;
  },

  validateOptions: function() {
    if (this.facetEnabled && this.resultEnabled)
      throw new FieldTypeValidationError(
              'Error defining field: ' + this.name + '. ' +
              'An IndexField may not be both FacetEnabled and ResultEnabled');
  }
};

exports.IndexField = IndexField;

IndexField.toColumnNamePart = function(fieldName) {
  return fieldName;
};
IndexField.toFieldName = function(columnNamePart) {
  return columnNamePart;
};
<|endoftext|>


<commit_before>/**
 * Carousel preparation methods
 */
const mixin = {
	methods: {
		/**
		 * Prepare settings object
		 */
		prepareSettings () {
			if (!this.initialSettings.responsive) {
				this.toggleFade()
				this.toggleAutoPlay()
				return false
			}

			let newSettings = Object.assign({}, this.initialSettings)
			delete newSettings.responsive

			this.initialSettings.responsive.forEach(option => {
				if (this.initialSettings.mobileFirst ? option.breakpoint < this.widthWindow : option.breakpoint > this.widthWindow) {
					for (let key in option.settings) {
						newSettings[key] = option.settings[key]
					}
				}
			})

			this.settings = Object.assign({}, newSettings)
		},

		/**
		 * Prepare slides classes and styles
		 */
		prepareSlides () {
			if (this.ssr) {
				return false
			}

			this.slides = this.htmlCollectionToArray(this.$refs.slides.children)

			// Probably timeout needed
			if (this.clonedSlides) {
				this.slidesClonedBefore = this.htmlCollectionToArray(this.$refs.slidesClonedBefore.children)
				this.slidesClonedAfter = this.htmlCollectionToArray(this.$refs.slidesClonedAfter.children)
			}

			for (let slide of this.allSlides) {
				slide.classList.add('agile__slide')
			}
		},

		/**
		 *  Prepare slides active/current classes
		 */
		prepareSlidesClasses () {
			if (this.currentSlide === null) {
				return false
			}

			// Remove active & current classes
			for (let i = 0; i < this.slidesCount; i++) {
				this.slides[i].classList.remove('agile__slide--active')
				this.slides[i].classList.remove('agile__slide--current')
			}

			// Add active & current class for current slide
			setTimeout(() => this.slides[this.currentSlide].classList.add('agile__slide--active'), this.changeDelay)

			let start = (this.clonedSlides) ? this.slidesCount + this.currentSlide : this.currentSlide

			if (this.centerMode) {
				start -= (Math.floor(this.settings.slidesToShow / 2) - +(this.settings.slidesToShow % 2 === 0))
			}

			// To account for the combination of infinite = false and centerMode = true, ensure we don't overrun the bounds of the slide count.
			for (let i = Math.max(start, 0); i < Math.min(start + this.settings.slidesToShow, this.slidesCount); i++) {
				this.allSlides[i].classList.add('agile__slide--current')
			}
		},

		/**
		 * Prepare carousel styles
		 */
		prepareCarousel () {
			this.widthSlide = !this.settings.unagile ? this.widthContainer / this.settings.slidesToShow : 'auto'

			// Actions on document resize
			for (let i = 0; i < this.allSlidesCount; i++) {
				this.allSlides[i].style.width = (this.settings.unagile) ? '' : this.widthSlide + 'px'
			}

			// Prepare track
			if (this.settings.unagile) {
				this.translateX = 0
			} else {
				if (this.currentSlide === null && this.slidesCount) {
					this.currentSlide = this.settings.initialSlide
				}

				this.goTo(this.currentSlide, false, false)
			}
		}
	}
}

export default mixin
<commit_msg>Slide preparing on server side<commit_after>/**
 * Carousel preparation methods
 */
const mixin = {
	methods: {
		/**
		 * Prepare settings object
		 */
		prepareSettings () {
			if (!this.initialSettings.responsive) {
				this.toggleFade()
				this.toggleAutoPlay()
				return false
			}

			let newSettings = Object.assign({}, this.initialSettings)
			delete newSettings.responsive

			this.initialSettings.responsive.forEach(option => {
				if (this.initialSettings.mobileFirst ? option.breakpoint < this.widthWindow : option.breakpoint > this.widthWindow) {
					for (let key in option.settings) {
						newSettings[key] = option.settings[key]
					}
				}
			})

			this.settings = Object.assign({}, newSettings)
		},

		/**
		 * Prepare slides classes and styles
		 */
		prepareSlides () {
			this.slides = this.htmlCollectionToArray(this.$slots.default)

			// Probably timeout needed
			if (!this.ssr && this.clonedSlides) {
				this.slidesClonedBefore = this.htmlCollectionToArray(this.$refs.slidesClonedBefore.children)
				this.slidesClonedAfter = this.htmlCollectionToArray(this.$refs.slidesClonedAfter.children)
			}

			for (let slide of this.allSlides) {
				slide.classList.add('agile__slide')
			}
		},

		/**
		 *  Prepare slides active/current classes
		 */
		prepareSlidesClasses () {
			if (this.currentSlide === null) {
				return false
			}

			// Remove active & current classes
			for (let i = 0; i < this.slidesCount; i++) {
				this.slides[i].classList.remove('agile__slide--active')
				this.slides[i].classList.remove('agile__slide--current')
			}

			// Add active & current class for current slide
			setTimeout(() => this.slides[this.currentSlide].classList.add('agile__slide--active'), this.changeDelay)

			let start = (this.clonedSlides) ? this.slidesCount + this.currentSlide : this.currentSlide

			if (this.centerMode) {
				start -= (Math.floor(this.settings.slidesToShow / 2) - +(this.settings.slidesToShow % 2 === 0))
			}

			// To account for the combination of infinite = false and centerMode = true, ensure we don't overrun the bounds of the slide count.
			for (let i = Math.max(start, 0); i < Math.min(start + this.settings.slidesToShow, this.slidesCount); i++) {
				this.allSlides[i].classList.add('agile__slide--current')
			}
		},

		/**
		 * Prepare carousel styles
		 */
		prepareCarousel () {
			this.widthSlide = !this.settings.unagile ? this.widthContainer / this.settings.slidesToShow : 'auto'

			// Actions on document resize
			for (let i = 0; i < this.allSlidesCount; i++) {
				this.allSlides[i].style.width = (this.settings.unagile) ? '' : this.widthSlide + 'px'
			}

			// Prepare track
			if (this.settings.unagile) {
				this.translateX = 0
			} else {
				if (this.currentSlide === null && this.slidesCount) {
					this.currentSlide = this.settings.initialSlide
				}

				this.goTo(this.currentSlide, false, false)
			}
		}
	}
}

export default mixin
<|endoftext|>


<commit_before>$(document).ready(function() {
  // preloader 가동하기
  // $('#modal2').openModal();

  $('.button-collapse').sideNav({
      menuWidth : 240,
      activationWidth : 70
  });

  $('.grid').isotope({
          itemSelector : '.grid-item',
          masonry : {
              columnWidth : 50,
              gutter : 10
          }
      });

  // 사용할 앱의 JavaScript 키를 설정해 주세요.
  Kakao.init('d0dd75755ece80295a757c6042496f9b');

  //URL 파싱하기
  var $search = function() {
    var s = window.location.search.substr(1),p = s.split(/\&/),l = p.length,kv,r = {};
    if (l === 0) {return false;}
    while (l--) {
      kv = p[l].split(/\=/);
      r[kv[0]] = decodeURIComponent(kv[1] || '') || true;
    }
    return r;
  }();

    var url = "http://munsangdong.cafe24.com/api/card";
    var callApi = function( url, successFn ) {
        $.ajax({
            type : 'GET',
            url : url,
            dataType : "json",
            success : successFn
        });
    };

    // #ID를 달고 브라우저를 직접 접속했을 때, hash를 ?id= 로 리다이렉트 시키는 것이 필요함.
    if( window.location.hash !== "" ) {
      var URLis = "?id=" + window.location.hash.substr(1);
      $("#FeviCard").empty();

      callApi( url + URLis, response_id );
    //   console.log(window.location.search);
    //
    } else {
      callApi( url + window.location.search, response_json );
    }

    // addMore 버튼을 누르면 카드를 10개 더 추가한다.
    var addMoreCard = function( e ){
      var pageNm = $("#currentPage").text();
      var pageNmInt = Number(pageNm) + 1;
      // console.log(pageNmInt);
      var nextPageUrl = "?size=5&page=" + pageNmInt;
      $("#addMore").remove();
      callApi(url + nextPageUrl, response_json);
    };

    // 카드를 누르면 카드가 확대된다.
    $("body").on("click", ".activator", function ( e ){
      window.location.hash = $(this).parents('div[id]').attr('id');
      $(this).parents(".grid-item").removeClass("grid-item s12 m12 l3").addClass("expanded s12 m12 l12");

      // 클릭시 비디오가 플레이 된다.
      // 모바일에서는 지극히 느려져서.. 삭제
        // var $play = $(this).parents('.card').children('div.card-reveal').children('video').get(0);
        // $play.play();

      $('.grid').isotope();
    });

    // 닫기를 누르면 카드가 다시 작아진다.
    var contractCard = function() {
      //비디오는 플레이가 중지된다.
      var $pause = $(document).find('.expanded').find('video').get(0);
      $pause.pause();

      $(document).find(".expanded").removeClass("expanded s12 m12 l12").addClass("grid-item s12 m12 l3");
      // 카드의 해쉬 값을 삭제한다.
      window.location.hash = []
      /* refrence 부분 클릭시 이동하는 높이값 수정 */
        var tr;
        setTimeout(function(){
          tr=$('body').scrollTop()-100;
        },100);

        setTimeout(function(){
          $('body').scrollTop(tr);
        },200);

      // 카드를 재 정렬한다.
      $('.grid').isotope();
      };
    // 카드를 닫기를 누르면 닫힌다.
    $( "body" ).on( "click", "div.card-reveal > span", function( e ) {
      contractCard();
    });

    //esc를 누르면 닫힌다.
    document.onkeydown = function(evt) {
    evt = evt || window.event;
    if (evt.keyCode == 27) {
        contractCard();
    }
  };

    // 공유 버튼을 누르면 모달 팝업이 뜬다.
    $("body").on("click", "i.sharing", function(e){
      var shareId = $(this).attr("data-id");
      console.log(shareId);
      callApi(url + "?id=" + shareId, response_share);
      $('#modal1').openModal();
    });

    function response_json(json) {
        var video_list = json.content;
        var addMore = "
" +
          "
" +
            "
playlist_add
" +
          "
"+
        "
";

        video_list.forEach(function(v, i) {
            var item = v;
            // 카드를 구성한다
            var card = "
" +
                "
" +
                    "
" +
                            "" +
                            "" + item.category + "play_circle_filled" +
                    "
" +
                    "
" +
                        " " + item.name + "" +
                            "
" + item.description + "
" +
                    "
" +
                    "
" + item.category + "close"+
                    ""+
                      // ""+
                      // "share" +
                      // ""+
                        "<video width='100%' controls loop preload='auto' poster='" + item.picture + "' src='" + item.source + "'>" +
                        "</video>"+
                        "

" +
                            "[공유하기] " + item.name + "" +
                            "
" + item.description + "
"+
                            "send"+
                            "

" +
                    "
" +
                  "
" ;

                  Kakao.Link.createTalkLinkButton({
                    container: '#sendkakao',
                    image: {
                      src: item.picture,
                      width: item.width,
                      height: item.height
                    },
                    label: item.description,
                    webButton: {
                      text: item.name,
                      url: window.location.href + "?utm_source=kakaoLink&utm_medium=social" // 앱 설정의 웹 플랫폼에 등록한 도메인의 URL이어야 합니다.
                    },
                    fail: console.log('모바일에서 사용하시기 바랍니다.')
                    // webLink : {
                    //   text: item.name,
                    //   url: 'http://facebook.com/' + item.id
                    // }
                  });

                  Kakao.Link.cleanup();

            //카드를 화면에 표시한다.
            $('.grid').isotope('insert', $(card));
        });

        // $("#FeviCard").append(addMore);
        $('.grid').isotope('insert', $(addMore));

        //page 및 각종 앨리먼트 정보를 표시한다.
        $("#totalElements").text(json.totalElements);
        $("#totalPages").text(json.totalPages);
        $("#cardSize").text(json.size);
        $("#currentPage").text(json.number);
        $("#firstPage").text(json.first);
        $("#lastPage").text(json.last);

        $('.grid').imagesLoaded().done(function() {
          // $('#modal2').closeModal();
          $('.grid').isotope();
        });

    };

    function response_id (json) {
      $("#addMoreCircle").remove();
        var video_list = json.content;
        video_list.forEach(function(v, i) {
            var item = v;
            // 카드를 구성한다
            var card = "
" +
                    "
" +
                        "<video class='video-js vjs-default-skin' controls loop preload='auto' poster='" + item.picture + "' src='" + item.source + "' width='100%' >" +
                        "</video>" +
                        "
" +
                          "
"+
                          "" + item.category + "share"+
                          "
"+
                          "
" +
                              "" + item.name + "" +
                              "
updated: " + item.updated_time + "
" +
                                  "created: " + item.created_time + "
"+
                              "send"+
                          "
"+
                          "
play_arrow"+
                            "Description" +
                            "
"+ item.description +"
"+
                          "
"+
                          "
add"+
                            "더 많은 동영상 보기" +
                            "
FEVI에서 더 많은 영상을 볼 수 있습니다. 지금 FEVI를 방문하세요!
"+
                          "
"+
                        "
" +
                    "
"+
                  "
" ;

            //카드를 화면에 표시한다.
            $('.grid').isotope('insert', $(card));

            //ID로 접속한 경우에는 페이지 정보는 삭제한다.
            $("#video_list").remove();

            // ID 별로 파라메터를 따로 설정을 한다.
            var virtualPvByParam =  "index.html?id=" + item.id;
            console.log(virtualPvByParam);
            ga('send', 'pageview', virtualPvByParam);
        });
      }

    // google-analytics 카드 어디를 누를지 체크
    $("body").on("click", ".activator", function ( e ){
      var contentID = $(this).parents('div[id]').attr('id');
      var clickedPath = $(this).attr('alt');
      ga('send', 'event', "card-reveal", clickedPath, contentID  );
      });

    // 카드를 눌렀을 때는 해당 카드의 PV를 따로 잡는다.
    // hash를 따로 달고 날아오는 경우와 동일하게 통계를 잡는다.
    $("body").on("click", ".activator", function ( e ){
      var contentID = $(this).parents('div[id]').attr('id');
      var virtualPvByID = "index.html?id=" + contentID;
      console.log(virtualPvByID);
      ga('send', 'pageview', virtualPvByID);
    });

    // addmore 버튼 큰 것을 누르면 여기로 통계를 잡는다.
    $("body").on("click", "#addMore", function(){
      addMoreCard();
      ga('send', 'event', "Add More", "click-cardbtn" );

    });

    // addmore 버튼 작은 것은 여기서 통계를 잡는다.
    $("#addMoreCircle").click(function(){
      addMoreCard();
      ga('send', 'event', "Add More", "click-Floating" );
    });

    //google-analytics 비디오 플레이를 눌렀는지 체크
    $('body').on('click', '.card-reveal', function(e){
    //   var videID = $(this).parent().attr('data-id');
      // console.log(this);
    });

    // 하단 fix 버튼 클릭시 움직임
    $('#scrollTop').click(function(){
      $('html, body').animate({ scrollTop: 0}, "slow");
      return false;
    });

    // 더보기 버튼을 어떤 것을 많이 누를까?

});
<commit_msg>카카오링크 수정<commit_after>$(document).ready(function() {
  // preloader 가동하기
  // $('#modal2').openModal();

  $('.button-collapse').sideNav({
      menuWidth : 240,
      activationWidth : 70
  });

  $('.grid').isotope({
          itemSelector : '.grid-item',
          masonry : {
              columnWidth : 50,
              gutter : 10
          }
      });

  // 사용할 앱의 JavaScript 키를 설정해 주세요.
  Kakao.init('d0dd75755ece80295a757c6042496f9b');

  //URL 파싱하기
  var $search = function() {
    var s = window.location.search.substr(1),p = s.split(/\&/),l = p.length,kv,r = {};
    if (l === 0) {return false;}
    while (l--) {
      kv = p[l].split(/\=/);
      r[kv[0]] = decodeURIComponent(kv[1] || '') || true;
    }
    return r;
  }();

    var url = "http://munsangdong.cafe24.com/api/card";
    var callApi = function( url, successFn ) {
        $.ajax({
            type : 'GET',
            url : url,
            dataType : "json",
            success : successFn
        });
    };

    // #ID를 달고 브라우저를 직접 접속했을 때, hash를 ?id= 로 리다이렉트 시키는 것이 필요함.
    if( window.location.hash !== "" ) {
      var URLis = "?id=" + window.location.hash.substr(1);
      $("#FeviCard").empty();

      callApi( url + URLis, response_id );
    //   console.log(window.location.search);
    //
    } else {
      callApi( url + window.location.search, response_json );
    }

    // addMore 버튼을 누르면 카드를 10개 더 추가한다.
    var addMoreCard = function( e ){
      var pageNm = $("#currentPage").text();
      var pageNmInt = Number(pageNm) + 1;
      // console.log(pageNmInt);
      var nextPageUrl = "?size=5&page=" + pageNmInt;
      $("#addMore").remove();
      callApi(url + nextPageUrl, response_json);
    };

    // 카드를 누르면 카드가 확대된다.
    $("body").on("click", ".activator", function ( e ){
      window.location.hash = $(this).parents('div[id]').attr('id');
      $(this).parents(".grid-item").removeClass("grid-item s12 m12 l3").addClass("expanded s12 m12 l12");

      // 클릭시 비디오가 플레이 된다.
      // 모바일에서는 지극히 느려져서.. 삭제
        // var $play = $(this).parents('.card').children('div.card-reveal').children('video').get(0);
        // $play.play();

      $('.grid').isotope();
    });

    // 닫기를 누르면 카드가 다시 작아진다.
    var contractCard = function() {
      //비디오는 플레이가 중지된다.
      var $pause = $(document).find('.expanded').find('video').get(0);
      $pause.pause();

      $(document).find(".expanded").removeClass("expanded s12 m12 l12").addClass("grid-item s12 m12 l3");
      // 카드의 해쉬 값을 삭제한다.
      window.location.hash = []
      /* refrence 부분 클릭시 이동하는 높이값 수정 */
        var tr;
        setTimeout(function(){
          tr=$('body').scrollTop()-100;
        },100);

        setTimeout(function(){
          $('body').scrollTop(tr);
        },200);

      // 카드를 재 정렬한다.
      $('.grid').isotope();
      };
    // 카드를 닫기를 누르면 닫힌다.
    $( "body" ).on( "click", "div.card-reveal > span", function( e ) {
      contractCard();
    });

    //esc를 누르면 닫힌다.
    document.onkeydown = function(evt) {
    evt = evt || window.event;
    if (evt.keyCode == 27) {
        contractCard();
    }
  };

    // 카카오 공유 공유 버튼을 누르면 모달 팝업이 뜬다.
    $("body").on("click", ".sendkakao", function(e){
      var shareId = $(this).attr("data-id");
      callApi(url + "?id=" + shareId, response_share);
    });

    function response_share(json) {

      var video_list = json.content;
        video_list.forEach(function(v, i) {
            var item = v;
            $('.sendkakao').click(function() {
              // 카카오톡 링크 버튼을 생성합니다. 처음 한번만 호출하면 됩니다.
              Kakao.Link.sendTalkLink({
                label: item.description,
                image: {
                  src: item.picture,
                  width: item.width,
                  height: item.height
                },
                webButton: {
                  text: item.name,
                  url: window.location.href + "?utm_source=kakaoLink&utm_medium=social" // 앱 설정의 웹 플랫폼에 등록한 도메인의 URL이어야 합니다.
                },
                fail: console.log('카카오톡 링크는 카카오톡 앱이 설치되어 있는 모바일 기기에서만 전송 가능합니다.')
                // webLink : {
                //   text: item.name,
                //   url: 'http://facebook.com/' + item.id
                // }
              });
              Kakao.Link.cleanup();
            });
          });
        }

    function response_json(json) {
        var video_list = json.content;
        var addMore = "
" +
          "
" +
            "
playlist_add
" +
          "
"+
        "
";

        video_list.forEach(function(v, i) {
            var item = v;
            // 카드를 구성한다
            var card = "
" +
                "
" +
                    "
" +
                            "" +
                            "" + item.category + "play_circle_filled" +
                    "
" +
                    "
" +
                        " " + item.name + "" +
                            "
" + item.description + "
" +
                    "
" +
                    "
" + item.category + "close"+
                    ""+
                      // ""+
                      // "share" +
                      // ""+
                        "<video width='100%' controls loop preload='auto' poster='" + item.picture + "' src='" + item.source + "'>" +
                        "</video>"+
                        "

" +
                            "[공유하기] " + item.name + "" +
                            "
" + item.description + "
"+
                            "send"+
                            "

" +
                    "
" +
                  "
" ;

            //카드를 화면에 표시한다.
            $('.grid').isotope('insert', $(card));
        });

        // $("#FeviCard").append(addMore);
        $('.grid').isotope('insert', $(addMore));

        //page 및 각종 앨리먼트 정보를 표시한다.
        $("#totalElements").text(json.totalElements);
        $("#totalPages").text(json.totalPages);
        $("#cardSize").text(json.size);
        $("#currentPage").text(json.number);
        $("#firstPage").text(json.first);
        $("#lastPage").text(json.last);

        $('.grid').imagesLoaded().done(function() {
          // $('#modal2').closeModal();
          $('.grid').isotope();
        });

    };

    function response_id (json) {
      $("#addMoreCircle").remove();
        var video_list = json.content;
        video_list.forEach(function(v, i) {
            var item = v;
            // 카드를 구성한다
            var card = "
" +
                    "
" +
                        "<video class='video-js vjs-default-skin' controls loop preload='auto' poster='" + item.picture + "' src='" + item.source + "' width='100%' >" +
                        "</video>" +
                        "
" +
                          "
"+
                          "" + item.category + "share"+
                          "
"+
                          "
" +
                              "" + item.name + "" +
                              "
updated: " + item.updated_time + "
" +
                                  "created: " + item.created_time + "
"+
                              "send"+
                          "
"+
                          "
play_arrow"+
                            "Description" +
                            "
"+ item.description +"
"+
                          "
"+
                          "
add"+
                            "더 많은 동영상 보기" +
                            "
FEVI에서 더 많은 영상을 볼 수 있습니다. 지금 FEVI를 방문하세요!
"+
                          "
"+
                        "
" +
                    "
"+
                  "
" ;

            //카드를 화면에 표시한다.
            $('.grid').isotope('insert', $(card));

            //ID로 접속한 경우에는 페이지 정보는 삭제한다.
            $("#video_list").remove();

            // ID 별로 파라메터를 따로 설정을 한다.
            var virtualPvByParam =  "index.html?id=" + item.id;
            console.log(virtualPvByParam);
            ga('send', 'pageview', virtualPvByParam);
        });
      }

    // google-analytics 카드 어디를 누를지 체크
    $("body").on("click", ".activator", function ( e ){
      var contentID = $(this).parents('div[id]').attr('id');
      var clickedPath = $(this).attr('alt');
      ga('send', 'event', "card-reveal", clickedPath, contentID  );
      });

    // 카드를 눌렀을 때는 해당 카드의 PV를 따로 잡는다.
    // hash를 따로 달고 날아오는 경우와 동일하게 통계를 잡는다.
    $("body").on("click", ".activator", function ( e ){
      var contentID = $(this).parents('div[id]').attr('id');
      var virtualPvByID = "index.html?id=" + contentID;
      console.log(virtualPvByID);
      ga('send', 'pageview', virtualPvByID);
    });

    // addmore 버튼 큰 것을 누르면 여기로 통계를 잡는다.
    $("body").on("click", "#addMore", function(){
      addMoreCard();
      ga('send', 'event', "Add More", "click-cardbtn" );

    });

    // addmore 버튼 작은 것은 여기서 통계를 잡는다.
    $("#addMoreCircle").click(function(){
      addMoreCard();
      ga('send', 'event', "Add More", "click-Floating" );
    });

    //google-analytics 비디오 플레이를 눌렀는지 체크
    $('body').on('click', '.card-reveal', function(e){
    //   var videID = $(this).parent().attr('data-id');
      // console.log(this);
    });

    // 하단 fix 버튼 클릭시 움직임
    $('#scrollTop').click(function(){
      $('html, body').animate({ scrollTop: 0}, "slow");
      return false;
    });

    // 더보기 버튼을 어떤 것을 많이 누를까?

});
<|endoftext|>


<commit_before>$(document).ready(function() {
    $('.button-collapse').sideNav();
});

//GA Tracking
(function(i,s,o,g,r,a,m){i['GoogleAnalyticsObject']=r;i[r]=i[r]||function(){
(i[r].q=i[r].q||[]).push(arguments)},i[r].l=1*new Date();a=s.createElement(o),
m=s.getElementsByTagName(o)[0];a.async=1;a.src=g;m.parentNode.insertBefore(a,m)
})(window,document,'script','//www.google-analytics.com/analytics.js','ga');

ga('create', 'UA-59224610-1', 'auto');
ga('send', 'pageview');<commit_msg>Revert "+ GA"<commit_after>$(document).ready(function() {
    $('.button-collapse').sideNav();
});<|endoftext|>


<commit_before>(function($){
  $(function(){

    $('.button-collapse').sideNav();
    $('.parallax').parallax();
    $('.scrollspy').scrollSpy();

    var fname, lname, email, messsage;
    $("input:radio[name=group1]").click(function() {
        subject = $(this).val();
    });
    $("#submit-button").click(function() {
        fname = $("#first_name").val();
        lname = $("#last_name").val();
        email = $("#email").val();
        message = $("#message").val();
        $.post("https://tranquil-cove-4564.herokuapp.com/sendmsg", {
            furstname: name,
            lastname: phone,
            email: subject,
            msg: message
        }, function(data) {
            Materialize.toast('Your message has been delivered!', 4000);
            $("#first_name").val('');
            $("#last_name").val('');
            $("#email").val('');
            $("#message").val('');
        });
    });

  });
})(jQuery);<commit_msg>Added email server<commit_after>(function($){
  $(function(){

    $('.button-collapse').sideNav();
    $('.parallax').parallax();
    $('.scrollspy').scrollSpy();

    var fname, lname, email, messsage;
    $("input:radio[name=group1]").click(function() {
        subject = $(this).val();
    });
    $("#submit-button").click(function() {
        fname = $("#first_name").val();
        lname = $("#last_name").val();
        email = $("#email").val();
        message = $("#message").val();
        $.post("https://tranquil-cove-4564.herokuapp.com/sendmsg", {
            firstname: fname,
            lastname: lname,
            email: email,
            msg: message
        }, function(data) {
            Materialize.toast('Your message has been delivered!', 4000);
            $("#first_name").val('');
            $("#last_name").val('');
            $("#email").val('');
            $("#message").val('');
        });
    });

  });
})(jQuery);<|endoftext|>


<commit_before>/**
 * init.js
 * -------
 * Author & Copyright (c) 2013: Nathan Davies, www.nathandavies.co.uk
 */

jQuery(function($) {
    // Elements
    var heading = $('h1'),
        message,
        start;

    // Level of logging
    if (!isNaN(URLParameters.log))
        Utilities.Trace.level = URLParameters.log;

    // Remove body scripts
    $('body script').remove();

    // Show the start button
    start = $(Mustache.render(HTML.div,{id:'start',content:'Start'})).insertAfter(heading);
    start.bind('click initiation', function() {
        $(this).remove();
        InitiateGame();
    });

    // Initiate the game
    function InitiateGame(bypassHost) {
        // Loading indicator
        Loader.Start();

        // Peers
        PeerHandler.peer = new Peer({host:'peer.nathandavies.co.uk'});
        PeerHandler.peer.on('open', function(id) {
            Trace.Information('Local peer identifier: '+id);

            // Connect to hosting peer?
            if (URLParameters.session && !bypassHost) {
                PeerHandler.connection = PeerHandler.peer.connect(URLParameters.session);
                Trace.Information('Connecting to peer: '+PeerHandler.connection.peer);

                // Open the game
                PeerHandler.connection.on('open', function() {
                    PeerHandler.connection.on('data', function(data) {
                        data = $.parseJSON(data);

                        if (data.state == 'initiation')
                            new Game();
                        else if (data.state == 'gameisfull')
                            SessionIssue('Session is full');
                    });
                });
            }
            else
                new Game();
        }).on('error', function(error) {
            // Session outdated?
            if (!error.type)
                SessionIssue('Session no longer exists');
            else
                ShowError('Technical difficulties =(', 'Error establishing a peer connection; '+error.type);
        });
    }

    // If a session identifier has been supplied, auto-start the initiation
    if (URLParameters.session)
        start.trigger('initiation');

    // New session option
    function SessionIssue(error) {
        ShowError(error);
        PeerHandler.connection = null;

        // New session
        var newSession = $(Mustache.render(HTML.div,{id:'newsession',content:'+ New session'})).insertAfter(message);
        newSession.bind('click', function() {
            $(this).remove();
            message.remove();
            InitiateGame(true);
        });
    }

    // Show error
    function ShowError(error, trace) {
        // Trace error
        Trace.Error((!trace) ? error : trace);

        // Stop the loader, and display the error
        Loader.Stop();
        message = $(Mustache.render(HTML.div,{id:'message',content:error})).insertAfter('h1');
    }
});<commit_msg>Updating Peer URL<commit_after>/**
 * init.js
 * -------
 * Author & Copyright (c) 2013: Nathan Davies, www.nathandavies.co.uk
 */

jQuery(function($) {
    // Elements
    var heading = $('h1'),
        message,
        start;

    // Level of logging
    if (!isNaN(URLParameters.log))
        Utilities.Trace.level = URLParameters.log;

    // Remove body scripts
    $('body script').remove();

    // Show the start button
    start = $(Mustache.render(HTML.div,{id:'start',content:'Start'})).insertAfter(heading);
    start.bind('click initiation', function() {
        $(this).remove();
        InitiateGame();
    });

    // Initiate the game
    function InitiateGame(bypassHost) {
        // Loading indicator
        Loader.Start();

        // Peers
        PeerHandler.peer = new Peer({host:'peer.nathandavies.ninja'});
        PeerHandler.peer.on('open', function(id) {
            Trace.Information('Local peer identifier: '+id);

            // Connect to hosting peer?
            if (URLParameters.session && !bypassHost) {
                PeerHandler.connection = PeerHandler.peer.connect(URLParameters.session);
                Trace.Information('Connecting to peer: '+PeerHandler.connection.peer);

                // Open the game
                PeerHandler.connection.on('open', function() {
                    PeerHandler.connection.on('data', function(data) {
                        data = $.parseJSON(data);

                        if (data.state == 'initiation')
                            new Game();
                        else if (data.state == 'gameisfull')
                            SessionIssue('Session is full');
                    });
                });
            }
            else
                new Game();
        }).on('error', function(error) {
            // Session outdated?
            if (!error.type)
                SessionIssue('Session no longer exists');
            else
                ShowError('Technical difficulties =(', 'Error establishing a peer connection; '+error.type);
        });
    }

    // If a session identifier has been supplied, auto-start the initiation
    if (URLParameters.session)
        start.trigger('initiation');

    // New session option
    function SessionIssue(error) {
        ShowError(error);
        PeerHandler.connection = null;

        // New session
        var newSession = $(Mustache.render(HTML.div,{id:'newsession',content:'+ New session'})).insertAfter(message);
        newSession.bind('click', function() {
            $(this).remove();
            message.remove();
            InitiateGame(true);
        });
    }

    // Show error
    function ShowError(error, trace) {
        // Trace error
        Trace.Error((!trace) ? error : trace);

        // Stop the loader, and display the error
        Loader.Stop();
        message = $(Mustache.render(HTML.div,{id:'message',content:error})).insertAfter('h1');
    }
});<|endoftext|>


<commit_before>import { createMaze } from './maze';
import { Bullet } from './bullet';
import { Human } from './human';
import { createImages } from './img';
import { kladKeys } from './keys';
import { levels } from './levels';

export class Klad {
    constructor(context) {
        context.addEventListener('DOMContentLoaded',
            function () {
                var GAME_MODE_LOSE = 1,
                    GAME_MODE_GAME = 2,
                    GAME_MODE_FINISH = 3,
                    gameMode = GAME_MODE_GAME,
                    currentLevel = 0,
                    ctx = context.getElementById('canvas').getContext('2d'),
                    delayUpdate = 0,
                    delayUpdateAliens = 0,
                    maze = createMaze(),
                    player = new Human(false, maze),
                    alien = new Human(true, maze),
                    alien1 = null,
                    bullet = new Bullet(maze),
                    images = createImages();

                function restartLevel() {
                    maze.loadLevel(currentLevel, levels);
                    bullet = new Bullet(maze);
                    player.resetFinished();
                    player.respawn(levels[currentLevel].player.x, levels[currentLevel].player.y);
                    player.resetKeyFound();
                    alien.respawn(levels[currentLevel].aliens[0].x, levels[currentLevel].aliens[0].y);
                    alien1 = null;
                    if (levels[currentLevel].aliens[1]) {
                        alien1 = new Human(true, maze);
                        alien1.respawn(levels[currentLevel].aliens[1].x, levels[currentLevel].aliens[1].y);
                    }
                }

                function updateLose() {
                    if (delayUpdate < 60) {
                        delayUpdate += 1;
                        return;
                    }
                    gameMode = GAME_MODE_GAME;
                    restartLevel();
                }

                function updateFinish() {
                    if (delayUpdate < 30) {
                        delayUpdate += 1;
                        return;
                    }
                    gameMode = GAME_MODE_GAME;
                    currentLevel += 1;
                    if (currentLevel >= 5) {
                        currentLevel = 0;
                    }
                    restartLevel();
                }

                function updateGame() {
                    delayUpdate += 1;
                    if (delayUpdate < 2) {
                        return;
                    }
                    delayUpdate = 0;

                    delayUpdateAliens += 1;
                    if (delayUpdateAliens > 2) {
                        delayUpdateAliens = 0;
                    } else {
                        alien.moveToHuman(player);
                        if (alien1) {
                            alien1.moveToHuman(player);
                        }
                    }

                    var caught = player.caught(alien);
                    if (alien1) {
                        if (alien1.caught(player)) {
                            caught = true;
                        }
                    }

                    if (caught) {
                        player.kill();
                        alien.kill();
                        if (alien1) {
                            alien1.kill();
                        }
                    }

                    bullet.move();
                    maze.wallRegen();

                    player.move(kladKeys.isDown(kladKeys.LEFT),
                        kladKeys.isDown(kladKeys.RIGHT),
                        kladKeys.isDown(kladKeys.UP),
                        kladKeys.isDown(kladKeys.DOWN));

                    if (kladKeys.isDown(kladKeys.FIRE_LEFT)) {
                        bullet.shotLeft(player.getPos());
                    }
                    if (kladKeys.isDown(kladKeys.FIRE_RIGHT)) {
                        bullet.shotRight(player.getPos());
                    }

                    if (player.isFinished()) {
                        gameMode = GAME_MODE_FINISH;
                        return;
                    }

                    if (player.isDead()) {
                        gameMode = GAME_MODE_LOSE;
                    }
                }

                function update() {
                    switch (gameMode) {
                        case GAME_MODE_LOSE:
                            updateLose();
                            break;
                        case GAME_MODE_GAME:
                            updateGame();
                            break;
                        case GAME_MODE_FINISH:
                            updateFinish();
                            break;
                    }
                }

                function render() {
                    maze.render(ctx, images);
                    player.render(ctx, images);
                    alien.render(ctx, images);
                    if (alien1) {
                        alien1.render(ctx, images);
                    }
                    bullet.render(ctx, images);
                }

                function frame() {
                    update();
                    render();
                    requestAnimationFrame(frame);
                }

                window.addEventListener('keyup', function (event) {
                    kladKeys.onKeyup(event);
                }, false);

                window.addEventListener('keydown', function (event) {
                    kladKeys.onKeydown(event);
                }, false);

                window.onblur = function () {
                    kladKeys.reset();
                };

                ctx.scale(2, 2);
                restartLevel();
                requestAnimationFrame(frame);
            });

    }
}
<commit_msg>Refactor main module to class style<commit_after>import { createMaze } from './maze';
import { Bullet } from './bullet';
import { Human } from './human';
import { createImages } from './img';
import { kladKeys } from './keys';
import { levels } from './levels';

const GAME_MODE_LOSE = 1;
const GAME_MODE_GAME = 2;
const GAME_MODE_FINISH = 3;

export class Klad {

    constructor(context) {
        var that = this;
        document.addEventListener('DOMContentLoaded', function () {
            that.run(context);
        });
    }

    run(context) {
        this.gameMode = GAME_MODE_GAME;
        this.currentLevel = 0;
        this.ctx = context.getElementById('canvas').getContext('2d');
        this.delayUpdate = 0;
        this.delayUpdateAliens = 0;
        this.maze = createMaze();
        this.player = new Human(false, this.maze);
        this.alien = new Human(true, this.maze);
        this.alien1 = null;
        this.bullet = new Bullet(this.maze);
        this.images = createImages();

        context.addEventListener('keyup', function (event) {
            kladKeys.onKeyup(event);
        }, false);

        context.addEventListener('keydown', function (event) {
            kladKeys.onKeydown(event);
        }, false);

        context.onblur = function () {
            kladKeys.reset();
        };

        this.ctx.scale(2, 2);
        this.restartLevel();
        requestAnimationFrame(this.frame.bind(this));
    }

    restartLevel() {
        this.maze.loadLevel(this.currentLevel, levels);
        this.bullet = new Bullet(this.maze);
        this.player.resetFinished();
        this.player.respawn(levels[this.currentLevel].player.x, levels[this.currentLevel].player.y);
        this.player.resetKeyFound();
        this.alien.respawn(levels[this.currentLevel].aliens[0].x, levels[this.currentLevel].aliens[0].y);
        this.alien1 = null;
        if (levels[this.currentLevel].aliens[1]) {
            this.alien1 = new Human(true, this.maze);
            this.alien1.respawn(levels[this.currentLevel].aliens[1].x, levels[this.currentLevel].aliens[1].y);
        }
    }

    updateLose() {
        if (this.delayUpdate < 60) {
            this.delayUpdate += 1;
            return;
        }
        this.gameMode = GAME_MODE_GAME;
        restartLevel();
    }

    updateFinish() {
        if (this.delayUpdate < 30) {
            this.delayUpdate += 1;
            return;
        }
        this.gameMode = GAME_MODE_GAME;
        this.currentLevel += 1;
        if (this.currentLevel >= 5) {
            this.currentLevel = 0;
        }
        restartLevel();
    }

    updateGame() {
        this.delayUpdate += 1;
        if (this.delayUpdate < 2) {
            return;
        }
        this.delayUpdate = 0;

        this.delayUpdateAliens += 1;
        if (this.delayUpdateAliens > 2) {
            this.delayUpdateAliens = 0;
        } else {
            this.alien.moveToHuman(this.player);
            if (this.alien1) {
                this.alien1.moveToHuman(this.player);
            }
        }

        let caught = this.player.caught(this.alien);
        if (this.alien1) {
            if (this.alien1.caught(this.player)) {
                caught = true;
            }
        }

        if (caught) {
            this.player.kill();
            this.alien.kill();
            if (this.alien1) {
                this.alien1.kill();
            }
        }

        this.bullet.move();
        this.maze.wallRegen();

        this.player.move(kladKeys.isDown(kladKeys.LEFT),
            kladKeys.isDown(kladKeys.RIGHT),
            kladKeys.isDown(kladKeys.UP),
            kladKeys.isDown(kladKeys.DOWN));

        if (kladKeys.isDown(kladKeys.FIRE_LEFT)) {
            this.bullet.shotLeft(this.player.getPos());
        }
        if (kladKeys.isDown(kladKeys.FIRE_RIGHT)) {
            this.bullet.shotRight(this.player.getPos());
        }

        if (this.player.isFinished()) {
            this.gameMode = GAME_MODE_FINISH;
            return;
        }

        if (this.player.isDead()) {
            this.gameMode = GAME_MODE_LOSE;
        }
    }

    update() {
        switch (this.gameMode) {
            case GAME_MODE_LOSE:
                this.updateLose();
                break;
            case GAME_MODE_GAME:
                this.updateGame();
                break;
            case GAME_MODE_FINISH:
                this.updateFinish();
                break;
        }
    }

    render() {
        this.maze.render(this.ctx, this.images);
        this.player.render(this.ctx, this.images);
        this.alien.render(this.ctx, this.images);
        if (this.alien1) {
            this.alien1.render(this.ctx, this.images);
        }
        this.bullet.render(this.ctx, this.images);
    }

    frame() {
        this.update();
        this.render();
        requestAnimationFrame(this.frame.bind(this));
    }
}
<|endoftext|>


<commit_before>var lbry = {
  isConnected: false,
  rootPath: '.',
  colors: {
    primary: '#155B4A'
  }
};

lbry.call = function (method, params, callback, errorCallback, connectFailedCallback)
{
  var xhr = new XMLHttpRequest;
  xhr.addEventListener('load', function() {
    var response = JSON.parse(xhr.responseText);

    if (response.error) {
      if (errorCallback) {
        errorCallback(response.error);
      }
    } else if (callback) {
      callback(response.result);
    }
  });

  if (connectFailedCallback) {
    xhr.addEventListener('error', function (e) {
      connectFailedCallback(e);
    });
  }

  xhr.open('POST', 'http://localhost:5279/lbryapi', true);
  xhr.send(JSON.stringify({
    'jsonrpc': '2.0',
    'method': method,
    'params': [params, ],
    'id': 0
  }));
}

//core
lbry.connect = function(callback)
{
  // Check every half second to see if the daemon's running.
  // Returns true to callback once connected, or false if it takes too long and we give up.
  function checkDaemonRunning(tryNum=0) {
    lbry.daemonRunningStatus(function (runningStatus) {
      if (runningStatus) {
        lbry.isConnected = true;
        callback(true);
      } else {
        if (tryNum <= 600) { // Move # of tries into constant or config option
          setTimeout(function () {
            checkDaemonRunning(tryNum + 1);
          }, 500);
        } else {
          callback(false);
        }
      }
    });
  }
  checkDaemonRunning();
}

lbry.daemonRunningStatus = function (callback) {
  // Returns true/false whether the daemon is running (i.e. fully conncected to the network),
  // or null if the AJAX connection to the daemon fails.

  lbry.call('is_running', {}, callback, null, function () {
    callback(null);
  });
};

lbry.getDaemonStatus = function (callback) {
  lbry.call('daemon_status', {}, callback);
};

lbry.getStartNotice = function(callback) {
  lbry.call('get_start_notice', {}, callback);
}

lbry.checkFirstRun = function(callback) {
  lbry.call('is_first_run', {}, callback);
}

lbry.getNewAddress = function(callback) {
  lbry.call('get_new_address', {}, callback);
}

lbry.getSettings = function(callback) {
  lbry.call('get_settings', {}, callback);
};

lbry.setSettings = function(settings, callback) {
  lbry.call('set_settings', settings, callback);
};

lbry.getBalance = function(callback)
{
  lbry.call("get_balance", {}, callback);
}

lbry.sendToAddress = function(amount, address, callback, errorCallback)
{
  lbry.call("send_amount_to_address", { "amount" : amount, "address": address }, callback, errorCallback);
}

lbry.search = function(query, callback)
{
  lbry.call("search_nametrie", { "search": query }, callback);
}

lbry.resolveName = function(name, callback) {
  lbry.call('resolve_name', { 'name': name }, callback, () => {
    // For now, assume any error means the name was not resolved
    callback(null);
  });
}

lbry.getStream = function(name, callback) {
  lbry.call('get', { 'name': name }, callback);
};

lbry.getClaimInfo = function(name, callback) {
  lbry.call('get_claim_info', { name: name }, callback);
}

lbry.getCostEstimate = function(name, callback) {
  lbry.call('get_est_cost', { name: name }, callback);
}

lbry.getFileStatus = function(name, callback) {
  lbry.call('get_lbry_file', { 'name': name }, callback);
}

lbry.getFilesInfo = function(callback) {
  lbry.call('get_lbry_files', {}, callback);
}

lbry.startFile = function(name, callback) {
  lbry.call('start_lbry_file', { name: name }, callback);
}

lbry.stopFile = function(name, callback) {
  lbry.call('stop_lbry_file', { name: name }, callback);
}

lbry.deleteFile = function(name, deleteTargetFile=true, callback) {
  lbry.call('delete_lbry_file', {
    name: name,
    delete_target_file: deleteTargetFile,
  }, callback);
}

lbry.revealFile = function(path, callback) {
  lbry.call('reveal', { path: path }, callback);
}

lbry.publish = function(params, callback, errorCallback) {
  // Use ES6 named arguments instead of directly passing param dict?
  lbry.call('publish', params, callback, (errorInfo) => {
    errorCallback({
      name: fault.fault,
      message: fault.faultString,
    });
  });
}

lbry.getVersionInfo = function(callback) {
  lbry.call('version', {}, callback);
};

lbry.checkNewVersionAvailable = function(callback) {
  lbry.call('version', {}, function(versionInfo) {
    var ver = versionInfo.lbrynet_version.split('.');

    var maj = parseInt(ver[0]),
        min = parseInt(ver[1]),
        patch = parseInt(ver[2]);

    var remoteVer = versionInfo.remote_lbrynet.split('.');
    var remoteMaj = parseInt(remoteVer[0]),
        remoteMin = parseInt(remoteVer[1]),
        remotePatch = parseInt(remoteVer[2]);

    if (maj < remoteMaj) {
      var newVersionAvailable = true;
    } else if (maj == remoteMaj) {
      if (min < remoteMin) {
        var newVersionAvailable = true;
      } else if (min == remoteMin) {
        var newVersionAvailable = (patch < remotePatch);
      } else {
        var newVersionAvailable = false;
      }
    } else {
      var newVersionAvailable = false;
    }
    callback(newVersionAvailable);
  }, function(err) {
    if (err.fault == 'NoSuchFunction') {
      // Really old daemon that can't report a version
      callback(true);
    }
  });
}

lbry.reportBug = function(message, callback) {
  lbry.call('upload_log', {
    name_prefix: 'report',
    exclude_previous: false,
    force: true,
    message: message
  }, callback);
}

//utilities
lbry.formatCredits = function(amount, precision)
{
  return amount.toFixed(precision || 1);
}

lbry.loadJs = function(src, type, onload)
{
  var lbryScriptTag = document.getElementById('lbry'),
      newScriptTag = document.createElement('script'),
      type = type || 'text/javascript';

  newScriptTag.src = src;
  newScriptTag.type = type;
  if (onload)
  {
    newScript.onload = onload;
  }
  lbryScriptTag.parentNode.insertBefore(newScriptTag, lbryScriptTag);
}

lbry.imagePath = function(file)
{
  return lbry.rootPath + '/img/' + file;
}

lbry.getMediaType = function(filename) {
  var dotIndex = filename.lastIndexOf('.');
  if (dotIndex == -1) {
    return 'unknown';
  }

  var ext = filename.substr(dotIndex + 1);
  if (/^mp4|mov|m4v|flv|f4v$/i.test(ext)) {
    return 'video';
  } else if (/^mp3|m4a|aac|wav|flac|ogg$/i.test(ext)) {
    return 'audio';
  } else if (/^html|htm|pdf|odf|doc|docx|md|markdown|txt$/i.test(ext)) {
    return 'document';
  } else {
    return 'unknown';
  }
}

lbry.stop = function(callback) {
  lbry.call('stop', {}, callback);
};

<commit_msg>Refactor JSON-RPC handling into generic function<commit_after>var lbry = {
  isConnected: false,
  rootPath: '.',
  daemonConnectionString: 'http://localhost:5279/lbryapi',
  colors: {
    primary: '#155B4A'
  }
};

lbry.jsonrpc_call = function (connectionString, method, params, callback, errorCallback, connectFailedCallback) {
  var xhr = new XMLHttpRequest;
  xhr.addEventListener('load', function() {
    var response = JSON.parse(xhr.responseText);

    if (response.error) {
      if (errorCallback) {
        errorCallback(response.error);
      }
    } else if (callback) {
      callback(response.result);
    }
  });

  if (connectFailedCallback) {
    xhr.addEventListener('error', function (e) {
      connectFailedCallback(e);
    });
  }

  xhr.open('POST', connectionString, true);
  xhr.send(JSON.stringify({
    'jsonrpc': '2.0',
    'method': method,
    'params': params,
    'id': 0
  }));
}

lbry.call = function (method, params, callback, errorCallback, connectFailedCallback) {
  lbry.jsonrpc_call(lbry.daemonConnectionString, method, [params], callback, errorCallback, connectFailedCallback);
}

//core
lbry.connect = function(callback)
{
  // Check every half second to see if the daemon's running.
  // Returns true to callback once connected, or false if it takes too long and we give up.
  function checkDaemonRunning(tryNum=0) {
    lbry.daemonRunningStatus(function (runningStatus) {
      if (runningStatus) {
        lbry.isConnected = true;
        callback(true);
      } else {
        if (tryNum <= 600) { // Move # of tries into constant or config option
          setTimeout(function () {
            checkDaemonRunning(tryNum + 1);
          }, 500);
        } else {
          callback(false);
        }
      }
    });
  }
  checkDaemonRunning();
}

lbry.daemonRunningStatus = function (callback) {
  // Returns true/false whether the daemon is running (i.e. fully conncected to the network),
  // or null if the AJAX connection to the daemon fails.

  lbry.call('is_running', {}, callback, null, function () {
    callback(null);
  });
};

lbry.getDaemonStatus = function (callback) {
  lbry.call('daemon_status', {}, callback);
};

lbry.getStartNotice = function(callback) {
  lbry.call('get_start_notice', {}, callback);
}

lbry.checkFirstRun = function(callback) {
  lbry.call('is_first_run', {}, callback);
}

lbry.getNewAddress = function(callback) {
  lbry.call('get_new_address', {}, callback);
}

lbry.getSettings = function(callback) {
  lbry.call('get_settings', {}, callback);
};

lbry.setSettings = function(settings, callback) {
  lbry.call('set_settings', settings, callback);
};

lbry.getBalance = function(callback)
{
  lbry.call("get_balance", {}, callback);
}

lbry.sendToAddress = function(amount, address, callback, errorCallback)
{
  lbry.call("send_amount_to_address", { "amount" : amount, "address": address }, callback, errorCallback);
}

lbry.search = function(query, callback)
{
  lbry.call("search_nametrie", { "search": query }, callback);
}

lbry.resolveName = function(name, callback) {
  lbry.call('resolve_name', { 'name': name }, callback, () => {
    // For now, assume any error means the name was not resolved
    callback(null);
  });
}

lbry.getStream = function(name, callback) {
  lbry.call('get', { 'name': name }, callback);
};

lbry.getClaimInfo = function(name, callback) {
  lbry.call('get_claim_info', { name: name }, callback);
}

lbry.getCostEstimate = function(name, callback) {
  lbry.call('get_est_cost', { name: name }, callback);
}

lbry.getFileStatus = function(name, callback) {
  lbry.call('get_lbry_file', { 'name': name }, callback);
}

lbry.getFilesInfo = function(callback) {
  lbry.call('get_lbry_files', {}, callback);
}

lbry.startFile = function(name, callback) {
  lbry.call('start_lbry_file', { name: name }, callback);
}

lbry.stopFile = function(name, callback) {
  lbry.call('stop_lbry_file', { name: name }, callback);
}

lbry.deleteFile = function(name, deleteTargetFile=true, callback) {
  lbry.call('delete_lbry_file', {
    name: name,
    delete_target_file: deleteTargetFile,
  }, callback);
}

lbry.revealFile = function(path, callback) {
  lbry.call('reveal', { path: path }, callback);
}

lbry.publish = function(params, callback, errorCallback) {
  // Use ES6 named arguments instead of directly passing param dict?
  lbry.call('publish', params, callback, (errorInfo) => {
    errorCallback({
      name: fault.fault,
      message: fault.faultString,
    });
  });
}

lbry.getVersionInfo = function(callback) {
  lbry.call('version', {}, callback);
};

lbry.checkNewVersionAvailable = function(callback) {
  lbry.call('version', {}, function(versionInfo) {
    var ver = versionInfo.lbrynet_version.split('.');

    var maj = parseInt(ver[0]),
        min = parseInt(ver[1]),
        patch = parseInt(ver[2]);

    var remoteVer = versionInfo.remote_lbrynet.split('.');
    var remoteMaj = parseInt(remoteVer[0]),
        remoteMin = parseInt(remoteVer[1]),
        remotePatch = parseInt(remoteVer[2]);

    if (maj < remoteMaj) {
      var newVersionAvailable = true;
    } else if (maj == remoteMaj) {
      if (min < remoteMin) {
        var newVersionAvailable = true;
      } else if (min == remoteMin) {
        var newVersionAvailable = (patch < remotePatch);
      } else {
        var newVersionAvailable = false;
      }
    } else {
      var newVersionAvailable = false;
    }
    callback(newVersionAvailable);
  }, function(err) {
    if (err.fault == 'NoSuchFunction') {
      // Really old daemon that can't report a version
      callback(true);
    }
  });
}

lbry.reportBug = function(message, callback) {
  lbry.call('upload_log', {
    name_prefix: 'report',
    exclude_previous: false,
    force: true,
    message: message
  }, callback);
}

//utilities
lbry.formatCredits = function(amount, precision)
{
  return amount.toFixed(precision || 1);
}

lbry.loadJs = function(src, type, onload)
{
  var lbryScriptTag = document.getElementById('lbry'),
      newScriptTag = document.createElement('script'),
      type = type || 'text/javascript';

  newScriptTag.src = src;
  newScriptTag.type = type;
  if (onload)
  {
    newScript.onload = onload;
  }
  lbryScriptTag.parentNode.insertBefore(newScriptTag, lbryScriptTag);
}

lbry.imagePath = function(file)
{
  return lbry.rootPath + '/img/' + file;
}

lbry.getMediaType = function(filename) {
  var dotIndex = filename.lastIndexOf('.');
  if (dotIndex == -1) {
    return 'unknown';
  }

  var ext = filename.substr(dotIndex + 1);
  if (/^mp4|mov|m4v|flv|f4v$/i.test(ext)) {
    return 'video';
  } else if (/^mp3|m4a|aac|wav|flac|ogg$/i.test(ext)) {
    return 'audio';
  } else if (/^html|htm|pdf|odf|doc|docx|md|markdown|txt$/i.test(ext)) {
    return 'document';
  } else {
    return 'unknown';
  }
}

lbry.stop = function(callback) {
  lbry.call('stop', {}, callback);
};

<|endoftext|>