<commit_before>/**
 * @author bhouston / http://clara.io/
 */

THREE.MSAAPass = function ( scene, camera, params ) {

  this.scene = scene;
  this.camera = camera;

  this.sampleLevel = 4;

  this.params = params || { minFilter: THREE.NearestFilter, magFilter: THREE.NearestFilter, format: THREE.RGBAFormat };
  this.params.minFilter = THREE.NearestFilter;
  this.params.maxFilter = THREE.NearestFilter;
  console.log( 'this.params', this.params );
  this.enabled = true;

  this.needsSwap = true;

  if ( THREE.CompositeShader === undefined ) {
		console.error( "THREE.MSAAPass relies on THREE.CompositeShader" );
	}

  var compositeShader = THREE.CompositeShader;
  this.uniforms = THREE.UniformsUtils.clone( compositeShader.uniforms );

  this.materialComposite = new THREE.ShaderMaterial(  {

		uniforms: this.uniforms,
		vertexShader: compositeShader.vertexShader,
		fragmentShader: compositeShader.fragmentShader,
    transparent: true,
    blending: THREE.CustomBlending,
    blendSrc: THREE.OneFactor,
    blendDst: THREE.OneFactor,
    blendEquation: THREE.AddEquation,
    depthTest: false,
    depthWrite: false

	} );

  this.camera2 = new THREE.OrthographicCamera( -1, 1, 1, -1, 0, 1 );
  this.scene2  = new THREE.Scene();
  this.quad2 = new THREE.Mesh( new THREE.PlaneGeometry( 2, 2 ), this.materialComposite );
  this.scene2.add( this.quad2 );

};

THREE.MSAAPass.prototype = {

  dispose: function() {

    if( this.sampleRenderTarget ) {

      this.sampleRenderTarget.dispose();
      this.sampleRenderTarget = null;

    }

  },

  render: function ( renderer, writeBuffer, readBuffer, delta ) {

    if( ! this.sampleRenderTarget ) {

      this.sampleRenderTarget = new THREE.WebGLRenderTarget( readBuffer.width, readBuffer.height, this.params, "msaa.renderTarget0" );

    }

    var camera = ( this.camera || this.scene.camera );

    var jitterOffsets = THREE.MSAAPass.JitterVectors[ Math.max( 0, Math.min( this.sampleLevel, 5 ) ) ];

    this.uniforms[ "tForeground" ].value = this.sampleRenderTarget;
    this.uniforms[ "scale" ].value = 1.0 / jitterOffsets.length;

    //renderer.setClearColor( new THREE.Color( 0, 0, 0 ), 0.0 );

    for( var i = 0; i < jitterOffsets.length; i ++ ) {

      if( camera.setViewOffset ) camera.setViewOffset( readBuffer.width, readBuffer.height, jitterOffsets[i].x, jitterOffsets[i].y, readBuffer.width, readBuffer.height );

      renderer.render( this.scene, camera, this.sampleRenderTarget, false );

      renderer.render( this.scene2, this.camera2, writeBuffer, false );

    }

    if( camera.setViewOffset ) camera.setViewOffset( undefined, undefined, undefined, undefined, undefined, undefined );

  }

};

THREE.MSAAPass.normalizedJitterOffsets = function( jitterVectors ) {

  var vectors2 = [];

  for( var i = 0; i < jitterVectors.length; i ++ ) {

    vectors2.push( new THREE.Vector2( jitterVectors[i][0], jitterVectors[i][1] ).multiplyScalar( 1.0 / 16.0 ) );

  }

  return vectors2;
},

THREE.MSAAPass.JitterVectors = [
  THREE.MSAAPass.normalizedJitterOffsets( [
    [  0,  0 ]
  ] ),
  THREE.MSAAPass.normalizedJitterOffsets( [
    [  4,  4 ],
    [ -4, -4 ]
  ] ),
  THREE.MSAAPass.normalizedJitterOffsets( [
    [ -2, -6 ],
    [  6, -2 ],
    [ -6,  2 ],
    [  2,  6 ]
  ] ),
  THREE.MSAAPass.normalizedJitterOffsets( [
    [  1, -3 ],
    [ -1,  3 ],
    [  5,  1 ],
    [ -3, -5 ],
    [ -5,  5 ],
    [ -7, -1 ],
    [  3,  7 ],
    [  7, -7 ]
  ] ),
  THREE.MSAAPass.normalizedJitterOffsets( [
    [  1,  1 ],
    [ -1, -3 ],
    [ -3,  2 ],
    [  4, -1 ],

    [ -5, -2 ],
    [  2,  5 ],
    [  5,  3 ],
    [  3, -5 ],

    [ -2,  6 ],
    [  0, -7 ],
    [ -4, -6 ],
    [ -6,  4 ],

    [ -8,  0 ],
    [  7, -4 ],
    [  6,  7 ],
    [ -7, -8 ]
  ] ),
  THREE.MSAAPass.normalizedJitterOffsets( [
    [ -4, -7 ],
    [ -7, -5 ],
    [ -3, -5 ],
    [ -5, -4 ],

    [ -1, -4 ],
    [ -2, -2 ],
    [ -6, -1 ],
    [ -4,  0 ],

    [ -7,  1 ],
    [ -1,  2 ],
    [ -6,  3 ],
    [ -3,  3 ],

    [ -7,  6 ],
    [ -3,  6 ],
    [ -5,  7 ],
    [ -1,  7 ],

    [  5, -7 ],
    [  1, -6 ],
    [  6, -5 ],
    [  4, -4 ],

    [  2, -3 ],
    [  7, -2 ],
    [  1, -1 ],
    [  4, -1 ],

    [  2,  1 ],
    [  6,  2 ],
    [  0,  4 ],
    [  4,  4 ],

    [  2,  5 ],
    [  7,  5 ],
    [  5,  6 ],
    [  3,  7 ]
  ] )
];
<commit_msg>add comments.<commit_after>/**
 * @author bhouston / http://clara.io/
 */

THREE.MSAAPass = function ( scene, camera, params ) {

  this.scene = scene;
  this.camera = camera;

  this.sampleLevel = 4;

  this.params = params || { minFilter: THREE.NearestFilter, magFilter: THREE.NearestFilter, format: THREE.RGBAFormat };
  this.params.minFilter = THREE.NearestFilter;
  this.params.maxFilter = THREE.NearestFilter;
  console.log( 'this.params', this.params );
  this.enabled = true;

  this.needsSwap = true;

  if ( THREE.CompositeShader === undefined ) {
		console.error( "THREE.MSAAPass relies on THREE.CompositeShader" );
	}

  var compositeShader = THREE.CompositeShader;
  this.uniforms = THREE.UniformsUtils.clone( compositeShader.uniforms );

  this.materialComposite = new THREE.ShaderMaterial(  {

		uniforms: this.uniforms,
		vertexShader: compositeShader.vertexShader,
		fragmentShader: compositeShader.fragmentShader,
    transparent: true,
    blending: THREE.CustomBlending,
    blendSrc: THREE.OneFactor,
    blendDst: THREE.OneFactor,
    blendEquation: THREE.AddEquation,
    depthTest: false,
    depthWrite: false

	} );

  this.camera2 = new THREE.OrthographicCamera( -1, 1, 1, -1, 0, 1 );
  this.scene2  = new THREE.Scene();
  this.quad2 = new THREE.Mesh( new THREE.PlaneGeometry( 2, 2 ), this.materialComposite );
  this.scene2.add( this.quad2 );

};

THREE.MSAAPass.prototype = {

  dispose: function() {

    if( this.sampleRenderTarget ) {

      this.sampleRenderTarget.dispose();
      this.sampleRenderTarget = null;

    }

  },

  render: function ( renderer, writeBuffer, readBuffer, delta ) {

    if( ! this.sampleRenderTarget ) {

      this.sampleRenderTarget = new THREE.WebGLRenderTarget( readBuffer.width, readBuffer.height, this.params, "msaa.renderTarget0" );

    }

    var camera = ( this.camera || this.scene.camera );

    var jitterOffsets = THREE.MSAAPass.JitterVectors[ Math.max( 0, Math.min( this.sampleLevel, 5 ) ) ];

    this.uniforms[ "tForeground" ].value = this.sampleRenderTarget;
    this.uniforms[ "scale" ].value = 1.0 / jitterOffsets.length;

    //renderer.setClearColor( new THREE.Color( 0, 0, 0 ), 0.0 );

    for( var i = 0; i < jitterOffsets.length; i ++ ) {

      // only jitters perspective cameras.  TODO: add support for jittering orthogonal cameras
      if( camera.setViewOffset ) camera.setViewOffset( readBuffer.width, readBuffer.height, jitterOffsets[i].x, jitterOffsets[i].y, readBuffer.width, readBuffer.height );

      renderer.render( this.scene, camera, this.sampleRenderTarget, true );

      // clear on the first render, accumulate the others
      renderer.render( this.scene2, this.camera2, writeBuffer, i === 0 );

    }

    // reset jitter to nothing.  TODO: add support for orthogonal cameras
    if( camera.setViewOffset ) camera.setViewOffset( undefined, undefined, undefined, undefined, undefined, undefined );

  }

};

THREE.MSAAPass.normalizedJitterOffsets = function( jitterVectors ) {

  var scaledJitterOffsets = [];

  for( var i = 0; i < jitterVectors.length; i ++ ) {

    scaledJitterOffsets.push( new THREE.Vector2( jitterVectors[i][0], jitterVectors[i][1] ).multiplyScalar( 1.0 / 16.0 ) );

  }

  return scaledJitterOffsets;

},

// These jitter vectors are specified in integers because it is easier.
// I am assuming a [-8,8] integer grid, but it needs to be mapped onto [-0.5,0.5]
// before being used, thus these integers need to be scaled by 1/16.
THREE.MSAAPass.JitterVectors = [
  THREE.MSAAPass.normalizedJitterOffsets( [
    [  0,  0 ]
  ] ),
  THREE.MSAAPass.normalizedJitterOffsets( [
    [  4,  4 ],
    [ -4, -4 ]
  ] ),
  THREE.MSAAPass.normalizedJitterOffsets( [
    [ -2, -6 ],
    [  6, -2 ],
    [ -6,  2 ],
    [  2,  6 ]
  ] ),
  THREE.MSAAPass.normalizedJitterOffsets( [
    [  1, -3 ],
    [ -1,  3 ],
    [  5,  1 ],
    [ -3, -5 ],
    [ -5,  5 ],
    [ -7, -1 ],
    [  3,  7 ],
    [  7, -7 ]
  ] ),
  THREE.MSAAPass.normalizedJitterOffsets( [
    [  1,  1 ],
    [ -1, -3 ],
    [ -3,  2 ],
    [  4, -1 ],

    [ -5, -2 ],
    [  2,  5 ],
    [  5,  3 ],
    [  3, -5 ],

    [ -2,  6 ],
    [  0, -7 ],
    [ -4, -6 ],
    [ -6,  4 ],

    [ -8,  0 ],
    [  7, -4 ],
    [  6,  7 ],
    [ -7, -8 ]
  ] ),
  THREE.MSAAPass.normalizedJitterOffsets( [
    [ -4, -7 ],
    [ -7, -5 ],
    [ -3, -5 ],
    [ -5, -4 ],

    [ -1, -4 ],
    [ -2, -2 ],
    [ -6, -1 ],
    [ -4,  0 ],

    [ -7,  1 ],
    [ -1,  2 ],
    [ -6,  3 ],
    [ -3,  3 ],

    [ -7,  6 ],
    [ -3,  6 ],
    [ -5,  7 ],
    [ -1,  7 ],

    [  5, -7 ],
    [  1, -6 ],
    [  6, -5 ],
    [  4, -4 ],

    [  2, -3 ],
    [  7, -2 ],
    [  1, -1 ],
    [  4, -1 ],

    [  2,  1 ],
    [  6,  2 ],
    [  0,  4 ],
    [  4,  4 ],

    [  2,  5 ],
    [  7,  5 ],
    [  5,  6 ],
    [  3,  7 ]
  ] )
];
<|endoftext|>


