<commit_before>suite('SimpleLength', function() {
  test('SimpleLength is a SimpleLength, LengthValue and StyleValue', function() {
    var simpleLength = new SimpleLength(3, 'px');
    assert.instanceOf(simpleLength, SimpleLength, 'A new SimpleLength should be an instance of SimpleLength');
    assert.instanceOf(simpleLength, LengthValue, 'A new SimpleLength should be an instance of LengthValue');
    assert.instanceOf(simpleLength, StyleValue, 'A new SimpleLength should be an instance of StyleValue');
  });

  test('SimpleLength constructor throws exception for invalid types', function() {
    assert.throws(function() {new SimpleLength(3, 'pxp')});
    assert.throws(function() {new SimpleLength({})});
    assert.throws(function() {new SimpleLength({}, 'px')});
  });

  // Possible constructors: SimpleLength(SimpleLength),
  // SimpleLength(number, type), SimpleLength(numeric string, type)
  test('SimpleLength constructor works correctly for numbers and numeric strings', function() {
    var valueFromString;
    assert.doesNotThrow(function() {valueFromString = new SimpleLength('9.2', 'px')});
    assert.strictEqual(valueFromString.type, 'px');
    assert.strictEqual(valueFromString.value, 9.2);

    var valueFromNumber;
    assert.doesNotThrow(function() {valueFromNumber = new SimpleLength(10, 'px')});
    assert.strictEqual(valueFromNumber.type, 'px');
    assert.strictEqual(valueFromNumber.value, 10);
  });

  test('SimpleLength cssString is correctly defined for different values and types', function() {
    var valueFromString;
    assert.doesNotThrow(function() {valueFromString = new SimpleLength('9.2', 'px')});
    assert.strictEqual(valueFromString.cssString, '9.2px');

    var valueFromNumber;
    assert.doesNotThrow(function() {valueFromNumber = new SimpleLength(10, 'px')});
    assert.strictEqual(valueFromNumber.cssString, '10px');

    var percentValue;
    assert.doesNotThrow(function() {percentValue = new SimpleLength(10, 'percent')});
    assert.strictEqual(percentValue.cssString, '10%');

    var negativeValue;
    assert.doesNotThrow(function() {negativeValue = new SimpleLength(-3.2, 'px')});
    assert.strictEqual(negativeValue.cssString, '-3.2px');
  });

  test('Multiplication of a SimpleLength produces a new SimpleLength object', function() {
    var simpleLength = new SimpleLength(3, 'px');
    var calcOutput = simpleLength.multiply(3);
    assert.strictEqual(calcOutput.type, 'px');
    assert.strictEqual(calcOutput.value, 9);
  });

  test('Multiplication of a SimpleLength that contains decimals produces correct output value', function() {
    var simpleLength = new SimpleLength(5.3, 'px');
    var calcOutput = simpleLength.multiply(3);
    assert.strictEqual(calcOutput.type, 'px');
    assert.strictEqual(calcOutput.value, (5.3 * 3));
  });

  test('Division of a SimpleLength produces a new SimpleLength object', function() {
    var simpleLength = new SimpleLength(27, 'px');
    var calcOutput = simpleLength.divide(3);
    assert.strictEqual(calcOutput.type, 'px');
    assert.strictEqual(calcOutput.value, 9);
  });

  test('Division of a SimpleLength that contains decimals produces correct output value', function() {
    var simpleLength = new SimpleLength(33.2, 'px');
    var calcOutput = simpleLength.divide(5);
    assert.strictEqual(calcOutput.type, 'px');
    assert.strictEqual(calcOutput.value, (33.2 / 5));
  });

  test('Adding two SimpleLength of the same kind returns a new SimpleLength of the same kind', function() {
    var length1 = new SimpleLength(10, 'em');
    var length2 = new SimpleLength(5, 'em');
    var lengthAddition = length1.add(length2);
    assert.instanceOf(lengthAddition, SimpleLength, 'two added SimpleLength of same type should be an instance of SimpleLength');
    assert.strictEqual(lengthAddition.type, 'em');
    assert.strictEqual(lengthAddition.value, 15);
  });

  test('subtracting two SimpleLength of the same kind returns a new SimpleLength of the same kind', function() {
    var length1 = new SimpleLength(10, 'em');
    var length2 = new SimpleLength(5, 'em');
    var lengthAddition = length1.subtract(length2);
    assert.instanceOf(lengthAddition, SimpleLength, 'two subtracted SimpleLength of same type should be an instance of SimpleLength');
    assert.strictEqual(lengthAddition.type, 'em');
    assert.strictEqual(lengthAddition.value, 5);
  });

});
<commit_msg>Created simple unit test case for _convertToCalcLength() in SimpleLength class<commit_after>suite('SimpleLength', function() {
  test('SimpleLength is a SimpleLength, LengthValue and StyleValue', function() {
    var simpleLength = new SimpleLength(3, 'px');
    assert.instanceOf(simpleLength, SimpleLength, 'A new SimpleLength should be an instance of SimpleLength');
    assert.instanceOf(simpleLength, LengthValue, 'A new SimpleLength should be an instance of LengthValue');
    assert.instanceOf(simpleLength, StyleValue, 'A new SimpleLength should be an instance of StyleValue');
  });

  test('SimpleLength constructor throws exception for invalid types', function() {
    assert.throws(function() {new SimpleLength(3, 'pxp')});
    assert.throws(function() {new SimpleLength({})});
    assert.throws(function() {new SimpleLength({}, 'px')});
  });

  // Possible constructors: SimpleLength(SimpleLength),
  // SimpleLength(number, type), SimpleLength(numeric string, type)
  test('SimpleLength constructor works correctly for numbers and numeric strings', function() {
    var valueFromString;
    assert.doesNotThrow(function() {valueFromString = new SimpleLength('9.2', 'px')});
    assert.strictEqual(valueFromString.type, 'px');
    assert.strictEqual(valueFromString.value, 9.2);

    var valueFromNumber;
    assert.doesNotThrow(function() {valueFromNumber = new SimpleLength(10, 'px')});
    assert.strictEqual(valueFromNumber.type, 'px');
    assert.strictEqual(valueFromNumber.value, 10);
  });

  test('SimpleLength cssString is correctly defined for different values and types', function() {
    var valueFromString;
    assert.doesNotThrow(function() {valueFromString = new SimpleLength('9.2', 'px')});
    assert.strictEqual(valueFromString.cssString, '9.2px');

    var valueFromNumber;
    assert.doesNotThrow(function() {valueFromNumber = new SimpleLength(10, 'px')});
    assert.strictEqual(valueFromNumber.cssString, '10px');

    var percentValue;
    assert.doesNotThrow(function() {percentValue = new SimpleLength(10, 'percent')});
    assert.strictEqual(percentValue.cssString, '10%');

    var negativeValue;
    assert.doesNotThrow(function() {negativeValue = new SimpleLength(-3.2, 'px')});
    assert.strictEqual(negativeValue.cssString, '-3.2px');
  });

  test('Multiplication of a SimpleLength produces a new SimpleLength object', function() {
    var simpleLength = new SimpleLength(3, 'px');
    var calcOutput = simpleLength.multiply(3);
    assert.strictEqual(calcOutput.type, 'px');
    assert.strictEqual(calcOutput.value, 9);
  });

  test('Multiplication of a SimpleLength that contains decimals produces correct output value', function() {
    var simpleLength = new SimpleLength(5.3, 'px');
    var calcOutput = simpleLength.multiply(3);
    assert.strictEqual(calcOutput.type, 'px');
    assert.strictEqual(calcOutput.value, (5.3 * 3));
  });

  test('Division of a SimpleLength produces a new SimpleLength object', function() {
    var simpleLength = new SimpleLength(27, 'px');
    var calcOutput = simpleLength.divide(3);
    assert.strictEqual(calcOutput.type, 'px');
    assert.strictEqual(calcOutput.value, 9);
  });

  test('Division of a SimpleLength that contains decimals produces correct output value', function() {
    var simpleLength = new SimpleLength(33.2, 'px');
    var calcOutput = simpleLength.divide(5);
    assert.strictEqual(calcOutput.type, 'px');
    assert.strictEqual(calcOutput.value, (33.2 / 5));
  });

  test('Adding two SimpleLength of the same kind returns a new SimpleLength of the same kind', function() {
    var length1 = new SimpleLength(10, 'em');
    var length2 = new SimpleLength(5, 'em');
    var lengthAddition = length1.add(length2);
    assert.instanceOf(lengthAddition, SimpleLength, 'two added SimpleLength of same type should be an instance of SimpleLength');
    assert.strictEqual(lengthAddition.type, 'em');
    assert.strictEqual(lengthAddition.value, 15);
  });

  test('subtracting two SimpleLength of the same kind returns a new SimpleLength of the same kind', function() {
    var length1 = new SimpleLength(10, 'em');
    var length2 = new SimpleLength(5, 'em');
    var lengthAddition = length1.subtract(length2);
    assert.instanceOf(lengthAddition, SimpleLength, 'two subtracted SimpleLength of same type should be an instance of SimpleLength');
    assert.strictEqual(lengthAddition.type, 'em');
    assert.strictEqual(lengthAddition.value, 5);
  });

  test('convertToCalcLength method returns a CalcLength object with a single legnth value type when called from a SimpleLength object', function() {
    var sLength = new SimpleLength(10, 'em');
    var convertedCalcLength = sLength._convertToCalcLength();
    var testCalcLength = new CalcLength({})
    assert.strictEqual(convertedCalcLength, convertedCalcLength);
  });

});
<|endoftext|>


<commit_before>/**
 * @author oldj
 * @blog http://oldj.net
 */

'use strict';

const fs = require('fs');
const path = require('path');
// const util = require('util');
const exec = require('child_process').exec;
const gulp = require('gulp');
const beautify = require('js-beautify').js_beautify;

gulp.task('ver', () => {
    let fn = path.join(__dirname, 'src', 'version.js');
    let version = require('./src/version').version;
    version[3]++;

    console.log(`version -> ${version.join('.')}`);

    let cnt = `exports.version = ${JSON.stringify(version)};`;
    fs.writeFileSync(fn, cnt, 'utf-8');

    // update package.json
    fn = './package.json';
    cnt = fs.readFileSync(fn);
    let d = JSON.parse(cnt);
    d.version = version.slice(0, 3).join('.');
    cnt = beautify(JSON.stringify(d), {indent_size: 2});
    fs.writeFileSync(fn, cnt, 'utf-8');
});

gulp.task('pack', () => {
    let version = require('./src/version').version;
    let v1 = version.slice(0, 3).join('.');
    let v2 = version[3];

    let cmds = `
# for macOS
electron-packager . 'SwitchHosts!' --platform=darwin --arch=x64 --overwrite --asar=true --prune --icon=../assets/app.icns --ignore=node_modules/.bin --ignore=.git --ignore=dist --ignore=node_modules/electron-* --out=dist --app-version=${v1} --build-version=${v2}

# for windows x64
electron-packager . 'SwitchHosts!' --platform=win32  --arch=x64 --overwrite --asar=true --prune --icon=../assets/app.ico  --ignore=node_modules/.bin --ignore=.git --ignore=dist --ignore=node_modules/electron-* --out=dist --app-version=${v1} --build-version=${v2}

# for windows ia32
electron-packager . 'SwitchHosts!' --platform=win32  --arch=ia32 --overwrite --asar=true --prune --icon=../assets/app.ico  --ignore=node_modules/.bin --ignore=.git --ignore=dist --ignore=node_modules/electron-* --out=dist --app-version=${v1} --build-version=${v2}
`;

    console.log(`start packing, v: ${v1}.${v2} ..`);
    console.log(cmds);
    exec(cmds, (error, stdout, stderr) => {
        console.log('end pack.');
        if (error) {
            console.error(`exec error: ${error}`);
        }
        // if (stdout) console.log(`${stdout}`);
        // if (stderr) console.log(`${stderr}`);
    });
});