<commit_before>function getStates(region) {
   console.log(region);
   var regionColors = ['#5c7981', '#643c18', '#b2721a', '#dbd543', '#679a61', '#e28e45', '#508dac', '#a48f70',
       '#9dcbdb', '#d99b9c', '#b2721a', '#dbd543', '#b2721a', '#e28e45', '#d99b9c', '#0080ff'];
   var regionStates = [
      ['CT', 'MA', 'ME', 'NH', 'RI', 'VT', ],
      ['NJ', 'NY', ],
      ['DE', 'MD', 'PA', 'VA', 'WV', ],
      ['AL', 'FL', 'GA', 'KY', 'MS', 'NC', 'SC', 'TN', ],
      ['IL', 'IN', 'MI', 'MN', 'OH', 'WI', ],
      ['AR', 'LA', 'TX', 'NM', 'OK', ],
      ['IA', 'KS', 'MO', 'NE', ],
      ['CO', 'MT', 'ND', 'SD', 'UT', 'WY', ],
      ['AZ', 'CA', 'HI', 'NV', ],
      ['AK', 'ID', 'OR', 'WA', ],
      ['PA'],
      ['GA'],
      ['MD'],
      ['TX'],
      ['OR'],
       ['CA']
   ];

   var style = {};
   if (region == 55) { // CA
       style['CA'] = {fill: '#0080ff'};
   }
   var defaultNumRegion = 16
   for(var i = 0; i < defaultNumRegion-1; i++) {
      if(region === 0 || region === i + 1) {
         for(var j = 0; j < regionStates[i].length; j++) {
            style[regionStates[i][j]] = {fill: regionColors[i]};
         }
      }
   }
   console.log(style);
   return style;
}
<commit_msg>debug snapshot<commit_after>function getStates(region) {
   var regionColors = ['#5c7981', '#643c18', '#b2721a', '#dbd543', '#679a61', '#e28e45', '#508dac', '#a48f70',
       '#9dcbdb', '#d99b9c', '#b2721a', '#dbd543', '#b2721a', '#e28e45', '#d99b9c', '#9dcbdb'];
   var regionStates = [
      ['CT', 'MA', 'ME', 'NH', 'RI', 'VT', ],
      ['NJ', 'NY', ],
      ['DE', 'MD', 'PA', 'VA', 'WV', ],
      ['AL', 'FL', 'GA', 'KY', 'MS', 'NC', 'SC', 'TN', ],
      ['IL', 'IN', 'MI', 'MN', 'OH', 'WI', ],
      ['AR', 'LA', 'TX', 'NM', 'OK', ],
      ['IA', 'KS', 'MO', 'NE', ],
      ['CO', 'MT', 'ND', 'SD', 'UT', 'WY', ],
      ['AZ', 'CA', 'HI', 'NV', ],
      ['AK', 'ID', 'OR', 'WA', ],
      ['PA'],
      ['GA'],
      ['MD'],
      ['TX'],
      ['OR'],
       ['CA']
   ];

   var style = {};
   if (region == 55) { // CA
       style['CA'] = {fill: '#9dcbdb'};
   }
   return style;

   var defaultNumRegion = 16
   for(var i = 0; i < defaultNumRegion-1; i++) {
      if(region === 0 || region === i + 1) {
         for(var j = 0; j < regionStates[i].length; j++) {
            style[regionStates[i][j]] = {fill: regionColors[i]};
         }
      }
   }
   return style;
}
<|endoftext|>


<commit_before>var mongoose = require('mongoose'),
	uuid = require('uuid/v1'),
	Cards = require('./CardsModel'),
	Schema = mongoose.Schema,
	PlayerSchema = new Schema({
		sessionId: {
			type: String,
			required: true,
			// select: false
		},
		name: {
			type: String,
			required: true,
			trim: true
		},
		img: String,
		isActive: {
			type: Boolean,
			default: false
		},
		score: {
			type: Number,
			default: 0
		},
		cardsInHand: [{
				type: Schema.Types.ObjectId,
				ref: Cards.model
		}],
		cardsUsed: [{
			type: Schema.Types.ObjectId,
			ref: Cards.model
		}]
	}, {
		collection: 'players',
		timestamps: true
	});

const log = require('loggy');

PlayerSchema.set('toJSON', {
	transform: function(doc, ret, options) {
		delete ret._id;
		return ret;
	},
	virtuals: true
});

module.exports = {
	schema: PlayerSchema,
	model: mongoose.model('Player', PlayerSchema)
};
<commit_msg>Update PlayerModel schema to hide certain fields<commit_after>var mongoose = require('mongoose'),
	uuid = require('uuid/v1'),
	Cards = require('./CardsModel'),
	Schema = mongoose.Schema,
	PlayerSchema = new Schema({
		sessionId: {
			type: String,
			required: true,
			select: false
		},
		name: {
			type: String,
			required: true,
			trim: true
		},
		img: String,
		isActive: {
			type: Boolean,
			default: false
		},
		score: {
			type: Number,
			default: 0
		},
		cardsInHand: {
			type: [Schema.Types.ObjectId],
			ref: Cards.model,
			select: false
		},
		cardsUsed: {
			type: [Schema.Types.ObjectId],
			ref: Cards.model
		}
	}, {
		collection: 'players',
		timestamps: true
	});

const log = require('loggy');

PlayerSchema.set('toJSON', {
	transform: function(doc, ret, options) {
		delete ret._id;
		return ret;
	},
	virtuals: true
});

module.exports = {
	schema: PlayerSchema,
	model: mongoose.model('Player', PlayerSchema)
};
<|endoftext|>


<commit_before>import { isArray, camelCase } from './utils';

function letToVar(cmd, ...vars) {
  const varPairs = [];
  for (let i = 0; i < vars.length; i += 2) {
    let name = vars[ i ];
    let val = vars[ i + 1 ];
    if (name && val) {
      if (isArray(val)) {
        val = toJsString(val);
      }

      let statement = `${name} = ${val}`;
      varPairs.push(statement);
    }
  }

  if (varPairs.length < 1) {
    return '';
  }
  else {
    return `var ${varPairs.join(', ')};`;
  }
}

function math_operator(operator, ...params) {
  const separator = ` ${operator} `;
  const statements = [];
  for (let i = 0; i < params.length; i++) {
    let statement = params[ i ];
    if (isArray(statement)) {
      statement = toJsString(statement);
    }
    statements.push(statement);
  }
  return `(${statements.join(separator)})`;
}

function define_function(operator, name, params, ...body) {
  if (isArray(name)) {
    body.unshift(params);
    params = name;
    name = "";
  }

  let statements = body.map(toJsString);
  let final = statements.pop();
  statements = statements
    .map(s => s + ";")
    .join(' ');
  params = params.join(', ');

  return `(function ${name}(${params}) {${statements} return ${final};})`;
}

function define_module(operator, name, ...body) {
  const statements = body
    .map(toJsString)
    .map(s => s + ";")
    .join(' ');

  return `module('${name}', function (require, export) {${statements}})`;
}

function function_call(fn, ...params) {
  const evaluated_params = params.map(p => toJsString(p));

  return `${fn}( ${evaluated_params.join(', ')} )`;
}

export const toJsString = function (arr) {
  if (!isArray(arr)) {
    return arr;
  }

  switch(arr[0]) {
    case 'function': return define_function(...arr);
    case 'module': return define_module(...arr);
    case 'let': return letToVar(...arr);
    case '+': return math_operator(...arr);
    case '-': return math_operator(...arr);
    case '*': return math_operator(...arr);
    case '/': return math_operator(...arr);
  }

  return function_call(...arr);
};
<commit_msg>require and export are next<commit_after>import { isArray, camelCase } from './utils';

function letToVar(cmd, ...vars) {
  const varPairs = [];
  for (let i = 0; i < vars.length; i += 2) {
    let name = vars[ i ];
    let val = vars[ i + 1 ];
    if (name && val) {
      if (isArray(val)) {
        val = toJsString(val);
      }

      let statement = `${name} = ${val}`;
      varPairs.push(statement);
    }
  }

  if (varPairs.length < 1) {
    return '';
  }
  else {
    return `var ${varPairs.join(', ')};`;
  }
}

function math_operator(operator, ...params) {
  const separator = ` ${operator} `;
  const statements = [];
  for (let i = 0; i < params.length; i++) {
    let statement = params[ i ];
    if (isArray(statement)) {
      statement = toJsString(statement);
    }
    statements.push(statement);
  }
  return `(${statements.join(separator)})`;
}

function define_function(operator, name, params, ...body) {
  if (isArray(name)) {
    body.unshift(params);
    params = name;
    name = "";
  }

  let statements = body.map(toJsString);
  let final = statements.pop();
  statements = statements
    .map(s => s + ";")
    .join(' ');
  params = params.join(', ');

  return `(function ${name}(${params}) {${statements} return ${final};})`;
}

function define_module(operator, name, ...body) {
  const statements = body
    .map(toJsString)
    .map(s => s + ";")
    .join(' ');

  return `module('${name}', function (require, export) {${statements}})`;
}

function module_require() {
  return "";
}

function module_export() {
  return "";
}

function function_call(fn, ...params) {
  const evaluated_params = params.map(p => toJsString(p));

  return `${fn}( ${evaluated_params.join(', ')} )`;
}

export const toJsString = function (arr) {
  if (!isArray(arr)) {
    return arr;
  }

  switch(arr[0]) {
    case 'function': return define_function(...arr);
    case 'module': return define_module(...arr);
    case 'require': return module_require(...arr);
    case 'export': return module_export(...arr);
    case 'let': return letToVar(...arr);
    case '+': return math_operator(...arr);
    case '-': return math_operator(...arr);
    case '*': return math_operator(...arr);
    case '/': return math_operator(...arr);
  }

  return function_call(...arr);
};
<|endoftext|>


<commit_before>import {
  camelCase,
  isArray,
  merge
} from './utils';
import {
  block_statement,
  empty_statement,
  function_statement,
  infix_statement,
  multi_line_statement,
  token_statement
} from './statement';
import {
  token_macros,
  list_macros
} from './builtin-macros';

function let_to_var([cmd, ...vars], options) {
  const varPairs = [];
  for (let i = 0; i < vars.length; i += 2) {
    let name = vars[ i ];
    let val = vars[ i + 1 ];

    if (name && val) {
      varPairs.push(infix_statement({
        statements: [
          token_statement({ token: `var ${name}`}),
          toJsTree(val, { embedded: true })
        ],
        separator: ' = ',
        terminate: true
      }));
    }
  }

  if (varPairs.length < 1) {
    return empty_statement();
  }

  return multi_line_statement(merge(options, {
    statements: varPairs
  }));
}

function if_block([operator, conditional, truePath, falsePath], options) {
  const truePathBlock = block_statement({
    openBlock: infix_statement({
      statements: [
        token_statement({ token: 'if' }),
        toJsTree(conditional, { embedded: true }),
        token_statement({ token: '{' })
      ],
      separator: ' '
    }),
    statements: [
      toJsTree(truePath, { terminate: true })
    ],
    closeBlock: token_statement({ token: '}' })
  });

  if (falsePath) {
    const falsePathBlock = block_statement({
      openBlock: token_statement({ token: 'else {' }),
      statements: [ toJsTree(falsePath, { terminate: true }) ],
      closeBlock: token_statement({ token: '}' })
    });

    return multi_line_statement({
      statements: [ truePathBlock, falsePathBlock ]
    });
  }
  else {
    return truePathBlock;
  }
}

function cond_block([operator, ...branches], options) {
  return empty_statement();
}

function math_operator([operator, ...params], options) {
  return infix_statement(merge(options, {
    statements: params.map(param => toJsTree(param, { embedded: true })),
    separator: ` ${operator} `
  }));
}

function logical_operator([operator, ...params], options) {
  if (operator === '=') {
    operator = '===';
  }

  if (params.length <= 1) {
    throw "logical operators require at least two parameters";
  }
  else if (params.length === 2) {
    return infix_statement(merge(options, {
      statements: params.map(param => toJsTree(param, { embedded: true })),
      separator: ` ${operator} `
    }));
  }
  else {
    let pairs = [];
    for (let i = 0; i < params.length - 1; i++) {
      let first = params[ i ];
      let second = params [ i + 1 ];

      pairs.push(infix_statement({
        statements: [
          toJsTree(first, { embedded: true }),
          toJsTree(second, { embedded: true })
        ],
        separator: ` ${operator} `,
        embedded: true
      }));
    }

    return infix_statement(merge(options, {
      statements: pairs,
      separator: ` && `
    }));
  }
}

function define_function([operator, name, params, ...body], options) {
  if (isArray(name)) {
    body.unshift(params);
    params = name;
    name = "";
  }
  params = params.join(', ');

  let final = body.pop();
  if (final) {
    final = toJsTree(final, { returnStatement: true, terminate: true });
  } else {
    final = token_statement({ token: 'null', returnStatement: true, terminate: true });
  }

  let statements = body.map(s => toJsTree(s, { terminate: true }));
  statements.push(final);

  return block_statement(merge(options, {
    openBlock: token_statement({ token: `function ${name}(${params}) {` }),
    statements,
    closeBlock: token_statement({ token: `}` })
  }));
}

function define_module([operator, name, ...body], options) {
  const statements = body.map(s => toJsTree(s, { terminate: true }));

  return block_statement(merge(options, {
    openBlock: token_statement({ token: `module('${name}', function (require, export) {` }),
    statements,
    closeBlock: token_statement({ token: `})` })
  }));
}

function module_require([operator, moduleName, reqTokens], options) {
  const statements = reqTokens.map(token => token_statement({
    token: `var ${token} = ${moduleName}['${token}']`,
    terminate: true
  }));

  statements.unshift(token_statement({
    token: `var ${moduleName} = require('${moduleName}')`,
    terminate: true
  }));

  return multi_line_statement(merge(options, { statements }));
}

function module_export([operator, moduleName, statement], options) {
  return function_statement(merge(options, {
    openStatement: `export(`,
    parameters: [
      token_statement({ token: `'${moduleName}'` }),
      toJsTree(statement, { embedded: true })
    ],
    closeStatement: `)`
  }));
}

function function_call([fn, ...params], options) {
  return function_statement(merge(options, {
    openStatement: `${fn}(`,
    parameters: params.map(p => toJsTree(p, { embedded: true })),
    closeStatement: `)`
  }));
}

export const toJsTree = function (arr, options = { }) {
  if (!isArray(arr)) {
    arr = token_macros(arr, options);

    return token_statement(merge(options, { token: arr }));
  }

  arr = list_macros(arr, options);

  switch(arr[0]) {
    case 'function': return define_function(arr, options);
    case 'module': return define_module(arr, options);
    case 'require': return module_require(arr, options);
    case 'export': return module_export(arr, options);

    case 'let': return let_to_var(arr, options);
    case 'if': return if_block(arr, options);
    case 'cond': return cond_block(arr, options);

    case '+': return math_operator(arr, options);
    case '-': return math_operator(arr, options);
    case '*': return math_operator(arr, options);
    case '/': return math_operator(arr, options);
    case '=': return logical_operator(arr, options);
    case '>': return logical_operator(arr, options);
    case '<': return logical_operator(arr, options);
    case '>=': return logical_operator(arr, options);
    case '<=': return logical_operator(arr, options);

    default: return function_call(arr, options);
  }
};
<commit_msg>passing return through the if was remarkably simple<commit_after>import {
  camelCase,
  isArray,
  merge
} from './utils';
import {
  block_statement,
  empty_statement,
  function_statement,
  infix_statement,
  multi_line_statement,
  token_statement
} from './statement';
import {
  token_macros,
  list_macros
} from './builtin-macros';

function let_to_var([cmd, ...vars], options) {
  const varPairs = [];
  for (let i = 0; i < vars.length; i += 2) {
    let name = vars[ i ];
    let val = vars[ i + 1 ];

    if (name && val) {
      varPairs.push(infix_statement({
        statements: [
          token_statement({ token: `var ${name}`}),
          toJsTree(val, { embedded: true })
        ],
        separator: ' = ',
        terminate: true
      }));
    }
  }

  if (varPairs.length < 1) {
    return empty_statement();
  }

  return multi_line_statement(merge(options, {
    statements: varPairs
  }));
}

function if_block([operator, conditional, truePath, falsePath], options) {
  const truePathBlock = block_statement({
    openBlock: infix_statement({
      statements: [
        token_statement({ token: 'if' }),
        toJsTree(conditional, { embedded: true }),
        token_statement({ token: '{' })
      ],
      separator: ' '
    }),
    statements: [
      toJsTree(truePath, merge(options, { terminate: true }))
    ],
    closeBlock: token_statement({ token: '}' })
  });

  if (falsePath) {
    const falsePathBlock = block_statement({
      openBlock: token_statement({ token: 'else {' }),
      statements: [
        toJsTree(falsePath, merge(options, { terminate: true }))
      ],
      closeBlock: token_statement({ token: '}' })
    });

    return multi_line_statement({
      statements: [ truePathBlock, falsePathBlock ]
    });
  }
  else {
    return truePathBlock;
  }
}

function cond_block([operator, ...branches], options) {
  return empty_statement();
}

function math_operator([operator, ...params], options) {
  return infix_statement(merge(options, {
    statements: params.map(param => toJsTree(param, { embedded: true })),
    separator: ` ${operator} `
  }));
}

function logical_operator([operator, ...params], options) {
  if (operator === '=') {
    operator = '===';
  }

  if (params.length <= 1) {
    throw "logical operators require at least two parameters";
  }
  else if (params.length === 2) {
    return infix_statement(merge(options, {
      statements: params.map(param => toJsTree(param, { embedded: true })),
      separator: ` ${operator} `
    }));
  }
  else {
    let pairs = [];
    for (let i = 0; i < params.length - 1; i++) {
      let first = params[ i ];
      let second = params [ i + 1 ];

      pairs.push(infix_statement({
        statements: [
          toJsTree(first, { embedded: true }),
          toJsTree(second, { embedded: true })
        ],
        separator: ` ${operator} `,
        embedded: true
      }));
    }

    return infix_statement(merge(options, {
      statements: pairs,
      separator: ` && `
    }));
  }
}

function define_function([operator, name, params, ...body], options) {
  if (isArray(name)) {
    body.unshift(params);
    params = name;
    name = "";
  }
  params = params.join(', ');

  let final = body.pop();
  if (final) {
    final = toJsTree(final, { returnStatement: true, terminate: true });
  } else {
    final = token_statement({ token: 'null', returnStatement: true, terminate: true });
  }

  let statements = body.map(s => toJsTree(s, { terminate: true }));
  statements.push(final);

  return block_statement(merge(options, {
    openBlock: token_statement({ token: `function ${name}(${params}) {` }),
    statements,
    closeBlock: token_statement({ token: `}` })
  }));
}

function define_module([operator, name, ...body], options) {
  const statements = body.map(s => toJsTree(s, { terminate: true }));

  return block_statement(merge(options, {
    openBlock: token_statement({ token: `module('${name}', function (require, export) {` }),
    statements,
    closeBlock: token_statement({ token: `})` })
  }));
}

function module_require([operator, moduleName, reqTokens], options) {
  const statements = reqTokens.map(token => token_statement({
    token: `var ${token} = ${moduleName}['${token}']`,
    terminate: true
  }));

  statements.unshift(token_statement({
    token: `var ${moduleName} = require('${moduleName}')`,
    terminate: true
  }));

  return multi_line_statement(merge(options, { statements }));
}

function module_export([operator, moduleName, statement], options) {
  return function_statement(merge(options, {
    openStatement: `export(`,
    parameters: [
      token_statement({ token: `'${moduleName}'` }),
      toJsTree(statement, { embedded: true })
    ],
    closeStatement: `)`
  }));
}

function function_call([fn, ...params], options) {
  return function_statement(merge(options, {
    openStatement: `${fn}(`,
    parameters: params.map(p => toJsTree(p, { embedded: true })),
    closeStatement: `)`
  }));
}

export const toJsTree = function (arr, options = { }) {
  if (!isArray(arr)) {
    arr = token_macros(arr, options);

    return token_statement(merge(options, { token: arr }));
  }

  arr = list_macros(arr, options);

  switch(arr[0]) {
    case 'function': return define_function(arr, options);
    case 'module': return define_module(arr, options);
    case 'require': return module_require(arr, options);
    case 'export': return module_export(arr, options);

    case 'let': return let_to_var(arr, options);
    case 'if': return if_block(arr, options);
    case 'cond': return cond_block(arr, options);

    case '+': return math_operator(arr, options);
    case '-': return math_operator(arr, options);
    case '*': return math_operator(arr, options);
    case '/': return math_operator(arr, options);
    case '=': return logical_operator(arr, options);
    case '>': return logical_operator(arr, options);
    case '<': return logical_operator(arr, options);
    case '>=': return logical_operator(arr, options);
    case '<=': return logical_operator(arr, options);

    default: return function_call(arr, options);
  }
};
<|endoftext|>


<commit_before>/*
 *
 * Licensed to the Apache Software Foundation (ASF) under one
 * or more contributor license agreements.  See the NOTICE file
 * distributed with this work for additional information
 * regarding copyright ownership.  The ASF licenses this file
 * to you under the Apache License, Version 2.0 (the
 * "License"); you may not use this file except in compliance
 * with the License.  You may obtain a copy of the License at
 *
 *   http://www.apache.org/licenses/LICENSE-2.0
 *
 * Unless required by applicable law or agreed to in writing,
 * software distributed under the License is distributed on an
 * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
 * KIND, either express or implied.  See the License for the
 * specific language governing permissions and limitations
 * under the License.
 *
*/

var exec = require('cordova/exec');
var channel = require('cordova/channel');
var modulemapper = require('cordova/modulemapper');
var urlutil = require('cordova/urlutil');

function InAppBrowser() {
   this.channels = {
        'loadstart': channel.create('loadstart'),
        'loadstop' : channel.create('loadstop'),
        'loaderror' : channel.create('loaderror'),
        'exit' : channel.create('exit')
   };
}

InAppBrowser.prototype = {
    _eventHandler: function (event) {
        if (event && (event.type in this.channels)) {
            this.channels[event.type].fire(event);
        }
    },
    close: function (eventname) {
        exec(null, null, "InAppBrowser", "close", []);
    },
    show: function (eventname) {
      exec(null, null, "InAppBrowser", "show", []);
    },
    addEventListener: function (eventname,f) {
        if (eventname in this.channels) {
            this.channels[eventname].subscribe(f);
        }
    },
    removeEventListener: function(eventname, f) {
        if (eventname in this.channels) {
            this.channels[eventname].unsubscribe(f);
        }
    },

    executeScript: function(injectDetails, cb) {
        if (injectDetails.code) {
            exec(cb, null, "InAppBrowser", "injectScriptCode", [injectDetails.code, !!cb]);
        } else if (injectDetails.file) {
            exec(cb, null, "InAppBrowser", "injectScriptFile", [injectDetails.file, !!cb]);
        } else {
            throw new Error('executeScript requires exactly one of code or file to be specified');
        }
    },

    insertCSS: function(injectDetails, cb) {
        if (injectDetails.code) {
            exec(cb, null, "InAppBrowser", "injectStyleCode", [injectDetails.code, !!cb]);
        } else if (injectDetails.file) {
            exec(cb, null, "InAppBrowser", "injectStyleFile", [injectDetails.file, !!cb]);
        } else {
            throw new Error('insertCSS requires exactly one of code or file to be specified');
        }
    }
};

module.exports = function(strUrl, strWindowName, strWindowFeatures, callbacks) {
    // Don't catch calls that write to existing frames (e.g. named iframes).
    if (window.frames && window.frames[strWindowName]) {
        var origOpenFunc = modulemapper.getOriginalSymbol(window, 'open');
        return origOpenFunc.apply(window, arguments);
    }

    strUrl = urlutil.makeAbsolute(strUrl);
    var iab = new InAppBrowser();

    callbacks = callbacks || {};
    for (var callbackName in callbacks) {
        iab.addEventListener(callbackName, callbacks[callbackName]);
    }

    var cb = function(eventname) {
       iab._eventHandler(eventname);
    };

    strWindowFeatures = strWindowFeatures || "";

    exec(cb, cb, "InAppBrowser", "open", [strUrl, strWindowName, strWindowFeatures]);
    return iab;
};

<commit_msg>CB-9760 InAppBrowser: fallback to default window.open behavior on Ripple<commit_after>/*
 *
 * Licensed to the Apache Software Foundation (ASF) under one
 * or more contributor license agreements.  See the NOTICE file
 * distributed with this work for additional information
 * regarding copyright ownership.  The ASF licenses this file
 * to you under the Apache License, Version 2.0 (the
 * "License"); you may not use this file except in compliance
 * with the License.  You may obtain a copy of the License at
 *
 *   http://www.apache.org/licenses/LICENSE-2.0
 *
 * Unless required by applicable law or agreed to in writing,
 * software distributed under the License is distributed on an
 * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
 * KIND, either express or implied.  See the License for the
 * specific language governing permissions and limitations
 * under the License.
 *
*/