gulp.task('zip', () => {
    let version = require('./src/version').version;
    let v = version.join('.');

    let cmds = `
cd ./dist
rm -f ./SwitchHosts-*.zip
zip -ry SwitchHosts-macOS-x64_v${v}.zip ./SwitchHosts\\!-darwin-x64/SwitchHosts\\!.app
zip -ry SwitchHosts-win32-x64_v${v}.zip ./SwitchHosts\\!-win32-x64
zip -ry SwitchHosts-win32-ia32_v${v}.zip ./SwitchHosts\\!-win32-ia32
cd ..
`;

    console.log(`start zip ..`);
    exec(cmds, (error, stdout, stderr) => {
        console.log('end zip.');
        if (error) {
            console.error(`exec error: ${error}`);
        }
        // if (stdout) console.log(`${stdout}`);
        // if (stderr) console.log(`${stderr}`);
    });

});

gulp.task('default', () => {
    gulp.start('ver');

    gulp.watch([
        './main.js',
        './index.html',
        './src/**/*.*',
        '!./src/version.js'
    ], ['ver']);
});
<commit_msg>增加Linux x86_64的编译与打包<commit_after>/**
 * @author oldj
 * @blog http://oldj.net
 */

'use strict';

const fs = require('fs');
const path = require('path');
// const util = require('util');
const exec = require('child_process').exec;
const gulp = require('gulp');
const beautify = require('js-beautify').js_beautify;

gulp.task('ver', () => {
    let fn = path.join(__dirname, 'src', 'version.js');
    let version = require('./src/version').version;
    version[3]++;

    console.log(`version -> ${version.join('.')}`);

    let cnt = `exports.version = ${JSON.stringify(version)};`;
    fs.writeFileSync(fn, cnt, 'utf-8');

    // update package.json
    fn = './package.json';
    cnt = fs.readFileSync(fn);
    let d = JSON.parse(cnt);
    d.version = version.slice(0, 3).join('.');
    cnt = beautify(JSON.stringify(d), {indent_size: 2});
    fs.writeFileSync(fn, cnt, 'utf-8');
});

gulp.task('pack', () => {
    let version = require('./src/version').version;
    let v1 = version.slice(0, 3).join('.');
    let v2 = version[3];

    let cmds = `
# for macOS
electron-packager . 'SwitchHosts!' --platform=darwin --arch=x64 --overwrite --asar=true --prune --icon=../assets/app.icns --ignore=node_modules/.bin --ignore=.git --ignore=dist --ignore=node_modules/electron-* --out=dist --app-version=${v1} --build-version=${v2}

# for windows x64
electron-packager . 'SwitchHosts!' --platform=win32  --arch=x64 --overwrite --asar=true --prune --icon=../assets/app.ico  --ignore=node_modules/.bin --ignore=.git --ignore=dist --ignore=node_modules/electron-* --out=dist --app-version=${v1} --build-version=${v2}

# for windows ia32
electron-packager . 'SwitchHosts!' --platform=win32  --arch=ia32 --overwrite --asar=true --prune --icon=../assets/app.ico  --ignore=node_modules/.bin --ignore=.git --ignore=dist --ignore=node_modules/electron-* --out=dist --app-version=${v1} --build-version=${v2}

# for linux x86_64
electron-packager . 'SwitchHosts!' --platform=linux  --arch=x64 --overwrite --asar=true --prune --icon=../assets/app.ico  --ignore=node_modules/.bin --ignore=.git --ignore=dist --ignore=node_modules/electron-* --out=dist --app-version=${v1} --build-version=${v2}
`;

    console.log(`start packing, v: ${v1}.${v2} ..`);
    console.log(cmds);
    exec(cmds, (error, stdout, stderr) => {
        console.log('end pack.');
        if (error) {
            console.error(`exec error: ${error}`);
        }
        // if (stdout) console.log(`${stdout}`);
        // if (stderr) console.log(`${stderr}`);
    });
});

gulp.task('zip', () => {
    let version = require('./src/version').version;
    let v = version.join('.');

    let cmds = `
cd ./dist
rm -f ./SwitchHosts-*.zip
zip -ry SwitchHosts-macOS-x64_v${v}.zip ./SwitchHosts\\!-darwin-x64/SwitchHosts\\!.app
zip -ry SwitchHosts-win32-x64_v${v}.zip ./SwitchHosts\\!-win32-x64
zip -ry SwitchHosts-win32-ia32_v${v}.zip ./SwitchHosts\\!-win32-ia32
zip -ry SwitchHosts-linux-x64_v${v}.zip ./SwitchHosts\\!-linux-x64
cd ..
`;

    console.log(`start zip ..`);
    exec(cmds, (error, stdout, stderr) => {
        console.log('end zip.');
        if (error) {
            console.error(`exec error: ${error}`);
        }
        // if (stdout) console.log(`${stdout}`);
        // if (stderr) console.log(`${stderr}`);
    });

});

gulp.task('default', () => {
    gulp.start('ver');

    gulp.watch([
        './main.js',
        './index.html',
        './src/**/*.*',
        '!./src/version.js'
    ], ['ver']);
});
<|endoftext|>


<commit_before>
// internal libs
import Router from 'src/libs/router';
import Eventhandler from 'src/libs/eventhandler';

describe('Class Router', () => {

	describe('static newUrl() method', () => {

		it('should return url object with fragment property', () => {

			let url = Router.newUrl('http://www.mydomain.com/path/to/somewhere.html?a=1&b=2');
			url.fragment.should.equal('/path/to/somewhere.html?a=1&b=2');

		});

	});

	describe('on created new instance', () => {

		let element = null;

		beforeEach(() => {

			element = document.createElement("div");
			element.classList.add('anchor-container');
			element.innerHTML = `
				 Index
				 Details
				 Params
				 Params
			`;
			document.body.appendChild(element);

		});

		afterEach(() => {
			document.body.removeChild(element);
		});

		it('should trigger "urlchange" on pushState or on click of an a-link', () => {

			// setup
			let count = 0;
			let fragment = null;
			let router = Router.create({
				config: {
					Eventhandler,
				}
			});
			sinon.spy(router, '_onUrlchange');
			router.onUrlchange( event => {
				fragment = event.detail.fragment;
				++count;
			});
			// TODO: implment it with promise
			// router.on('urlchange').then((event) => {
			//
			// });

			// run test
			element.querySelector('.foo').click();
			count.should.equal(1);
			element.querySelector('.bar').click();
			count.should.equal(2);
			element.querySelector('.baz').click();
			count.should.equal(3);

			element.querySelector('.qux').click();
			count.should.equal(4);
			element.querySelector('.qux').click();
			count.should.equal(4);

			// test popstate
			// TODO: in chrome router.back() does not work
			router.back();
			router.back();
			router.back();

			// cleanup
			// TODO: cleanup failed
			// router.destroy(); FAILED

		});

	});

	it.skip('just an idea', () => {

		let router = Router.create({
			routes : {
				'product::detail': {
					'/product/detail/{{ id }}' : () => {

					}
				},
				'product::site': {
					'/product/detail/{{ id }}?foo={{ a }}&bar={{ b }}#baz={{ c }}': ({ id, b, c }) => {

					}
				}
			}
		});

		router.on('product::detail', '/product/detail/{{ id }}', ({ id }) => {

		});

		router.on('product::site', '/product/detail/{{ id }}?foo={{ a }}&bar={{ b }}#baz={{ c }}', ({ id, b, c }) => {

		});

		router.on('checkout::login', /.*?thats={{ it }}:*/, ({ it }) => {

		});

		router.on('checkout::login', /.*logout(?:token=([0-9])+)?/, ([ number ]) => {

		});

	});

});
<commit_msg>router.spec.js: refactored id<commit_after>
// internal libs
import Router from 'src/libs/router';
import Eventhandler from 'src/libs/eventhandler';

describe('Class Router', () => {

	describe('static newUrl() method', () => {

		it('should return url object with fragment property', () => {

			let url = Router.newUrl('http://www.mydomain.com/path/to/somewhere.html?a=1&b=2');
			url.fragment.should.equal('/path/to/somewhere.html?a=1&b=2');

		});

	});

	describe('on created new instance', () => {

		let element = null;

		beforeEach(() => {

			element = document.createElement("div");
			element.classList.add('anchor-container');
			element.innerHTML = `
				 Index
				 Details
				 Params
				 Params
			`;
			document.body.appendChild(element);

		});

		afterEach(() => {
			document.body.removeChild(element);
		});

		it('should trigger "urlchange" on pushState or on click of an a-link', () => {

			// setup
			let count = 0;
			let fragment = null;
			let router = Router.create({
				config: {
					Eventhandler,
				}
			});
			sinon.spy(router, '_onUrlchange');
			router.onUrlchange( event => {
				fragment = event.detail.fragment;
				++count;
			});
			// TODO: implment it with promise
			// router.on('urlchange').then((event) => {
			//
			// });

			// run test
			element.querySelector('.foo').click();
			count.should.equal(1);
			element.querySelector('.bar').click();
			count.should.equal(2);
			element.querySelector('.baz').click();
			count.should.equal(3);

			element.querySelector('.qux').click();
			count.should.equal(4);
			element.querySelector('.qux').click();
			count.should.equal(4);

			// test popstate
			// TODO: in chrome router.back() does not work
			router.back();
			router.back();
			router.back();

			// cleanup
			// TODO: cleanup failed
			// router.destroy(); FAILED

		});

	});

	it.skip('just an idea', () => {

		let router = Router.create({
			routes : {
				'product::detail': {
					'/product/detail/{{ id }}' : () => {

					}
				},
				'product::site': {
					'/product/detail/{{ id }}?foo={{ a }}&bar={{ b }}#baz={{ c }}': ({ id, b, c }) => {

					}
				}
			}
		});

		router.addRoute('product::detail', '/product/detail/{{ id }}').then(({ id }) => {

		});

		router.addRoute('product::site', '/product/detail/{{ id }}?foo={{ a }}&bar={{ b }}#baz={{ c }}').then(({ id, a, b, c }) => {

		});

		router.addRoute('checkout::login', /.*?thats={{ awesome }}:*/).then(({ awesome }) => {

		});

		async function chckout_login(){

			// 'checkout::login' can forwarding to some service (see thirt ar
			let invoice = await router.addRoute('checkout::login', /.*logout(?:token=([0-9])+)?/, 'http://www.mydomain/cat/document/1');

			// do something
			// ...
			// ...

			router.addRoute('checkout::login', '/login/user/{{ name }/messages/{{ id }}').then(({ name, messages }) => {

			});

		};

	});

});
<|endoftext|>


<commit_before>var tape = require('tape');
var event_stream = require('event-stream');
var Document = require('pelias-model').Document;
var _ = require('lodash');

var stream = require('../src/lookupStream');

function test_stream(input, testedStream, callback) {
    var input_stream = event_stream.readArray(input);
    var destination_stream = event_stream.writeArray(callback);

    input_stream.pipe(testedStream).pipe(destination_stream);
}