// special patch to correctly work on Ripple emulator (CB-9760)
if (window.parent && !!window.parent.ripple) { // https://gist.github.com/triceam/4658021
    module.exports = window.open.bind(window); // fallback to default window.open behaviour
    return;
}

var exec = require('cordova/exec');
var channel = require('cordova/channel');
var modulemapper = require('cordova/modulemapper');
var urlutil = require('cordova/urlutil');

function InAppBrowser() {
   this.channels = {
        'loadstart': channel.create('loadstart'),
        'loadstop' : channel.create('loadstop'),
        'loaderror' : channel.create('loaderror'),
        'exit' : channel.create('exit')
   };
}

InAppBrowser.prototype = {
    _eventHandler: function (event) {
        if (event && (event.type in this.channels)) {
            this.channels[event.type].fire(event);
        }
    },
    close: function (eventname) {
        exec(null, null, "InAppBrowser", "close", []);
    },
    show: function (eventname) {
      exec(null, null, "InAppBrowser", "show", []);
    },
    addEventListener: function (eventname,f) {
        if (eventname in this.channels) {
            this.channels[eventname].subscribe(f);
        }
    },
    removeEventListener: function(eventname, f) {
        if (eventname in this.channels) {
            this.channels[eventname].unsubscribe(f);
        }
    },

    executeScript: function(injectDetails, cb) {
        if (injectDetails.code) {
            exec(cb, null, "InAppBrowser", "injectScriptCode", [injectDetails.code, !!cb]);
        } else if (injectDetails.file) {
            exec(cb, null, "InAppBrowser", "injectScriptFile", [injectDetails.file, !!cb]);
        } else {
            throw new Error('executeScript requires exactly one of code or file to be specified');
        }
    },

    insertCSS: function(injectDetails, cb) {
        if (injectDetails.code) {
            exec(cb, null, "InAppBrowser", "injectStyleCode", [injectDetails.code, !!cb]);
        } else if (injectDetails.file) {
            exec(cb, null, "InAppBrowser", "injectStyleFile", [injectDetails.file, !!cb]);
        } else {
            throw new Error('insertCSS requires exactly one of code or file to be specified');
        }
    }
};

module.exports = function(strUrl, strWindowName, strWindowFeatures, callbacks) {
    // Don't catch calls that write to existing frames (e.g. named iframes).
    if (window.frames && window.frames[strWindowName]) {
        var origOpenFunc = modulemapper.getOriginalSymbol(window, 'open');
        return origOpenFunc.apply(window, arguments);
    }

    strUrl = urlutil.makeAbsolute(strUrl);
    var iab = new InAppBrowser();

    callbacks = callbacks || {};
    for (var callbackName in callbacks) {
        iab.addEventListener(callbackName, callbacks[callbackName]);
    }

    var cb = function(eventname) {
       iab._eventHandler(eventname);
    };

    strWindowFeatures = strWindowFeatures || "";

    exec(cb, cb, "InAppBrowser", "open", [strUrl, strWindowName, strWindowFeatures]);
    return iab;
};

<|endoftext|>


<commit_before>

var StartView = function(homeView) {

    this.homeView = homeView;

    this.initialize = function() {
        // 'div' wrapper to attach html and events to
        this.el = $('<div/>');
    };

    this.render = function() {
	if (!this.homeView) {
	    this.homeView = { enteredName:  "" }
	}
        this.el.html(StartView.template(this.homeView));

        return this;
    };

    this.getPhoneGapPath = function {

	var path = window.location.pathname;
	path = path.substr( path, path.length - 10 );
	return 'file://' + path;
    };

    this.playAudio = function {

	var url = getPhoneGapPath() + 'audio/eab-innovation.wav';

	var snd = new Media(url, function () { console.log("playAudio():Audio Success"); },
			         function (err) { console.log("playAudio():Audio Error: " + err); }
			   );

	// Play audio
	snd.play();

    }

    this.crossfade = function() {
	$("#svg-bubbles-div").animate({ opacity: 0 }, 700);
	$("#after-bubbles").css("display","block").animate({ opacity: 1 }, 700);

	this.playAudio();
    };

    this.initialize();
}

StartView.template = Handlebars.compile($("#start-tpl").html());

<commit_msg>Syntax error fix<commit_after>

var StartView = function(homeView) {

    this.homeView = homeView;

    this.initialize = function() {
        // 'div' wrapper to attach html and events to
        this.el = $('<div/>');
    };

    this.render = function() {
	if (!this.homeView) {
	    this.homeView = { enteredName:  "" }
	}
        this.el.html(StartView.template(this.homeView));

        return this;
    };

    this.getPhoneGapPath = function() {

	var path = window.location.pathname;
	path = path.substr( path, path.length - 10 );
	return 'file://' + path;
    };

    this.playAudio = function() {

	var url = this.getPhoneGapPath() + 'audio/eab-innovation.wav';

	var snd = new Media(url, function () { console.log("playAudio():Audio Success"); },
			         function (err) { console.log("playAudio():Audio Error: " + err); }
			   );

	// Play audio
	snd.play();

    };

    this.crossfade = function() {
	$("#svg-bubbles-div").animate({ opacity: 0 }, 700);
	$("#after-bubbles").css("display","block").animate({ opacity: 1 }, 700);

	this.playAudio();
    };

    this.initialize();
}

StartView.template = Handlebars.compile($("#start-tpl").html());

<|endoftext|>


<commit_before>function reloadKML() {
  var algo = 1;
  if (!wpc.layers.visible) return;
  if(osm.map.getZoom()<8) algo = 2;
  var zoom = osm.map.getZoom();
  var bounds = osm.map.getBounds();
  var minll = bounds.getSouthWest();
  var maxll = bounds.getNorthEast();
  if(wpc.zoom && wpc.bbox)
    if(wpc.zoom == zoom && minll.lng >= wpc.bbox[0] && minll.lat >= wpc.bbox[1] && maxll.lng <= wpc.bbox[2] && maxll.lat <= wpc.bbox[3])
      return;
  var w = maxll.lng - minll.lng;
  var h = maxll.lat - minll.lat;
  wpc.bbox = []
  wpc.bbox[0] = minll.lng - w/2;
  wpc.bbox[1] = minll.lat - h/2;
  wpc.bbox[2] = maxll.lng + w/2;
  wpc.bbox[3] = maxll.lat + h/2;
  wpc.zoom = zoom;
  wpc.layers.clearLayers();
  var url = 'wpc.php?bbox=' + wpc.bbox[0] + ',' + wpc.bbox[1] + ',' + wpc.bbox[2] + ',' + wpc.bbox[3] + '&algo=' + algo;
  wpc.layers.addKML(url);
}

osm.saveLocation = function() {
  var ll = osm.map.getCenter();
  var z = osm.map.getZoom();
  var currentBaseLayer = osm.map.control_layers.currentBaseLayer();
  var l = currentBaseLayer ? (osm.layerHashes[currentBaseLayer.name]) : '';

  var ol = '';
  var curOverlays = osm.map.control_layers.listCurrentOverlays();
  for(var i in curOverlays){
    var hash = osm.layerHashes[curOverlays[i].name] || '';
    //don't save OSB layer
    if(hash != 'U'){
        ol += hash;
    }
  }

  osm.setCookie("_osm_location=" + ll.lng + "|" + ll.lat + "|" + z + "|" + l + "|" + ol);
}

osm.editUpdate = function() {
  var pos = osm.map.getBounds();
  var url="http://127.0.0.1:8111/load_and_zoom?left=" + pos._southWest.lng + "&top=" + pos._northEast.lat + "&right=" + pos._northEast.lng + "&bottom=" + pos._southWest.lat;
  var edit = $_('EditJOSM');
  edit.target = 'hiddenIframe';
  edit.href = url;
}

osm.setLinkOSB = function() {
  if (parseInt(get['bugid'])) {
    osm.map.addLayer(osm.layers.osb);
    osm.map.control_layers._update();
  }
};

osm.leftpan.refsizetab = function() {
  var mi=$("#leftpantab .leftgroup");
  var dykH=$("#leftpantab #DidYouKnow")[0].offsetHeight;
  if (dykH)
    dykH += 34;
  var miHeight = +$("#leftpantab .leftgroup h1")[0].offsetHeight + parseFloat(mi.css('margin-bottom'))
  height=$("#leftpantab")[0].offsetHeight-(miHeight*mi.length+dykH);
  if (height < 100)
    height = 100;
  $('#leftpan .leftgroup .leftcontent').css('height', height+12+'px');
}

osm.leftpan.toggle = function(on, isClick) {
  fntoggle = function(id) {
    var el=$('#leftpantab #'+id+' .leftcontent');
    if (el.is(':visible'))
      $("#leftpan .leftcontent").hide("normal");
    else {
      all = $("#leftpan .leftcontent:visible");
      delay = 0;
      if (all.length){
        all.hide("normal");
        delay = 300;
      }
      el.stop().delay(delay).show("normal");
    }
  };
  if (typeof on == "undefined") on = !this.on;
  if (on != this.on) {
    this.on = on;
    if (on && on !== true) {
      $('#downpan').removeClass('left-off');
      search.disable();
      osm.validators.disable();
      osm.poi.disable();
      if (on === 'leftpersmap') {
        osm.markers.personalMap();
      } else if (on === "leftvalidator") {
        $('#lefterrorspan').addClass('on');
        $('#mainmenu .current li.errors').addClass('active');
        osm.validators.enable();
      } else if (on === 'leftpoi') {
        osm.poi.enable();
      } else if (on === 'leftsearch') {
        search.enable();
        $('#leftsearch').show();
      } else if (on) {
      }
      if (on != 1) fntoggle(on)
    } else {
      osm.setCookie("_osm_leftpan=" + on);
      if (on) {
        $('#downpan').removeClass('left-off');
        osm.leftpan.refsizetab();
      }
      else
        $('#downpan').addClass('left-off');
    }
    osm.map.invalidateSize();
  }
  else if (isClick)
    fntoggle(on);
};

osm.onPermalink = function () {
  mapCenter=osm.map.getCenter();
  osm.permalink.href = 'http://' + location.host + '?lat=' + mapCenter.lat + '&lon=' + mapCenter.lng + '&zoom=' + osm.map._zoom;
};

osm.ui.whereima = function() {
	osm.map.on('locationerror', function(e) {
		console.log("Browser based geo-location failed");
	});

	osm.map.locate({setView: true, maxZoom: 16});
};

osm.ui.togglehtp = function() {
  $('body').hasClass('htp') ? $('#htpbutton').html("↑") : $('#htpbutton').html("↓");
  $('body').toggleClass('htp');
  var on = !$('body').hasClass('htp');
  osm.setCookie("_osm_htp=" + on);
  setTimeout("osm.leftpan.refsizetab()", 100);
};

osm.ui.searchsubmit = function() {
  return search.search($_('qsearch').value);
}

osm.osbclickon = function(e) {
  if (e.className!="on") {
    osm.map.addLayer(osm.layers.osb);
  }
  else {
    osm.map.removeLayer(osm.layers.osb);
  }
  osm.map.control_layers._update();
}

osm.osbclick = function(e,on) {
  if (on==null) on=e.className!="on"
  if (on) {
    e.className="on";
    osm.map._mapPane.style.cursor="crosshair"
  }
  else {
    e.className="";
    osm.map._mapPane.style.cursor=""
  }
};

osm.opento = function() {
  var center = osm.map.getCenter();
  var zoom = osm.map.getZoom();
  $('#opento-osmorg')[0].href = 'http://openstreetmap.org/?' + 'lat=' + center.lat + '&lon=' + center.lng + '&zoom=' + zoom;
  $('#opento-google')[0].href = 'https://maps.google.ru/?' + 'll=' + center.lat + ',' + center.lng + '&z=' + zoom;
  $('#opento-yandex')[0].href = 'http://maps.yandex.ru/?' + 'll=' + center.lng + ',' + center.lat + '&z=' + zoom;
  $('#opento-wikimapia')[0].href = 'http://wikimapia.org/#' + 'lat=' + center.lat + '&lon=' + center.lng + '&z=' + zoom;
  $('#opento-bing')[0].href = 'http://www.bing.com/maps/?' + 'cp=' + center.lat + '~' + center.lng + '&lvl=' + zoom;
  $('#opento-panoramio')[0].href = 'http://www.panoramio.com/map/#' + 'lt=' + center.lat + '&ln=' + center.lng + '&z=' + (17 - zoom);
}

<commit_msg>fix высоты открытого элемента в левой панели<commit_after>function reloadKML() {
  var algo = 1;
  if (!wpc.layers.visible) return;
  if(osm.map.getZoom()<8) algo = 2;
  var zoom = osm.map.getZoom();
  var bounds = osm.map.getBounds();
  var minll = bounds.getSouthWest();
  var maxll = bounds.getNorthEast();
  if(wpc.zoom && wpc.bbox)
    if(wpc.zoom == zoom && minll.lng >= wpc.bbox[0] && minll.lat >= wpc.bbox[1] && maxll.lng <= wpc.bbox[2] && maxll.lat <= wpc.bbox[3])
      return;
  var w = maxll.lng - minll.lng;
  var h = maxll.lat - minll.lat;
  wpc.bbox = []
  wpc.bbox[0] = minll.lng - w/2;
  wpc.bbox[1] = minll.lat - h/2;
  wpc.bbox[2] = maxll.lng + w/2;
  wpc.bbox[3] = maxll.lat + h/2;
  wpc.zoom = zoom;
  wpc.layers.clearLayers();
  var url = 'wpc.php?bbox=' + wpc.bbox[0] + ',' + wpc.bbox[1] + ',' + wpc.bbox[2] + ',' + wpc.bbox[3] + '&algo=' + algo;
  wpc.layers.addKML(url);
}

osm.saveLocation = function() {
  var ll = osm.map.getCenter();
  var z = osm.map.getZoom();
  var currentBaseLayer = osm.map.control_layers.currentBaseLayer();
  var l = currentBaseLayer ? (osm.layerHashes[currentBaseLayer.name]) : '';

  var ol = '';
  var curOverlays = osm.map.control_layers.listCurrentOverlays();
  for(var i in curOverlays){
    var hash = osm.layerHashes[curOverlays[i].name] || '';
    //don't save OSB layer
    if(hash != 'U'){
        ol += hash;
    }
  }

  osm.setCookie("_osm_location=" + ll.lng + "|" + ll.lat + "|" + z + "|" + l + "|" + ol);
}

osm.editUpdate = function() {
  var pos = osm.map.getBounds();
  var url="http://127.0.0.1:8111/load_and_zoom?left=" + pos._southWest.lng + "&top=" + pos._northEast.lat + "&right=" + pos._northEast.lng + "&bottom=" + pos._southWest.lat;
  var edit = $_('EditJOSM');
  edit.target = 'hiddenIframe';
  edit.href = url;
}

osm.setLinkOSB = function() {
  if (parseInt(get['bugid'])) {
    osm.map.addLayer(osm.layers.osb);
    osm.map.control_layers._update();
  }
};

osm.leftpan.refsizetab = function() {
  var mi=$("#leftpantab .leftgroup");
  var dykH=$("#leftpantab #DidYouKnow")[0].offsetHeight;
  var count = mi.length - ($("#leftpantab #leftsearch")[0].offsetHeight?0:1)
  if (dykH)
    dykH += 34;
  var miHeight = +$("#leftpantab .leftgroup h1")[0].offsetHeight + parseFloat(mi.css('margin-bottom'))
  height=$("#leftpantab")[0].offsetHeight-(miHeight*count+dykH);
  if (height < 100)
    height = 100;
  $('#leftpan .leftgroup .leftcontent').css('height', height-12+'px');
}

osm.leftpan.toggle = function(on, isClick) {
  fntoggle = function(id) {
    var el=$('#leftpantab #'+id+' .leftcontent');
    if (el.is(':visible'))
      $("#leftpan .leftcontent").hide("normal");
    else {
      all = $("#leftpan .leftcontent:visible");
      delay = 0;
      if (all.length){
        all.hide("normal");
        delay = 300;
      }
      el.stop().delay(delay).show("normal");
    }
  };
  if (typeof on == "undefined") on = !this.on;
  if (on != this.on) {
    this.on = on;
    if (on && on !== true) {
      $('#downpan').removeClass('left-off');
      search.disable();
      osm.validators.disable();
      osm.poi.disable();
      if (on === 'leftpersmap') {
        osm.markers.personalMap();
      } else if (on === "leftvalidator") {
        $('#lefterrorspan').addClass('on');
        $('#mainmenu .current li.errors').addClass('active');
        osm.validators.enable();
      } else if (on === 'leftpoi') {
        osm.poi.enable();
      } else if (on === 'leftsearch') {
        search.enable();
        $('#leftsearch').show();
        osm.leftpan.refsizetab();
      } else if (on) {
      }
      if (on != 1) fntoggle(on)
    } else {
      osm.setCookie("_osm_leftpan=" + on);
      if (on) {
        $('#downpan').removeClass('left-off');
        osm.leftpan.refsizetab();
      }
      else
        $('#downpan').addClass('left-off');
    }
    osm.map.invalidateSize();
  }
  else if (isClick)
    fntoggle(on);
};

osm.onPermalink = function () {
  mapCenter=osm.map.getCenter();
  osm.permalink.href = 'http://' + location.host + '?lat=' + mapCenter.lat + '&lon=' + mapCenter.lng + '&zoom=' + osm.map._zoom;
};

osm.ui.whereima = function() {
	osm.map.on('locationerror', function(e) {
		console.log("Browser based geo-location failed");
	});

	osm.map.locate({setView: true, maxZoom: 16});
};

osm.ui.togglehtp = function() {
  $('body').hasClass('htp') ? $('#htpbutton').html("↑") : $('#htpbutton').html("↓");
  $('body').toggleClass('htp');
  var on = !$('body').hasClass('htp');
  osm.setCookie("_osm_htp=" + on);
  setTimeout("osm.leftpan.refsizetab()", 100);
};

osm.ui.searchsubmit = function() {
  return search.search($_('qsearch').value);
}

osm.osbclickon = function(e) {
  if (e.className!="on") {
    osm.map.addLayer(osm.layers.osb);
  }
  else {
    osm.map.removeLayer(osm.layers.osb);
  }
  osm.map.control_layers._update();
}

osm.osbclick = function(e,on) {
  if (on==null) on=e.className!="on"
  if (on) {
    e.className="on";
    osm.map._mapPane.style.cursor="crosshair"
  }
  else {
    e.className="";
    osm.map._mapPane.style.cursor=""
  }
};

osm.opento = function() {
  var center = osm.map.getCenter();
  var zoom = osm.map.getZoom();
  $('#opento-osmorg')[0].href = 'http://openstreetmap.org/?' + 'lat=' + center.lat + '&lon=' + center.lng + '&zoom=' + zoom;
  $('#opento-google')[0].href = 'https://maps.google.ru/?' + 'll=' + center.lat + ',' + center.lng + '&z=' + zoom;
  $('#opento-yandex')[0].href = 'http://maps.yandex.ru/?' + 'll=' + center.lng + ',' + center.lat + '&z=' + zoom;
  $('#opento-wikimapia')[0].href = 'http://wikimapia.org/#' + 'lat=' + center.lat + '&lon=' + center.lng + '&z=' + zoom;
  $('#opento-bing')[0].href = 'http://www.bing.com/maps/?' + 'cp=' + center.lat + '~' + center.lng + '&lvl=' + zoom;
  $('#opento-panoramio')[0].href = 'http://www.panoramio.com/map/#' + 'lt=' + center.lat + '&ln=' + center.lng + '&z=' + (17 - zoom);
}

<|endoftext|>


<commit_before>/*
 *
 * Licensed to the Apache Software Foundation (ASF) under one
 * or more contributor license agreements.  See the NOTICE file
 * distributed with this work for additional information
 * regarding copyright ownership.  The ASF licenses this file
 * to you under the Apache License, Version 2.0 (the
 * "License"); you may not use this file except in compliance
 * with the License.  You may obtain a copy of the License at
 *
 *   http://www.apache.org/licenses/LICENSE-2.0
 *
 * Unless required by applicable law or agreed to in writing,
 * software distributed under the License is distributed on an
 * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
 * KIND, either express or implied.  See the License for the
 * specific language governing permissions and limitations
 * under the License.
 *
*/

var exec = require('cordova/exec');
var platform = require('cordova/platform');

/**
 * Provides access to notifications on the device.
 */

module.exports = {

    /**
     * Open a native alert dialog, with a customizable title and button text.
     *
     * @param {String} message              Message to print in the body of the alert
     * @param {Function} completeCallback   The callback that is called when user clicks on a button.
     * @param {String} title                Title of the alert dialog (default: Alert)
     * @param {String} buttonLabel          Label of the close button (default: OK)
     */
    alert: function(message, completeCallback, title, buttonLabel) {
        var _message = (typeof message === "string" ? message : JSON.stringify(message));
        var _title = (typeof title === "string" ? title : "Alert");
        var _buttonLabel = (buttonLabel || "OK");
        exec(completeCallback, null, "Notification", "alert", [_message, _title, _buttonLabel]);
    },

    /**
     * Open a native confirm dialog, with a customizable title and button text.
     * The result that the user selects is returned to the result callback.
     *
     * @param {String} message              Message to print in the body of the alert
     * @param {Function} resultCallback     The callback that is called when user clicks on a button.
     * @param {String} title                Title of the alert dialog (default: Confirm)
     * @param {Array} buttonLabels          Array of the labels of the buttons (default: ['OK', 'Cancel'])
     */
    confirm: function(message, resultCallback, title, buttonLabels) {
        var _message = (typeof message === "string" ? message : JSON.stringify(message));
        var _title = (typeof title === "string" ? title : "Confirm");
        var _buttonLabels = (buttonLabels || ["OK", "Cancel"]);

        // Strings are deprecated!
        if (typeof _buttonLabels === 'string') {
            console.log("Notification.confirm(string, function, string, string) is deprecated.  Use Notification.confirm(string, function, string, array).");
        }

        _buttonLabels = convertButtonLabels(_buttonLabels);

        exec(resultCallback, null, "Notification", "confirm", [_message, _title, _buttonLabels]);
    },

    /**
     * Open a native prompt dialog, with a customizable title and button text.
     * The following results are returned to the result callback:
     *  buttonIndex     Index number of the button selected.
     *  input1          The text entered in the prompt dialog box.
     *
     * @param {String} message              Dialog message to display (default: "Prompt message")
     * @param {Function} resultCallback     The callback that is called when user clicks on a button.
     * @param {String} title                Title of the dialog (default: "Prompt")
     * @param {Array} buttonLabels          Array of strings for the button labels (default: ["OK","Cancel"])
     * @param {String} defaultText          Textbox input value (default: empty string)
     */
    prompt: function(message, resultCallback, title, buttonLabels, defaultText) {
        var _message = (typeof message === "string" ? message : JSON.stringify(message));
        var _title = (typeof title === "string" ? title : "Prompt");
        var _buttonLabels = (buttonLabels || ["OK","Cancel"]);

        // Strings are deprecated!
        if (typeof _buttonLabels === 'string') {
            console.log("Notification.prompt(string, function, string, string) is deprecated.  Use Notification.confirm(string, function, string, array).");
        }

        _buttonLabels = convertButtonLabels(_buttonLabels);

        var _defaultText = (defaultText || "");
        exec(resultCallback, null, "Notification", "prompt", [_message, _title, _buttonLabels, _defaultText]);
    },

    /**
     * Causes the device to beep.
     * On Android, the default notification ringtone is played "count" times.
     *
     * @param {Integer} count       The number of beeps.
     */
    beep: function(count) {
        var defaultedCount = count || 1;
        exec(null, null, "Notification", "beep", [ defaultedCount ]);
    }
};