tape('tests', function(test) {
  test.test('doc without centroid should not modify input', function(t) {
    var input = [
      new Document( 'whosonfirst', 'placetype', '1')
    ];

    var lookupStream = stream.createLookupStream();

    test_stream(input, lookupStream, function(err, actual) {
      t.deepEqual(actual, input, 'nothing should have changed');
      t.end();
    });

  });

  test.test('country, region, county, locality, and neighborhood fields should be set into document', function(t) {
    var input = [
      new Document( 'whosonfirst', 'placetype', '1').setCentroid({ lat: 12.121212, lon: 21.212121 })
    ];

    var expected = [
      new Document( 'whosonfirst', 'placetype', '1')
        .setCentroid({ lat: 12.121212, lon: 21.212121 })
        .setAdmin( 'admin0', 'Country 1')
        .addParent('country', 'Country 1', '1')
        .setAdmin( 'admin1', 'Region 1')
        .addParent('region', 'Region 1', '3')
        .setAdmin( 'admin2', 'County 1')
        .addParent('county', 'County 1', '5')
        .setAdmin( 'locality', 'Locality 1')
        .addParent('locality', 'Locality 1', '7')
        .setAdmin( 'local_admin', 'LocalAdmin 1')
        .addParent('localadmin', 'LocalAdmin 1', '9')
        .setAdmin( 'neighborhood', 'Neighbourhood 1')
        .addParent('neighbourhood', 'Neighbourhood 1', '11')
    ];

    var resolver = function(centroid, callback) {
      var result = {
        country: [
          { id: 1, name: 'Country 1'},
          { id: 2, name: 'Country 2'}
        ],
        region: [
          { id: 3, name: 'Region 1'},
          { id: 4, name: 'Region 2'}
        ],
        county: [
          { id: 5, name: 'County 1'},
          { id: 6, name: 'County 2'}
        ],
        locality: [
          { id: 7, name: 'Locality 1'},
          { id: 8, name: 'Locality 2'}
        ],
        localadmin: [
          { id: 9, name: 'LocalAdmin 1'},
          { id: 10, name: 'LocalAdmin 2'}
        ],
        neighbourhood: [
          { id: 11, name: 'Neighbourhood 1'},
          { id: 12, name: 'Neighbourhood 2'}
        ]
      };

      setTimeout(callback, 0, null, result);

    };

    var lookupStream = stream.createLookupStream(resolver);

    test_stream(input, lookupStream, function(err, actual) {
      t.deepEqual(actual, expected, 'all fields should have been set');
      t.end();
    });

  });

  test.test('resolver with field-less result should only set fields that are present', function(t) {
    var input = [
      new Document( 'whosonfirst', 'placetype', '1')
        .setCentroid({ lat: 12.121212, lon: 21.212121 }),
      new Document( 'whosonfirst', 'placetype', '1')
        .setCentroid({ lat: 13.131313, lon: 31.313131 })
    ];

    var expected = [
      new Document( 'whosonfirst', 'placetype', '1')
        .setCentroid({ lat: 12.121212, lon: 21.212121 })
        .setAdmin( 'admin1', 'Region')
        .addParent('region', 'Region', '1'),
      new Document( 'whosonfirst', 'placetype', '1')
        .setCentroid({ lat: 13.131313, lon: 31.313131 })
        .setAdmin( 'admin0', 'Country')
        .addParent('country', 'Country', '2')
    ];

    var resolver = function(centroid, callback) {
      if (_.isEqual(centroid, { lat: 12.121212, lon: 21.212121 } )) {
        setTimeout(callback, 0, null, { region: [ { id: 1, name: 'Region' } ] });
      } else if (_.isEqual(centroid, { lat: 13.131313, lon: 31.313131 })) {
        setTimeout(callback, 0, null, { country: [ {id: 2, name: 'Country' } ] });
      }

    };

    var lookupStream = stream.createLookupStream(resolver);

    test_stream(input, lookupStream, function(err, actual) {
      t.deepEqual(actual, expected, 'result with missing fields should not set anything in doc');
      t.end();
    });

  });

  test.test('resolver throwing error should push doc onto stream unmodified', function(t) {
    var input = new Document( 'whosonfirst', 'placetype', '1')
        .setCentroid({ lat: 12.121212, lon: 21.212121 });

    var expected = new Document( 'whosonfirst', 'placetype', '1')
        .setCentroid({ lat: 12.121212, lon: 21.212121 });

    var resolver = function(centroid, callback) {
      setTimeout(callback, 0, 'this is an error', { region: 'Region' } );
    };

    var lookupStream = stream.createLookupStream(resolver);

    var input_stream = event_stream.readArray([input]);
    var destination_stream = event_stream.writeArray(function() {
      t.fail('this stream should not have been called');
      t.end();
    });

    input_stream.pipe(lookupStream).on('error', function(e) {
      t.equal(e, 'this is an error');
      t.deepEqual(input, expected, 'the document should not have been modified');
      t.end();
    }).pipe(destination_stream);

  });

  test.test('abbreviation supporting country and region should set region abbreviation', function(t) {
    var input = [
      new Document( 'whosonfirst', 'placetype', '1').setCentroid({ lat: 12.121212, lon: 21.212121 })
    ];

    var expected = [
      new Document( 'whosonfirst', 'placetype', '1')
        .setCentroid({ lat: 12.121212, lon: 21.212121 })
        .setAdmin( 'admin0', 'United States')
        .addParent('country', 'United States', '1')
        .setAdmin( 'admin1', 'Pennsylvania')
        .addParent('region', 'Pennsylvania', '3', 'PA')
    ];

    var resolver = function(centroid, callback) {
      var result = {
        country: [
          { id: 1, name: 'United States'}
        ],
        region: [
          { id: 3, name: 'Pennsylvania'}
        ]
      };

      setTimeout(callback, 0, null, result);

    };

    var lookupStream = stream.createLookupStream(resolver);

    test_stream(input, lookupStream, function(err, actual) {
      t.deepEqual(actual, expected, 'all fields should have been set');
      t.end();
    });

  });

});
<commit_msg>added coverage tests<commit_after>var tape = require('tape');
var event_stream = require('event-stream');
var Document = require('pelias-model').Document;
var _ = require('lodash');

var stream = require('../src/lookupStream');

function test_stream(input, testedStream, callback) {
    var input_stream = event_stream.readArray(input);
    var destination_stream = event_stream.writeArray(callback);

    input_stream.pipe(testedStream).pipe(destination_stream);
}

tape('tests', function(test) {
  test.test('doc without centroid should not modify input', function(t) {
    var input = [
      new Document( 'whosonfirst', 'placetype', '1')
    ];

    var lookupStream = stream.createLookupStream();

    test_stream(input, lookupStream, function(err, actual) {
      t.deepEqual(actual, input, 'nothing should have changed');
      t.end();
    });

  });

  test.test('country, region, county, locality, and neighborhood fields should be set into document', function(t) {
    var input = [
      new Document( 'whosonfirst', 'placetype', '1').setCentroid({ lat: 12.121212, lon: 21.212121 })
    ];

    var expected = [
      new Document( 'whosonfirst', 'placetype', '1')
        .setCentroid({ lat: 12.121212, lon: 21.212121 })
        .setAdmin( 'admin0', 'Country 1')
        .addParent('country', 'Country 1', '1')
        .setAdmin( 'admin1', 'Region 1')
        .addParent('region', 'Region 1', '3')
        .setAdmin( 'admin2', 'County 1')
        .addParent('county', 'County 1', '5')
        .setAdmin( 'locality', 'Locality 1')
        .addParent('locality', 'Locality 1', '7')
        .setAdmin( 'local_admin', 'LocalAdmin 1')
        .addParent('localadmin', 'LocalAdmin 1', '9')
        .setAdmin( 'neighborhood', 'Neighbourhood 1')
        .addParent('neighbourhood', 'Neighbourhood 1', '11')
    ];

    var resolver = function(centroid, callback) {
      var result = {
        country: [
          { id: 1, name: 'Country 1'},
          { id: 2, name: 'Country 2'}
        ],
        region: [
          { id: 3, name: 'Region 1'},
          { id: 4, name: 'Region 2'}
        ],
        county: [
          { id: 5, name: 'County 1'},
          { id: 6, name: 'County 2'}
        ],
        locality: [
          { id: 7, name: 'Locality 1'},
          { id: 8, name: 'Locality 2'}
        ],
        localadmin: [
          { id: 9, name: 'LocalAdmin 1'},
          { id: 10, name: 'LocalAdmin 2'}
        ],
        neighbourhood: [
          { id: 11, name: 'Neighbourhood 1'},
          { id: 12, name: 'Neighbourhood 2'}
        ]
      };

      setTimeout(callback, 0, null, result);

    };

    var lookupStream = stream.createLookupStream(resolver);

    test_stream(input, lookupStream, function(err, actual) {
      t.deepEqual(actual, expected, 'all fields should have been set');
      t.end();
    });

  });

  test.test('resolver with field-less result should only set fields that are present', function(t) {
    var input = [
      new Document( 'whosonfirst', 'placetype', '1')
        .setCentroid({ lat: 12.121212, lon: 21.212121 }),
      new Document( 'whosonfirst', 'placetype', '1')
        .setCentroid({ lat: 13.131313, lon: 31.313131 })
    ];

    var expected = [
      new Document( 'whosonfirst', 'placetype', '1')
        .setCentroid({ lat: 12.121212, lon: 21.212121 })
        .setAdmin( 'admin1', 'Region')
        .addParent('region', 'Region', '1'),
      new Document( 'whosonfirst', 'placetype', '1')
        .setCentroid({ lat: 13.131313, lon: 31.313131 })
        .setAdmin( 'admin0', 'Country')
        .addParent('country', 'Country', '2')
    ];

    var resolver = function(centroid, callback) {
      if (_.isEqual(centroid, { lat: 12.121212, lon: 21.212121 } )) {
        setTimeout(callback, 0, null, { region: [ { id: 1, name: 'Region' } ] });
      } else if (_.isEqual(centroid, { lat: 13.131313, lon: 31.313131 })) {
        setTimeout(callback, 0, null, { country: [ {id: 2, name: 'Country' } ] });
      }

    };

    var lookupStream = stream.createLookupStream(resolver);

    test_stream(input, lookupStream, function(err, actual) {
      t.deepEqual(actual, expected, 'result with missing fields should not set anything in doc');
      t.end();
    });

  });

  test.test('resolver throwing error should push doc onto stream unmodified', function(t) {
    var input = new Document( 'whosonfirst', 'placetype', '1')
        .setCentroid({ lat: 12.121212, lon: 21.212121 });

    var expected = new Document( 'whosonfirst', 'placetype', '1')
        .setCentroid({ lat: 12.121212, lon: 21.212121 });

    var resolver = function(centroid, callback) {
      setTimeout(callback, 0, 'this is an error', { region: 'Region' } );
    };

    var lookupStream = stream.createLookupStream(resolver);

    var input_stream = event_stream.readArray([input]);
    var destination_stream = event_stream.writeArray(function() {
      t.fail('this stream should not have been called');
      t.end();
    });

    input_stream.pipe(lookupStream).on('error', function(e) {
      t.equal(e, 'this is an error');
      t.deepEqual(input, expected, 'the document should not have been modified');
      t.end();
    }).pipe(destination_stream);

  });

  test.test('abbreviation supporting country and region should set region abbreviation', function(t) {
    var input = [
      new Document( 'whosonfirst', 'placetype', '1').setCentroid({ lat: 12.121212, lon: 21.212121 })
    ];

    var expected = [
      new Document( 'whosonfirst', 'placetype', '1')
        .setCentroid({ lat: 12.121212, lon: 21.212121 })
        .setAdmin( 'admin0', 'United States')
        .addParent('country', 'United States', '1')
        .setAdmin( 'admin1', 'Pennsylvania')
        .addParent('region', 'Pennsylvania', '3', 'PA')
    ];

    var resolver = function(centroid, callback) {
      var result = {
        country: [
          { id: 1, name: 'United States'}
        ],
        region: [
          { id: 3, name: 'Pennsylvania'}
        ]
      };

      setTimeout(callback, 0, null, result);

    };

    var lookupStream = stream.createLookupStream(resolver);

    test_stream(input, lookupStream, function(err, actual) {
      t.deepEqual(actual, expected, 'all fields should have been set');
      t.end();
    });

  });

  test.test('supported country and unsupported region should not set region abbreviation', function(t) {
    var input = [
      new Document( 'whosonfirst', 'placetype', '1').setCentroid({ lat: 12.121212, lon: 21.212121 })
    ];

    var expected = [
      new Document( 'whosonfirst', 'placetype', '1')
        .setCentroid({ lat: 12.121212, lon: 21.212121 })
        .setAdmin( 'admin0', 'United States')
        .addParent('country', 'United States', '1')
        .setAdmin( 'admin1', 'unknown US state')
        .addParent('region', 'unknown US state', '3')
    ];

    var resolver = function(centroid, callback) {
      var result = {
        country: [
          { id: 1, name: 'United States'}
        ],
        region: [
          { id: 3, name: 'unknown US state'}
        ]
      };

      setTimeout(callback, 0, null, result);

    };

    var lookupStream = stream.createLookupStream(resolver);

    test_stream(input, lookupStream, function(err, actual) {
      t.deepEqual(actual, expected, 'all fields should have been set');
      t.end();
    });

  });

  test.test('unsupported country and supported region should not set region abbreviation', function(t) {
    var input = [
      new Document( 'whosonfirst', 'placetype', '1').setCentroid({ lat: 12.121212, lon: 21.212121 })
    ];

    var expected = [
      new Document( 'whosonfirst', 'placetype', '1')
        .setCentroid({ lat: 12.121212, lon: 21.212121 })
        .setAdmin( 'admin0', 'unsupported country')
        .addParent('country', 'unsupported country', '1')
        .setAdmin( 'admin1', 'Pennsylvania')
        .addParent('region', 'Pennsylvania', '3')
    ];

    var resolver = function(centroid, callback) {
      var result = {
        country: [
          { id: 1, name: 'unsupported country'}
        ],
        region: [
          { id: 3, name: 'Pennsylvania'}
        ]
      };

      setTimeout(callback, 0, null, result);

    };

    var lookupStream = stream.createLookupStream(resolver);

    test_stream(input, lookupStream, function(err, actual) {
      t.deepEqual(actual, expected, 'all fields should have been set');
      t.end();
    });

  });

});
<|endoftext|>


<commit_before>const nest = require('depnest')
const { h } = require('mutant')
const insertCss = require('insert-css')
const electron = require('electron')

exports.gives = nest('app.html.app')

exports.needs = nest({
  'app.async.catchLinkClick': 'first',
  'app.html.externalConfirm': 'first',
  'app.html.tabs': 'first',
  'app.page.errors': 'first',
  'app.sync.window': 'reduce',
  'app.sync.addPage': 'first',
  'app.sync.catchKeyboardShortcut': 'first',
  'router.sync.router': 'first',
  'router.sync.normalise': 'first',
  'styles.css': 'reduce',
  'settings.sync.get': 'first',
  'settings.sync.set': 'first'
})

exports.create = function (api) {
  return nest('app.html.app', app)

  function app () {
    window = api.app.sync.window(window)
    const css = values(api.styles.css()).join('\n')
    insertCss(css)

    const initialTabs = [ '/public', '/private', '/notifications' ]
    // NB router converts these to { page: '/public' }
    const tabs = api.app.html.tabs(initialTabs)

    const App = h('App', tabs)

    // Catch keyboard shortcuts
    api.app.sync.catchKeyboardShortcut(window, { tabs })

    // Catch link clicks
    api.app.async.catchLinkClick(App, (link, { ctrlKey: openBackground, isExternal }) => {
      if (isExternal) return api.app.html.externalConfirm(link)

      // TODO tidy up who and where this logic happens (do when adding patch-history)
      const location = api.router.sync.normalise(link)
      const tabId = JSON.stringify(location)
      if (tabs.has(tabId)) tabs.select(tabId)
      else {
        const changeTab = !openBackground
        api.app.sync.addPage(location, changeTab)
      }
    })

    // Catch errors
    var { container: errorPage, addError } = api.router.sync.router('/errors')
    window.addEventListener('error', ev => {
      if (!tabs.has('/errors')) tabs.add(errorPage, true)

      addError(ev.error || ev)
    })

    window.addEventListener('resize', function(e){
	var wc = electron.remote.getCurrentWebContents()
	wc && wc.getZoomFactor((zf) => {
	    api.settings.sync.set({
		'electron-zoomFactor': zf,
		'electron-windowBounds': electron.remote.getCurrentWindow().getBounds()
	    })
	})
    })

    var zoomFactor = api.settings.sync.get('electron-zoomFactor')
    if (zoomFactor)
	electron.remote.getCurrentWebContents().setZoomFactor(zoomFactor)
    var bounds = api.settings.sync.get('electron-windowBounds')
    if (bounds)
	electron.remote.getCurrentWindow().setBounds(bounds)

    return App
  }
}

function values (object) {
  const keys = Object.keys(object)
  return keys.map(k => object[k])
}
<commit_msg>change settings from dash nesting to object nesting<commit_after>const nest = require('depnest')
const { h } = require('mutant')
const insertCss = require('insert-css')
const electron = require('electron')

exports.gives = nest('app.html.app')

exports.needs = nest({
  'app.async.catchLinkClick': 'first',
  'app.html.externalConfirm': 'first',
  'app.html.tabs': 'first',
  'app.page.errors': 'first',
  'app.sync.window': 'reduce',
  'app.sync.addPage': 'first',
  'app.sync.catchKeyboardShortcut': 'first',
  'router.sync.router': 'first',
  'router.sync.normalise': 'first',
  'styles.css': 'reduce',
  'settings.sync.get': 'first',
  'settings.sync.set': 'first'
})

exports.create = function (api) {
  return nest('app.html.app', app)

  function app () {
    window = api.app.sync.window(window)
    const css = values(api.styles.css()).join('\n')
    insertCss(css)

    const initialTabs = [ '/public', '/private', '/notifications' ]
    // NB router converts these to { page: '/public' }
    const tabs = api.app.html.tabs(initialTabs)

    const App = h('App', tabs)

    // Catch keyboard shortcuts
    api.app.sync.catchKeyboardShortcut(window, { tabs })

    // Catch link clicks
    api.app.async.catchLinkClick(App, (link, { ctrlKey: openBackground, isExternal }) => {
      if (isExternal) return api.app.html.externalConfirm(link)

      // TODO tidy up who and where this logic happens (do when adding patch-history)
      const location = api.router.sync.normalise(link)
      const tabId = JSON.stringify(location)
      if (tabs.has(tabId)) tabs.select(tabId)
      else {
        const changeTab = !openBackground
        api.app.sync.addPage(location, changeTab)
      }
    })

    // Catch errors
    var { container: errorPage, addError } = api.router.sync.router('/errors')
    window.addEventListener('error', ev => {
      if (!tabs.has('/errors')) tabs.add(errorPage, true)

      addError(ev.error || ev)
    })

    // TODO - extract this to keep patch-lite isolated from electron
    window.addEventListener('resize', () => {
      var wc = electron.remote.getCurrentWebContents()
      wc && wc.getZoomFactor((zf) => {
        api.settings.sync.set({
          electron: {
          zoomFactor: zf,
          windowBounds: electron.remote.getCurrentWindow().getBounds()
          }
        })
      })
    })

    var zoomFactor = api.settings.sync.get('electron.zoomFactor')
    if (zoomFactor)
      electron.remote.getCurrentWebContents().setZoomFactor(zoomFactor)

    var bounds = api.settings.sync.get('electron.windowBounds')
    if (bounds)
      electron.remote.getCurrentWindow().setBounds(bounds)
    ///////////////////

    return App
  }
}

function values (object) {
  const keys = Object.keys(object)
  return keys.map(k => object[k])
}
<|endoftext|>


<commit_before>/*
 * Beard Functionality
 * Matthew Evans, Autumn 2013
 * No License
 *
 */
;(function($){

	var Beard = {

		// Initialize the player
		init: function (elm) {

			// Cache the element as a jQuery object
			var $elm = $(elm);

			// Cache other DOM elements
			Beard.elements             = {};
			Beard.elements.$player     = $elm;
			Beard.elements.$text       = $elm.find('.text');
			Beard.elements.$time       = $elm.find('.time');
			Beard.elements.$progress   = $elm.find('.progress');
			Beard.elements.$seek       = $elm.find('.seek');
			Beard.elements.$seekCursor = $elm.find('.seek .cursor');
			Beard.elements.$play       = $elm.find('.play');

			// Instantiate a new Audio object
			Beard.audio = new Audio();

			// Set the source of the audio object if the data-source attribute exists
			if($elm.attr('data-source')) {
				Beard.setSource($elm.attr('data-source'));
			}

			// Bind Audio events
			$(Beard.audio).on('timeupdate', Beard.displayTime);
			$(Beard.audio).on('timeupdate', Beard.displayProgress);
			$(Beard.audio).on('canplay', Beard.displayTime);

			// Bind DOM events
			Beard.elements.$player.on('click', '.play', Beard.play);
			Beard.elements.$seek.on('mousemove', Beard.placeSeekCursor);
			Beard.elements.$seek.on('click', 'a', Beard.seek);

		},
		load: function (options) {

			// Must have a valid source
			if(!Beard.parseValidAudioFormat(options.url)) {
				Beard.error('Invalid audio url.');
				return;
			}

			// Stop audio
			Beard.pause();

			// Set the values
			Beard.displayText(options.text);
			Beard.setSource(options.url);

		},
		error: function (message) {

			// Cache current message
			var prevMessage = Beard.elements.$text.text();

			// Display the error message
			Beard.displayText('Error: ' + message);

			// After 3 seconds, return to the previous message
			setInterval(function(){
				Beard.displayText(prevMessage);
			}, 3000)

		},
		setSource: function (url) {

			// Set the audio source to the new URL
			Beard.audio.src = url;

		},
		displayProgress: function () {

			// Cache the current and total time
			var currentTime = Math.round(Beard.audio.currentTime);
			var totalTime = Math.round(Beard.audio.duration);

			// Compute the percentage out of 100
			var progressPercent = ( currentTime / totalTime ) * 100;

			// Set the width of the progress bar as a percent value
			Beard.elements.$progress.css('width', progressPercent + '%');

		},
		displayText: function (text) {

			// Inject text into the text display element
			Beard.elements.$text.text(text);

		},
		displayTime: function () {

			// Parse the time properties fromt the audio object
			var currentTime = Beard.parseSecondsToReadableFormat(Beard.audio.currentTime);
			var duration = '';
			if(Beard.audio.duration) {
				duration = ' of ' + Beard.parseSecondsToReadableFormat(Beard.audio.duration);
			} else {
				currentTime = 'loading...';
			}

			// Create a time string
			var timeString = currentTime + duration;

			// Update the view
			Beard.elements.$time.text(timeString);

		},
		parseSecondsToReadableFormat: function (seconds) {

			// Trim the decimals from the time
			var trimmedSeconds = Math.round(seconds);

			// If it's less than one minute
			if(trimmedSeconds < 60) { return '0:' + ( '0' + trimmedSeconds).slice(-2) };

			// If it is a multiple of one minute
			if(trimmedSeconds % 60 == 0) { return  ( trimmedSeconds / 60 ) + ':00'; }

			// If it is more than one minute
			return ( '' + (trimmedSeconds / 60))[0] + ':' + ('0' + Math.round(trimmedSeconds % 60)).slice(-2);

		},
		parseValidAudioFormat: function (url) {

			// Allowable audio formats
			var whitelist = ['mp3', 'ogg', 'mp4'];

			// Valid is false by default
			var valid = false;

			// With the url...
			if(url) {
				// Check to make sure that the format exists in the whitelist
				var splitUrl = url.split('.');
				var ext = splitUrl[splitUrl.length - 1];
				if( $.inArray(ext, whitelist) >= 0 ) {
					// If it exists, it's valid
					valid = true;
				}
			}

			return valid;

		},
		computeMouseOffsetX: function (e) {

			var parentOffset = $(e.target).parent().offset();
			return e.pageX - parentOffset.left;

		},
		play: function () {

			// We use the same buton for play and pause
			if(Beard.playing) {

				return Beard.pause();

			}

			// Start audio
			Beard.audio.play();

			// Set a playing property
			Beard.playing = true;

			// Set the DOM element to playing
			Beard.elements.$player.addClass('playing');

			// Set the text
			Beard.elements.$play.text('Pause');

		},
		pause: function () {

			// Pause audio
			Beard.audio.pause();

			// Unset the playing property
			Beard.playing = false;

			// Unset the DOM playing class
			Beard.elements.$player.removeClass('playing');

			// Set the text
			Beard.elements.$play.text('Play');

		},
		seek: function (e) {

			// Stop the default action/page jumping.
			e.preventDefault();

			// Divide the width of the player by the positon of the cursor.
			// Use that percentage to place the currentTime of the track.
			var beardWidth = Beard.elements.$player.width();
			var mouseX = Beard.computeMouseOffsetX(e);

			var seekPercentage = ( mouseX / beardWidth );
			var duration = Beard.audio.duration;
			var seekTime = duration * seekPercentage;

			Beard.audio.currentTime = seekTime;

		},
		placeSeekCursor: function (e) {

			// Place the seek cursor directly on the mouse cursor when hovered.
			var mouseX = Beard.computeMouseOffsetX(e);
			Beard.elements.$seekCursor.css('left', mouseX);

		}
	};

	// Expose the functions as collection methods.
	$.extend($.fn, {

		// This method initializes values from attributes and binds events.
		beard: function (options) {

			// We only support one player element (for now)
			Beard.init(this[0]);

			// If this is for testing purposes we return the Beard object instead.
			if(options && options.internals === true) {
				return Beard;
			}

			// Otherwise we return the jQuery object for chainability.
			return this;

		},
		// Load a new source URL
		load: function (options) {

			Beard.load(options);
			return this;

		}

	});

})(jQuery);<commit_msg>Update beard.js<commit_after>/*
 * Beard Functionality
 * Matthew Evans, Autumn 2013
 *
 */