function convertButtonLabels(buttonLabels) {

    // Some platforms take an array of button label names.
    // Other platforms take a comma separated list.
    // For compatibility, we convert to the desired type based on the platform.
    if (platform.id == "amazon-fireos" || platform.id == "android" || platform.id == "ios" ||
        platform.id == "windowsphone" || platform.id == "firefoxos" || platform.id == "ubuntu" ||
        platform.id == "windows8" || platform.id == "windows") {

        if (typeof buttonLabels === 'string') {
            buttonLabels = buttonLabels.split(","); // not crazy about changing the var type here
        }
    } else {
        if (Array.isArray(buttonLabels)) {
            var buttonLabelArray = buttonLabels;
            buttonLabels = buttonLabelArray.toString();
        }
    }

    return buttonLabels;
}
<commit_msg>Make sure the alert buttonLabel is a string<commit_after>/*
 *
 * Licensed to the Apache Software Foundation (ASF) under one
 * or more contributor license agreements.  See the NOTICE file
 * distributed with this work for additional information
 * regarding copyright ownership.  The ASF licenses this file
 * to you under the Apache License, Version 2.0 (the
 * "License"); you may not use this file except in compliance
 * with the License.  You may obtain a copy of the License at
 *
 *   http://www.apache.org/licenses/LICENSE-2.0
 *
 * Unless required by applicable law or agreed to in writing,
 * software distributed under the License is distributed on an
 * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
 * KIND, either express or implied.  See the License for the
 * specific language governing permissions and limitations
 * under the License.
 *
*/

var exec = require('cordova/exec');
var platform = require('cordova/platform');

/**
 * Provides access to notifications on the device.
 */

module.exports = {

    /**
     * Open a native alert dialog, with a customizable title and button text.
     *
     * @param {String} message              Message to print in the body of the alert
     * @param {Function} completeCallback   The callback that is called when user clicks on a button.
     * @param {String} title                Title of the alert dialog (default: Alert)
     * @param {String} buttonLabel          Label of the close button (default: OK)
     */
    alert: function(message, completeCallback, title, buttonLabel) {
        var _message = (typeof message === "string" ? message : JSON.stringify(message));
        var _title = (typeof title === "string" ? title : "Alert");
        var _buttonLabel = (typeof buttonLabel === "string" ? buttonLabel : "OK");
        exec(completeCallback, null, "Notification", "alert", [_message, _title, _buttonLabel]);
    },

    /**
     * Open a native confirm dialog, with a customizable title and button text.
     * The result that the user selects is returned to the result callback.
     *
     * @param {String} message              Message to print in the body of the alert
     * @param {Function} resultCallback     The callback that is called when user clicks on a button.
     * @param {String} title                Title of the alert dialog (default: Confirm)
     * @param {Array} buttonLabels          Array of the labels of the buttons (default: ['OK', 'Cancel'])
     */
    confirm: function(message, resultCallback, title, buttonLabels) {
        var _message = (typeof message === "string" ? message : JSON.stringify(message));
        var _title = (typeof title === "string" ? title : "Confirm");
        var _buttonLabels = (buttonLabels || ["OK", "Cancel"]);

        // Strings are deprecated!
        if (typeof _buttonLabels === 'string') {
            console.log("Notification.confirm(string, function, string, string) is deprecated.  Use Notification.confirm(string, function, string, array).");
        }

        _buttonLabels = convertButtonLabels(_buttonLabels);

        exec(resultCallback, null, "Notification", "confirm", [_message, _title, _buttonLabels]);
    },

    /**
     * Open a native prompt dialog, with a customizable title and button text.
     * The following results are returned to the result callback:
     *  buttonIndex     Index number of the button selected.
     *  input1          The text entered in the prompt dialog box.
     *
     * @param {String} message              Dialog message to display (default: "Prompt message")
     * @param {Function} resultCallback     The callback that is called when user clicks on a button.
     * @param {String} title                Title of the dialog (default: "Prompt")
     * @param {Array} buttonLabels          Array of strings for the button labels (default: ["OK","Cancel"])
     * @param {String} defaultText          Textbox input value (default: empty string)
     */
    prompt: function(message, resultCallback, title, buttonLabels, defaultText) {
        var _message = (typeof message === "string" ? message : JSON.stringify(message));
        var _title = (typeof title === "string" ? title : "Prompt");
        var _buttonLabels = (buttonLabels || ["OK","Cancel"]);

        // Strings are deprecated!
        if (typeof _buttonLabels === 'string') {
            console.log("Notification.prompt(string, function, string, string) is deprecated.  Use Notification.confirm(string, function, string, array).");
        }

        _buttonLabels = convertButtonLabels(_buttonLabels);

        var _defaultText = (defaultText || "");
        exec(resultCallback, null, "Notification", "prompt", [_message, _title, _buttonLabels, _defaultText]);
    },

    /**
     * Causes the device to beep.
     * On Android, the default notification ringtone is played "count" times.
     *
     * @param {Integer} count       The number of beeps.
     */
    beep: function(count) {
        var defaultedCount = count || 1;
        exec(null, null, "Notification", "beep", [ defaultedCount ]);
    }
};

function convertButtonLabels(buttonLabels) {

    // Some platforms take an array of button label names.
    // Other platforms take a comma separated list.
    // For compatibility, we convert to the desired type based on the platform.
    if (platform.id == "amazon-fireos" || platform.id == "android" || platform.id == "ios" ||
        platform.id == "windowsphone" || platform.id == "firefoxos" || platform.id == "ubuntu" ||
        platform.id == "windows8" || platform.id == "windows") {

        if (typeof buttonLabels === 'string') {
            buttonLabels = buttonLabels.split(","); // not crazy about changing the var type here
        }
    } else {
        if (Array.isArray(buttonLabels)) {
            var buttonLabelArray = buttonLabels;
            buttonLabels = buttonLabelArray.toString();
        }
    }

    return buttonLabels;
}
<|endoftext|>


<commit_before>import parser from 'ua-parser-js';
import { steamBrowser, supportedLanguages, unsupported } from './browsercheck-utils';

// Adapted from 'is-browser-supported' npm package. Separate from index.js so it'll run even if that fails.
// This is also intentionally written in es5 and not TypeScript because it should not use any new features.

function getBrowserName(agent) {
  if (agent.browser.name === 'Chrome' && agent.os.name === 'Android') {
    return 'and_chr';
  } else if (agent.browser.name === 'Firefox' && agent.os.name === 'Android') {
    return 'and_ff';
  } else if (agent.browser.name === 'Mobile Safari' || agent.os.name === 'iOS') {
    return 'ios_saf';
  } else if (agent.browser.name === 'Chromium') {
    return 'chrome';
  } else if (agent.browser.name === 'Opera') {
    return 'opera';
  }
  return agent.browser.name;
}

function getUserLocale() {
  var lang = (window.navigator.userLanguage || window.navigator.language).toLowerCase() || 'en';
  console.info('Language Detected: ' + lang);
  if (!supportedLanguages.includes(lang)) {
    lang = lang.split('-', 1);
  }
  if (!supportedLanguages.includes(lang)) {
    // fallback to 'en' if unsupported language after removing dialect
    lang = 'en';
  }
  console.info('Language Assigned: ' + lang);
  return lang;
}

function getBrowserVersionFromUserAgent(agent) {
  var browserName = getBrowserName(agent).toLowerCase();
  var version = (
    browserName === 'ios_saf' ? agent.os.version : agent.browser.version || agent.os.version || ''
  ).split('.');
  while (version.length > 0) {
    try {
      return browserName + ' ' + version.join('.');
    } catch (e) {
      // Ignore unknown browser query error
    }
    version.pop();
  }
  return 'unknown';
}

export function isSupported(browsersSupported, userAgent) {
  if (userAgent.includes('Steam')) {
    return false;
  }

  if (navigator.standalone) {
    // Assume support if we're installed as an iOS PWA.
    return true;
  }

  var agent = parser(userAgent);

  // Build a map from browser version to minimum supported version
  var minBrowserVersions = {};
  for (var i = 0; i < browsersSupported.length; i++) {
    // ios_saf 11.0-11.2 => [ios_saf, 11.0, 11.2]
    var supportedBrowserVersion = browsersSupported[i].split(/[- ]/);
    minBrowserVersions[supportedBrowserVersion[0]] = Math.min(
      minBrowserVersions[supportedBrowserVersion[0]] || 999999,
      parseFloat(supportedBrowserVersion[1])
    );
  }

  function isBrowserSupported(browser) {
    var nameAndVersion = browser.split(' ');
    if (
      minBrowserVersions[nameAndVersion[0]] &&
      minBrowserVersions[nameAndVersion[0]] <= parseFloat(nameAndVersion[1])
    ) {
      return true;
    }
    return false;
  }

  var browser = getBrowserVersionFromUserAgent(agent);
  var supported = isBrowserSupported(browser);

  if (!supported && agent.os.name !== 'Android') {
    // Detect anything based on chrome as if it were chrome
    var chromeMatch = /Chrome\/(\d+)/.exec(agent.ua);
    if (chromeMatch) {
      browser = 'chrome ' + chromeMatch[1];
      supported = isBrowserSupported(browser);
    }
  }
  if (!supported) {
    console.warn(
      'Browser ' + browser + ' is not supported by DIM. Supported browsers:',
      browsersSupported
    );
  }
  return supported;
}

var lang = getUserLocale();

if ($BROWSERS.length && lang) {
  // t('Browsercheck.Unsupported')
  // t('Browsercheck.Steam')
  var supported = isSupported($BROWSERS, navigator.userAgent);
  if (!supported) {
    document.getElementById('browser-warning').innerText = unsupported[lang];
    document.getElementById('browser-warning').style.display = 'block';
    if (navigator.userAgent.includes('Steam')) {
      document.getElementById('browser-warning').innerText = steamBrowser[lang];
    }
  }
}
<commit_msg>language detection fix<commit_after>import parser from 'ua-parser-js';
import { steamBrowser, supportedLanguages, unsupported } from './browsercheck-utils';

// Adapted from 'is-browser-supported' npm package. Separate from index.js so it'll run even if that fails.
// This is also intentionally written in es5 and not TypeScript because it should not use any new features.

function getBrowserName(agent) {
  if (agent.browser.name === 'Chrome' && agent.os.name === 'Android') {
    return 'and_chr';
  } else if (agent.browser.name === 'Firefox' && agent.os.name === 'Android') {
    return 'and_ff';
  } else if (agent.browser.name === 'Mobile Safari' || agent.os.name === 'iOS') {
    return 'ios_saf';
  } else if (agent.browser.name === 'Chromium') {
    return 'chrome';
  } else if (agent.browser.name === 'Opera') {
    return 'opera';
  }
  return agent.browser.name;
}

function getUserLocale() {
  var lang = (window.navigator.userLanguage || window.navigator.language).toLowerCase() || 'en';
  console.info('Language Detected: ' + lang);
  if (!supportedLanguages.includes(lang)) {
    lang = lang.split('-', 1)[0];
  }
  if (!supportedLanguages.includes(lang)) {
    // fallback to 'en' if unsupported language after removing dialect
    lang = 'en';
  }
  console.info('Language Assigned: ' + lang);
  return lang;
}

function getBrowserVersionFromUserAgent(agent) {
  var browserName = getBrowserName(agent).toLowerCase();
  var version = (
    browserName === 'ios_saf' ? agent.os.version : agent.browser.version || agent.os.version || ''
  ).split('.');
  while (version.length > 0) {
    try {
      return browserName + ' ' + version.join('.');
    } catch (e) {
      // Ignore unknown browser query error
    }
    version.pop();
  }
  return 'unknown';
}

export function isSupported(browsersSupported, userAgent) {
  if (userAgent.includes('Steam')) {
    return false;
  }

  if (navigator.standalone) {
    // Assume support if we're installed as an iOS PWA.
    return true;
  }

  var agent = parser(userAgent);

  // Build a map from browser version to minimum supported version
  var minBrowserVersions = {};
  for (var i = 0; i < browsersSupported.length; i++) {
    // ios_saf 11.0-11.2 => [ios_saf, 11.0, 11.2]
    var supportedBrowserVersion = browsersSupported[i].split(/[- ]/);
    minBrowserVersions[supportedBrowserVersion[0]] = Math.min(
      minBrowserVersions[supportedBrowserVersion[0]] || 999999,
      parseFloat(supportedBrowserVersion[1])
    );
  }

  function isBrowserSupported(browser) {
    var nameAndVersion = browser.split(' ');
    if (
      minBrowserVersions[nameAndVersion[0]] &&
      minBrowserVersions[nameAndVersion[0]] <= parseFloat(nameAndVersion[1])
    ) {
      return true;
    }
    return false;
  }

  var browser = getBrowserVersionFromUserAgent(agent);
  var supported = isBrowserSupported(browser);

  if (!supported && agent.os.name !== 'Android') {
    // Detect anything based on chrome as if it were chrome
    var chromeMatch = /Chrome\/(\d+)/.exec(agent.ua);
    if (chromeMatch) {
      browser = 'chrome ' + chromeMatch[1];
      supported = isBrowserSupported(browser);
    }
  }
  if (!supported) {
    console.warn(
      'Browser ' + browser + ' is not supported by DIM. Supported browsers:',
      browsersSupported
    );
  }
  return supported;
}