;(function($){

	var Beard = {

		// Initialize the player
		init: function (elm) {

			// Cache the element as a jQuery object
			var $elm = $(elm);

			// Cache other DOM elements
			Beard.elements             = {};
			Beard.elements.$player     = $elm;
			Beard.elements.$text       = $elm.find('.text');
			Beard.elements.$time       = $elm.find('.time');
			Beard.elements.$progress   = $elm.find('.progress');
			Beard.elements.$seek       = $elm.find('.seek');
			Beard.elements.$seekCursor = $elm.find('.seek .cursor');
			Beard.elements.$play       = $elm.find('.play');

			// Instantiate a new Audio object
			Beard.audio = new Audio();

			// Set the source of the audio object if the data-source attribute exists
			if($elm.attr('data-source')) {
				Beard.setSource($elm.attr('data-source'));
			}

			// Bind Audio events
			$(Beard.audio).on('timeupdate', Beard.displayTime);
			$(Beard.audio).on('timeupdate', Beard.displayProgress);
			$(Beard.audio).on('canplay', Beard.displayTime);

			// Bind DOM events
			Beard.elements.$player.on('click', '.play', Beard.play);
			Beard.elements.$seek.on('mousemove', Beard.placeSeekCursor);
			Beard.elements.$seek.on('click', 'a', Beard.seek);

		},
		load: function (options) {

			// Must have a valid source
			if(!Beard.parseValidAudioFormat(options.url)) {
				Beard.error('Invalid audio url.');
				return;
			}

			// Stop audio
			Beard.pause();

			// Set the values
			Beard.displayText(options.text);
			Beard.setSource(options.url);

		},
		error: function (message) {

			// Cache current message
			var prevMessage = Beard.elements.$text.text();

			// Display the error message
			Beard.displayText('Error: ' + message);

			// After 3 seconds, return to the previous message
			setInterval(function(){
				Beard.displayText(prevMessage);
			}, 3000)

		},
		setSource: function (url) {

			// Set the audio source to the new URL
			Beard.audio.src = url;

		},
		displayProgress: function () {

			// Cache the current and total time
			var currentTime = Math.round(Beard.audio.currentTime);
			var totalTime = Math.round(Beard.audio.duration);

			// Compute the percentage out of 100
			var progressPercent = ( currentTime / totalTime ) * 100;

			// Set the width of the progress bar as a percent value
			Beard.elements.$progress.css('width', progressPercent + '%');

		},
		displayText: function (text) {

			// Inject text into the text display element
			Beard.elements.$text.text(text);

		},
		displayTime: function () {

			// Parse the time properties fromt the audio object
			var currentTime = Beard.parseSecondsToReadableFormat(Beard.audio.currentTime);
			var duration = '';
			if(Beard.audio.duration) {
				duration = ' of ' + Beard.parseSecondsToReadableFormat(Beard.audio.duration);
			} else {
				currentTime = 'loading...';
			}

			// Create a time string
			var timeString = currentTime + duration;

			// Update the view
			Beard.elements.$time.text(timeString);

		},
		parseSecondsToReadableFormat: function (seconds) {

			// Trim the decimals from the time
			var trimmedSeconds = Math.round(seconds);

			// If it's less than one minute
			if(trimmedSeconds < 60) { return '0:' + ( '0' + trimmedSeconds).slice(-2) };

			// If it is a multiple of one minute
			if(trimmedSeconds % 60 == 0) { return  ( trimmedSeconds / 60 ) + ':00'; }

			// If it is more than one minute
			return ( '' + (trimmedSeconds / 60))[0] + ':' + ('0' + Math.round(trimmedSeconds % 60)).slice(-2);

		},
		parseValidAudioFormat: function (url) {

			// Allowable audio formats
			var whitelist = ['mp3', 'ogg', 'mp4'];

			// Valid is false by default
			var valid = false;

			// With the url...
			if(url) {
				// Check to make sure that the format exists in the whitelist
				var splitUrl = url.split('.');
				var ext = splitUrl[splitUrl.length - 1];
				if( $.inArray(ext, whitelist) >= 0 ) {
					// If it exists, it's valid
					valid = true;
				}
			}

			return valid;

		},
		computeMouseOffsetX: function (e) {

			var parentOffset = $(e.target).parent().offset();
			return e.pageX - parentOffset.left;

		},
		play: function () {

			// We use the same buton for play and pause
			if(Beard.playing) {

				return Beard.pause();

			}

			// Start audio
			Beard.audio.play();

			// Set a playing property
			Beard.playing = true;

			// Set the DOM element to playing
			Beard.elements.$player.addClass('playing');

			// Set the text
			Beard.elements.$play.text('Pause');

		},
		pause: function () {

			// Pause audio
			Beard.audio.pause();

			// Unset the playing property
			Beard.playing = false;

			// Unset the DOM playing class
			Beard.elements.$player.removeClass('playing');

			// Set the text
			Beard.elements.$play.text('Play');

		},
		seek: function (e) {

			// Stop the default action/page jumping.
			e.preventDefault();

			// Divide the width of the player by the positon of the cursor.
			// Use that percentage to place the currentTime of the track.
			var beardWidth = Beard.elements.$player.width();
			var mouseX = Beard.computeMouseOffsetX(e);

			var seekPercentage = ( mouseX / beardWidth );
			var duration = Beard.audio.duration;
			var seekTime = duration * seekPercentage;

			Beard.audio.currentTime = seekTime;

		},
		placeSeekCursor: function (e) {

			// Place the seek cursor directly on the mouse cursor when hovered.
			var mouseX = Beard.computeMouseOffsetX(e);
			Beard.elements.$seekCursor.css('left', mouseX);

		}
	};

	// Expose the functions as collection methods.
	$.extend($.fn, {

		// This method initializes values from attributes and binds events.
		beard: function (options) {

			// We only support one player element (for now)
			Beard.init(this[0]);

			// If this is for testing purposes we return the Beard object instead.
			if(options && options.internals === true) {
				return Beard;
			}

			// Otherwise we return the jQuery object for chainability.
			return this;

		},
		// Load a new source URL
		load: function (options) {

			Beard.load(options);
			return this;

		}

	});

})(jQuery);
<|endoftext|>


<commit_before>
var contentstatus=0;
var count =1;
var timer;
var flag = 1 ;
var mapflag=1;
var page = 1;
////////////////////////////////random img start///////////////////////////////////
setInterval(function()
{
$(".hero").fadeOut( 1500, function() {
$(".hero").attr("style",'background:url("css/img/img'+count+'.jpg")');});
$('.hero').css('display', 'block');
$('.hero').animate({ opacity: 0 }, 0);
$('.hero').animate({ opacity: 1, top: "-10px" }, 2000);
    // Animation complete.
    if(count === 4)
    {
    	count=1;
    }
  count++ ;

}, 10000);

/////////////////////////////////script google analytics//////////////////////////////////////

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

  ga('create', 'UA-51359625-1', 'worldresident.net');
  ga('send', 'pageview');

///////////////////////////////////random img end///////////////////////////////////////