var lang = getUserLocale();

if ($BROWSERS.length && lang) {
  // t('Browsercheck.Unsupported')
  // t('Browsercheck.Steam')
  var supported = isSupported($BROWSERS, navigator.userAgent);
  if (!supported) {
    document.getElementById('browser-warning').innerText = unsupported[lang];
    document.getElementById('browser-warning').style.display = 'block';
    if (navigator.userAgent.includes('Steam')) {
      document.getElementById('browser-warning').innerText = steamBrowser[lang];
    }
  }
}
<|endoftext|>


<commit_before>
/**
 * UI.Field
 */

UI.Field = new Class({

	Extends: UI.Control,

	options: {
		name: 'field',
		base: 'control',
		tag: 'div',
		type: 'input',
		value: null,
		error: true,
		useTextAsLabel: false,
		inkFx: {
		    duration: 200,
		    link: 'chain',
		    transition: Fx.Transitions.Quart.easeOut
		},
		binding: {
			_list: ['input'],
			input: {
				'input.keyup': '_onKeyUp',
				'input.keydown': '_onKeyDown',
				'input.mousedown': '_onMouseDown',
				'input.focus': '_onFocus',
				'input.blur': '_onBlur'
			}
		}
	},

	/**
	 * [_initElement description]
	 * @return {[type]} [description]
	 */
	_initElement: function(){
		//create a new div as input element
		this.parent();

		var opts = this.options;

		this.element.addClass('ui-field');

		if (opts.klss)
			this.element.addClass(opts.klss);

		if (opts.label !== false)
			this._initLabel();

		this._initInput();

		if (opts.error)
			this._initError();
	},

	/**
	 * [_initLabel description]
	 * @return {[type]} [description]
	 */
	_initLabel: function()  {
		var text = this.options.name;

		if (this.options.useTextAsLabel)
			text = this.options.text;

		this.label = new Element('label', {
			html: text,
			'for': this.options.name
		}).inject(this.element);
	},

	/**
	 * [_initInput description]
	 * @return {[type]} [description]
	 */
	_initInput: function()  {
		//_log('_initInput', this.options);

		this.input = new Element('input', {
			name: this.options.name,
			type: this.options.type,
			value: this.options.value,
			placeholder: this.options.text
		}).inject(this.element);

		if (this.readonly) {
			this.input.set('readonly', 'readonly');
			this.input.set('tabindex', '-1');
		}

		return this.input;
	},

	/**
	 * [_initName description]
	 * @param  {[type]} name [description]
	 * @return {[type]}      [description]
	 */
	_initName: function(name) {
		var opts = this.options;

		if (opts.name) {
			this.label.set('html', name);
			this.input.set('name', name);
		}
	},

	/**
	 * [_initValue description]
	 * @return {[type]} [description]
	 */
	_initValue: function(){
		var opts = this.options;

		//create a new div as input element
		if (opts.value)
			this.setValue(opts.value);
	},

	/**
	 * [getValue description]
	 * @return {[type]} [description]
	 */
	getValue: function(){
		return this.input.get('value');
	},

	/**
	 * [setValue description]
	 * @param {[type]} value [description]
	 */
	setValue: function(value){
		this.input.set('value', value);
		this.value = value;
		this.fireEvent('change' , value);
	},

	/**
	 * [_initEvents description]
	 * @return {[type]} [description]
	 */
	_initEvents: function() {
		this.parent();

		this.addEvents({
			blur: this.setState.bind(this, 'default'),
			focus: this.setState.bind(this, 'focus')
		});
	},

	/**
	 * [_onKeyUp description]
	 * @return {[type]} [description]
	 */
	_onKeyUp: function(e) {
		this.fireEvent('change', this.get('value'));
	},

	/**
	 * [_onKeyUp description]
	 * @return {[type]} [description]
	 */
	onKeyDown: function(e) {
		//_log('keydown');
		if (this.readonly) {
			e.stop();
			return;
		}

		this.fireEvent('change', this.get('value'));
	},

	/**
	 * [_onMouseDown description]
	 * @return {[type]} [description]
	 */
	_onMouseDown: function(e) {
		//_log('mousedown');

		if (this.readonly) return;

		this.isFocused = true;
		this.setState('focus');
		this._inputFocus(e);
		//e.stopPropagation();
		//this.focus();
		//this._inputFocus(e);
	},

	/**
	 * [_onFocus description]
	 * @return {[type]} [description]
	 */
	_onFocus: function(e) {
		//_log('focus');

		if (this.readonly) return;

		this.isFocused = true;
		this.setState('focus');
		this._inputFocus(e);
	},

	/**
	 * [_onBlur description]
	 * @return {[type]} [description]
	 */
	_onBlur: function(e) {
		//_log('_onBlur');

		if (this.readonly) return;

		this.setState(null);
		this._hideInk();
		this.isFocused = false;
	},

	/**
	 * [_inputFocus description]
	 * @param  {event} e [description]
	 * @return {[type]}   [description]
	 */
	_inputFocus: function(e) {
		//_log('_inputFocus', e);

		this.fireEvent('mousedown');

		this._showInk(e);

		this.isFocused = true;
	},

	/**
	 * [_initInk description]
	 * @return {[type]} [description]
	 */
	_initInk: function() {
		var opts = this.options;

		this.ink = new Element('span', {
			class: 'field-ink'
		}).inject(this.element);

		this.inkFx = new Fx.Morph(this.ink, opts.inkFx);
	},

	/**
	 * [_initEffect description]
	 * @param  {[type]} inner [description]
	 * @param  {[type]} x     [description]
	 * @param  {[type]} y     [description]
	 * @return {[type]}       [description]
	 */
	_showInk: function(e) {
		_log('_showInk');

		if (this.readonly) return;

		//if (this.ink) return;

		var coord = this.input.getCoordinates(this.element);

		var x = coord.width / 2;

		if (e === 0)
			x = 0;
		else if (e && e.event && e.event.offsetX)
			x = e.event.offsetX;

		var size = coord.width,
			top = 0;

		if (!this.ink)
			this._initInk();

		this.ink.setStyles({
			left: x
		});

		this.inkFx.start({
		    width: size,
		    top: coord.top + coord.height - 2,
		    bottom: 'initial',
		    left: coord.left,
		    opacity: 1
		});
	},

	/**
	 * [_initEffect description]
	 * @param  {[type]} inner [description]
	 * @param  {[type]} x     [description]
	 * @param  {[type]} y     [description]
	 * @return {[type]}       [description]
	 */
	_setInk: function(e) {
		_log('_showInk');

		if (this.readonly) return;

		//if (this.ink) return;

		var coord = this.input.getCoordinates(this.element);

		var x = coord.width / 2;

		var size = coord.width,
			top = 0;

		if (!this.ink)
			this._initInk();

		this.inkFx.set({
		    width: size,
		    top: coord.top + coord.height - 2,
		    bottom: 'initial',
		    left: coord.left,
		    opacity: 1
		});
	},

	/**
	 * [_initEffect description]
	 * @param  {[type]} inner [description]
	 * @param  {[type]} x     [description]
	 * @param  {[type]} y     [description]
	 * @return {[type]}       [description]
	 */
	_hideInk: function() {
		var self= this;
		var coord = this.input.getCoordinates(this.element);
		var size = coord.width / 2;

		if (!this.inkFx) {
			//console.log('errorrrrrrr');
			return;
		}

		this.inkFx.start({
		    width: 0,
		    left:size,
		    top: coord.top + coord.height - 2,
		    bottom: 'initial',
			opacity: 0
		});

		(function() {
			if (self.ink) {
				self.ink.destroy();
				self.ink = null;
			}
		}).delay(100);
	},

	/**
	 * [_initError description]
	 * @return {[type]} [description]
	 */
	_initError: function() {
		this.error = new Element('span', {
			class: 'error-message'
		}).inject(this.element);
	},

	/**
	 * [set description]
	 * @param {[type]} name  [description]
	 * @param {[type]} value [description]
	 */
	set: function(value) {
		//_log('set', value);

		this.input.set('value', value);
		this.fireEvent('change', value);
	},

	/**
	 * [setError description]
	 * @param {[type]} error [description]
	 */
	setError: function(error) {

		if (error) {
			this.element.addClass('field-error');
				if (this.error)
					this.error.set('html', error);
		} else {
			if (this.error)
				this.element.removeClass('field-error');
				if (this.error)
					this.error.set('html', '');
		}

	}

});

<commit_msg>remove log<commit_after>
/**
 * UI.Field
 */