$(document).ready(function(){

///////////////init////////////////
$(".sel_district").attr('disabled','disabled');
$(".sel_provine").attr('disabled','disabled');
$(".sel_amphures").attr('disabled','disabled');

//////////////////////////////Moblie controller/////////////////////////////////////////////////////////////////////////
if( /Android|webOS|iPhone|iPad|iPod|BlackBerry|IEMobile|Opera Mini/i.test(navigator.userAgent) ) {
//alert(navigator.userAgent);
}

$$(".content1").swipeRight(function(){expandmap();});
$$(".content1").swipeLeft(function(){minimizemap();});
////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////
//////////////////////init page//////////////////////////////////////////////////////////
$(".auto_map_info").attr("height","0px");
$(".auto_map_info iframe").attr("height","0px");
$(".auto_map_info").attr("width","66%");
$(".auto_map_info iframe").attr("width","66%");
$("#loginopen").on("click",function(){
$(".loginfrm").css("visibility","visible");
$("#username_txt").focus();
});
/////////////////////////////////////////////////////////////////////////////////////////
////////////////////////////////////function zone////////////////////////////////////////
function expandmap(){$(".auto_map_info").animate({height:window.screen.height-385+"px"});$(".auto_map_info iframe").animate({height:window.screen.height-385+"px"});$(".content1").animate({width:"100%"});$("#imgleftside").hide();};
function minimizemap(){$(".content1").animate({width:"23.23176%"});$("#imgleftside").show();$("#menu_index").show();};
function showlogin(){$(".loginfrm").css("visibility","visible");};
function hidelogin(){$(".loginfrm").css("visibility","hidden");};
/////////////////////////////////////////////////////////////////////////////////////////

$("#password_txt").focus(showlogin);
$("#username_txt").focus(showlogin);
$("#password_txt").focusout(hidelogin);
$("#username_txt").focusout(hidelogin);
$("#search_txt").focusout(function(){if(flag==0){minimizemap(); $("#menu_index").show();}});
$("#search_txt").on("click",function(){expandmap(); $("#menu_index").hide();});
$(".content1").on({
    'mouseover': function () {if(flag===1){timer = setTimeout(function () {contentstatus=1;expandmap();}, 1000);}},
    'mouseout' : function () {if(contentstatus===1){minimizemap(); contentstatus=0;}clearTimeout(timer);}
});
$(".pin").on({'mouseover': function () {flag=0;},'mouseout' : function () {flag=1;}});
$("#menu_index").on({'mouseover': function () {flag=0;},'mouseout' : function () {flag=1;}});
$(".content13").on({'mouseover': function () {flag=0;},'mouseout' : function () {flag=1;}});

$("#map_canvas").on("click",function(){$(".auto_map_info").animate({height:"0px"});$(".auto_map_info iframe").animate({height:"0px"});});
$("#tbrshow").html("");
$.ajax({type:'GET',url:'http://www.worldresident.net/getdb',success:function(data) {for(var i=0;i<10;i++){
					if(i==0)
					$("#tbrshow").append("

"+data[i].title+"
</ld>
");
					else
					$("#tbrshow").append("

"+data[i].title+"
</ld>
");
					}
                    $(".linkme").on({
    'mouseover': function () {$(this).addClass("hover");},
    'mouseout' : function () {$(this).removeClass("hover");}
});
                     $(".linkme").bind("tap",function(){window.open("http://www.worldresident.net/info.html?id="+$(this).attr('id'),"_blank");});

				},
				error:function(err) {
					//alert("Sorry, I can't get the feed");
				}
			});

});
///////////////////////zipcode request//////////////////////////////////////////////////////////
$('.sel_amphures_plus').change(function(){

  $('.txt_amphures').val($(this).val());
});
$('.sel_District_plus').change(function(){

  $('.txt_district').val($(this).val());
});

$('#txt_zipcode1').on('input',function(){fetchzip($('#txt_zipcode1'));});
$('#txt_zipcode2').on('input',function(){fetchzip($('#txt_zipcode2'));});
$('#txt_zipcode3').on('input',function(){fetchzip($('#txt_zipcode3'));});

function fetchzip(ele){

  if($(ele).val().length>=2)
{
$.ajax({
                type:'GET',
                url:'http://www.worldresident.net/zip?zip='+$(ele).val(),
                success:function(data) {
                    var pro = new Array();
                    var amp =new Array();
                    var dis = new Array();
                    var pos = new Array();

  $('.sel_amphures_plus').html("");
   $('.sel_District_plus').html("");
  for(var i=0;i<data.length;i++)
  {
    pos.push(data[i].zipcode);
    pro.push(data[i].province_name);
    dis.push(data[i].amphur_name);
     amp.push(data[i].district_name);
  }
  pos = eliminateDuplicates(pos);
   pro = eliminateDuplicates(pro);
   amp = eliminateDuplicates(amp);
   dis = eliminateDuplicates(dis);

// globals
var rawTags = pos;

var initInputFieldValue = $(ele).val();
var dataList = document.getElementById('htmlListTags');
var initNbVirgules = (initInputFieldValue.match(/,/g)||[]).length;

fillDatalist("");

function fillDatalist(prefix) {
  var nbRawList = rawTags.length;
  // vide la liste initiale (pas utile si elle est vide au début) // FIXME
  while(dataList.childNodes.length > 0) {
    dataList.removeChild(dataList.childNodes[0]);
  }
  // la recréé avec les tags de l’array
  for (i=0; i < nbRawList; i++ ) {
    var nOpt = document.createElement("option");
    nOpt.value = prefix+rawTags[i];
    dataList.appendChild(nOpt);
  }
}

function mainLoop() {
  var currInputFieldValue = $(ele).val();
  var currInputFieldValueTrimed = $(ele).val().replace(/^\s+|\s+$/g, "");
  var currNbVirgules = (currInputFieldValue.match(/,/g)||[]).length;

  // renouvelle les "option" uniquement si le contenu de l’input à changé.
  if (currInputFieldValueTrimed != initInputFieldValue) {
    // renouvelle que si on a tout juste ajouté ou retiré une virgule depuis le dernier passage.
    if (initNbVirgules != currNbVirgules) {
      // récupère l’emplacement de la dernière virgule
      var lsIndex = currInputFieldValueTrimed.lastIndexOf(",");
      // récupère la chaine contenant jusqu’au dernier tag entier dans le contenu du champ
      var str = (lsIndex != -1) ? currInputFieldValueTrimed.substr(0, lsIndex)+", " : "";
      fillDatalist(str);
      initNbVirgules = currNbVirgules;
    }
    initInputFieldValue = currInputFieldValueTrimed;
  }
  setTimeout("mainLoop()", 100); // la fonction se redéclenchera dans 0,1s
  return true;
}
try{
mainLoop();
}catch(ex){}

   $.each(dis, function(key, value) {
     $('.sel_District_plus')
         .append($("<option></option>")
         .attr("value",value)
         .text(value));
});
   if($('.txt_district').val()!="")
   {$('.txt_district').attr('style','border-color:green');}

  if($('.txt_amphures').val()!="")
   {$('.txt_amphures').attr('style','border-color:green');}

 if($('.txt_provinces').val()!="")
   {$('.txt_provinces').attr('style','border-color:green');}

 $('.txt_district').val(dis[0]);

$('.txt_amphures').val(amp[0]);
   $(".txt_provinces").val(pro);

       $.each(amp, function(key, value) {
     $('.sel_amphures_plus')
         .append($("<option></option>")
         .attr("value",value)
         .text(value));
});

                },
                error:function(err) {
                    alert("Something bad happend, IN " +url );

                }
            });
}
if($(ele).val().length==0)
{

   $('.txt_district').attr('style','border-color:red');
   $('.txt_district').val("");
   $('.txt_amphures').attr('style','border-color:red');
   $('.txt_amphures').val("");
   $('.txt_provinces').attr('style','border-color:red');
      $('.txt_provinces').val("");
}
}

function eliminateDuplicates(arr) {
  var i,
      len=arr.length,
      out=[],
      obj={};

  for (i=0;i<len;i++) {
    obj[arr[i]]=0;
  }
  for (i in obj) {
    out.push(i);
  }
  return out;
}

//$(".linkme").on('tap',window.location="/worldresiden/info?id="+$$(this).id);
/////////////////////////////////////////////////for info request////////////////////////////////
var parameter = window.location.search.replace( "?", "" );
var values = parameter.split("=");
 var lat ;
                    var loong ;
 if(values[0]==="id"&&values[1]!=null)
 {

    $.ajax({
                type:'GET',
                url:'http://www.worldresident.net/info?'+values[0]+"="+values[1],
                success:function(data) {
                  try{
                     lat = data.location[0];
                     loong = data.location[1];
                     console.log(data.location[1]);

                        if(data.location!=null)

                       {
                    $("#locationaprt").html('');
                   }
                   else
                   {
                    $("#locationaprt").html(" ")
                   }
                   }
                   catch(ex){

                    console.log(ex);
                   }
                    $("#nameaprt").html(data.title);
                    $("#detailaprt").html(data.detail);

                    $("#nameaprt").html(data.title);
                    $("#detailaprt").html(data.detail);

                    $("#imageaprt").html(data.image);
                },
                error:function(err) {
                    alert("Something bad happend, IN " +url );

                }
            });
 }
if(values[0]==="page"&&values[1]!=null)
{
   $.ajax({
                type:'GET',
                url:'http://www.worldresident.net/page?'+values[0]+"="+values[1],
                success:function(data) {

            for(var i=0;i<15;i++)
				{
					var stat = 0;

				for(var j =0;j<20;j++)

					{
					try{	if(data[i].images[j].match(/jpg/g)||data[i].images[j].match(/png/g))
						{
						$("#columns").append('

'+data[i].title+'

');
              						j=20;
									stat=1;
						}
					   }
					catch(ex){}
					}

					if(stat===0)
					{
						$("#columns").append('

'+data[i].title+'

');

						}

                }
                 $(".pin").on("click",function(){window.open("http://www.worldresident.net/info.html?id="+$(this).attr('id'),"_blank")});

                },
                error:function(err) {
                    alert("Something bad happend, IN " +url );

                }
            });

}
/////////////////////////////////////////check page action ////////////////////////////////////////
$(window).scroll(function() {
   if($(window).scrollTop() + $(window).height() == $(document).height()+100) {
	   page++;
        $.ajax({
                type:'GET',
                url:'http://www.worldresident.net/page?page='+page,
                success:function(data) {

            for(var i=0;i<15;i++)
				{
					var stat = 0;

				for(var j =0;j<20;j++)

					{ try{
						if(data[i].images[j].match(/jpg/g)||data[i].images[j].match(/png/g))
						{
						$("#columns").append('

'+data[i].title+'

');
              						j=20;
									stat=1;
						}
						}
					catch(ex){}
					}
					if(stat===0)
					{
						$("#columns").append('

'+data[i].title+'

');

						}

                }

          $(".pin").unbind();
           $(".pin").bind("click",function(){window.open("http://www.worldresident.net/info.html?id="+$(this).attr('id'))});

                },
                error:function(err) {
                    alert("Something bad happend, IN " +url );

                }

            });
   }
});

////////////////////////////////// page control ///////////////////////////////////

$("#regiscommon").on('click',function(){
$("#selector").attr("style","display:none");
$("#box1").attr("style","display:block");

});
$("#regisnone").on('click',function(){
$("#selector").attr("style","display:none");
$("#box2").attr("style","display:block");

});
$("#regiscoop").on('click',function(){
$("#selector").attr("style","display:none");
$("#box3").attr("style","display:block");

});

$(".btn_cancle").on('click',function(){
$("#box1").attr("style","display:none");
$("#box2").attr("style","display:none");
$("#box3").attr("style","display:none");
$("#selector").attr("style","display:block");

});

<commit_msg>scroll bug<commit_after>
var contentstatus=0;
var count =1;
var timer;
var flag = 1 ;
var mapflag=1;
var page = 1;
////////////////////////////////random img start///////////////////////////////////
setInterval(function()
{
$(".hero").fadeOut( 1500, function() {
$(".hero").attr("style",'background:url("css/img/img'+count+'.jpg")');});
$('.hero').css('display', 'block');
$('.hero').animate({ opacity: 0 }, 0);
$('.hero').animate({ opacity: 1, top: "-10px" }, 2000);
    // Animation complete.
    if(count === 4)
    {
    	count=1;
    }
  count++ ;

}, 10000);

/////////////////////////////////script google analytics//////////////////////////////////////

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

  ga('create', 'UA-51359625-1', 'worldresident.net');
  ga('send', 'pageview');

///////////////////////////////////random img end///////////////////////////////////////

$(document).ready(function(){

///////////////init////////////////
$(".sel_district").attr('disabled','disabled');
$(".sel_provine").attr('disabled','disabled');
$(".sel_amphures").attr('disabled','disabled');

//////////////////////////////Moblie controller/////////////////////////////////////////////////////////////////////////
if( /Android|webOS|iPhone|iPad|iPod|BlackBerry|IEMobile|Opera Mini/i.test(navigator.userAgent) ) {
//alert(navigator.userAgent);
}

$$(".content1").swipeRight(function(){expandmap();});
$$(".content1").swipeLeft(function(){minimizemap();});
////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////
//////////////////////init page//////////////////////////////////////////////////////////
$(".auto_map_info").attr("height","0px");
$(".auto_map_info iframe").attr("height","0px");
$(".auto_map_info").attr("width","66%");
$(".auto_map_info iframe").attr("width","66%");
$("#loginopen").on("click",function(){
$(".loginfrm").css("visibility","visible");
$("#username_txt").focus();
});
/////////////////////////////////////////////////////////////////////////////////////////
////////////////////////////////////function zone////////////////////////////////////////
function expandmap(){$(".auto_map_info").animate({height:window.screen.height-385+"px"});$(".auto_map_info iframe").animate({height:window.screen.height-385+"px"});$(".content1").animate({width:"100%"});$("#imgleftside").hide();};
function minimizemap(){$(".content1").animate({width:"23.23176%"});$("#imgleftside").show();$("#menu_index").show();};
function showlogin(){$(".loginfrm").css("visibility","visible");};
function hidelogin(){$(".loginfrm").css("visibility","hidden");};
/////////////////////////////////////////////////////////////////////////////////////////

$("#password_txt").focus(showlogin);
$("#username_txt").focus(showlogin);
$("#password_txt").focusout(hidelogin);
$("#username_txt").focusout(hidelogin);
$("#search_txt").focusout(function(){if(flag==0){minimizemap(); $("#menu_index").show();}});
$("#search_txt").on("click",function(){expandmap(); $("#menu_index").hide();});
$(".content1").on({
    'mouseover': function () {if(flag===1){timer = setTimeout(function () {contentstatus=1;expandmap();}, 1000);}},
    'mouseout' : function () {if(contentstatus===1){minimizemap(); contentstatus=0;}clearTimeout(timer);}
});
$(".pin").on({'mouseover': function () {flag=0;},'mouseout' : function () {flag=1;}});
$("#menu_index").on({'mouseover': function () {flag=0;},'mouseout' : function () {flag=1;}});
$(".content13").on({'mouseover': function () {flag=0;},'mouseout' : function () {flag=1;}});

$("#map_canvas").on("click",function(){$(".auto_map_info").animate({height:"0px"});$(".auto_map_info iframe").animate({height:"0px"});});
$("#tbrshow").html("");
$.ajax({type:'GET',url:'http://www.worldresident.net/getdb',success:function(data) {for(var i=0;i<10;i++){
					if(i==0)
					$("#tbrshow").append("

"+data[i].title+"
</ld>
");
					else
					$("#tbrshow").append("

"+data[i].title+"
</ld>
");
					}
                    $(".linkme").on({
    'mouseover': function () {$(this).addClass("hover");},
    'mouseout' : function () {$(this).removeClass("hover");}
});
                     $(".linkme").bind("tap",function(){window.open("http://www.worldresident.net/info.html?id="+$(this).attr('id'),"_blank");});

				},
				error:function(err) {
					//alert("Sorry, I can't get the feed");
				}
			});

});
///////////////////////zipcode request//////////////////////////////////////////////////////////
$('.sel_amphures_plus').change(function(){

  $('.txt_amphures').val($(this).val());
});
$('.sel_District_plus').change(function(){

  $('.txt_district').val($(this).val());
});

$('#txt_zipcode1').on('input',function(){fetchzip($('#txt_zipcode1'));});
$('#txt_zipcode2').on('input',function(){fetchzip($('#txt_zipcode2'));});
$('#txt_zipcode3').on('input',function(){fetchzip($('#txt_zipcode3'));});

function fetchzip(ele){

  if($(ele).val().length>=2)
{
$.ajax({
                type:'GET',
                url:'http://www.worldresident.net/zip?zip='+$(ele).val(),
                success:function(data) {
                    var pro = new Array();
                    var amp =new Array();
                    var dis = new Array();
                    var pos = new Array();

  $('.sel_amphures_plus').html("");
   $('.sel_District_plus').html("");
  for(var i=0;i<data.length;i++)
  {
    pos.push(data[i].zipcode);
    pro.push(data[i].province_name);
    dis.push(data[i].amphur_name);
     amp.push(data[i].district_name);
  }
  pos = eliminateDuplicates(pos);
   pro = eliminateDuplicates(pro);
   amp = eliminateDuplicates(amp);
   dis = eliminateDuplicates(dis);

// globals
var rawTags = pos;

var initInputFieldValue = $(ele).val();
var dataList = document.getElementById('htmlListTags');
var initNbVirgules = (initInputFieldValue.match(/,/g)||[]).length;

fillDatalist("");

function fillDatalist(prefix) {
  var nbRawList = rawTags.length;
  // vide la liste initiale (pas utile si elle est vide au début) // FIXME
  while(dataList.childNodes.length > 0) {
    dataList.removeChild(dataList.childNodes[0]);
  }
  // la recréé avec les tags de l’array
  for (i=0; i < nbRawList; i++ ) {
    var nOpt = document.createElement("option");
    nOpt.value = prefix+rawTags[i];
    dataList.appendChild(nOpt);
  }
}

function mainLoop() {
  var currInputFieldValue = $(ele).val();
  var currInputFieldValueTrimed = $(ele).val().replace(/^\s+|\s+$/g, "");
  var currNbVirgules = (currInputFieldValue.match(/,/g)||[]).length;

  // renouvelle les "option" uniquement si le contenu de l’input à changé.
  if (currInputFieldValueTrimed != initInputFieldValue) {
    // renouvelle que si on a tout juste ajouté ou retiré une virgule depuis le dernier passage.
    if (initNbVirgules != currNbVirgules) {
      // récupère l’emplacement de la dernière virgule
      var lsIndex = currInputFieldValueTrimed.lastIndexOf(",");
      // récupère la chaine contenant jusqu’au dernier tag entier dans le contenu du champ
      var str = (lsIndex != -1) ? currInputFieldValueTrimed.substr(0, lsIndex)+", " : "";
      fillDatalist(str);
      initNbVirgules = currNbVirgules;
    }
    initInputFieldValue = currInputFieldValueTrimed;
  }
  setTimeout("mainLoop()", 100); // la fonction se redéclenchera dans 0,1s
  return true;
}
try{
mainLoop();
}catch(ex){}

   $.each(dis, function(key, value) {
     $('.sel_District_plus')
         .append($("<option></option>")
         .attr("value",value)
         .text(value));
});
   if($('.txt_district').val()!="")
   {$('.txt_district').attr('style','border-color:green');}

  if($('.txt_amphures').val()!="")
   {$('.txt_amphures').attr('style','border-color:green');}

 if($('.txt_provinces').val()!="")
   {$('.txt_provinces').attr('style','border-color:green');}

 $('.txt_district').val(dis[0]);

$('.txt_amphures').val(amp[0]);
   $(".txt_provinces").val(pro);

       $.each(amp, function(key, value) {
     $('.sel_amphures_plus')
         .append($("<option></option>")
         .attr("value",value)
         .text(value));
});

                },
                error:function(err) {
                    alert("Something bad happend, IN " +url );

                }
            });
}
if($(ele).val().length==0)
{

   $('.txt_district').attr('style','border-color:red');
   $('.txt_district').val("");
   $('.txt_amphures').attr('style','border-color:red');
   $('.txt_amphures').val("");
   $('.txt_provinces').attr('style','border-color:red');
      $('.txt_provinces').val("");
}
}

function eliminateDuplicates(arr) {
  var i,
      len=arr.length,
      out=[],
      obj={};

  for (i=0;i<len;i++) {
    obj[arr[i]]=0;
  }
  for (i in obj) {
    out.push(i);
  }
  return out;
}

//$(".linkme").on('tap',window.location="/worldresiden/info?id="+$$(this).id);
/////////////////////////////////////////////////for info request////////////////////////////////
var parameter = window.location.search.replace( "?", "" );
var values = parameter.split("=");
 var lat ;
                    var loong ;
 if(values[0]==="id"&&values[1]!=null)
 {

    $.ajax({
                type:'GET',
                url:'http://www.worldresident.net/info?'+values[0]+"="+values[1],
                success:function(data) {
                  try{
                     lat = data.location[0];
                     loong = data.location[1];
                     console.log(data.location[1]);

                        if(data.location!=null)

                       {
                    $("#locationaprt").html('');
                   }
                   else
                   {
                    $("#locationaprt").html(" ")
                   }
                   }
                   catch(ex){

                    console.log(ex);
                   }
                    $("#nameaprt").html(data.title);
                    $("#detailaprt").html(data.detail);

                    $("#nameaprt").html(data.title);
                    $("#detailaprt").html(data.detail);

                    $("#imageaprt").html(data.image);
                },
                error:function(err) {
                    alert("Something bad happend, IN " +url );

                }
            });
 }
if(values[0]==="page"&&values[1]!=null)
{
   $.ajax({
                type:'GET',
                url:'http://www.worldresident.net/page?'+values[0]+"="+values[1],
                success:function(data) {

            for(var i=0;i<15;i++)
				{
					var stat = 0;

				for(var j =0;j<20;j++)

					{
					try{	if(data[i].images[j].match(/jpg/g)||data[i].images[j].match(/png/g))
						{
						$("#columns").append('

'+data[i].title+'

');
              						j=20;
									stat=1;
						}
					   }
					catch(ex){}
					}

					if(stat===0)
					{
						$("#columns").append('

'+data[i].title+'

');

						}

                }
                 $(".pin").on("click",function(){window.open("http://www.worldresident.net/info.html?id="+$(this).attr('id'),"_blank")});

                },
                error:function(err) {
                    alert("Something bad happend, IN " +url );

                }
            });

}
/////////////////////////////////////////check page action ////////////////////////////////////////
$(window).scroll(function() {
   if($(window).scrollTop() + $(window).height() == $(document).height()-100) {
	   page++;
        $.ajax({
                type:'GET',
                url:'http://www.worldresident.net/page?page='+page,
                success:function(data) {

            for(var i=0;i<15;i++)
				{
					var stat = 0;

				for(var j =0;j<20;j++)

					{ try{
						if(data[i].images[j].match(/jpg/g)||data[i].images[j].match(/png/g))
						{
						$("#columns").append('

'+data[i].title+'

');
              						j=20;
									stat=1;
						}
						}
					catch(ex){}
					}
					if(stat===0)
					{
						$("#columns").append('

'+data[i].title+'

');

						}

                }

          $(".pin").unbind();
           $(".pin").bind("click",function(){window.open("http://www.worldresident.net/info.html?id="+$(this).attr('id'))});

                },
                error:function(err) {
                    alert("Something bad happend, IN " +url );

                }

            });
   }
});

////////////////////////////////// page control ///////////////////////////////////

$("#regiscommon").on('click',function(){
$("#selector").attr("style","display:none");
$("#box1").attr("style","display:block");

});
$("#regisnone").on('click',function(){
$("#selector").attr("style","display:none");
$("#box2").attr("style","display:block");

});
$("#regiscoop").on('click',function(){
$("#selector").attr("style","display:none");
$("#box3").attr("style","display:block");

});

$(".btn_cancle").on('click',function(){
$("#box1").attr("style","display:none");
$("#box2").attr("style","display:none");
$("#box3").attr("style","display:none");
$("#selector").attr("style","display:block");

});

<|endoftext|>


<commit_before>// Global variables
var csvFields;
var map;
var zoom;
var layer;
var percent;
var fieldSelect;
var fieldsById;
var stat;
var body;
var topology;
var carto;
var geometries;
var URL_TOPO;
var latitude = null;
var longitude = null;
var col = null;
var pScale = null;

/*
 * Main program instructions
 */
console.log("Running Cartograms 4 All Web App");

$(document).ready(function() {
  // if not already set, set new cookie.
  var session_id = generateSessionID(16);
  if( readCookie('user_session_cookie') === null ){
    createCookie('user_session_cookie', session_id, 10, '/');
  }else{
    //importUserSettings()
  }
  init();
});

/*
 * End of main program instructions
 */

function init() {
  run();
  // don't initialize until user has uploaded a .csv file
  if(document.getElementById('input_csv').files[0] == null){
    console.log("Cartograms 4 All: Waiting for user inputted CSV file");
    return;
  }
/*
  if(document.getElementById('input_topo').files[0] == null){
    console.log("Cartograms 4 All: Waiting for user inputted topojson file");
    return;
  }
 if(latitude == null){
    console.log("please enter the projection for latitude");
    return;
  }

  if(longitude == null){
    console.log("please enter the projection for longitude");
    return;
  }

  if(pScale == null){
    console.log("please enter the scale of projection");
    return;
  }
*/
  // CODE TO TEST FUNCTIONALITY OF writeToServer() and readFromServer()
  SESSION_ID = readCookie('user_session_cookie');

  //var send_text = "my_text_to_save";
  //writeToServer(SESSION_ID, send_text);
  //console.log(SESSION_ID);

  //var return_string = readFromServer(SESSION_ID);
  //console.log(return_string);
  // CODE TO TEST FUNCTIONALITY OF writeToServer() and readFromServer()

  USER_CSV = document.getElementById('input_csv').files[0];
  saveCSV(USER_CSV);

  USER_TOPO = document.getElementById('input_topo').files[0]
  if (USER_TOPO == null){
    URL_TOPO = "data/us-states.topojson";
  }

  console.log("Cartograms 4 All: Start init()");
  map = d3.select("#map");
  zoom = d3.behavior.zoom()
    .translate([-38, 32])
    .scale(.94)
    .scaleExtent([0.5, 10.0])
    .on("zoom", updateZoom);
  layer = map.append("g")
    .attr("id", "layer"),
    states = layer.append("g")
    .attr("id", "states")
    .selectAll("path");

  csvFields = getCSVFields(initCartogram);
var width = 1215,  //2100
    height = 600;

//var center = [38.996815, 34.802075];
var center = [latitude, longitude];

//d3.geo.albersUsa()
var latitude = 1 // default to be USA
if (latitude == 1){

  var proj = d3.geo.albersUsa(),
      rawData,
    dataById = {};

}else{

  var proj = d3.geo.conicConformal()
    .center(center)
    .clipAngle(180)
    // Size of the map itself, you may want to play around with this in
    // relation to your canvas size
    .scale(pScale)
    // Center the map in the middle of the canvas
    .translate([width / 2, height / 2])
    .precision(.1),
    rawData,
    dataById = {};
  }

  carto = d3.cartogram()
    .projection(proj)
    .properties(function(d) {
      return dataById[d.id];
    })
    .value(function(d) {
      return +d.properties[field];
    });
      //URL_TOPO = URL.createObjectURL(USER_TOPO);

  var URL_TOPO = DATA_DIRECTORY + "us-states.topojson";
  d3.json(URL_TOPO, function(topology) {
    this.topology = topology;
    geometries = topology.objects.states.geometries;
    d3.csv(CSV_URL, function(rawData) {
      dataById = d3.nest()
        .key(function(d) {
          return d.NAME;
        })
        .rollup(function(d) {
          return d[0];
        })
        .map(rawData);
      var features = carto.features(topology, geometries),
        path = d3.geo.path().projection(proj);

      states = states.data(features)
        .enter()
        .append("path")
        .attr("class", "state")
        .attr("id", function(d) {
          return d.properties.NAME;
        })
        .attr("fill", "#fff")
        .attr("d", path);
      states.append("title");

      // Waits until fields has been defined
      function waitForFields() {
        if (typeof someVariable !== "undefined") {

            console.log("calling PaserHash");

          parseHash(fieldsById);
        } else {
          setTimeout(waitForFields, 250);
        }
      }

      // Waits until fields has been defined
      function waitForTopology() {
        if (typeof someVariable !== "undefined") {
          console.log("calling PaserHash");

          initTopo();
        } else {
          setTimeout(topology, 250);
        }
      }
    });
  });

  console.log("Cartograms 4 All: Finished init()");
}

//initialization of the new cartogram,
//based on the csv fields passed in.
function initCartogram(csvFields) {
  fields = csvFields;
  // Data info for the cartogram
  percent = (function() {
      var fmt = d3.format(".2f");
      return function(n) {
        return fmt(n) + "%";
      };
    })(),
    fields = csvFields,
    // TODO: Make this customizable
    // NOTE: Might just have this detect if there are digits at the end of the column or beginning,
      // and if there are then use those as a year
    // TODO: Make a custom function getTimeInField() which will clear
    fieldsById = d3.nest()
    .key(function(d) {
      return d.id;
    })
    .rollup(function(d) {
      return d[0];
    })
    .map(fields),
    // TODO: Set default field to something that looks like data
    field = fields[1],
    // TODO: Allow for customization of map color
    colors = colorbrewer.RdYlBu[3]
    .reverse()
    .map(function(rgb) {
      return d3.hsl(rgb);
    });

  body = d3.select("body");
  stat = d3.select("#status");

  fieldSelect = d3.select("#field")
    .on("change", function(e) {
      field = fields[this.selectedIndex];
      location.hash = "#" + field.id;
    });

  fieldSelect.selectAll("option")
    .data(fields)
    .enter()
    .append("option")
    .attr("value", function(d) {
      return d.id;
    })
    .text(function(d) {
      return d.name;
    });

  /* TODO: Reincorporate year
  var yearSelect = d3.select("#year")
      .on("change", function(e) {
          year = years[this.selectedIndex];
          location.hash = "#" + [field.id, year].join("/");
      });

  yearSelect.selectAll("option")
      .data(years)
      .enter()
      .append("option")
      .attr("value", function(y) { return y; })
      .text(function(y) { return y; })
  */

  updateZoom();
}

window.onhashchange = function() {
  console.log("calling parseHash(fieldsById)")
  parseHash(fieldsById);
};

var deferredUpdate = (function() {
  var timeout;
  return function() {
    var args = arguments;
    clearTimeout(timeout);
    stat.text("calculating...");
    return timeout = setTimeout(function() {
      update.apply(null, arguments);
    }, 10);
  };
})();

var hashish = d3.selectAll("a.hashish")
  .datum(function() {
    return this.href;
  });
<commit_msg>Deploy<commit_after>// Global variables
var csvFields;
var map;
var zoom;
var layer;
var percent;
var fieldSelect;
var fieldsById;
var stat;
var body;
var topology;
var carto;
var geometries;
var URL_TOPO;
var latitude = null;
var longitude = null;
var col = null;
var pScale = null;

/*
 * Main program instructions
 */
console.log("Running Cartograms 4 All Web App");

$(document).ready(function() {
  // if not already set, set new cookie.
  var session_id = generateSessionID(16);
  if( readCookie('user_session_cookie') === null ){
    createCookie('user_session_cookie', session_id, 10, '/');
  }else{
    //importUserSettings()
  }
  init();
});

/*
 * End of main program instructions
 */

function init() {
  run();
  // don't initialize until user has uploaded a .csv file
  if(document.getElementById('input_csv').files[0] == null){
    console.log("Cartograms 4 All: Waiting for user inputted CSV file");
    return;
  }
/*
  if(document.getElementById('input_topo').files[0] == null){
    console.log("Cartograms 4 All: Waiting for user inputted topojson file");
    return;
  }
 if(latitude == null){
    console.log("please enter the projection for latitude");
    return;
  }

  if(longitude == null){
    console.log("please enter the projection for longitude");
    return;
  }

  if(pScale == null){
    console.log("please enter the scale of projection");
    return;
  }
*/
  // CODE TO TEST FUNCTIONALITY OF writeToServer() and readFromServer()
  SESSION_ID = readCookie('user_session_cookie');

  //var send_text = "my_text_to_save";
  //writeToServer(SESSION_ID, send_text);
  //console.log(SESSION_ID);

  //var return_string = readFromServer(SESSION_ID);
  //console.log(return_string);
  // CODE TO TEST FUNCTIONALITY OF writeToServer() and readFromServer()

  USER_CSV = document.getElementById('input_csv').files[0];
  saveCSV(USER_CSV);

  USER_TOPO = document.getElementById('input_topo').files[0]
  if (USER_TOPO == null){
    URL_TOPO = "data/us-states.topojson";
  }

  console.log("Cartograms 4 All: Start init()");
  map = d3.select("#map");
  zoom = d3.behavior.zoom()
    .translate([-38, 32])
    .scale(.94)
    .scaleExtent([0.5, 10.0])
    .on("zoom", updateZoom);
  layer = map.append("g")
    .attr("id", "layer"),
    states = layer.append("g")
    .attr("id", "states")
    .selectAll("path");

  csvFields = getCSVFields(initCartogram);
var width = 1215,  //2100
    height = 600;

//var center = [38.996815, 34.802075];
var center = [latitude, longitude];

//d3.geo.albersUsa()
var latitude = 1 // default to be USA
if (latitude == 1){

  var proj = d3.geo.albersUsa(),
      rawData,
    dataById = {};

}else{

  var proj = d3.geo.conicConformal()
    .center(center)
    .clipAngle(180)
    // Size of the map itself, you may want to play around with this in
    // relation to your canvas size
    .scale(pScale)
    // Center the map in the middle of the canvas
    .translate([width / 2, height / 2])
    .precision(.1),
    rawData,
    dataById = {};
  }

  carto = d3.cartogram()
    .projection(proj)
    .properties(function(d) {
      return dataById[d.id];
    })
    .value(function(d) {
      return +d.properties[field];
    });
      //URL_TOPO = URL.createObjectURL(USER_TOPO);

  console.log("Before state initlization");
  var URL_TOPO = DATA_DIRECTORY + "us-states.topojson";
  d3.json(URL_TOPO, function(topology) {
    this.topology = topology;
    geometries = topology.objects.states.geometries;
    d3.csv(CSV_URL, function(rawData) {
      dataById = d3.nest()
        .key(function(d) {
          return d.NAME;
        })
        .rollup(function(d) {
          return d[0];
        })
        .map(rawData);
      var features = carto.features(topology, geometries),
        path = d3.geo.path().projection(proj);

      states = states.data(features)
        .enter()
        .append("path")
        .attr("class", "state")
        .attr("id", function(d) {
          return d.properties.NAME;
        })
        .attr("fill", "#fff")
        .attr("d", path);
      states.append("title");

      // Waits until fields has been defined
      function waitForFields() {
        if (typeof someVariable !== "undefined") {

            console.log("calling PaserHash");

          parseHash(fieldsById);
        } else {
          setTimeout(waitForFields, 250);
        }
      }

      // Waits until fields has been defined
      function waitForTopology() {
        if (typeof someVariable !== "undefined") {
          console.log("calling PaserHash");

          initTopo();
        } else {
          setTimeout(topology, 250);
        }
      }
    });
  });

  console.log("Cartograms 4 All: Finished init()");
}

//initialization of the new cartogram,
//based on the csv fields passed in.
function initCartogram(csvFields) {
  fields = csvFields;
  // Data info for the cartogram
  percent = (function() {
      var fmt = d3.format(".2f");
      return function(n) {
        return fmt(n) + "%";
      };
    })(),
    fields = csvFields,
    // TODO: Make this customizable
    // NOTE: Might just have this detect if there are digits at the end of the column or beginning,
      // and if there are then use those as a year
    // TODO: Make a custom function getTimeInField() which will clear
    fieldsById = d3.nest()
    .key(function(d) {
      return d.id;
    })
    .rollup(function(d) {
      return d[0];
    })
    .map(fields),
    // TODO: Set default field to something that looks like data
    field = fields[1],
    // TODO: Allow for customization of map color
    colors = colorbrewer.RdYlBu[3]
    .reverse()
    .map(function(rgb) {
      return d3.hsl(rgb);
    });

  body = d3.select("body");
  stat = d3.select("#status");

  fieldSelect = d3.select("#field")
    .on("change", function(e) {
      field = fields[this.selectedIndex];
      location.hash = "#" + field.id;
    });

  fieldSelect.selectAll("option")
    .data(fields)
    .enter()
    .append("option")
    .attr("value", function(d) {
      return d.id;
    })
    .text(function(d) {
      return d.name;
    });

  /* TODO: Reincorporate year
  var yearSelect = d3.select("#year")
      .on("change", function(e) {
          year = years[this.selectedIndex];
          location.hash = "#" + [field.id, year].join("/");
      });

  yearSelect.selectAll("option")
      .data(years)
      .enter()
      .append("option")
      .attr("value", function(y) { return y; })
      .text(function(y) { return y; })
  */

  updateZoom();
}

window.onhashchange = function() {
  console.log("calling parseHash(fieldsById)")
  parseHash(fieldsById);
};

var deferredUpdate = (function() {
  var timeout;
  return function() {
    var args = arguments;
    clearTimeout(timeout);
    stat.text("calculating...");
    return timeout = setTimeout(function() {
      update.apply(null, arguments);
    }, 10);
  };
})();

var hashish = d3.selectAll("a.hashish")
  .datum(function() {
    return this.href;
  });
<|endoftext|>