UI.Field = new Class({

	Extends: UI.Control,

	options: {
		name: 'field',
		base: 'control',
		tag: 'div',
		type: 'input',
		value: null,
		error: true,
		useTextAsLabel: false,
		inkFx: {
		    duration: 200,
		    link: 'chain',
		    transition: Fx.Transitions.Quart.easeOut
		},
		binding: {
			_list: ['input'],
			input: {
				'input.keyup': '_onKeyUp',
				'input.keydown': '_onKeyDown',
				'input.mousedown': '_onMouseDown',
				'input.focus': '_onFocus',
				'input.blur': '_onBlur'
			}
		}
	},

	/**
	 * [_initElement description]
	 * @return {[type]} [description]
	 */
	_initElement: function(){
		//create a new div as input element
		this.parent();

		var opts = this.options;

		this.element.addClass('ui-field');

		if (opts.klss)
			this.element.addClass(opts.klss);

		if (opts.label !== false)
			this._initLabel();

		this._initInput();

		if (opts.error)
			this._initError();
	},

	/**
	 * [_initLabel description]
	 * @return {[type]} [description]
	 */
	_initLabel: function()  {
		var text = this.options.name;

		if (this.options.useTextAsLabel)
			text = this.options.text;

		this.label = new Element('label', {
			html: text,
			'for': this.options.name
		}).inject(this.element);
	},

	/**
	 * [_initInput description]
	 * @return {[type]} [description]
	 */
	_initInput: function()  {
		//_log('_initInput', this.options);

		this.input = new Element('input', {
			name: this.options.name,
			type: this.options.type,
			value: this.options.value,
			placeholder: this.options.text
		}).inject(this.element);

		if (this.readonly) {
			this.input.set('readonly', 'readonly');
			this.input.set('tabindex', '-1');
		}

		return this.input;
	},

	/**
	 * [_initName description]
	 * @param  {[type]} name [description]
	 * @return {[type]}      [description]
	 */
	_initName: function(name) {
		var opts = this.options;

		if (opts.name) {
			this.label.set('html', name);
			this.input.set('name', name);
		}
	},

	/**
	 * [_initValue description]
	 * @return {[type]} [description]
	 */
	_initValue: function(){
		var opts = this.options;

		//create a new div as input element
		if (opts.value)
			this.setValue(opts.value);
	},

	/**
	 * [getValue description]
	 * @return {[type]} [description]
	 */
	getValue: function(){
		return this.input.get('value');
	},

	/**
	 * [setValue description]
	 * @param {[type]} value [description]
	 */
	setValue: function(value){
		this.input.set('value', value);
		this.value = value;
		this.fireEvent('change' , value);
	},

	/**
	 * [_initEvents description]
	 * @return {[type]} [description]
	 */
	_initEvents: function() {
		this.parent();

		this.addEvents({
			blur: this.setState.bind(this, 'default'),
			focus: this.setState.bind(this, 'focus')
		});
	},

	/**
	 * [_onKeyUp description]
	 * @return {[type]} [description]
	 */
	_onKeyUp: function(e) {
		this.fireEvent('change', this.get('value'));
	},

	/**
	 * [_onKeyUp description]
	 * @return {[type]} [description]
	 */
	onKeyDown: function(e) {
		//_log('keydown');
		if (this.readonly) {
			e.stop();
			return;
		}

		this.fireEvent('change', this.get('value'));
	},

	/**
	 * [_onMouseDown description]
	 * @return {[type]} [description]
	 */
	_onMouseDown: function(e) {
		//_log('mousedown');

		if (this.readonly) return;

		this.isFocused = true;
		this.setState('focus');
		this._inputFocus(e);
		//e.stopPropagation();
		//this.focus();
		//this._inputFocus(e);
	},

	/**
	 * [_onFocus description]
	 * @return {[type]} [description]
	 */
	_onFocus: function(e) {
		//_log('focus');

		if (this.readonly) return;

		this.isFocused = true;
		this.setState('focus');
		this._inputFocus(e);
	},

	/**
	 * [_onBlur description]
	 * @return {[type]} [description]
	 */
	_onBlur: function(e) {
		//_log('_onBlur');

		if (this.readonly) return;

		this.setState(null);
		this._hideInk();
		this.isFocused = false;
	},

	/**
	 * [_inputFocus description]
	 * @param  {event} e [description]
	 * @return {[type]}   [description]
	 */
	_inputFocus: function(e) {
		//_log('_inputFocus', e);

		this.fireEvent('mousedown');

		this._showInk(e);

		this.isFocused = true;
	},

	/**
	 * [_initInk description]
	 * @return {[type]} [description]
	 */
	_initInk: function() {
		var opts = this.options;

		this.ink = new Element('span', {
			class: 'field-ink'
		}).inject(this.element);

		this.inkFx = new Fx.Morph(this.ink, opts.inkFx);
	},

	/**
	 * [_initEffect description]
	 * @param  {[type]} inner [description]
	 * @param  {[type]} x     [description]
	 * @param  {[type]} y     [description]
	 * @return {[type]}       [description]
	 */
	_showInk: function(e) {
		_log('_showInk');

		if (this.readonly) return;

		//if (this.ink) return;

		var coord = this.input.getCoordinates(this.element);

		var x = coord.width / 2;

		if (e === 0)
			x = 0;
		else if (e && e.event && e.event.offsetX)
			x = e.event.offsetX;

		var size = coord.width,
			top = 0;

		if (!this.ink)
			this._initInk();

		this.ink.setStyles({
			left: x
		});

		this.inkFx.start({
		    width: size,
		    top: coord.top + coord.height - 2,
		    bottom: 'initial',
		    left: coord.left,
		    opacity: 1
		});
	},

	/**
	 * [_initEffect description]
	 * @param  {[type]} inner [description]
	 * @param  {[type]} x     [description]
	 * @param  {[type]} y     [description]
	 * @return {[type]}       [description]
	 */
	_setInk: function(e) {
		//_log('_showInk');

		if (this.readonly) return;

		//if (this.ink) return;

		var coord = this.input.getCoordinates(this.element);

		var x = coord.width / 2;

		var size = coord.width,
			top = 0;

		if (!this.ink)
			this._initInk();

		this.inkFx.set({
		    width: size,
		    top: coord.top + coord.height - 2,
		    bottom: 'initial',
		    left: coord.left,
		    opacity: 1
		});
	},

	/**
	 * [_initEffect description]
	 * @param  {[type]} inner [description]
	 * @param  {[type]} x     [description]
	 * @param  {[type]} y     [description]
	 * @return {[type]}       [description]
	 */
	_hideInk: function() {
		var self= this;
		var coord = this.input.getCoordinates(this.element);
		var size = coord.width / 2;

		if (!this.inkFx) {
			//console.log('errorrrrrrr');
			return;
		}

		this.inkFx.start({
		    width: 0,
		    left:size,
		    top: coord.top + coord.height - 2,
		    bottom: 'initial',
			opacity: 0
		});

		(function() {
			if (self.ink) {
				self.ink.destroy();
				self.ink = null;
			}
		}).delay(100);
	},

	/**
	 * [_initError description]
	 * @return {[type]} [description]
	 */
	_initError: function() {
		this.error = new Element('span', {
			class: 'error-message'
		}).inject(this.element);
	},

	/**
	 * [set description]
	 * @param {[type]} name  [description]
	 * @param {[type]} value [description]
	 */
	set: function(value) {
		//_log('set', value);

		this.input.set('value', value);
		this.fireEvent('change', value);
	},

	/**
	 * [setError description]
	 * @param {[type]} error [description]
	 */
	setError: function(error) {

		if (error) {
			this.element.addClass('field-error');
				if (this.error)
					this.error.set('html', error);
		} else {
			if (this.error)
				this.element.removeClass('field-error');
				if (this.error)
					this.error.set('html', '');
		}

	}

});

<|endoftext|>


<commit_before>/*!
	Adds a SQL filter to a query based on
	the resource_request object information
*/

var typs = require('typs');
var squel = require('squel');

// adds WHERE clause to a query
var filterBy = function (query, request, context) {

	let resource = context.resources[request.type];

	if (typs(request.superset).def().check()) {
		query =	query.where(
			// the primary key of the request resource
			request.type + '.' + context.resources[request.type].primary_key + ' IN ?',
			// is in the values returned by the relationship
			squel.select()
				.from(request.relationship.sql_table)
				.field(request.relationship.to_key)
				// filter from the superset
				.where(
					request.relationship.from_key + ' IN ?',
					filterBy(
						squel.select()
							.from(context.resources[request.superset.type].sql_table)
							.field(context.resources[request.superset.type].primary_key),
						request.superset,
						context
					)
				)
		);
	}

	if (typs(request.ids).def().check() && request.ids[0] !== 'any') {
		query = query.where(resource.sql_table + '.' + resource.primary_key + ' IN ?', request.ids);
	}

	request.filters.forEach(({field, values}) => {
		query = query.where(resource.sql_table + '.' + resource.columns[field] + ' IN ?', values);
	});

	request.sorters.forEach(({field, asc}) => {
		query = query.order(resource.sql_table + '.' + resource.columns[field], asc);
	});

	return query;
};

var selectBy = function (request, context) {
	// alias columns to exposed field names
	let addFields = (query, req, prefix) => {
		return req.fields.reduce((q, field) => q.field(prefix + '.' + context.resources[req.type].columns[field], prefix + '$' + field), query);
	};

	// base query
	let query = squel.select();
	let base_alias = request.main.type;

	query = query.from(context.resources[request.main.type].sql_table, base_alias);

	// related resources
	if (typs(request.related).def().check()) {

		// craft the prefix for deep relationships
		let ancestors = (rel) => {
			if (typs(rel).equals(request.main).check()) {
				return base_alias;
			} else if (typs(rel.superset).def().check()) {
				// chain the name of the relationships
				return ancestors(rel.superset).concat(rel.superset.relationship.name);
			}
			return [request.main.type];//[rel.relationship.type];
		};

		// dig down the tree of relationships
		// and extract the correct joins to do
		// moreover, rearrange them to respect order of conditions
		let buildJoin = (rel, query) => {
			// prefix the names with their relationship path
			let makeAlias = (r) => ancestors(r).concat(r.relationship.name).join('$');

			// if the relationship is deep, we have to build it to the top
			if (typs(rel.superset).def().check()) {
				query = buildJoin(rel.superset, query);
			}

			let rel_alias = makeAlias(rel);
			let rel_info_alias = rel_alias + '$info';
			let rel_superset = rel.superset || request.main;
			let rel_superset_alias = typs(rel.superset).def().check() ? makeAlias(rel.superset) : base_alias;

			// table where is stored the related resource
			query = query.join(
				context.resources[rel.relationship.type].sql_table,
				rel_alias
			);
			// table where is stored the relationship
			query = query.join(
				rel.relationship.sql_table,
				rel_info_alias,
				rel_alias + '.' + context.resources[rel.relationship.type].primary_key +
				' = ' +
				rel_info_alias + '.' + rel.relationship.to_key +
				' AND ' +
				rel_info_alias + '.' + rel.relationship.from_key +
				' = ' +
				rel_superset_alias + '.' + context.resources[rel_superset.type].primary_key
			);

			return query;
		};

		request.related.forEach((rel) => {
			// set the fields to fetch
			query = addFields(
				// build then add the joins
				buildJoin(rel, query),
				rel,
				ancestors(rel).concat(rel.relationship.name).join('$')
			);
		});
	}

	// add main resource fields
	query = addFields(filterBy(query, request.main, context), request.main, base_alias);

	return query;
};

module.exports = {filterBy, selectBy};
<commit_msg>fixed duplicate joins bug<commit_after>/*!
	Adds a SQL filter to a query based on
	the resource_request object information
*/

var typs = require('typs');
var squel = require('squel');

// adds WHERE clause to a query
var filterBy = function (query, request, context) {

	let resource = context.resources[request.type];

	if (typs(request.superset).def().check()) {
		query =	query.where(
			// the primary key of the request resource
			request.type + '.' + context.resources[request.type].primary_key + ' IN ?',
			// is in the values returned by the relationship
			squel.select()
				.from(request.relationship.sql_table)
				.field(request.relationship.to_key)
				// filter from the superset
				.where(
					request.relationship.from_key + ' IN ?',
					filterBy(
						squel.select()
							.from(context.resources[request.superset.type].sql_table)
							.field(context.resources[request.superset.type].primary_key),
						request.superset,
						context
					)
				)
		);
	}

	if (typs(request.ids).def().check() && request.ids[0] !== 'any') {
		query = query.where(resource.sql_table + '.' + resource.primary_key + ' IN ?', request.ids);
	}

	request.filters.forEach(({field, values}) => {
		query = query.where(resource.sql_table + '.' + resource.columns[field] + ' IN ?', values);
	});

	request.sorters.forEach(({field, asc}) => {
		query = query.order(resource.sql_table + '.' + resource.columns[field], asc);
	});

	return query;
};

var selectBy = function (request, context) {
	// alias columns to exposed field names
	let addFields = (query, req, prefix) => {
		return req.fields.reduce((q, field) => q.field(prefix + '.' + context.resources[req.type].columns[field], prefix + '$' + field), query);
	};

	// base query
	let query = squel.select();
	let base_alias = request.main.type;

	query = query.from(context.resources[request.main.type].sql_table, base_alias);

	// related resources
	if (typs(request.related).def().check()) {

		// craft the prefix for deep relationships
		let ancestors = (rel) => {
			if (typs(rel).equals(request.main).check()) {
				return base_alias;
			} else if (typs(rel.superset).def().check()) {
				// chain the name of the relationships
				return ancestors(rel.superset).concat(rel.superset.relationship.name);
			}
			return [request.main.type];//[rel.relationship.type];
		};

		// list of the joined tables
		let joined = [];

		// dig down the tree of relationships
		// and extract the correct joins to do
		// moreover, rearrange them to respect order of conditions
		let buildJoin = (rel, query) => {
			// prefix the names with their relationship path
			let makeAlias = (r) => ancestors(r).concat(r.relationship.name).join('$');

			// if the relationship is deep, we have to build it to the top
			if (typs(rel.superset).def().check()) {
				query = buildJoin(rel.superset, query);
			}

			let rel_alias = makeAlias(rel);
			let rel_info_alias = rel_alias + '$info';
			let rel_superset = rel.superset || request.main;
			let rel_superset_alias = typs(rel.superset).def().check() ? makeAlias(rel.superset) : base_alias;

			if (typs(rel_alias).oneOf(joined).doesntCheck()) {
				// table where is stored the related resource
				query = query.join(
					context.resources[rel.relationship.type].sql_table,
					rel_alias
				);
				joined.push(rel_alias);
			}
			if (typs(rel_info_alias).oneOf(joined).doesntCheck()) {
				// table where is stored the relationship
				query = query.join(
					rel.relationship.sql_table,
					rel_info_alias,
					rel_alias + '.' + context.resources[rel.relationship.type].primary_key +
					' = ' +
					rel_info_alias + '.' + rel.relationship.to_key +
					' AND ' +
					rel_info_alias + '.' + rel.relationship.from_key +
					' = ' +
					rel_superset_alias + '.' + context.resources[rel_superset.type].primary_key
				);
				joined.push(rel_info_alias);
			}

			return query;
		};

		request.related.forEach((rel) => {
			// set the fields to fetch
			query = addFields(
				// build then add the joins
				buildJoin(rel, query),
				rel,
				ancestors(rel).concat(rel.relationship.name).join('$')
			);
		});
	}

	// add main resource fields
	query = addFields(filterBy(query, request.main, context), request.main, base_alias);

	return query;
};

module.exports = {filterBy, selectBy};
<|endoftext|>